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
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
// use crate::LayerSurfaceContainer;
// use crate::PopupContainer;
// use crate::SubsurfaceContainer;
// use crate::WindowContainer;
use log::trace;
use smithay_client_toolkit::compositor::CompositorHandler;
use smithay_client_toolkit::compositor::CompositorState;
use smithay_client_toolkit::delegate_compositor;
use smithay_client_toolkit::delegate_keyboard;
use smithay_client_toolkit::delegate_layer;
use smithay_client_toolkit::delegate_output;
use smithay_client_toolkit::delegate_pointer;
use smithay_client_toolkit::delegate_registry;
use smithay_client_toolkit::delegate_seat;
use smithay_client_toolkit::delegate_shm;
use smithay_client_toolkit::delegate_simple;
use smithay_client_toolkit::delegate_subcompositor;
use smithay_client_toolkit::delegate_xdg_popup;
use smithay_client_toolkit::delegate_xdg_shell;
use smithay_client_toolkit::delegate_xdg_window;
use smithay_client_toolkit::output::OutputHandler;
use smithay_client_toolkit::output::OutputState;
use smithay_client_toolkit::registry::ProvidesRegistryState;
use smithay_client_toolkit::registry::RegistryState;
use smithay_client_toolkit::registry::SimpleGlobal;
use smithay_client_toolkit::registry_handlers;
use smithay_client_toolkit::seat::Capability;
use smithay_client_toolkit::seat::SeatHandler;
use smithay_client_toolkit::seat::SeatState;
use smithay_client_toolkit::seat::keyboard::KeyEvent;
use smithay_client_toolkit::seat::keyboard::KeyboardHandler;
use smithay_client_toolkit::seat::keyboard::Keysym;
use smithay_client_toolkit::seat::pointer::PointerEvent;
use smithay_client_toolkit::seat::pointer::PointerEventKind;
use smithay_client_toolkit::seat::pointer::PointerHandler;
use smithay_client_toolkit::seat::pointer::cursor_shape::CursorShapeManager;
use smithay_client_toolkit::shell::WaylandSurface;
use smithay_client_toolkit::shell::wlr_layer::LayerShell;
use smithay_client_toolkit::shell::wlr_layer::LayerShellHandler;
use smithay_client_toolkit::shell::wlr_layer::LayerSurface;
use smithay_client_toolkit::shell::wlr_layer::LayerSurfaceConfigure;
use smithay_client_toolkit::shell::xdg::XdgShell;
use smithay_client_toolkit::shell::xdg::popup::Popup;
use smithay_client_toolkit::shell::xdg::popup::PopupConfigure;
use smithay_client_toolkit::shell::xdg::popup::PopupHandler;
use smithay_client_toolkit::shell::xdg::window::Window;
use smithay_client_toolkit::shell::xdg::window::WindowConfigure;
use smithay_client_toolkit::shell::xdg::window::WindowHandler;
use smithay_client_toolkit::shm::Shm;
use smithay_client_toolkit::shm::ShmHandler;
use smithay_client_toolkit::subcompositor::SubcompositorState;
use smithay_clipboard::Clipboard;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex;
use std::thread::JoinHandle;
use wayland_backend::client::ObjectId;
use wayland_backend::client::WaylandError;
use wayland_client::Connection;
use wayland_client::Dispatch;
use wayland_client::EventQueue;
use wayland_client::Proxy;
use wayland_client::QueueHandle;
use wayland_client::globals::registry_queue_init;
use wayland_client::protocol::wl_keyboard::WlKeyboard;
use wayland_client::protocol::wl_output;
use wayland_client::protocol::wl_output::WlOutput;
use wayland_client::protocol::wl_pointer::WlPointer;
use wayland_client::protocol::wl_region::WlRegion;
use wayland_client::protocol::wl_seat;
use wayland_client::protocol::wl_surface::WlSurface;
use wayland_protocols::wp::cursor_shape::v1::client::wp_cursor_shape_device_v1::Shape;
use wayland_protocols::wp::cursor_shape::v1::client::wp_cursor_shape_device_v1::WpCursorShapeDeviceV1;
use wayland_protocols::wp::viewporter::client::wp_viewport::WpViewport;
use wayland_protocols::wp::viewporter::client::wp_viewport::{self};
use wayland_protocols::wp::viewporter::client::wp_viewporter::WpViewporter;

/// Enum representing different Wayland events
///
/// This is not same as smithay_client_toolkit events, this is an
/// application-level event enum.
#[derive(Debug, Clone)]
pub enum WaylandEvent {
    /// WlSurface and the timestamp
    Frame(WlSurface, u32),
    ScaleFactorChanged(WlSurface, i32),
    TransformChanged(WlSurface),
    SurfaceEnteredOutput(WlSurface, WlOutput),
    SurfaceLeftOutput(WlSurface, WlOutput),
    LayerShellClosed(LayerSurface),
    LayerShellConfigure(LayerSurface, LayerSurfaceConfigure),
    PopupConfigure(Popup, PopupConfigure),
    PopupDone(Popup),
    WindowRequestClose(Window),
    WindowConfigure(Window, WindowConfigure),
    OutputCreated(WlOutput),
    OutputUpdated(WlOutput),
    OutputDestroyed(WlOutput),
    KeyboardEnter(WlSurface, Vec<u32>, Vec<Keysym>),
    KeyboardLeave(WlSurface),
    KeyPress(KeyEvent),
    KeyRelease(KeyEvent),
    KeyRepeat(KeyEvent),
    PointerEvent((WlSurface, (f64, f64), PointerEventKind)),
    ModifiersChanged(smithay_client_toolkit::seat::keyboard::Modifiers),
}

impl WaylandEvent {
    pub fn get_wl_surface(&self) -> Option<&WlSurface> {
        match self {
            WaylandEvent::Frame(s, _) => Some(s),
            WaylandEvent::ScaleFactorChanged(s, _) => Some(s),
            WaylandEvent::TransformChanged(s) => Some(s),
            WaylandEvent::SurfaceEnteredOutput(s, _) => Some(s),
            WaylandEvent::SurfaceLeftOutput(s, _) => Some(s),
            WaylandEvent::WindowConfigure(w, _) => Some(&w.wl_surface()),
            WaylandEvent::LayerShellConfigure(layer, _) => Some(&layer.wl_surface()),
            WaylandEvent::LayerShellClosed(layer) => Some(&layer.wl_surface()),
            WaylandEvent::PopupConfigure(popup, _) => Some(&popup.wl_surface()),
            WaylandEvent::PopupDone(popup) => Some(&popup.wl_surface()),
            WaylandEvent::KeyboardEnter(s, _, _) => Some(s),
            WaylandEvent::KeyboardLeave(s) => Some(s),
            WaylandEvent::PointerEvent((s, _, _)) => Some(s),
            _ => None,
        }
    }
}

/// External dispatcher for emitting Wayland events from outside the application
#[derive(Clone)]
pub struct WaylandEventEmitter {
    dispatch_fn: Arc<dyn Fn(DispatchToken) + Send + Sync + 'static>,
    events: Arc<Mutex<Vec<WaylandEvent>>>,
}

impl WaylandEventEmitter {
    /// Emit events to the application
    pub fn emit_events(&self, events: Vec<WaylandEvent>) {
        self.events.lock().unwrap().extend(events);
        (self.dispatch_fn)(DispatchToken::external());
    }
}

pub struct Application {
    wayland_events: Arc<Mutex<Vec<WaylandEvent>>>,
    pub conn: Connection,
    event_queue: Option<EventQueue<Self>>,
    pub qh: QueueHandle<Self>,
    pub registry_state: RegistryState,
    pub seat_state: SeatState,
    pub output_state: OutputState,
    pub shm_state: Shm,
    pub compositor_state: CompositorState,
    pub subcompositor_state: SubcompositorState,
    pub xdg_shell: XdgShell,
    pub layer_shell: LayerShell,
    pub clipboard: Clipboard,
    pub viewporter: SimpleGlobal<WpViewporter, 1>,
    cursor_shape_manager: CursorShapeManager,
    last_pointer_enter_serial: Option<u32>,
    last_pointer: Option<WlPointer>,
    pointer_shape_devices: HashMap<ObjectId, WpCursorShapeDeviceV1>,
    keyboard_focused_surface: Option<ObjectId>,
    dispatcher: Option<InternalDispatcherThread>,
    dispatch_fn: Arc<dyn Fn(DispatchToken) + Send + Sync + 'static>,
}

impl Application {
    /// Create a new Application, initializing all Wayland globals and state.
    pub fn new<T: Fn(DispatchToken) + Send + Sync + 'static>(dispatch_fn: T) -> Self {
        let conn = Connection::connect_to_env().expect("Failed to connect to Wayland");
        let (globals, event_queue) =
            registry_queue_init::<Self>(&conn).expect("Failed to init registry");
        let qh: QueueHandle<Self> = event_queue.handle();

        // Bind required globals
        let compositor_state =
            CompositorState::bind(&globals, &qh).expect("wl_compositor not available");
        let subcompositor_state =
            SubcompositorState::bind(compositor_state.wl_compositor().clone(), &globals, &qh)
                .expect("wl_subcompositor not available");
        let xdg_shell = XdgShell::bind(&globals, &qh).expect("xdg shell not available");
        let shm_state = Shm::bind(&globals, &qh).expect("wl_shm not available");
        let layer_shell = LayerShell::bind(&globals, &qh).expect("layer shell not available");
        let cursor_shape_manager =
            CursorShapeManager::bind(&globals, &qh).expect("cursor shape manager not available");
        let viewporter = SimpleGlobal::<WpViewporter, 1>::bind(&globals, &qh)
            .expect("wp_viewporter not available");
        let clipboard = unsafe { Clipboard::new(conn.display().id().as_ptr() as *mut _) };

        Self {
            wayland_events: Arc::new(Mutex::new(Vec::new())),
            event_queue: Some(event_queue),
            conn,
            qh: qh.clone(),
            subcompositor_state,
            registry_state: RegistryState::new(&globals),
            seat_state: SeatState::new(&globals, &qh),
            output_state: OutputState::new(&globals, &qh),
            shm_state,
            compositor_state,
            xdg_shell,
            layer_shell,
            clipboard,
            viewporter,
            cursor_shape_manager,
            last_pointer_enter_serial: None,
            last_pointer: None,
            pointer_shape_devices: HashMap::new(),
            keyboard_focused_surface: None,
            dispatcher: None,
            dispatch_fn: Arc::new(dispatch_fn),
        }
    }

    pub fn take_wayland_events(&mut self) -> Vec<WaylandEvent> {
        let mut events = self.wayland_events.lock().unwrap();
        events.drain(..).collect()
    }

    pub fn get_event_emitter(&self) -> WaylandEventEmitter {
        WaylandEventEmitter {
            dispatch_fn: self.dispatch_fn.clone(),
            events: self.wayland_events.clone(),
        }
    }

    fn push_wayland_event(&self, event: WaylandEvent) {
        self.wayland_events.lock().unwrap().push(event);
    }

    pub fn set_cursor(&mut self, shape: Shape) {
        if let Some(serial) = self.last_pointer_enter_serial
            && let Some(pointer) = &self.last_pointer
        {
            let pointer_id = pointer.id();
            let device = self
                .pointer_shape_devices
                .entry(pointer_id)
                .or_insert_with(|| {
                    trace!(
                        "[COMMON] Creating new cursor shape device for pointer id {}",
                        pointer.id()
                    );
                    self.cursor_shape_manager
                        .get_shape_device(pointer, &self.qh)
                });
            device.set_shape(serial, shape);
        }
    }

    /// Asynchronous way to run the Wayland event loop
    ///
    /// Connection reading happens blockingly in separate thread, but
    /// dispatching is done by the user via `AsyncDispatcher::dispatch_pending`
    ///
    /// See egui_tokio_async.rs example for usage.
    ///
    /// This may panic if the event queue has already been taken.
    pub fn run_dispatcher(&mut self) {
        let event_queue = self.event_queue.take().expect("Event queue already used");
        let dispatch_fn = self.dispatch_fn.clone();
        let mut dispatcher =
            InternalDispatcherThread::new(self.conn.clone(), event_queue, dispatch_fn);
        dispatcher.start_thread();
        self.dispatcher = Some(dispatcher);
    }

    /// Dispatch pending events, and return collected Wayland events
    ///
    /// Used with `run_dispatcher` method, when dispatch_fn is signaled
    pub fn dispatch_pending(&mut self, token: DispatchToken) -> Vec<WaylandEvent> {
        // Two types of WaylandEvent sources:
        // 1. External events emitted via WaylandEventEmitter (they don't need to
        //    trigger dispatching)
        // 2. Events coming from Wayland connection
        if !token.from_wayland() {
            self.wayland_events.lock().unwrap().drain(..).collect()
        } else {
            if let Some(mut dispatcher) = self.dispatcher.take() {
                let res = dispatcher.dispatch_pending(self);
                self.dispatcher = Some(dispatcher);
                res
            } else {
                panic!("Dispatcher not running, call run_dispatcher first");
            }
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub struct DispatchToken(bool);

impl DispatchToken {
    /// Create a token indicating dispatch from Wayland connection
    pub(crate) fn wayland() -> Self {
        DispatchToken(true)
    }

    /// Create a token indicating external dispatch
    pub(crate) fn external() -> Self {
        DispatchToken(false)
    }

    /// Check if the dispatch is from Wayland connection
    fn from_wayland(&self) -> bool {
        self.0
    }
}

enum InternalDispatcherError {
    RecvError(std::sync::mpsc::RecvError),
    WaylandError(WaylandError),
}
impl From<std::sync::mpsc::RecvError> for InternalDispatcherError {
    fn from(e: std::sync::mpsc::RecvError) -> Self {
        InternalDispatcherError::RecvError(e)
    }
}
impl From<WaylandError> for InternalDispatcherError {
    fn from(e: WaylandError) -> Self {
        InternalDispatcherError::WaylandError(e)
    }
}

struct InternalDispatcherThread {
    conn: Option<Connection>,
    event_queue: EventQueue<Application>,
    count_reader: Option<std::sync::mpsc::Receiver<Option<usize>>>,
    count_sender: std::sync::mpsc::Sender<Option<usize>>,
    dispatch_fn: Option<Arc<dyn Fn(DispatchToken) + Sync + Send + 'static>>,
    #[allow(dead_code)]
    reader_thread: Option<JoinHandle<()>>,
}

impl InternalDispatcherThread {
    fn new(
        conn: Connection,
        event_queue: EventQueue<Application>,
        dispatch_fn: Arc<dyn Fn(DispatchToken) + Sync + Send + 'static>,
    ) -> Self {
        let (count_sender, count_reader) = std::sync::mpsc::channel::<Option<usize>>();
        InternalDispatcherThread {
            conn: Some(conn),
            event_queue,
            count_sender,
            count_reader: Some(count_reader),
            dispatch_fn: Some(dispatch_fn),
            reader_thread: None,
        }
    }

    /// Start the blocking reading thread
    pub(crate) fn start_thread(&mut self) {
        let count_reader = self.count_reader.take().expect("Count reader missing");
        let dispatch_fn = self.dispatch_fn.take().expect("Dispatch function missing");
        let conn = self.conn.take().expect("Connection missing");

        self.reader_thread = Some(std::thread::spawn(move || {
            // Initial trigger dispatching
            (dispatch_fn)(DispatchToken::wayland());

            loop {
                match InternalDispatcherThread::read_blocking(&conn, &dispatch_fn, &count_reader) {
                    Ok(cont) => {
                        if !cont {
                            break;
                        }
                    }
                    Err(InternalDispatcherError::RecvError(_)) => {
                        // Sender dropped, exit thread
                        break;
                    }
                    Err(InternalDispatcherError::WaylandError(e)) => {
                        eprintln!("Error in Wayland reader thread: {:?}", e);
                        break;
                    }
                }
            }
        }));
    }

    /// Reads the wayland connection blockingly, and calls the user defined
    /// dispatch function
    #[inline]
    fn read_blocking(
        conn: &Connection,
        dispatch_fn: &Arc<dyn Fn(DispatchToken) + Sync + Send + 'static>,
        count_reader: &std::sync::mpsc::Receiver<Option<usize>>,
    ) -> Result<bool, InternalDispatcherError> {
        // Implementation follows `EventQueue::blocking_dispatch` logic
        match count_reader.recv()? {
            Some(count) => {
                if count > 0 {
                    (dispatch_fn)(DispatchToken::wayland());
                    return Ok(true);
                }
            }
            None => return Ok(false),
        }

        conn.flush()?;

        // This function execution can take sometimes seconds (if no events are coming)
        if let Some(guard) = conn.prepare_read() {
            guard.read_without_dispatch()?;
        } else {
            // Goal is that this branch is never or very seldomly hit
            #[cfg(feature = "_example")]
            println!("♦️♦️♦️♦️♦️ Failed to read");
        }

        (dispatch_fn)(DispatchToken::wayland());
        Ok(true) // Continue
    }

    /// Dispatch pending events, and return collected Wayland events
    pub(crate) fn dispatch_pending(&mut self, app: &mut Application) -> Vec<WaylandEvent> {
        let count = self
            .event_queue
            .dispatch_pending(app)
            .expect("Wayland dispatch failed");
        let _ = self.count_sender.send(Some(count));
        app.take_wayland_events()
    }
}

// This doesn't work properly because it is
// more likely that the locking thread is stuck at prepare_read or
// read_without_dispatch, then the signaling here won't be received until those
// calls return.
// impl Drop for AsyncDispatcher {
//     fn drop(&mut self) {
//         // Terminate the lock thread
//         self.count_sender.send(None).unwrap();
//         if let Some(thread) = self.lock_thread.take() {
//             let _ = thread.join();
//         }
//     }
// }

impl CompositorHandler for Application {
    fn scale_factor_changed(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        surface: &WlSurface,
        new_factor: i32,
    ) {
        self.push_wayland_event(WaylandEvent::ScaleFactorChanged(
            surface.clone(),
            new_factor,
        ));
    }

    fn transform_changed(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        surface: &WlSurface,
        _new_transform: wl_output::Transform,
    ) {
        self.push_wayland_event(WaylandEvent::TransformChanged(surface.clone()));
    }

    fn frame(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        surface: &WlSurface,
        time: u32,
    ) {
        self.push_wayland_event(WaylandEvent::Frame(surface.clone(), time));
    }

    fn surface_enter(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        surface: &WlSurface,
        output: &WlOutput,
    ) {
        self.push_wayland_event(WaylandEvent::SurfaceEnteredOutput(
            surface.clone(),
            output.clone(),
        ));
    }

    fn surface_leave(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        surface: &WlSurface,
        output: &WlOutput,
    ) {
        self.push_wayland_event(WaylandEvent::SurfaceLeftOutput(
            surface.clone(),
            output.clone(),
        ));
    }
}

impl OutputHandler for Application {
    fn output_state(&mut self) -> &mut OutputState {
        &mut self.output_state
    }

    fn new_output(&mut self, _conn: &Connection, _qh: &QueueHandle<Self>, output: WlOutput) {
        self.push_wayland_event(WaylandEvent::OutputCreated(output));
    }

    fn update_output(&mut self, _conn: &Connection, _qh: &QueueHandle<Self>, output: WlOutput) {
        self.push_wayland_event(WaylandEvent::OutputUpdated(output));
    }

    fn output_destroyed(&mut self, _conn: &Connection, _qh: &QueueHandle<Self>, output: WlOutput) {
        self.push_wayland_event(WaylandEvent::OutputDestroyed(output));
    }
}

impl LayerShellHandler for Application {
    fn closed(&mut self, _conn: &Connection, _qh: &QueueHandle<Self>, target_layer: &LayerSurface) {
        self.push_wayland_event(WaylandEvent::LayerShellClosed(target_layer.clone()));
    }

    fn configure(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        target_layer: &LayerSurface,
        configure: LayerSurfaceConfigure,
        _serial: u32,
    ) {
        self.push_wayland_event(WaylandEvent::LayerShellConfigure(
            target_layer.clone(),
            configure.clone(),
        ));
    }
}

impl PopupHandler for Application {
    fn configure(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        target_popup: &Popup,
        config: PopupConfigure,
    ) {
        self.push_wayland_event(WaylandEvent::PopupConfigure(
            target_popup.clone(),
            config.clone(),
        ));

        trace!("[COMMON] XDG popup configure");
    }

    fn done(&mut self, _conn: &Connection, _qh: &QueueHandle<Self>, target_popup: &Popup) {
        self.push_wayland_event(WaylandEvent::PopupDone(target_popup.clone()));

        trace!("[COMMON] XDG popup done");
    }
}

impl WindowHandler for Application {
    fn request_close(&mut self, _: &Connection, _: &QueueHandle<Self>, target_window: &Window) {
        trace!("[COMMON] XDG window close requested");
        self.push_wayland_event(WaylandEvent::WindowRequestClose(target_window.clone()));
    }

    fn configure(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        target_window: &Window,
        configure: WindowConfigure,
        _serial: u32,
    ) {
        self.push_wayland_event(WaylandEvent::WindowConfigure(
            target_window.clone(),
            configure.clone(),
        ));

        trace!("[COMMON] XDG window configure");
    }
}

impl PointerHandler for Application {
    fn pointer_frame(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        pointer: &WlPointer,
        events: &[PointerEvent],
    ) {
        for event in events {
            match event.kind {
                // Changing cursor shape requires last enter serial number, we are storing it here
                PointerEventKind::Enter { serial } => {
                    self.last_pointer_enter_serial = Some(serial);
                    self.last_pointer = Some(pointer.clone());
                }
                _ => {}
            }

            self.push_wayland_event(WaylandEvent::PointerEvent((
                event.surface.clone(),
                event.position,
                event.kind.clone(),
            )));
        }
    }
}

impl KeyboardHandler for Application {
    fn enter(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _keyboard: &WlKeyboard,
        surface: &WlSurface,
        _serial: u32,
        _raw: &[u32],
        _keysyms: &[Keysym],
    ) {
        trace!("[MAIN] Keyboard focus gained on surface {:?}", surface.id());
        self.push_wayland_event(WaylandEvent::KeyboardEnter(
            surface.clone(),
            _raw.to_vec(),
            _keysyms.to_vec(),
        ));

        self.keyboard_focused_surface = Some(surface.id());
    }

    fn leave(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _keyboard: &WlKeyboard,
        surface: &WlSurface,
        _serial: u32,
    ) {
        trace!("[MAIN] Keyboard focus lost");
        self.push_wayland_event(WaylandEvent::KeyboardLeave(surface.clone()));
    }

    fn press_key(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _keyboard: &WlKeyboard,
        _serial: u32,
        event: KeyEvent,
    ) {
        trace!("[MAIN] Key pressed: keycode={}", event.raw_code);
        self.push_wayland_event(WaylandEvent::KeyPress(event.clone()));
    }

    fn release_key(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _keyboard: &WlKeyboard,
        _serial: u32,
        event: KeyEvent,
    ) {
        trace!("[MAIN] Key released: keycode={}", event.raw_code);
        self.push_wayland_event(WaylandEvent::KeyRelease(event.clone()));
    }

    fn update_modifiers(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _keyboard: &WlKeyboard,
        _serial: u32,
        modifiers: smithay_client_toolkit::seat::keyboard::Modifiers,
        _raw_modifiers: smithay_client_toolkit::seat::keyboard::RawModifiers,
        _layout: u32,
    ) {
        self.push_wayland_event(WaylandEvent::ModifiersChanged(modifiers.clone()));
    }

    fn repeat_key(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _keyboard: &WlKeyboard,
        _serial: u32,
        event: KeyEvent,
    ) {
        trace!("[MAIN] Key repeated: keycode={}", event.raw_code);
        self.push_wayland_event(WaylandEvent::KeyRepeat(event.clone()));
    }
}

impl SeatHandler for Application {
    fn seat_state(&mut self) -> &mut SeatState {
        &mut self.seat_state
    }

    fn new_seat(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_seat::WlSeat) {}

    fn new_capability(
        &mut self,
        _conn: &Connection,
        qh: &QueueHandle<Self>,
        seat: wl_seat::WlSeat,
        capability: Capability,
    ) {
        trace!("[MAIN] New seat capability: {:?}", capability);
        if capability == Capability::Keyboard {
            trace!("[MAIN] Creating wl_keyboard");
            match self.seat_state.get_keyboard(qh, &seat, None) {
                Ok(_wl_keyboard) => {
                    trace!("[MAIN] wl_keyboard created successfully");
                }
                Err(e) => {
                    trace!("[MAIN] Failed to create wl_keyboard: {:?}", e);
                }
            }
        }
        if capability == Capability::Pointer {
            let _ = self.seat_state.get_pointer(&qh, &seat);
            trace!("[MAIN] Creating themed pointer");
        }
    }

    fn remove_capability(
        &mut self,
        _conn: &Connection,
        _: &QueueHandle<Self>,
        _: wl_seat::WlSeat,
        _capability: Capability,
    ) {
    }

    fn remove_seat(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_seat::WlSeat) {}
}

impl ShmHandler for Application {
    fn shm_state(&mut self) -> &mut Shm {
        &mut self.shm_state
    }
}

impl ProvidesRegistryState for Application {
    registry_handlers![OutputState];

    fn registry(&mut self) -> &mut RegistryState {
        &mut self.registry_state
    }
}

impl AsMut<SimpleGlobal<WpViewporter, 1>> for Application {
    fn as_mut(&mut self) -> &mut SimpleGlobal<WpViewporter, 1> {
        &mut self.viewporter
    }
}

impl Dispatch<WpViewport, ()> for Application {
    fn event(
        _: &mut Application,
        _: &WpViewport,
        _: wp_viewport::Event,
        _: &(),
        _: &Connection,
        _: &QueueHandle<Self>,
    ) {
        // No events expected from wp_viewport
    }
}

impl Dispatch<WlRegion, ()> for Application {
    fn event(
        _state: &mut Self,
        _proxy: &WlRegion,
        _event: <WlRegion as wayland_client::Proxy>::Event,
        _data: &(),
        _conn: &Connection,
        _qhandle: &QueueHandle<Self>,
    ) {
    }
}

delegate_compositor!(Application);
delegate_subcompositor!(Application);
delegate_output!(Application);
delegate_shm!(Application);
delegate_seat!(Application);
delegate_keyboard!(Application);
delegate_pointer!(Application);
delegate_layer!(Application);
delegate_xdg_shell!(Application);
delegate_xdg_window!(Application);
delegate_xdg_popup!(Application);
delegate_registry!(Application);
delegate_simple!(Application, WpViewporter, 1);

// ----------------------------------------------------------------
// Request frame helper
// ----------------------------------------------------------------
// pub trait RequestFrame {
//     fn request_frame(&self, qh: &QueueHandle<Application>);
// }

// impl RequestFrame for LayerSurface {
//     fn request_frame(&self, qh: &QueueHandle<Application>) {
//         let wl_surface = self.wl_surface();
//         wl_surface.frame(qh, wl_surface.clone());
//         wl_surface.commit();
//     }
// }

// impl RequestFrame for Window {
//     fn request_frame(&self, qh: &QueueHandle<Application>) {
//         let wl_surface = self.wl_surface();
//         wl_surface.frame(qh, wl_surface.clone());
//         wl_surface.commit();
//     }
// }

// impl RequestFrame for Popup {
//     fn request_frame(&self, qh: &QueueHandle<Application>) {
//         let wl_surface = self.wl_surface();
//         wl_surface.frame(qh, wl_surface.clone());
//         wl_surface.commit();
//     }
// }

// impl RequestFrame for WlSurface {
//     fn request_frame(&self, qh: &QueueHandle<Application>) {
//         self.frame(qh, self.clone());
//         self.commit();
//     }
// }