wayapp 0.2.2

A Wayland application wrapper using smithay-client-toolkit, supports currently just egui using wgpu
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
//! EGUI view manager implementation
//!
//! This module provides a ViewManager-based approach to handling EGUI surfaces
//! following the pattern from single_color.rs

use crate::Application;
use crate::EguiWgpuRenderer;
#[allow(unused_imports)]
use crate::EguiWgpuRendererThread;
use crate::FrameScheduler2 as FrameScheduler;
use crate::Kind;
use crate::WaylandEvent;
use crate::WaylandToEguiInput;
use crate::egui_to_cursor_shape;
use egui::Context;
use log::trace;
use smithay_client_toolkit::reexports::csd_frame::WindowState;
use smithay_client_toolkit::seat::keyboard::KeyEvent;
use smithay_client_toolkit::seat::keyboard::Modifiers as WaylandModifiers;
use smithay_client_toolkit::seat::pointer::PointerEvent;
use smithay_clipboard::Clipboard;
use std::num::NonZero;
use std::ops::Deref;
use std::ops::DerefMut;
use std::time::Duration;
use std::time::Instant;
use wayland_client::Proxy;
use wayland_client::protocol::wl_surface::WlSurface;
use wayland_protocols::wp::viewporter::client::wp_viewport::WpViewport;

/// Surface-specific EGUI state
pub struct EguiSurfaceState<T: Into<Kind> + Clone> {
    viewport: Option<WpViewport>,
    t: T,
    kind: Kind,
    // renderer: EguiWgpuRendererThread, // for async rendering thread
    renderer: EguiWgpuRenderer, // for direct rendering (sync)
    input_state: WaylandToEguiInput,
    init_width: u32,
    init_height: u32,
    width: u32,  // WGPU Surface width in logical pixels
    height: u32, // WGPU Surface height in logical pixels
    scale_factor: i32,
    suspended: bool,
    last_fulloutput: Option<egui::FullOutput>,
    frame_timings: Option<(Instant, Instant)>,
    has_keyboard_focus: bool,
    egui_context: Context,
    frame_scheduler: FrameScheduler,
}

impl<T: Into<Kind> + Clone> EguiSurfaceState<T> {
    pub fn new(app: &Application, t: T, width: u32, height: u32) -> Self {
        let kind = t.clone().into();
        let wl_surface = kind.get_wl_surface();
        let egui_context = Context::default();
        let renderer = EguiWgpuRenderer::new(&egui_context, wl_surface, &app.conn);
        let clipboard = unsafe { Clipboard::new(app.conn.display().id().as_ptr() as *mut _) };
        let input_state = WaylandToEguiInput::new(clipboard);
        let emitter = app.get_event_emitter();
        let wl_surface_clone = wl_surface.clone();
        let frame_scheduler = FrameScheduler::new(move || {
            // Note: Using wl_surface.frame(), wl_surface.commit(), conn.flush()
            // caused crashes with WGPU handling, so I created a way to emit Frame
            // event without Wayland dispatching.
            emitter.emit_events(vec![crate::WaylandEvent::Frame(
                wl_surface_clone.clone(),
                0,
            )]);
        });
        let frame_scheduler_fn = frame_scheduler.create_scheduler();
        egui_context.set_request_repaint_callback(move |i| {
            frame_scheduler_fn(i.delay);
        });

        Self {
            viewport: None,
            t,
            kind,
            renderer,
            input_state,
            init_height: height,
            init_width: width,
            width,
            height,
            scale_factor: 1,
            suspended: false,
            last_fulloutput: None,
            frame_timings: None,
            has_keyboard_focus: false,
            egui_context,
            frame_scheduler,
        }
    }

    pub fn get_content(&self) -> &T {
        &self.t
    }

    fn wl_surface(&self) -> &WlSurface {
        self.kind.get_wl_surface()
    }

    // pub fn get_kind(&self) -> &Kind {
    //     &self.kind
    // }

    // pub fn contains<V: Into<Kind>>(&self, other: V) -> bool {
    //     self.kind == other.into()
    // }

    fn configure(
        &mut self,
        app: &Application,
        width: u32,
        height: u32,
        window_state: Option<WindowState>,
    ) {
        self.resize_viewport(app, width, height);
        self.width = width.max(1);
        self.height = height.max(1);
        self.input_state.set_screen_size(self.width, self.height);
        self.suspended = window_state.map_or(false, |state| state.contains(WindowState::SUSPENDED));
        self.frame_scheduler.set_fps_target(
            if window_state.map_or(false, |state| state.contains(WindowState::SUSPENDED)) {
                0.05 // 0.0001
            } else {
                60.0
            },
        );
    }

    fn resize_viewport(&mut self, app: &Application, width: u32, height: u32) {
        let wl_surface = self.wl_surface().clone();
        let viewport = self.viewport.get_or_insert_with(|| {
            trace!("[EGUI] Creating viewport for surface {:?}", wl_surface.id());
            app.viewporter
                .get()
                .expect("wp_viewporter not available")
                .get_viewport(&wl_surface, &app.qh, ())
        });

        viewport.set_destination(width as i32, height as i32);
    }

    fn handle_pointer_event(&mut self, event: &PointerEvent) {
        self.input_state.handle_pointer_event(event);
    }

    fn handle_keyboard_enter(&mut self) {
        self.input_state.handle_keyboard_enter();
    }

    fn handle_keyboard_leave(&mut self) {
        self.input_state.handle_keyboard_leave();
    }

    fn handle_keyboard_event(&mut self, event: &KeyEvent, pressed: bool, repeat: bool) {
        self.input_state
            .handle_keyboard_event(event, pressed, repeat);
    }

    fn update_modifiers(&mut self, modifiers: &WaylandModifiers) {
        self.input_state.update_modifiers(modifiers);
    }

    fn scale_factor_changed(&mut self, new_factor: i32) {
        self.wl_surface().set_buffer_scale(new_factor);
        let factor = new_factor.max(1);
        if factor == self.scale_factor {
            return;
        }
        self.scale_factor = factor;
    }

    /// Request a frame via dispatching
    ///
    /// Strictly this wouldn't be necessary, as
    /// `egui_frame_scheduler.schedule_frame` could be used. However, this
    /// method can be used to break the FPS limit, and I wanted to break it
    /// for the window resizing events at least for now.
    fn request_dispatch_frame(&mut self, app: &mut Application) {
        self.wl_surface().frame(&app.qh, self.wl_surface().clone());
        self.wl_surface().commit();
        app.conn.flush().unwrap();
    }

    /// Request a frame via Frame scheduler
    pub fn request_frame(&mut self) {
        self.frame_scheduler.schedule_frame(Duration::ZERO);
    }

    /// Process EGUI frame (layout, input) without GPU rendering
    /// This is cheap and can be called frequently
    fn process_egui_frame(&mut self, ui: &mut impl FnMut(&egui::Context)) {
        let raw_input = self.input_state.take_raw_input();
        self.egui_context
            .set_pixels_per_point(self.physical_scale() as f32);
        let full_output = self.egui_context.run(raw_input, ui);
        for command in &full_output.platform_output.commands {
            self.input_state.handle_output_command(command);
        }
        if let Some(last_fulloutput) = &mut self.last_fulloutput {
            last_fulloutput.append(full_output);
        } else {
            self.last_fulloutput = Some(full_output);
        }
    }

    /// Render the last processed EGUI frame to WGPU
    /// Only call this when necessary (e.g., on frame callback or when content
    /// changed)
    fn render_to_wgpu(&mut self, full_output: egui::FullOutput) {
        let width = self.width.saturating_mul(self.physical_scale());
        let height = self.height.saturating_mul(self.physical_scale());
        let pixels_per_point = self.physical_scale() as f32;

        self.renderer
            .render_to_wgpu(full_output, width, height, pixels_per_point);

        // Update frame timings
        let now = Instant::now();
        let old = self
            .frame_timings
            .as_ref()
            .map(|(_, end)| *end)
            .unwrap_or(now);
        self.frame_timings = Some((old, now));
    }

    /// Full render of EGUI frame (layout, input + GPU rendering)
    fn render(&mut self, ui: &mut impl FnMut(&egui::Context)) {
        self.process_egui_frame(ui);

        if self.suspended {
            trace!(
                "[EGUI] Skipping rendering for suspended surface {:?}",
                self.wl_surface().id()
            );
            return;
        }

        if let Some(full_output) = self.last_fulloutput.take() {
            self.render_to_wgpu(full_output);
        }
    }

    fn physical_scale(&self) -> u32 {
        self.scale_factor.max(1) as u32
    }

    /// Get the last frame timings (previous frame time, current frame time)
    pub fn get_frame_timings(&self) -> Option<(Instant, Instant)> {
        self.frame_timings
    }

    /// Get FPS of last two frames
    ///
    /// EGUI is immediate mode GUI, this means it easier to show historical FPS,
    /// as most of the time it could be zero.
    pub fn get_fps(&self) -> f32 {
        if let Some((prev_frame, next_frame)) = &self.frame_timings {
            let frame_time = next_frame.duration_since(prev_frame.clone()).as_secs_f32();
            if frame_time > 0.0 {
                return 1.0 / frame_time;
            }
        }
        return 0.0;
    }

    /// Handle Wayland events and update surfaces accordingly
    /// Returns an optional cursor shape change
    pub fn handle_events(
        &mut self,
        app: &mut Application,
        events: &[WaylandEvent],
        ui: &mut impl FnMut(&egui::Context),
    ) {
        for event in events {
            if let Some(surface) = event.get_wl_surface() {
                if surface.id() != self.wl_surface().id() {
                    continue;
                }
            }
            match event {
                WaylandEvent::WindowConfigure(_, configure) => {
                    let width = configure
                        .new_size
                        .0
                        .unwrap_or_else(|| NonZero::new(self.init_width).unwrap())
                        .get();
                    let height = configure
                        .new_size
                        .1
                        .unwrap_or_else(|| NonZero::new(self.init_height).unwrap())
                        .get();

                    self.configure(app, width, height, Some(configure.state));
                    self.request_dispatch_frame(app);
                }
                WaylandEvent::LayerShellConfigure(_, config) => {
                    let width = config.new_size.0;
                    let height = config.new_size.1;

                    self.configure(app, width, height, None);
                    self.request_dispatch_frame(app);
                }
                WaylandEvent::PopupConfigure(_, config) => {
                    let width = config.width as u32;
                    let height = config.height as u32;

                    self.configure(app, width, height, None);
                    self.request_dispatch_frame(app);
                }
                WaylandEvent::Frame(_, _) => {
                    self.render(ui);
                }
                WaylandEvent::ScaleFactorChanged(_, factor) => {
                    self.scale_factor_changed(*factor);
                    self.process_egui_frame(ui);
                    self.request_frame();
                }
                WaylandEvent::PointerEvent((surface, position, event_kind)) => {
                    self.handle_pointer_event(&PointerEvent {
                        surface: surface.clone(),
                        position: position.clone(),
                        kind: event_kind.clone(),
                    });
                    self.process_egui_frame(ui);
                    if let Some(cursor) = self
                        .last_fulloutput
                        .as_ref()
                        .map(|o| o.platform_output.cursor_icon)
                    {
                        app.set_cursor(egui_to_cursor_shape(cursor));
                    }
                }
                WaylandEvent::KeyboardEnter(_, _serials, _keysyms) => {
                    self.handle_keyboard_enter();
                    self.has_keyboard_focus = true;
                    self.process_egui_frame(ui);
                }
                WaylandEvent::KeyboardLeave(_) => {
                    self.handle_keyboard_leave();
                    self.has_keyboard_focus = false;
                    self.process_egui_frame(ui);
                }
                WaylandEvent::KeyPress(key_event) => {
                    if self.has_keyboard_focus {
                        self.handle_keyboard_event(key_event, true, false);
                        self.process_egui_frame(ui);
                    }
                }
                WaylandEvent::KeyRelease(key_event) => {
                    if self.has_keyboard_focus {
                        self.handle_keyboard_event(key_event, false, false);
                        self.process_egui_frame(ui);
                    }
                }
                WaylandEvent::KeyRepeat(key_event) => {
                    if self.has_keyboard_focus {
                        self.handle_keyboard_event(key_event, true, true);
                        self.process_egui_frame(ui);
                    }
                }
                WaylandEvent::ModifiersChanged(modifiers) => {
                    self.update_modifiers(modifiers);
                    self.process_egui_frame(ui);

                    // Note: EGUI Doesn't have Event::ModifiersChanged, so we need to
                    // request a frame manually here. There doesn't appear to be a way to determine
                    // when modifiers change, but rather if they are pressed or not.
                    //
                    // Same problem in winit implementation:
                    //
                    // https://github.com/emilk/egui/blob/fa78d25564a5dbcb546ff6db0a9e14cb603ba03b/crates/egui-winit/src/lib.rs#L443-L465
                    //
                    // It doesn't call on_keyboard_input, it just updates state of modifiers without
                    // emitting events.
                    self.request_frame();
                }
                _ => {}
            }
        }
    }
}

impl<T: Into<Kind> + Clone> Deref for EguiSurfaceState<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.t
    }
}

impl<T: Into<Kind> + Clone> DerefMut for EguiSurfaceState<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.t
    }
}

/// Helper trait to allow calling `contains` on `Option<EguiSurfaceState<T>>`
pub trait OptionEguiSurfaceStateExt<T: Into<Kind> + Clone> {
    // fn contains<V: Into<Kind>>(&self, other: V) -> bool;

    fn handle_events(
        &mut self,
        app: &mut Application,
        events: &[WaylandEvent],
        ui: &mut impl FnMut(&egui::Context),
    ) -> ();
}

impl<T: Into<Kind> + Clone> OptionEguiSurfaceStateExt<T> for Option<EguiSurfaceState<T>> {
    // fn contains<V: Into<Kind>>(&self, other: V) -> bool {
    //     self.as_ref().map_or(false, |s| s.contains(other))
    // }

    fn handle_events(
        &mut self,
        app: &mut Application,
        events: &[WaylandEvent],
        ui: &mut impl FnMut(&egui::Context),
    ) -> () {
        if let Some(surface_state) = self {
            surface_state.handle_events(app, events, ui);
        }
    }
}