spell-framework 1.0.6

Make desktop widgets by the Mystic Arts of Spell
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
use crate::{
    PopupSlint, SpellAssociatedNew,
    configure::{Dimension, HomeHandle, PopupConf, WindowConf, set_up_tracing},
    slint_adapter::{ADAPTERS, SpellLayerShell, SpellSkiaWinAdapter},
    wayland_adapter::{
        common::PointerState,
        fractional_scaling::{FractionalScaleState, delegate_fractional_scale},
        viewporter::{Viewport, ViewporterState, delegate_viewporter},
        window,
    },
};
use i_slint_core::items::MouseCursor;
use smithay_client_toolkit::{
    compositor::{CompositorState, Region},
    delegate_compositor, delegate_keyboard, delegate_layer, delegate_output, delegate_pointer,
    delegate_registry, delegate_seat, delegate_shm, delegate_touch, delegate_xdg_popup,
    delegate_xdg_shell,
    output::OutputState,
    reexports::{
        calloop::{self, EventLoop, LoopHandle},
        calloop_wayland_source::WaylandSource,
        client::{
            Connection, QueueHandle,
            globals::registry_queue_init,
            protocol::{
                wl_keyboard::WlKeyboard,
                wl_output::{self, WlOutput},
                wl_shm,
                wl_surface::WlSurface,
                wl_touch::WlTouch,
            },
        },
    },
    registry::RegistryState,
    seat::{SeatState, pointer::cursor_shape::CursorShapeManager},
    shell::{
        WaylandSurface,
        wlr_layer::{KeyboardInteractivity, LayerShell, LayerSurface},
        xdg::XdgShell,
    },
    shm::{
        Shm,
        slot::{Buffer, SlotPool},
    },
};
use std::{
    cell::{Cell, RefCell},
    collections::HashMap,
    os::unix::net::UnixListener,
    rc::Rc,
    sync::{Once, OnceLock, RwLock},
};
use tracing::{Level, info, span, trace, warn};

mod input;
mod internal;
mod popup;
mod wayland;
pub use popup::SpellXDGPopup;

#[allow(clippy::type_complexity)]
static AVAILABLE_MONITORS: OnceLock<RwLock<HashMap<String, (wl_output::WlOutput, i32, i32)>>> =
    OnceLock::new();
static SET_SLINT_PLATFORM: Once = Once::new();

#[derive(Debug)]
struct States {
    registry_state: RegistryState,
    seat_state: SeatState,
    output_state: OutputState,
    compositor_state: CompositorState,
    pointer_state: PointerState,
    keyboard_state: Option<WlKeyboard>,
    touch_state: Option<WlTouch>,
    shm: Shm,
    viewporter_state: ViewporterState,
    fractional_scale_state: FractionalScaleState,
}

/// `SpellWin` is the main type for implementing widgets, it covers various properties
/// and trait implementation, thus providing various features.
pub struct SpellWin {
    adapter: Option<Rc<SpellSkiaWinAdapter>>,
    loop_handle: LoopHandle<'static, SpellWin>,
    /// UnixListener storing remote instructions from CLI.
    pub ipc_handler: Option<UnixListener>,
    /// Name of widget's layer.
    pub layer_name: String,
    /// Span required for proper logging.
    pub span: span::Span,
    queue: QueueHandle<SpellWin>,
    buffer: Option<Buffer>,
    states: States,
    layer: Option<LayerSurface>,
    first_configure: Cell<bool>,
    natural_scroll: bool,
    is_hidden: Cell<bool>,
    config: WindowConf,
    input_region: Region,
    opaque_region: Region,
    viewport: Option<Viewport>,
    xdg_shell: XdgShell,
    popup_manager: window::popup::PopupManager,
    event_loop: Rc<RefCell<EventLoop<'static, SpellWin>>>,
}

impl std::fmt::Debug for SpellWin {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SpellWin")
            .field("adapter", &self.adapter)
            .field("first_configure", &self.first_configure)
            .field("is_hidden", &self.is_hidden)
            .field("config", &self.config)
            .finish()
    }
}

impl SpellWin {
    fn create_window(
        conn: &Connection,
        mut window_conf: WindowConf,
        layer_name: String,
        handle: HomeHandle,
    ) -> Self {
        let (globals, mut event_queue) = registry_queue_init(conn).unwrap();
        let qh: QueueHandle<SpellWin> = event_queue.handle();
        let compositor =
            CompositorState::bind(&globals, &qh).expect("wl_compositor is not available");
        let event_loop: EventLoop<'static, SpellWin> =
            EventLoop::try_new().expect("Failed to initialize the event loop!");
        let layer_shell = LayerShell::bind(&globals, &qh).expect("layer shell is not available");
        let shm = Shm::bind(&globals, &qh).expect("wl_shm is not available");
        let cursor_manager =
            CursorShapeManager::bind(&globals, &qh).expect("cursor shape is not available");
        let surface = compositor.create_surface(&qh);
        let viewporter_state =
            ViewporterState::bind(&globals, &qh).expect("Couldn't set viewporter");
        let fractional_scale_state: FractionalScaleState =
            FractionalScaleState::bind(&globals, &qh).expect("Fractional Scale couldn't be set");
        let xdg_shell = XdgShell::bind(&globals, &qh).expect("Couldn't bind xdg_shell");
        let pointer_state = PointerState {
            pointer: None,
            pointer_data: None,
            cursor_shape: cursor_manager,
            current_wayland_cursor: MouseCursor::Default,
            last_cursor_enter_serial: None,
        };
        let input_region = Region::new(&compositor).expect("Couldn't create region");
        let opaque_region = Region::new(&compositor).expect("Couldn't create opaque region");

        let mut win = SpellWin {
            adapter: None,
            loop_handle: event_loop.handle(),
            ipc_handler: None,
            queue: qh.clone(),
            buffer: None,
            states: States {
                registry_state: RegistryState::new(&globals),
                seat_state: SeatState::new(&globals, &qh),
                output_state: OutputState::new(&globals, &qh),
                compositor_state: compositor,
                pointer_state,
                keyboard_state: None,
                touch_state: None,
                shm,
                viewporter_state,
                fractional_scale_state,
            },
            layer: None,
            first_configure: Cell::new(true),
            natural_scroll: window_conf.natural_scroll,
            is_hidden: Cell::new(false),
            config: window_conf.clone(),
            layer_name: layer_name.clone(),
            input_region,
            opaque_region,
            viewport: None,
            xdg_shell,
            popup_manager: window::popup::PopupManager::new(),
            event_loop: Rc::new(RefCell::new(event_loop)),
            span: span!(Level::INFO, "widget", name = layer_name.as_str(),),
        };

        if AVAILABLE_MONITORS.get().is_none() {
            match SpellWin::get_available_monitors(&mut event_queue, &mut win) {
                Some(monitors) => {
                    let _ = AVAILABLE_MONITORS.get_or_init(|| RwLock::new(monitors));
                }
                None => warn!("Failed to get available monitors"),
            }
        }

        let mut output_info: Option<(wl_output::WlOutput, i32, i32)> =
            if let Some(name) = &window_conf.monitor_name {
                let output = AVAILABLE_MONITORS
                    .get()
                    .and_then(|monitors| monitors.read().ok())
                    .and_then(|monitors| monitors.get(name).cloned());
                if output.is_none() {
                    warn!("Monitor '{}' not found, using default monitor", name);
                }
                output
            } else {
                None
            };

        match window_conf.width {
            Dimension::Pixel(x) => window_conf.evaluated_width = x,
            Dimension::Full => {
                window_conf.evaluated_width = output_info
                    .as_ref()
                    .expect("Output info couldn't be retrieved")
                    .1 as u32
            }
            Dimension::Percentage(y) => {
                window_conf.evaluated_width = output_info
                    .as_mut()
                    .expect("Output info couldn't be retrieved")
                    .1 as u32
                    / y;
            }
        }

        match window_conf.height {
            Dimension::Pixel(x) => window_conf.evaluated_height = x,
            Dimension::Full => {
                window_conf.evaluated_height = output_info
                    .as_ref()
                    .expect("Output info couldn't be retrieved")
                    .1 as u32
            }
            Dimension::Percentage(y) => {
                window_conf.evaluated_height = output_info
                    .as_ref()
                    .expect("Output info couldn't be retrieved")
                    .1 as u32
                    / y;
            }
        }
        win.config = window_conf.clone();

        info!(
            "Evaluated width: {}, evaluated_height: {}",
            window_conf.evaluated_width, window_conf.evaluated_height
        );

        let mut pool = SlotPool::new(
            (window_conf.evaluated_width * window_conf.evaluated_height * 4) as usize,
            &win.states.shm,
        )
        .expect("Failed to create pool");
        win.input_region.add(
            0,
            0,
            window_conf.evaluated_width as i32,
            window_conf.evaluated_height as i32,
        );

        let stride = window_conf.evaluated_width as i32 * 4;
        let (way_pri_buffer, _) = pool
            .create_buffer(
                window_conf.evaluated_width as i32,
                window_conf.evaluated_height as i32,
                stride,
                wl_shm::Format::Argb8888,
            )
            .expect("Creating Buffer");

        let primary_slot = way_pri_buffer.slot();
        let adapter_value: Rc<SpellSkiaWinAdapter> = SpellSkiaWinAdapter::new(
            Rc::new(RefCell::new(pool)),
            RefCell::new(primary_slot),
            window_conf.evaluated_width,
            window_conf.evaluated_height,
        );
        // win.popup_manager.set_pool(pool_mut.clone());
        win.adapter = Some(adapter_value.clone());
        win.buffer = Some(way_pri_buffer);

        let (slint_event_sender, slint_event_receiver) =
            calloop::channel::channel::<Box<dyn FnOnce() + Send>>();

        ADAPTERS.with_borrow_mut(|v| v.push(adapter_value.clone()));
        SET_SLINT_PLATFORM.call_once(|| {
            trace!("Slint platform set");
            if let Err(err) =
                slint::platform::set_platform(Box::new(SpellLayerShell::new(slint_event_sender)))
            {
                warn!("Error setting slint platform: {err}");
            }
        });
        win.adapter = Some(adapter_value);
        let target_output: Option<&WlOutput> = output_info.as_ref().map(|(a, _, _)| a);
        let layer = layer_shell.create_layer_surface(
            &qh,
            surface,
            window_conf.layer_type,
            Some(layer_name.clone()),
            target_output,
        );

        win.layer = Some(layer);
        win.set_config_internal();

        if let Err(err) = event_queue.roundtrip(&mut win) {
            warn!("Received roundtrip error: {}", err);
        }
        let surface: &WlSurface = win.layer.as_ref().unwrap().wl_surface();

        // This needs to occur after layer creation so as to ensure that layer
        // used in window is not null during use to scale. Details in issue 34.
        let fractional_scale = win.states.fractional_scale_state.get_scale(surface, &qh);
        let viewport = win
            .states
            .viewporter_state
            .get_viewport(surface, &qh, fractional_scale);
        win.viewport = Some(viewport);

        win.layer.as_ref().unwrap().commit();
        win.set_event_sources(handle, slint_event_receiver);

        info!("Win: {} layer created successfully.", layer_name);

        WaylandSource::new(conn.clone(), event_queue)
            .insert(win.loop_handle.clone())
            .unwrap();
        win
    }

    /// Returns a handle of [`WinHandle`] to invoke wayland specific features.
    pub fn get_handler(&self) -> WinHandle {
        info!("Win: Handle provided.");
        WinHandle(self.loop_handle.clone())
    }

    /// This function is called to create a instance of window. This window is then
    /// finally called by [`cast_spell`](crate::cast_spell) event loop.
    ///
    /// # Panics
    ///
    /// This function needs to be called "before" initialising your slint window to avoid
    /// panicing of this function.
    pub fn invoke_spell(name: &str, window_conf: WindowConf) -> Self {
        let handle = set_up_tracing(name);
        let conn = Connection::connect_to_env().unwrap();
        SpellWin::create_window(&conn, window_conf.clone(), name.to_string(), handle)
    }

    /// Hides the layer (aka the widget) if it is visible in screen.
    pub fn hide(&self) {
        if !self.is_hidden.replace(true) {
            info!("Win: Hiding window");
            self.layer.as_ref().unwrap().wl_surface().attach(None, 0, 0);
        }
    }

    /// Brings back the layer (aka the widget) back on screen if it is hidden.
    pub fn show_again(&self) {
        if self.is_hidden.replace(false) {
            info!("Win: Showing window again");
            self.set_config_internal();
            self.first_configure.set(true);
            self.layer.as_ref().unwrap().commit();
        }
    }

    /// Hides the widget if visible or shows the widget back if hidden.
    pub fn toggle(&self) {
        info!("Win: view toggled");
        if self.is_hidden.get() {
            self.show_again();
        } else {
            self.hide();
        }
    }

    /// This function adds specific rectangular regions of your complete layer to receive
    /// input events from pointer and/or touch. The coordinates are in surface local
    /// format from top left corener. By default, The whole layer is considered for input
    /// events. Adding existing areas again as input region has no effect. This function
    /// combined with transparent base widgets can be used to mimic resizable widgets.
    pub fn add_input_region(&self, x: i32, y: i32, width: i32, height: i32) {
        info!(
            "Win: input region added: [x: {}, y: {}, width: {}, height: {}]",
            x, y, width, height
        );
        self.input_region.add(x, y, width, height);
        self.set_config_internal();
        self.layer.as_ref().unwrap().commit();
    }

    /// This function subtracts specific rectangular regions of your complete layer from receiving
    /// input events from pointer and/or touch. The coordinates are in surface local
    /// format from top left corener. By default, The whole layer is considered for input
    /// events. Substracting input areas which are already not input regions has no effect.
    pub fn subtract_input_region(&self, x: i32, y: i32, width: i32, height: i32) {
        info!(
            "Win: input region removed: [x: {}, y: {}, width: {}, height: {}]",
            x, y, width, height
        );
        self.input_region.subtract(x, y, width, height);
        self.set_config_internal();
        self.layer.as_ref().unwrap().commit();
    }

    /// This function marks specific rectangular regions of your complete layer as opaque.
    /// This can result in specific optimisations from your wayland compositor, setting
    /// this property is optional. The coordinates are in surface local format from top
    /// left corener. Not adding opaque regions in it has no isuues but adding transparent
    /// regions of layer as opaque can cause weird behaviour and glitches.
    pub fn add_opaque_region(&self, x: i32, y: i32, width: i32, height: i32) {
        info!(
            "Win: opaque region added: [x: {}, y: {}, width: {}, height: {}]",
            x, y, width, height
        );
        self.opaque_region.add(x, y, width, height);
        self.set_config_internal();
        self.layer.as_ref().unwrap().commit();
    }

    /// This function removes specific rectangular regions of your complete layer from being opaque.
    /// This can result in specific optimisations from your wayland compositor, setting
    /// this property is optional. The coordinates are in surface local format from top
    /// left corener.
    pub fn subtract_opaque_region(&self, x: i32, y: i32, width: i32, height: i32) {
        info!(
            "Win: opaque region removed: [x: {}, y: {}, width: {}, height: {}]",
            x, y, width, height
        );
        self.opaque_region.subtract(x, y, width, height);
        self.set_config_internal();
        self.layer.as_ref().unwrap().commit();
    }

    /// Grabs the focus of keyboard. Can be used in combination with other functions
    /// to make the widgets keyboard navigable.
    pub fn grab_focus(&self) {
        if !self.is_hidden.get()
            && self.config.board_interactivity.get() != KeyboardInteractivity::Exclusive
        {
            self.config
                .board_interactivity
                .set(KeyboardInteractivity::Exclusive);
            self.layer
                .as_ref()
                .unwrap()
                .set_keyboard_interactivity(KeyboardInteractivity::Exclusive);
            self.layer.as_ref().unwrap().commit();
        }
    }

    /// Removes the focus of keyboard from window if it currently has it.
    pub fn remove_focus(&self) {
        if !self.is_hidden.get()
            && self.config.board_interactivity.get() != KeyboardInteractivity::None
        {
            self.config
                .board_interactivity
                .set(KeyboardInteractivity::None);
            self.layer
                .as_ref()
                .unwrap()
                .set_keyboard_interactivity(KeyboardInteractivity::None);
            self.layer.as_ref().unwrap().commit();
        }
    }

    /// This method is used to set exclusive zone. Generally, useful when
    /// dimensions of width are different than exclusive zone you want.
    // self.set_config_internal();
    pub fn set_exclusive_zone(&mut self, val: i32) {
        self.config.exclusive_zone = Some(val);
        self.layer.as_ref().unwrap().set_exclusive_zone(val);
        self.layer.as_ref().unwrap().commit();
    }

    /// Opens a popup given the [`PopupConf`]. It returns the ID of the popup if
    /// created successfully. The method fails if the concerned compositor fails
    /// to create a popup instance or doesn't support the protocol.
    pub fn open_popup<T: PopupSlint + 'static>(
        &mut self,
        popup_conf: PopupConf,
    ) -> Result<u32, Box<dyn std::error::Error>> {
        if let Some(core) = self.create_popup_core(popup_conf) {
            let popup = T::create_new(core);
            let id = self.popup_manager.add_popup(popup);
            info!("Popup created with id: {}", id);
            Ok(id)
        } else {
            warn!("couldn't create a popup");
            Err("Couldn't create Popup".into())
        }
    }

    /// WIP method not to be used.
    pub fn open_popup_with_instance<T: PopupSlint + 'static>(
        &mut self,
        popup_conf: PopupConf,
    ) -> Result<T, Box<dyn std::error::Error>> {
        if let Some(core) = self.create_popup_core(popup_conf) {
            info!("Popup created without id");
            Ok(T::create_new(core))
        } else {
            warn!("couldn't create a popup");
            Err("Couldn't create Popup".into())
        }
    }

    /// WIP method not to be used.
    pub fn add_popup<T: PopupSlint + 'static>(&mut self, popup_instance: T) -> u32 {
        self.popup_manager.add_popup(popup_instance)
    }

    /// Closes a popup given its ID.
    pub fn close_popup(&mut self, id: u32) {
        self.popup_manager.close_popup(&id);
    }
}

delegate_compositor!(SpellWin);
delegate_xdg_shell!(SpellWin);
delegate_xdg_popup!(SpellWin);
delegate_registry!(SpellWin);
delegate_output!(SpellWin);
delegate_shm!(SpellWin);
delegate_seat!(SpellWin);
delegate_keyboard!(SpellWin);
delegate_pointer!(SpellWin);
delegate_touch!(SpellWin);
delegate_layer!(SpellWin);
delegate_fractional_scale!(SpellWin);
delegate_viewporter!(SpellWin);

impl SpellAssociatedNew for SpellWin {
    fn on_call(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        let event_loop = self.event_loop.clone();
        event_loop
            .borrow_mut()
            .dispatch(std::time::Duration::from_millis(1), self)?;
        Ok(())
    }

    fn get_span(&self) -> tracing::span::Span {
        self.span.clone()
    }
}

/// This is a wrapper around calloop's [loop_handle](https://docs.rs/calloop/latest/calloop/struct.LoopHandle.html)
/// for calling wayland specific features of `SpellWin`. It can be accessed from
/// [`crate::wayland_adapter::SpellWin::get_handler`].
#[derive(Clone, Debug)]
pub struct WinHandle(pub LoopHandle<'static, SpellWin>);

impl WinHandle {
    /// Internally calls [`crate::wayland_adapter::SpellWin::hide`]
    pub fn hide(&self) {
        self.0.insert_idle(|win| win.hide());
    }

    /// Internally calls [`crate::wayland_adapter::SpellWin::show_again`]
    pub fn show_again(&self) {
        self.0.insert_idle(|win| win.show_again());
    }

    /// Internally calls [`crate::wayland_adapter::SpellWin::toggle`]
    pub fn toggle(&self) {
        self.0.insert_idle(|win| win.toggle());
    }

    /// Internally calls [`crate::wayland_adapter::SpellWin::grab_focus`]
    pub fn grab_focus(&self) {
        self.0.insert_idle(|win| win.grab_focus());
    }

    /// Internally calls [`crate::wayland_adapter::SpellWin::remove_focus`]
    pub fn remove_focus(&self) {
        self.0.insert_idle(|win| win.remove_focus());
    }

    /// Internally calls [`crate::wayland_adapter::SpellWin::add_input_region`]
    pub fn add_input_region(&self, x: i32, y: i32, width: i32, height: i32) {
        self.0
            .insert_idle(move |win| win.add_input_region(x, y, width, height));
    }

    /// Internally calls [`crate::wayland_adapter::SpellWin::subtract_input_region`]
    pub fn subtract_input_region(&self, x: i32, y: i32, width: i32, height: i32) {
        self.0
            .insert_idle(move |win| win.subtract_input_region(x, y, width, height));
    }

    /// Internally calls [`crate::wayland_adapter::SpellWin::add_opaque_region`]
    pub fn add_opaque_region(&self, x: i32, y: i32, width: i32, height: i32) {
        self.0
            .insert_idle(move |win| win.add_opaque_region(x, y, width, height));
    }

    /// Internally calls [`crate::wayland_adapter::SpellWin::subtract_opaque_region`]
    pub fn subtract_opaque_region(&self, x: i32, y: i32, width: i32, height: i32) {
        self.0
            .insert_idle(move |win| win.subtract_opaque_region(x, y, width, height));
    }

    /// Internally calls [`crate::wayland_adapter::SpellWin::set_exclusive_zone`]
    pub fn set_exclusive_zone(&self, val: i32) {
        self.0.insert_idle(move |win| win.set_exclusive_zone(val));
    }

    /// Internally calls [`crate::wayland_adapter::SpellWin::open_popup`]. Since,
    /// the handler can't be tuned to return anything(in this case the id), a callback
    /// is instead taken with ID as input, this is called after receiving the ID.
    /// It can be used to used to save the ID and perform actions with it.
    pub fn open_popup<T: PopupSlint + 'static>(
        &mut self,
        popup_conf: PopupConf,
        callback: Box<dyn FnOnce(u32)>,
    ) -> Result<u32, Box<dyn std::error::Error>> {
        self.0.insert_idle(|win| {
            if let Ok(id) = win.open_popup::<T>(popup_conf) {
                callback(id);
            }
        });
        Ok(0)
    }

    /// Internally calls [`crate::wayland_adapter::SpellWin::close_popup`].
    pub fn close_popup(&self, id: u32) {
        self.0.insert_idle(move |win| {
            win.close_popup(id);
        });
    }
}