kas-wgpu 0.4.0

KAS GUI / wgpu front-end
Documentation
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
// 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 log::{debug, info, trace};
use std::time::Instant;

use kas::event::{CursorIcon, ManagerState, UpdateHandle};
use kas::geom::{Coord, Rect, Size};
use kas::layout::SolveCache;
use kas::string::{CowString, CowStringL};
use kas::{ThemeAction, ThemeApi, TkAction, WindowId};
use kas_theme::Theme;
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, CustomWindow, DrawPipe, DrawWindow, TEX_FORMAT};
use crate::shared::{PendingAction, SharedState};
use crate::ProxyAction;

/// Per-window data
pub(crate) struct Window<CW: CustomWindow, TW> {
    pub(crate) widget: Box<dyn kas::Window>,
    pub(crate) window_id: WindowId,
    mgr: ManagerState,
    solve_cache: SolveCache,
    /// The winit window
    pub(crate) window: winit::window::Window,
    surface: wgpu::Surface,
    sc_desc: wgpu::SwapChainDescriptor,
    swap_chain: wgpu::SwapChain,
    draw: DrawWindow<CW>,
    theme_window: TW,
}

// Public functions, for use by the toolkit
impl<CW, TW> Window<CW, TW>
where
    CW: CustomWindow + 'static,
    TW: kas_theme::Window<DrawWindow<CW>> + 'static,
{
    /// Construct a window
    pub fn new<C, T>(
        shared: &mut SharedState<C, T>,
        elwt: &EventLoopWindowTarget<ProxyAction>,
        window_id: WindowId,
        mut widget: Box<dyn kas::Window>,
    ) -> Result<Self, OsError>
    where
        C: CustomPipe<Window = CW>,
        T: Theme<DrawPipe<C>, Window = TW>,
    {
        // Create draw immediately (with Size::ZERO) to find ideal window size
        let scale_factor = shared.scale_factor as f32;
        let mut draw = shared.draw.new_window(&mut shared.device, Size::ZERO);
        let mut theme_window = shared.theme.new_window(&mut draw, scale_factor);

        let mut size_handle = unsafe { theme_window.size_handle(&mut draw) };
        let solve_cache = SolveCache::find_constraints(widget.as_widget_mut(), &mut size_handle);
        let ideal = solve_cache.ideal(true);
        drop(size_handle);

        let mut builder = WindowBuilder::new().with_inner_size(ideal);
        let restrict_dimensions = widget.restrict_dimensions();
        if restrict_dimensions.0 {
            builder = builder.with_min_inner_size(solve_cache.min(true));
        }
        if restrict_dimensions.1 {
            builder = builder.with_max_inner_size(ideal);
        }
        let window = builder.with_title(widget.title()).build(elwt)?;

        let scale_factor = window.scale_factor();
        shared.scale_factor = scale_factor;
        let size: Size = window.inner_size().into();
        info!("Constucted new window with size {:?}", size);

        // draw was initially created with Size::ZERO; we must resize
        let buf = shared.draw.resize(&mut draw, &shared.device, size);
        shared.queue.submit(&[buf]);

        let surface = wgpu::Surface::create(&window);
        let sc_desc = wgpu::SwapChainDescriptor {
            usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT,
            format: TEX_FORMAT,
            width: size.0,
            height: size.1,
            present_mode: wgpu::PresentMode::Fifo,
        };
        let swap_chain = shared.device.create_swap_chain(&surface, &sc_desc);

        let mut mgr = ManagerState::new(scale_factor);
        let mut tkw = TkWindow::new(&window, shared);
        mgr.configure(&mut tkw, &mut *widget);

        let mut r = Window {
            widget,
            window_id,
            mgr,
            solve_cache,
            window,
            surface,
            sc_desc,
            swap_chain,
            draw,
            theme_window,
        };
        r.apply_size();
        Ok(r)
    }

    /// Recompute layout of widgets and redraw
    fn reconfigure<C, T>(&mut self, shared: &mut SharedState<C, T>)
    where
        C: CustomPipe<Window = CW>,
        T: Theme<DrawPipe<C>, Window = TW>,
    {
        debug!("Window::reconfigure");

        let mut tkw = TkWindow::new(&self.window, shared);
        self.mgr.configure(&mut tkw, &mut *self.widget);

        self.solve_cache.invalidate_rule_cache();
        self.apply_size();
    }

    pub fn theme_resize<C, T>(&mut self, shared: &SharedState<C, T>)
    where
        C: CustomPipe<Window = CW>,
        T: Theme<DrawPipe<C>, Window = TW>,
    {
        debug!("Window::theme_resize");
        let scale_factor = self.window.scale_factor() as f32;
        shared
            .theme
            .update_window(&mut self.theme_window, scale_factor);
        self.solve_cache.invalidate_rule_cache();
        self.apply_size();
    }

    /// Handle an event
    pub fn handle_event<C, T>(&mut self, shared: &mut SharedState<C, T>, event: WindowEvent)
    where
        C: CustomPipe<Window = CW>,
        T: Theme<DrawPipe<C>, Window = TW>,
    {
        // Note: resize must be handled here to update self.swap_chain.
        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;
                shared
                    .theme
                    .update_window(&mut self.theme_window, scale_factor as f32);
                self.mgr.set_dpi_factor(scale_factor);
                self.solve_cache.invalidate_rule_cache();
                self.do_resize(shared, *new_inner_size);
            }
            event @ _ => {
                let mut tkw = TkWindow::new(&self.window, shared);
                let widget = &mut *self.widget;
                self.mgr.with(&mut tkw, |mgr| {
                    mgr.handle_winit(widget, event);
                });
            }
        }
    }

    /// Update, after receiving all events
    pub fn update<C, T>(&mut self, shared: &mut SharedState<C, T>) -> (TkAction, Option<Instant>)
    where
        C: CustomPipe<Window = CW>,
        T: Theme<DrawPipe<C>, Window = TW>,
    {
        let mut tkw = TkWindow::new(&self.window, shared);
        let action = self.mgr.update(&mut tkw, &mut *self.widget);

        match action {
            TkAction::None => (),
            TkAction::Redraw => self.window.request_redraw(),
            TkAction::RegionMoved => {
                self.mgr.region_moved(&mut tkw, &mut *self.widget);
                self.window.request_redraw();
            }
            TkAction::Popup => {
                let mut size_handle = unsafe { self.theme_window.size_handle(&mut self.draw) };
                self.widget.resize_popups(&mut size_handle);

                self.mgr.region_moved(&mut tkw, &mut *self.widget);
                self.window.request_redraw();
            }
            TkAction::Reconfigure => self.reconfigure(shared),
            TkAction::Close | TkAction::CloseAll => (),
        }

        (action, self.mgr.next_resume())
    }

    pub fn handle_closure<C, T>(mut self, shared: &mut SharedState<C, T>) -> TkAction
    where
        C: CustomPipe<Window = CW>,
        T: Theme<DrawPipe<C>, Window = TW>,
    {
        let mut tkw = TkWindow::new(&self.window, shared);
        let widget = &mut *self.widget;
        self.mgr.with(&mut tkw, |mut mgr| {
            widget.handle_closure(&mut mgr);
        });
        self.mgr.update(&mut tkw, &mut *self.widget)
    }

    pub fn update_timer<C, T>(&mut self, shared: &mut SharedState<C, T>) -> Option<Instant>
    where
        C: CustomPipe<Window = CW>,
        T: Theme<DrawPipe<C>, Window = TW>,
    {
        let mut tkw = TkWindow::new(&self.window, shared);
        let widget = &mut *self.widget;
        self.mgr.with(&mut tkw, |mgr| {
            mgr.update_timer(widget);
        });
        self.mgr.next_resume()
    }

    pub fn update_handle<C, T>(
        &mut self,
        shared: &mut SharedState<C, T>,
        handle: UpdateHandle,
        payload: u64,
    ) where
        C: CustomPipe<Window = CW>,
        T: Theme<DrawPipe<C>, Window = TW>,
    {
        let mut tkw = TkWindow::new(&self.window, shared);
        let widget = &mut *self.widget;
        self.mgr.with(&mut tkw, |mgr| {
            mgr.update_handle(widget, handle, payload);
        });
    }

    pub fn add_popup<C, T>(
        &mut self,
        shared: &mut SharedState<C, T>,
        id: WindowId,
        popup: kas::Popup,
    ) where
        C: CustomPipe<Window = CW>,
        T: Theme<DrawPipe<C>, Window = TW>,
    {
        let window = &mut *self.widget;
        let mut size_handle = unsafe { self.theme_window.size_handle(&mut self.draw) };
        let mut tkw = TkWindow::new(&self.window, shared);
        self.mgr.with(&mut tkw, |mut mgr| {
            kas::Window::add_popup(window, &mut size_handle, &mut mgr, id, popup);
        });
    }

    pub fn send_action(&mut self, action: TkAction) {
        self.mgr.send_action(action);
    }

    pub fn send_close<C, T>(&mut self, shared: &mut SharedState<C, T>, id: WindowId)
    where
        C: CustomPipe<Window = CW>,
        T: Theme<DrawPipe<C>, Window = TW>,
    {
        if id == self.window_id {
            self.mgr.send_action(TkAction::Close);
        } else {
            let mut tkw = TkWindow::new(&self.window, shared);
            let widget = &mut *self.widget;
            self.mgr.with(&mut tkw, |mut mgr| {
                widget.remove_popup(&mut mgr, id);
            });
        }
    }
}

// Internal functions
impl<CW, TW> Window<CW, TW>
where
    CW: CustomWindow + 'static,
    TW: kas_theme::Window<DrawWindow<CW>> + 'static,
{
    fn apply_size(&mut self) {
        let size = Size(self.sc_desc.width, self.sc_desc.height);
        let rect = Rect::new(Coord::ZERO, size);
        debug!("Resizing window to rect = {:?}", rect);

        let mut size_handle = unsafe { self.theme_window.size_handle(&mut self.draw) };
        self.solve_cache
            .apply_rect(self.widget.as_widget_mut(), &mut size_handle, rect, true);
        self.widget.resize_popups(&mut size_handle);

        let restrict_dimensions = self.widget.restrict_dimensions();
        if restrict_dimensions.0 {
            self.window
                .set_min_inner_size(Some(self.solve_cache.min(true)));
        };
        if restrict_dimensions.1 {
            self.window
                .set_max_inner_size(Some(self.solve_cache.ideal(true)));
        };

        self.window.request_redraw();
    }

    fn do_resize<C, T>(&mut self, shared: &mut SharedState<C, T>, size: PhysicalSize<u32>)
    where
        C: CustomPipe<Window = CW>,
        T: Theme<DrawPipe<C>, Window = TW>,
    {
        let size = size.into();
        if size == Size(self.sc_desc.width, self.sc_desc.height) {
            return;
        }

        let buf = shared.draw.resize(&mut self.draw, &shared.device, size);
        shared.queue.submit(&[buf]);

        self.sc_desc.width = size.0;
        self.sc_desc.height = size.1;
        self.swap_chain = shared
            .device
            .create_swap_chain(&self.surface, &self.sc_desc);

        // Note that on resize, width adjustments may affect height
        // requirements; we therefore refresh size restrictions.
        self.apply_size();
    }

    pub(crate) fn do_draw<C, T>(&mut self, shared: &mut SharedState<C, T>)
    where
        C: CustomPipe<Window = CW>,
        T: Theme<DrawPipe<C>, Window = TW>,
    {
        trace!("Window::do_draw");
        let size = Size(self.sc_desc.width, self.sc_desc.height);
        let rect = Rect {
            pos: Coord::ZERO,
            size,
        };
        let mut draw_handle = unsafe {
            shared
                .theme
                .draw_handle(&mut self.draw, &mut self.theme_window, rect)
        };
        self.widget.draw(&mut draw_handle, &self.mgr, false);
        drop(draw_handle);

        let frame = self.swap_chain.get_next_texture().unwrap();
        let clear_color = to_wgpu_color(shared.theme.clear_colour());
        shared.render(&mut self.draw, &frame.view, clear_color);
    }
}

fn to_wgpu_color(c: kas::draw::Colour) -> 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> {
    window: &'a winit::window::Window,
    shared: &'a mut SharedState<C, T>,
}

impl<'a, C: CustomPipe, T> TkWindow<'a, C, T> {
    fn new(window: &'a winit::window::Window, shared: &'a mut SharedState<C, T>) -> Self {
        TkWindow { window, shared }
    }
}

impl<'a, C, T> kas::TkWindow for TkWindow<'a, C, T>
where
    C: CustomPipe,
    T: Theme<DrawPipe<C>>,
    T::Window: kas_theme::Window<DrawWindow<C::Window>>,
{
    fn add_popup(&mut self, popup: kas::Popup) -> WindowId {
        let id = self.shared.next_window_id();
        let parent_id = self.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 trigger_update(&mut self, handle: UpdateHandle, payload: u64) {
        self.shared
            .pending
            .push(PendingAction::Update(handle, payload));
    }

    #[inline]
    fn get_clipboard(&mut self) -> Option<CowString> {
        self.shared.get_clipboard()
    }

    #[inline]
    fn set_clipboard<'c>(&mut self, content: CowStringL<'c>) {
        self.shared.set_clipboard(content);
    }

    fn adjust_theme(&mut self, f: &mut dyn FnMut(&mut dyn ThemeApi) -> ThemeAction) {
        match f(&mut self.shared.theme) {
            ThemeAction::None => (),
            ThemeAction::RedrawAll => self.shared.pending.push(PendingAction::RedrawAll),
            ThemeAction::ThemeResize => self.shared.pending.push(PendingAction::ThemeResize),
        }
    }

    #[inline]
    fn set_cursor_icon(&mut self, icon: CursorIcon) {
        self.window.set_cursor_icon(icon);
    }
}