rust_widgets 2.0.0

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 60+ widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Wayland backend platform implementation.
//!
//! This module implements the `Platform` trait for the Wayland backend.
//!
//! # BLUE15: the host supplies a window and a drawing surface, not controls
//!
//! This backend used to answer every `create_<control>` override by inserting a
//! per-kind `WaylandHandleKind` record — and, where the protocol allowed it, by
//! building a compositor object to go with it. Under the self-drawn strategy that
//! is the duplication BLUE15 removes: the library paints every `WidgetKind`, and
//! the host owes the widget layer a **window** and a **drawing surface** (rules
//! #55/#56). Those overrides never produced a real control that the library could
//! not paint itself, and `xdg_shell` has no vocabulary for buttons, labels or
//! dialogs, so the control creators and the per-kind handle state that existed
//! only to serve them are gone (rule #59: delete means delete).
//!
//! What survives is the platform-facing part the library cannot replace:
//!
//! - [`Platform::create_window`], including the native `xdg_toplevel` path
//!   (`wl_surface` → `xdg_surface` → `xdg_toplevel`) and the connection-wide
//!   session it keeps alive for event dispatch.
//! - The runtime lifecycle (`init`/`run`/`quit`), the fd-based event loop and
//!   [`create_event_loop_pump`].
//! - Global discovery and scale handling: `wl_compositor`, `xdg_wm_base` and the
//!   `wl_output` scale event that feeds `dpi_scale_factor()`.
//! - The protocol dispatch implementations the compositor requires (registry
//!   globals, surface enter/leave, `xdg_wm_base` ping/pong, `xdg_surface`
//!   configure ack, `xdg_toplevel` configure/close).
//! - The injectable menu **data model** and the widget-trigger queue. Neither is
//!   control construction — see the menu note at `attach_menu_bar_to_window`.
//!
//! Per-widget state is still recorded in `BackendState<WaylandHandleKind>` for
//! windows, so the ordinary state operations (text, geometry, visibility, IME,
//! accessibility, clipboard, drag and drop) remain meaningful.
//!
//! ## Menu semantics (Wayland)
//!
//! Wayland defines no menu protocol: `xdg_shell` covers toplevels and popups only.
//! `MenuBar`/`Menu`/`MenuItem` are therefore an in-process data model with
//! kind-constrained parents, textual payload, and injectable trigger events — the
//! same shape of capability the iOS backend keeps (see
//! `platform/ios/platform_impl.rs`). They must not be described as native menus,
//! and `capabilities().native_menu` reports `false` accordingly.

use crate::core::ObjectId;
use crate::core::PlatformFamily;
use crate::event::EventLoop;
use crate::platform::types::{
    DropEvent, Platform, PlatformCapabilities, WidgetTriggerEvent, WidgetTriggerKind,
};
use crate::platform::wayland::types::{WaylandHandleKind, WaylandPlatform};

#[cfg(all(feature = "wayland-native", target_os = "linux"))]
use wayland_client as wl_client;

#[cfg(all(feature = "wayland-native", target_os = "linux"))]
use wayland_protocols as wl_protocols;

// ---------------------------------------------------------------------------
// Platform trait implementation
// ---------------------------------------------------------------------------

impl Platform for WaylandPlatform {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn backend_name(&self) -> &'static str {
        "wayland"
    }

    fn family(&self) -> PlatformFamily {
        PlatformFamily::Desktop
    }

    /// Reads `MemTotal` from `/proc/meminfo` via [`os_probes`].
    fn total_memory_mb(&self) -> Option<u64> {
        crate::platform::os_probes::total_memory_mb()
    }

    /// Reports whether any battery in `/sys/class/power_supply` is discharging.
    fn is_on_battery(&self) -> bool {
        crate::platform::os_probes::is_on_battery()
    }

    /// Samples RSS over VmSize for this process from `/proc/self/status`.
    fn process_memory_utilization(&self) -> Option<f32> {
        crate::platform::os_probes::process_memory_utilization()
    }

    /// Estimates CPU load as thread count over twice the available cores.
    fn process_cpu_utilization(&self) -> Option<f32> {
        crate::platform::os_probes::process_cpu_utilization()
    }

    /// Submits the job to the unix print spooler via [`os_probes`].
    fn spawn_print_job(&self, job_file: &std::path::Path) -> Result<(), String> {
        crate::platform::os_probes::spawn_print_job(job_file)
    }

    /// Wayland sessions on Linux use CUPS. The `lp`/`lpr` clients are the only
    /// thing consulted — no compositor capability is involved.
    fn has_print_support(&self) -> bool {
        crate::platform::types::unix_print_clients_available()
    }

    fn capabilities(&self) -> PlatformCapabilities {
        PlatformCapabilities {
            dpi_scaling: true,
            ime: true,
            accessibility: true,
            // Wayland has no menu protocol, so the menu tree this backend keeps is
            // in-process data the host renders and feeds back as injected triggers.
            // Advertising a native menu would be false.
            native_menu: false,
            typed_widget_trigger: true,
        }
    }

    fn dpi_scale_factor(&self) -> f32 {
        // Attempt to detect DPI from environment when wayland-client is not wired.
        // Check common environment variables set by Wayland compositors.
        if let Ok(scale_str) = std::env::var("GDK_SCALE") {
            if let Ok(scale) = scale_str.parse::<f32>() {
                if scale > 0.0 {
                    return scale;
                }
            }
        }
        if let Ok(scale_str) = std::env::var("QT_SCALE_FACTOR") {
            if let Ok(scale) = scale_str.parse::<f32>() {
                if scale > 0.0 {
                    return scale;
                }
            }
        }
        if let Ok(scale_str) = std::env::var("RUST_WIDGETS_DPI_SCALE") {
            if let Ok(scale) = scale_str.parse::<f32>() {
                if scale > 0.0 {
                    return scale;
                }
            }
        }
        // Fallback: assume 96 DPI (1.0 scale factor).
        // When wayland-native feature is active, check the native session
        // for wl_output scale factor obtained from the compositor.
        #[cfg(all(feature = "wayland-native", target_os = "linux"))]
        {
            if let Ok(guard) = self.native_session.lock() {
                if let Some(ref session) = *guard {
                    let scale = session.state.dpi_scale;
                    if scale > 0.0 {
                        return scale;
                    }
                }
            }
        }
        1.0
    }

    // -----------------------------------------------------------------------
    // Initialization / lifecycle
    // -----------------------------------------------------------------------

    fn init(&self) {
        self.runtime.initialized.store(true, std::sync::atomic::Ordering::SeqCst);
        log::info!("[wayland] Platform initialized (state-only backend).");
    }

    fn run(&self) {
        self.runtime.running.store(true, std::sync::atomic::Ordering::SeqCst);
        // Check environment to provide diagnostics about Wayland session state.
        let wayland_display =
            std::env::var("WAYLAND_DISPLAY").unwrap_or_else(|_| String::from("wayland-0"));
        let xdg_session =
            std::env::var("XDG_SESSION_TYPE").unwrap_or_else(|_| String::from("unknown"));
        log::info!(
            "[wayland] Platform running: XDG_SESSION_TYPE={}, WAYLAND_DISPLAY={}",
            xdg_session,
            wayland_display
        );

        // Start EventLoop with native pump for Wayland dispatch.
        // The EventLoop runs in a background thread and calls the pump
        // on each iteration to dispatch pending native Wayland events.
        // Meanwhile, this thread blocks waiting for the quit signal.
        let mut event_loop = EventLoop::new();
        #[cfg(all(feature = "wayland-native", not(alloc_frugal), target_os = "linux"))]
        if let Some(pump) = create_event_loop_pump() {
            event_loop.set_native_pump(pump);
        }
        event_loop.start();

        #[cfg(all(feature = "wayland-native", not(alloc_frugal), target_os = "linux"))]
        {
            self.run_native_event_loop();
        }

        #[cfg(not(all(feature = "wayland-native", not(alloc_frugal), target_os = "linux")))]
        while self.runtime.running.load(std::sync::atomic::Ordering::SeqCst) {
            std::thread::sleep(std::time::Duration::from_millis(16));
        }
    }

    fn quit(&self) {
        self.runtime.running.store(false, std::sync::atomic::Ordering::SeqCst);
        log::info!("[wayland] Platform quit.");
    }

    /// Release every registry entry the backend holds for `widget_id`.
    ///
    /// Beyond the authoritative `BackendState` record, the Wayland backend keeps
    /// per-widget entries in the menu bookkeeping (`menus`: the attachment map,
    /// the menu tree and the queued triggers). All must be purged, otherwise a UI
    /// rebuilt in a create/destroy loop would leak one entry per discarded widget.
    /// Every lock is scoped to its own statement so no two guards are ever held at
    /// the same time.
    ///
    /// The native session (`native_session`) is a single connection-wide object
    /// shared by every window rather than a per-widget registry, so there is
    /// nothing per-widget to release there and no protocol request is issued.
    fn destroy_widget(&self, widget_id: ObjectId) -> bool {
        if let Ok(mut menus) = self.menus.lock() {
            // The widget may be an attached menu bar (keyed by window id) or a
            // window owning one, so both directions are cleared.
            menus.attached_menu_bar.remove(&widget_id);
            menus.attached_menu_bar.retain(|_, bar| *bar != widget_id);
            // The widget may be a container in the menu tree: drop both the
            // children it owned and the child entry under its own parent.
            menus.menu_children.remove(&widget_id);
            for children in menus.menu_children.values_mut() {
                children.retain(|child| *child != widget_id);
            }
            // Drop queued triggers that reference a widget that no longer exists.
            menus.pending_menu_events.retain(|queued| *queued != widget_id);
            menus.pending_widget_events.retain(|event| event.widget_id != widget_id);
        } else {
            log::error!("[wayland] destroy_widget: menu mutex poisoned");
        }

        // The state record is the authority on whether the widget existed.
        self.state.destroy_widget(widget_id)
    }

    // -----------------------------------------------------------------------
    // Window
    // -----------------------------------------------------------------------

    fn create_window(&self, title: &str, x: i32, y: i32, width: u32, height: u32) -> ObjectId {
        // Try native Wayland surface creation when the wayland-native feature is active
        #[cfg(all(feature = "wayland-native", target_os = "linux"))]
        if let Some(id) = self.try_create_native_window(title, x, y, width, height) {
            return id;
        }
        // Fallback: state-only window
        self.insert_widget(WaylandHandleKind::Window, title, x, y, width, height)
    }

    // -----------------------------------------------------------------------
    // Menu system
    // -----------------------------------------------------------------------

    /// Attach a menu bar to a window.
    ///
    /// Wayland has no menu protocol at all: `xdg_shell` models toplevels and
    /// popups, and neither carries menu chrome. A `MenuBar`/`Menu`/`MenuItem` here
    /// is therefore an **in-process data model**, not a control the compositor
    /// builds — which is why this method survives the BLUE15 control-construction
    /// removal while every `create_<control>` override around it does not.
    ///
    /// This is an injectable event capability: the attachment only records which
    /// menu bar belongs to which window so the host can render the menu itself and
    /// feed activations back through [`Platform::inject_menu_trigger`]. It creates
    /// nothing in the compositor. A menu bar can only be attached in-process, so
    /// `capabilities().native_menu` is advertised as `false`; claiming otherwise
    /// would be the exact lie BLUE15 removes.
    fn attach_menu_bar_to_window(&self, window: ObjectId, menu_bar: ObjectId) -> bool {
        // Both the window and the menu bar must be live widgets of the right
        // kind, otherwise the attachment map would hold an invalid pair.
        if !matches!(self.state.kind_of(window), Some(WaylandHandleKind::Window)) {
            return false;
        }
        if !matches!(self.state.kind_of(menu_bar), Some(WaylandHandleKind::MenuBar)) {
            return false;
        }
        if let Ok(mut menus) = self.menus.lock() {
            menus.attached_menu_bar.insert(window, menu_bar);
            true
        } else {
            log::error!("[wayland] attach_menu_bar_to_window: mutex poisoned");
            false
        }
    }

    fn menu_add_item(&self, parent_menu: ObjectId, text: &str, shortcut: Option<&str>) -> ObjectId {
        if !matches!(self.state.kind_of(parent_menu), Some(WaylandHandleKind::Menu)) {
            return 0;
        }
        let display = if let Some(shortcut) = shortcut {
            format!("{}\t{}", text, shortcut)
        } else {
            text.to_string()
        };
        // The item text carries the shortcut in its display form. No accelerator is
        // registered with the compositor: Wayland has no menu protocol, so the
        // library renders the text and the host routes activations back in.
        let id = self.insert_widget(WaylandHandleKind::MenuItem, &display, 0, 0, 0, 0);
        if let Ok(mut menus) = self.menus.lock() {
            menus.menu_children.entry(parent_menu).or_default().push(id);
        }
        id
    }

    fn poll_menu_triggered(&self) -> Option<ObjectId> {
        if let Ok(mut menus) = self.menus.lock() {
            menus.pending_menu_events.pop_front()
        } else {
            log::error!("[wayland] poll_menu_triggered: mutex poisoned");
            None
        }
    }

    fn inject_menu_trigger(&self, menu_item_id: ObjectId) -> bool {
        // Only a menu item may produce a menu trigger.
        if !matches!(self.state.kind_of(menu_item_id), Some(WaylandHandleKind::MenuItem)) {
            return false;
        }
        if let Ok(mut menus) = self.menus.lock() {
            menus.pending_menu_events.push_back(menu_item_id);
            true
        } else {
            log::error!("[wayland] inject_menu_trigger: mutex poisoned");
            false
        }
    }

    // -----------------------------------------------------------------------
    // Widget trigger events
    // -----------------------------------------------------------------------

    fn poll_widget_triggered(&self) -> Option<ObjectId> {
        if let Ok(mut menus) = self.menus.lock() {
            menus.pending_widget_events.pop_front().map(|e| e.widget_id)
        } else {
            log::error!("[wayland] poll_widget_triggered: mutex poisoned");
            None
        }
    }

    fn poll_widget_trigger_event(&self) -> Option<WidgetTriggerEvent> {
        if let Ok(mut menus) = self.menus.lock() {
            menus.pending_widget_events.pop_front()
        } else {
            log::error!("[wayland] poll_widget_trigger_event: mutex poisoned");
            None
        }
    }

    fn inject_widget_trigger_event(&self, widget_id: ObjectId, kind: WidgetTriggerKind) -> bool {
        if !self.state.contains_widget(widget_id) {
            return false;
        }
        if let Ok(mut menus) = self.menus.lock() {
            menus.pending_widget_events.push_back(WidgetTriggerEvent { widget_id, kind });
            true
        } else {
            log::error!("[wayland] inject_widget_trigger_event: mutex poisoned");
            false
        }
    }

    // -----------------------------------------------------------------------
    // Widget lifecycle operations
    // -----------------------------------------------------------------------

    fn show_widget(&self, widget_id: ObjectId) {
        self.state.set_visible(widget_id, true);
    }

    fn hide_widget(&self, widget_id: ObjectId) {
        self.state.set_visible(widget_id, false);
    }

    fn set_widget_geometry(&self, widget_id: ObjectId, x: i32, y: i32, width: u32, height: u32) {
        self.state.set_geometry(widget_id, x, y, width, height);
    }

    fn set_widget_text(&self, widget_id: ObjectId, text: &str) {
        self.state.set_text(widget_id, text);
    }

    fn get_widget_text(&self, widget_id: ObjectId) -> String {
        self.state.text(widget_id)
    }

    fn set_widget_enabled(&self, widget_id: ObjectId, enabled: bool) {
        self.state.set_enabled(widget_id, enabled);
    }

    fn is_widget_enabled(&self, widget_id: ObjectId) -> bool {
        self.state.enabled(widget_id)
    }

    fn set_widget_visible(&self, widget_id: ObjectId, visible: bool) {
        self.state.set_visible(widget_id, visible);
    }

    fn is_widget_visible(&self, widget_id: ObjectId) -> bool {
        self.state.visible(widget_id)
    }

    // -----------------------------------------------------------------------
    // IME / Accessibility
    // -----------------------------------------------------------------------

    fn set_widget_ime_enabled(&self, widget_id: ObjectId, enabled: bool) -> bool {
        self.state.set_ime_enabled(widget_id, enabled)
    }

    fn is_widget_ime_enabled(&self, widget_id: ObjectId) -> bool {
        self.state.ime_enabled(widget_id)
    }

    fn set_widget_accessibility_name(&self, widget_id: ObjectId, name: &str) -> bool {
        self.state.set_accessibility_name(widget_id, name)
    }

    fn get_widget_accessibility_name(&self, widget_id: ObjectId) -> String {
        self.state.accessibility_name(widget_id)
    }

    // -----------------------------------------------------------------------
    // Clipboard
    // -----------------------------------------------------------------------

    fn set_clipboard_text(&self, text: &str) -> bool {
        self.state.set_clipboard_text(text)
    }

    fn get_clipboard_text(&self) -> String {
        self.state.clipboard_text()
    }

    // -----------------------------------------------------------------------
    // Drag and drop
    // -----------------------------------------------------------------------

    fn begin_drag(&self, source_widget_id: ObjectId, mime: &str, payload: &[u8]) -> bool {
        self.state.begin_drag(source_widget_id, mime, payload)
    }

    fn poll_drop_event(&self) -> Option<DropEvent> {
        self.state.pop_drop_event()
    }

    fn inject_drop_event(&self, event: DropEvent) -> bool {
        self.state.inject_drop_event(event)
    }
}

// ---------------------------------------------------------------------------
// Native Wayland window creation (gated by "wayland-native" feature)
// ---------------------------------------------------------------------------

#[cfg(all(feature = "wayland-native", target_os = "linux"))]
impl WaylandPlatform {
    /// Run the real Wayland event loop.
    ///
    /// Blocks on the connection's socket via `prepare_read()` → `poll()` so the
    /// thread sleeps until the compositor actually sends something, instead of
    /// busy-waiting. A `poll` timeout bounds how long the loop can sit idle
    /// before re-checking the `running` flag, so `quit()` is honoured promptly
    /// even with no incoming events.
    ///
    /// Falls back to the timed polling loop when no Wayland session exists
    /// (headless CI), which keeps `run()`/`quit()` semantics identical.
    #[cfg(all(feature = "wayland-native", not(alloc_frugal), target_os = "linux"))]
    fn run_native_event_loop(&self) {
        use std::os::fd::AsRawFd;

        // Idle timeout: bounds quit latency when the compositor is silent.
        const IDLE_TIMEOUT_MS: i32 = 50;

        log::info!("[wayland] Entering native fd-based event loop");
        loop {
            if !self.runtime.running.load(std::sync::atomic::Ordering::SeqCst) {
                break;
            }

            let mut guard = self.native_session.lock().unwrap();
            let Some(session) = guard.as_mut() else {
                // No native session yet (no window created): stay responsive to
                // quit without spinning.
                drop(guard);
                std::thread::sleep(std::time::Duration::from_millis(16));
                continue;
            };

            // Flush any queued requests before waiting for the reply.
            if let Err(e) = session.event_queue.flush() {
                log::warn!("[wayland] flush failed: {e}");
            }

            // Block until either the socket is readable or the timeout expires.
            match session.event_queue.prepare_read() {
                Some(read_guard) => {
                    let fd = read_guard.connection_fd().as_raw_fd();
                    let mut pollfd = libc::pollfd { fd, events: libc::POLLIN, revents: 0 };
                    let rc = unsafe { libc::poll(&mut pollfd, 1, IDLE_TIMEOUT_MS) };
                    if rc > 0 {
                        // Data available: read it, then dispatch to handlers.
                        if let Err(e) = read_guard.read() {
                            log::warn!("[wayland] read failed: {e}");
                        }
                        if let Err(e) = session.event_queue.dispatch_pending(&mut session.state) {
                            log::warn!("[wayland] dispatch failed: {e}");
                        }
                    } else if rc < 0 {
                        let err = std::io::Error::last_os_error();
                        log::warn!("[wayland] poll failed: {err}");
                        std::thread::sleep(std::time::Duration::from_millis(16));
                    }
                    // rc == 0: idle timeout, loop to re-check `running`.
                }
                None => {
                    // Events are already buffered; drain them without blocking.
                    let _ = session.event_queue.dispatch_pending(&mut session.state);
                }
            }
        }
        log::info!("[wayland] Native event loop exited");
    }

    /// Dispatch pending native Wayland events.
    ///
    /// Intended to be called from an `EventLoop` native pump callback
    /// on each iteration so that Wayland protocol events are dispatched
    /// without a separate blocking `run()` loop.
    #[cfg(not(alloc_frugal))]
    pub(crate) fn dispatch_native_events(&self) {
        let mut guard = self.native_session.lock().unwrap();
        if let Some(ref mut session) = *guard {
            let _ = session.event_queue.dispatch_pending(&mut session.state);
        }
    }

    /// Attempt to create a native Wayland xdg_toplevel for this window.
    /// Returns `Some(id)` on success, or `None` to fall back to state-only.
    fn try_create_native_window(
        &self,
        title: &str,
        x: i32,
        y: i32,
        width: u32,
        height: u32,
    ) -> Option<ObjectId> {
        // Helper: connect to Wayland display and discover globals.
        // Returns `Some(WaylandSession)` on success or `None` on failure.
        fn connect_wayland() -> Option<WaylandSession> {
            let conn = wl_client::Connection::connect_to_env()
                .inspect_err(|e| {
                    log::error!("[wayland] Failed to connect to Wayland display: {}", e)
                })
                .ok()?;
            let display = conn.display();
            let mut event_queue = conn.new_event_queue();
            let qh = event_queue.handle();
            let _registry = display.get_registry(&qh, ());

            let mut state = WaylandSessionState {
                compositor: None,
                xdg_wm_base: None,
                wl_output: None,
                dpi_scale: 1.0,
            };
            event_queue
                .roundtrip(&mut state)
                .inspect_err(|e| log::error!("[wayland] Registry roundtrip failed: {}", e))
                .ok()?;

            if state.compositor.is_none() {
                log::error!("[wayland] wl_compositor global not available");
                return None;
            }
            if state.xdg_wm_base.is_none() {
                log::error!("[wayland] xdg_wm_base global not available");
                return None;
            }

            log::info!("[wayland] Connected to display; compositor and xdg_wm_base bound.");
            Some(WaylandSession { conn, event_queue, state })
        }

        // Obtain or create the persistent Wayland session.
        let mut guard = self.native_session.lock().unwrap();
        if guard.is_none() {
            *guard = connect_wayland();
        }
        let session = guard.as_mut()?;

        // 5. Create wl_surface, xdg_surface, and xdg_toplevel
        let compositor = session.state.compositor.as_ref()?;
        let xdg_wm_base = session.state.xdg_wm_base.as_ref()?;
        let qh = session.event_queue.handle();

        let surface = compositor.create_surface(&qh, ());
        let xdg_surface = xdg_wm_base.get_xdg_surface(&surface, &qh, ());
        let toplevel = xdg_surface.get_toplevel(&qh, ());

        // 6. Set window properties
        toplevel.set_title(title.to_string());
        toplevel.set_app_id("rust_widgets".to_string());
        if width > 0 && height > 0 {
            toplevel.set_min_size(width as i32, height as i32);
        }

        // 7. Commit the surface to make the compositor aware of it
        surface.commit();

        // 8. Roundtrip to process the xdg_surface.configure event
        session.event_queue.roundtrip(&mut session.state).ok()?;

        log::info!("[wayland] Created xdg_toplevel '{}' ({}x{})", title, width, height);

        let id = self.insert_widget(WaylandHandleKind::Window, title, x, y, width, height);
        log::info!("[wayland] Window {} registered with state backend", id);

        Some(id)
    }
}

// ---------------------------------------------------------------------------
// Wayland session state & dispatch implementations
// ---------------------------------------------------------------------------

/// Dispatch state for the Wayland session.
/// Holds the global proxies obtained from the registry.
#[cfg(all(feature = "wayland-native", target_os = "linux"))]
pub(crate) struct WaylandSessionState {
    pub(crate) compositor: Option<wl_client::protocol::wl_compositor::WlCompositor>,
    pub(crate) xdg_wm_base: Option<wl_protocols::xdg::shell::client::xdg_wm_base::XdgWmBase>,
    /// wl_output proxy for DPI scale detection.
    pub(crate) wl_output: Option<wl_client::protocol::wl_output::WlOutput>,
    /// Logical-to-physical scale reported by the compositor. It scales the
    /// drawing surface and so the input-coordinate mapping, and is set by the
    /// `wl_output::scale` event; it stays 1.0 until then.
    pub(crate) dpi_scale: f32,
}

/// A persistent Wayland session containing the connection, event queue,
/// and proxy state. Stored inside `WaylandPlatform.native_session`.
///
/// This is one object per connection, shared by every window — not a per-widget
/// registry — so no per-widget protocol object is kept here. Widgets other than the
/// window are painted by the library, so the host has nothing to create for them.
#[cfg(all(feature = "wayland-native", target_os = "linux"))]
pub(crate) struct WaylandSession {
    /// The Wayland connection. Must stay alive while `event_queue` is in use.
    #[allow(dead_code)]
    pub(crate) conn: wl_client::Connection,
    pub(crate) event_queue: wl_client::EventQueue<WaylandSessionState>,
    pub(crate) state: WaylandSessionState,
}

// ---------------------------------------------------------------------------
// EventLoop native pump integration
// ---------------------------------------------------------------------------

/// Create a native platform event pump for the Wayland backend.
///
/// Returns a closure suitable for `EventLoop::set_native_pump()`.
/// When called, it looks up the global `WaylandPlatform` singleton and
/// dispatches pending Wayland events through `dispatch_pending()`.
///
/// Returns `None` if the active platform is not Wayland.
#[cfg(all(feature = "wayland-native", not(alloc_frugal), target_os = "linux"))]
pub fn create_event_loop_pump() -> Option<Box<dyn Fn() + Send + Sync>> {
    let platform = crate::platform::runtime::get_platform();
    let wayland = platform.as_any().downcast_ref::<WaylandPlatform>()?;
    Some(Box::new(move || {
        wayland.dispatch_native_events();
    }))
}

// --- Registry global discovery ---

#[cfg(all(feature = "wayland-native", target_os = "linux"))]
impl wl_client::Dispatch<wl_client::protocol::wl_registry::WlRegistry, ()> for WaylandSessionState {
    fn event(
        state: &mut Self,
        registry: &wl_client::protocol::wl_registry::WlRegistry,
        event: wl_client::protocol::wl_registry::Event,
        _data: &(),
        _conn: &wl_client::Connection,
        _qh: &wl_client::QueueHandle<WaylandSessionState>,
    ) {
        use wl_client::protocol::wl_registry::Event;
        if let Event::Global { name, interface, version } = event {
            log::debug!(
                "[wayland] Registry global: interface='{}', version={}",
                interface,
                version
            );
            match interface.as_str() {
                "wl_compositor" => {
                    let comp = registry
                        .bind::<wl_client::protocol::wl_compositor::WlCompositor, _, _>(
                            name,
                            version.min(4),
                            _qh,
                            (),
                        );
                    state.compositor = Some(comp);
                    log::info!("[wayland] Bound wl_compositor (v{})", version);
                }
                "xdg_wm_base" => {
                    let xdg = registry
                        .bind::<wl_protocols::xdg::shell::client::xdg_wm_base::XdgWmBase, _, _>(
                            name,
                            version.min(6),
                            _qh,
                            (),
                        );
                    state.xdg_wm_base = Some(xdg);
                    log::info!("[wayland] Bound xdg_wm_base (v{})", version);
                }
                "wl_output" => {
                    let output = registry.bind::<wl_client::protocol::wl_output::WlOutput, _, _>(
                        name,
                        version.min(4),
                        _qh,
                        (),
                    );
                    state.wl_output = Some(output);
                    log::info!("[wayland] Bound wl_output (v{})", version);
                }
                _ => { /* Other globals need no special handling */ }
            }
        }
    }
}

// --- wl_compositor (no events) ---

#[cfg(all(feature = "wayland-native", target_os = "linux"))]
impl wl_client::Dispatch<wl_client::protocol::wl_compositor::WlCompositor, ()>
    for WaylandSessionState
{
    fn event(
        _state: &mut Self,
        _proxy: &wl_client::protocol::wl_compositor::WlCompositor,
        _event: wl_client::protocol::wl_compositor::Event,
        _data: &(),
        _conn: &wl_client::Connection,
        _qh: &wl_client::QueueHandle<WaylandSessionState>,
    ) {
        // wl_compositor has no server-to-client events.
    }
}

// --- wl_output (handle scale events for DPI detection) ---

#[cfg(all(feature = "wayland-native", target_os = "linux"))]
impl wl_client::Dispatch<wl_client::protocol::wl_output::WlOutput, ()> for WaylandSessionState {
    fn event(
        state: &mut Self,
        _proxy: &wl_client::protocol::wl_output::WlOutput,
        event: wl_client::protocol::wl_output::Event,
        _data: &(),
        _conn: &wl_client::Connection,
        _qh: &wl_client::QueueHandle<WaylandSessionState>,
    ) {
        use wl_client::protocol::wl_output::Event;
        match event {
            Event::Scale { factor } => {
                state.dpi_scale = factor as f32;
                log::info!("[wayland] wl_output scale factor: {} (DPI: {})", factor, factor * 96);
            }
            Event::Done => {
                log::trace!("[wayland] wl_output done");
            }
            Event::Geometry { .. }
            | Event::Mode { .. }
            | Event::Name { .. }
            | Event::Description { .. } => {
                log::trace!("[wayland] wl_output event: {:?}", event);
            }
            _ => {
                log::trace!("[wayland] wl_output unhandled event: {:?}", event);
            }
        }
    }
}

// --- wl_surface (surface enter/leave events) ---

#[cfg(all(feature = "wayland-native", target_os = "linux"))]
impl wl_client::Dispatch<wl_client::protocol::wl_surface::WlSurface, ()> for WaylandSessionState {
    fn event(
        _state: &mut Self,
        _proxy: &wl_client::protocol::wl_surface::WlSurface,
        _event: wl_client::protocol::wl_surface::Event,
        _data: &(),
        _conn: &wl_client::Connection,
        _qh: &wl_client::QueueHandle<WaylandSessionState>,
    ) {
        // wl_surface events (enter/leave/frame/etc.) are logged but not acted upon:
        // the compositor side of a surface needs no bookkeeping here.
        log::trace!("[wayland] wl_surface event: {:?}", _event);
    }
}

// --- xdg_wm_base (handle ping events) ---

#[cfg(all(feature = "wayland-native", target_os = "linux"))]
impl wl_client::Dispatch<wl_protocols::xdg::shell::client::xdg_wm_base::XdgWmBase, ()>
    for WaylandSessionState
{
    fn event(
        _state: &mut Self,
        proxy: &wl_protocols::xdg::shell::client::xdg_wm_base::XdgWmBase,
        event: <wl_protocols::xdg::shell::client::xdg_wm_base::XdgWmBase as wl_client::Proxy>::Event,
        _data: &(),
        _conn: &wl_client::Connection,
        _qh: &wl_client::QueueHandle<WaylandSessionState>,
    ) {
        use wl_protocols::xdg::shell::client::xdg_wm_base::Event;
        if let Event::Ping { serial } = event {
            proxy.pong(serial);
            log::trace!("[wayland] xdg_wm_base ping/pong (serial={})", serial);
        }
    }
}

// --- xdg_surface (acknowledge configure events) ---

#[cfg(all(feature = "wayland-native", target_os = "linux"))]
impl wl_client::Dispatch<wl_protocols::xdg::shell::client::xdg_surface::XdgSurface, ()>
    for WaylandSessionState
{
    fn event(
        _state: &mut Self,
        proxy: &wl_protocols::xdg::shell::client::xdg_surface::XdgSurface,
        event: <wl_protocols::xdg::shell::client::xdg_surface::XdgSurface as wl_client::Proxy>::Event,
        _data: &(),
        _conn: &wl_client::Connection,
        _qh: &wl_client::QueueHandle<WaylandSessionState>,
    ) {
        use wl_protocols::xdg::shell::client::xdg_surface::Event;
        if let Event::Configure { serial } = event {
            proxy.ack_configure(serial);
            log::trace!("[wayland] xdg_surface configure ack (serial={})", serial);
        }
    }
}

// --- xdg_toplevel (handle configure / close) ---

#[cfg(all(feature = "wayland-native", target_os = "linux"))]
impl wl_client::Dispatch<wl_protocols::xdg::shell::client::xdg_toplevel::XdgToplevel, ()>
    for WaylandSessionState
{
    fn event(
        _state: &mut Self,
        _proxy: &wl_protocols::xdg::shell::client::xdg_toplevel::XdgToplevel,
        event: <wl_protocols::xdg::shell::client::xdg_toplevel::XdgToplevel as wl_client::Proxy>::Event,
        _data: &(),
        _conn: &wl_client::Connection,
        _qh: &wl_client::QueueHandle<WaylandSessionState>,
    ) {
        use wl_protocols::xdg::shell::client::xdg_toplevel::Event;
        match event {
            Event::Configure { width, height, states } => {
                log::trace!(
                    "[wayland] xdg_toplevel configure: {}x{}, states={:?}",
                    width,
                    height,
                    states
                );
            }
            Event::Close => {
                log::info!("[wayland] xdg_toplevel close requested");
            }
            Event::ConfigureBounds { .. } | Event::WmCapabilities { .. } => {
                log::trace!("[wayland] xdg_toplevel event: {:?}", event);
            }
            _ => {
                log::trace!("[wayland] xdg_toplevel unhandled event: {:?}", event);
            }
        }
    }
}