tauri-plugin-gpui 0.1.0

Render GPUI views inside ordinary Tauri windows
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
//! The shared GPUI runtime: one GPUI `App` per Tauri application, living on
//! the Tauri/TAO event-loop thread, plus the registry of attached windows.

#[cfg(gpui_android)]
mod android;
#[cfg(gpui_ios)]
mod ios;
#[cfg(all(any(target_os = "linux", target_os = "freebsd"), not(gpui_mobile)))]
mod x11;

use std::{
    cell::{Cell, RefCell},
    collections::{HashMap, VecDeque},
    rc::Rc,
    sync::{Arc, Mutex},
    thread::{self, ThreadId},
    time::{Duration, Instant},
};

use gpui::{
    AnyWindowHandle, App, Application, ApplicationHandle, AsyncApp, Bounds, QuitMode,
    TitlebarOptions, WindowBounds, WindowOptions,
};
#[cfg(not(gpui_android))]
use gpui::{point, px};
use gpui_wgpu::{CosmicTextSystem, WgpuRenderer, WgpuSurfaceConfig};
#[cfg(not(gpui_android))]
use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
use tauri::{AppHandle, EventLoopMessage, Wry};
use tauri_runtime_wry::{
    EventLoopIterationContext, Message, TaoWindowId, WindowMessage,
    tao::{
        event::{Event, WindowEvent},
        event_loop::EventLoopProxy,
    },
};

use crate::{
    GpuiConfig, GpuiError, GpuiOptions, events,
    ffi::lock,
    platform::{
        PENDING_SURFACE, TauriPlatform,
        dispatcher::{LoopWaker, TauriDispatcher},
        window::{RawWindow, WindowInner, default_window_state, logical},
    },
};

/// Upper bound on how long one drain may spend running GPUI tasks before
/// yielding back to TAO so input and redraws stay responsive.
const TASK_BUDGET: Duration = Duration::from_millis(8);

type OpenWindow = Box<dyn FnOnce(&mut App, WindowOptions) -> anyhow::Result<AnyWindowHandle>>;

/// Everything `attach` needs to know about the native surface.
pub(crate) struct SurfaceParams {
    raw: RawWindow,
    physical_size: gpui::Size<gpui::DevicePixels>,
    scale_factor: f32,
    origin: gpui::Point<gpui::Pixels>,
    appearance: gpui::WindowAppearance,
    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
    x11: Option<crate::platform::x11::X11Window>,
}

struct Mount {
    inner: Rc<WindowInner>,
    options: WindowOptions,
    open: OpenWindow,
}

pub(crate) struct Runtime {
    main_thread: ThreadId,
    /// Keeps the shared App alive; all access goes through `cx`.
    _app: ApplicationHandle,
    /// Unlike `ApplicationHandle::update`, `AsyncApp::update` runs a full
    /// GPUI update cycle, flushing the effects (`defer`, `notify`, `emit`,
    /// observers) the closure queued.
    cx: AsyncApp,
    platform: Rc<TauriPlatform>,
    dispatcher: Arc<TauriDispatcher>,
    waker: Arc<LoopWaker>,
    surfaces: RefCell<HashMap<String, Rc<WindowInner>>>,
    tao_labels: RefCell<HashMap<TaoWindowId, String>>,
    mounts: RefCell<VecDeque<Mount>>,
    deferred: Rc<RefCell<Vec<Box<dyn FnOnce()>>>>,
    depth: Cell<usize>,
    proxy_installed: Cell<bool>,
    #[cfg(gpui_android)]
    android: android::AndroidState,
    #[cfg(gpui_ios)]
    ios: ios::IosState,
}

thread_local! {
    /// Leaked on purpose: the shared GPUI App lives until the process exits,
    /// and dropping GPU resources from TLS destructors (after other thread
    /// locals are gone) panics. Surfaces are torn down on `LoopDestroyed`.
    static RUNTIME: Cell<Option<&'static Runtime>> = const { Cell::new(None) };
}

/// Runs `f` with the runtime of the current (main) thread.
pub(crate) fn with<R>(
    f: impl FnOnce(&'static Runtime) -> Result<R, GpuiError>,
) -> Result<R, GpuiError> {
    let runtime = RUNTIME.try_with(Cell::get).ok().flatten();
    match runtime {
        Some(runtime) => f(runtime),
        None if lock(&INITIALIZED).is_some() => Err(GpuiError::NotMainThread),
        None => Err(GpuiError::NotInitialized),
    }
}

/// Thread the runtime was created on, for diagnosing off-thread calls.
static INITIALIZED: Mutex<Option<ThreadId>> = Mutex::new(None);

/// Runs `f`, which feeds GPUI input from outside TAO's event callback (a
/// GTK signal handler), under the same reentrancy guard as TAO events.
/// `None` while GPUI is mid-update, or off the main thread.
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
pub(crate) fn input<R>(f: impl FnOnce() -> R) -> Option<R> {
    with(|runtime| {
        Ok((runtime.depth.get() == 0).then(|| {
            let _guard = runtime.enter();
            f()
        }))
    })
    .ok()
    .flatten()
}

struct DepthGuard<'a>(&'a Cell<usize>);

impl Drop for DepthGuard<'_> {
    fn drop(&mut self) {
        self.0.set(self.0.get() - 1);
    }
}

pub(crate) fn initialize(app: AppHandle<Wry>, config: GpuiConfig) -> Result<(), GpuiError> {
    {
        let mut initialized = lock(&INITIALIZED);
        if initialized.is_some() {
            return Err(GpuiError::AlreadyInitialized);
        }
        *initialized = Some(thread::current().id());
    }

    // Until the TAO proxy is captured on the first event, wake the loop by
    // posting an empty task through Tauri.
    let waker = Arc::new(LoopWaker::new(Box::new({
        let app = app.clone();
        move || {
            let _ = app.run_on_main_thread(|| {});
        }
    })));
    let dispatcher = Arc::new(TauriDispatcher::new(waker.clone()));
    let text_system = new_text_system(config.font_fallback.as_deref().unwrap_or(default_font()));
    let platform = Rc::new(TauriPlatform::new(app, dispatcher.clone(), text_system));

    let mut application =
        Application::with_platform(platform.clone()).with_quit_mode(QuitMode::Explicit);
    if let Some(configure) = config.configure {
        application = configure(application);
    }

    let app = application.run_embedded(|_| {});
    let runtime = Box::leak(Box::new(Runtime {
        main_thread: thread::current().id(),
        cx: app.to_async(),
        _app: app,
        platform,
        dispatcher,
        waker,
        surfaces: RefCell::default(),
        tao_labels: RefCell::default(),
        mounts: RefCell::default(),
        deferred: Rc::default(),
        depth: Cell::new(0),
        proxy_installed: Cell::new(false),
        #[cfg(gpui_android)]
        android: android::AndroidState::default(),
        #[cfg(gpui_ios)]
        ios: ios::IosState::default(),
    }));
    #[cfg(gpui_mobile)]
    crate::mobile::set_waker(runtime.waker.clone());
    // Published first so `on_launch` can use the plugin API (attaching
    // completes once the update returns, as from any GPUI code).
    RUNTIME.with(|slot| slot.set(Some(runtime)));
    if let Some(on_launch) = config.on_launch {
        runtime.update(on_launch)?;
    }
    Ok(())
}

fn is_dummy(window_id: &TaoWindowId) -> bool {
    // SAFETY: the dummy id is only compared, never used to address a window.
    *window_id == unsafe { TaoWindowId::dummy() }
}

#[cfg(not(gpui_mobile))]
fn new_text_system(fallback: &str) -> Arc<CosmicTextSystem> {
    Arc::new(CosmicTextSystem::new(fallback))
}

#[cfg(gpui_mobile)]
fn new_text_system(fallback: &str) -> Arc<CosmicTextSystem> {
    // fontdb has no Android or iOS system font discovery.
    let text_system = Arc::new(CosmicTextSystem::new_without_system_fonts(fallback));
    #[cfg(gpui_android)]
    android::load_system_fonts(&*text_system);
    #[cfg(gpui_ios)]
    ios::load_system_fonts(&*text_system);
    text_system
}

fn default_font() -> &'static str {
    if cfg!(target_os = "android") {
        "Roboto"
    } else if cfg!(any(target_os = "macos", target_os = "ios")) {
        "Helvetica Neue"
    } else if cfg!(target_os = "windows") {
        "Segoe UI"
    } else {
        "DejaVu Sans"
    }
}

impl Runtime {
    fn enter(&self) -> DepthGuard<'_> {
        self.depth.set(self.depth.get() + 1);
        DepthGuard(&self.depth)
    }

    fn is_main_thread(&self) -> bool {
        thread::current().id() == self.main_thread
    }

    /// Borrows the shared GPUI `App`. Fails instead of panicking when the App
    /// is already borrowed further up the stack.
    pub(crate) fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> Result<R, GpuiError> {
        if !self.is_main_thread() {
            return Err(GpuiError::NotMainThread);
        }
        if self.depth.get() > 0 {
            return Err(GpuiError::Reentrant);
        }
        let _guard = self.enter();
        Ok(self.cx.update(f))
    }

    pub(crate) fn attach(
        &self,
        window: &tauri::Window<Wry>,
        options: GpuiOptions,
        open: OpenWindow,
    ) -> Result<(), GpuiError> {
        if !self.is_main_thread() {
            return Err(GpuiError::NotMainThread);
        }
        let label = window.label().to_string();
        if self.surfaces.borrow().contains_key(&label) {
            return Err(GpuiError::AlreadyAttached { label });
        }
        if !window.webviews().is_empty() {
            return Err(GpuiError::NotEligible {
                label,
                reason: "the window hosts a WebView; GPUI and WebView content cannot share a window",
            });
        }
        #[cfg(gpui_android)]
        {
            self.attach_android(window, options, open)
        }
        #[cfg(gpui_ios)]
        {
            self.attach_ios(window, options, open)
        }
        #[cfg(not(gpui_mobile))]
        {
            #[allow(unused_mut)]
            let mut params = Self::desktop_surface(window)?;
            #[cfg(any(target_os = "linux", target_os = "freebsd"))]
            self.x11_surface(window, &mut params);
            self.attach_surface(window, options, open, params)
        }
    }

    #[cfg(not(gpui_android))]
    fn desktop_surface(window: &tauri::Window<Wry>) -> Result<SurfaceParams, GpuiError> {
        // A window built hidden has no X11 window until GTK realizes it, so
        // realize it here to attach GPUI before it is first shown.
        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
        if let Ok(gtk_window) = window.gtk_window() {
            use gtk::prelude::WidgetExt;
            if !gtk_window.is_realized() {
                gtk_window.realize();
            }
        }
        let scale_factor = window.scale_factor()? as f32;
        // On iOS the view fills the whole window, while `inner_size` is only
        // its safe area; the safe area is reported as insets instead.
        let physical = if cfg!(gpui_ios) {
            window.outer_size()?
        } else {
            window.inner_size()?
        };
        let physical_size = events::physical_size(physical.width.max(1), physical.height.max(1));
        let origin = if cfg!(gpui_ios) {
            point(px(0.), px(0.))
        } else {
            window
                .outer_position()
                .map(|p| {
                    let p = p.to_logical::<f32>(scale_factor as f64);
                    point(px(p.x), px(p.y))
                })
                .unwrap_or_default()
        };
        let appearance = window
            .theme()
            .map_or(gpui::WindowAppearance::Light, crate::platform::appearance);

        let raw = RawWindow {
            window: window
                .window_handle()
                .map_err(|e| GpuiError::PlatformInitialization(format!("window handle: {e}")))?
                .as_raw(),
            display: window
                .display_handle()
                .map_err(|e| GpuiError::PlatformInitialization(format!("display handle: {e}")))?
                .as_raw(),
        };
        Ok(SurfaceParams {
            raw,
            physical_size,
            scale_factor,
            origin,
            appearance,
            #[cfg(any(target_os = "linux", target_os = "freebsd"))]
            x11: None,
        })
    }

    /// Creates the renderer for a prepared native surface and mounts GPUI.
    fn attach_surface(
        &self,
        window: &tauri::Window<Wry>,
        options: GpuiOptions,
        open: OpenWindow,
        params: SurfaceParams,
    ) -> Result<(), GpuiError> {
        let SurfaceParams {
            raw,
            physical_size,
            scale_factor,
            origin,
            appearance,
            #[cfg(any(target_os = "linux", target_os = "freebsd"))]
            x11,
        } = params;
        let label = window.label().to_string();
        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
        let wayland = crate::platform::wayland::Content::new(raw.window, raw.display);
        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
        let raw = match &wayland {
            Some(content) => RawWindow {
                window: content.window_handle(),
                ..raw
            },
            None => raw,
        };
        // FIFO blocks the main thread on frame callbacks, which compositors
        // hold back from surfaces not yet mapped, hidden or minimized (and
        // GTK, which maps the window, runs on that thread). GPUI's own
        // Wayland platform presents in mailbox mode for the same reason.
        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
        let present_mode = wayland
            .is_some()
            .then_some(gpui_wgpu::wgpu::PresentMode::Mailbox);
        #[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
        let present_mode = None;
        let renderer = WgpuRenderer::new(
            self.platform.gpu_context.clone(),
            &raw,
            WgpuSurfaceConfig {
                size: physical_size,
                transparent: options.transparent,
                preferred_present_mode: present_mode,
            },
            None,
        )
        .map_err(|e| GpuiError::RendererInitialization(format!("{e:#}")))?;

        let sprite_atlas: Arc<dyn gpui::PlatformAtlas> = renderer.sprite_atlas().clone();
        #[cfg(all(feature = "test-support", not(gpui_mobile)))]
        let capture = crate::platform::capture::Capture::new(sprite_atlas.clone());
        #[cfg(all(feature = "test-support", not(gpui_mobile)))]
        let sprite_atlas = capture.as_ref().map_or(sprite_atlas, |c| c.atlas());
        let defer: Rc<dyn Fn(Box<dyn FnOnce()>)> = Rc::new({
            let deferred = self.deferred.clone();
            let waker = self.waker.clone();
            move |action| {
                deferred.borrow_mut().push(action);
                waker.wake();
            }
        });
        // The weak handle lets native input-method callbacks reach the window.
        let inner = Rc::new_cyclic(|_weak| WindowInner {
            label: label.clone(),
            tauri_window: window.clone(),
            raw: Cell::new(raw),
            state: RefCell::new(default_window_state(
                physical_size,
                scale_factor,
                origin,
                appearance,
                renderer,
            )),
            callbacks: RefCell::default(),
            frame_pending: Cell::new(false),
            force_present: Cell::new(false),
            mode_dirty: Cell::new(true),
            display_dirty: Cell::new(true),
            reported_visible: Cell::new(true),
            transparent: Cell::new(options.transparent),
            sprite_atlas,
            #[cfg(all(feature = "test-support", not(gpui_mobile)))]
            capture,
            closed: Cell::new(false),
            gpui_handle: Cell::new(None),
            display: RefCell::default(),
            waker: self.waker.clone(),
            defer,
            #[cfg(not(gpui_mobile))]
            webviews: RefCell::default(),
            #[cfg(not(gpui_mobile))]
            file_drop: RefCell::default(),
            #[cfg(any(target_os = "linux", target_os = "freebsd"))]
            ime: crate::platform::ime::linux::Ime::new(window, _weak.clone()),
            #[cfg(not(gpui_mobile))]
            a11y: RefCell::default(),
            #[cfg(not(gpui_mobile))]
            a11y_bounds_dirty: Cell::new(true),
            #[cfg(any(target_os = "linux", target_os = "freebsd"))]
            wayland,
            #[cfg(any(target_os = "linux", target_os = "freebsd"))]
            x11,
        });
        #[cfg(all(not(gpui_mobile), any(target_os = "linux", target_os = "freebsd")))]
        crate::platform::file_drop::gtk::install(window, Rc::downgrade(&inner));
        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
        if inner.wayland.is_some() {
            crate::platform::wayland::install(window, Rc::downgrade(&inner));
        }
        // The window may have been built maximized, fullscreen or minimized.
        inner.sync_window_mode();
        inner.reported_visible.set(inner.state.borrow().visible);
        self.surfaces.borrow_mut().insert(label, inner.clone());

        let window_options = WindowOptions {
            window_bounds: Some(WindowBounds::Windowed(Bounds::new(
                origin,
                logical(physical_size, scale_factor),
            ))),
            // GPUI only reads the title, as the accessible name of the window.
            titlebar: Some(TitlebarOptions {
                title: window.title().ok().map(Into::into),
                ..Default::default()
            }),
            focus: options.focus,
            show: false,
            ..Default::default()
        };
        let mount = Mount {
            inner,
            options: window_options,
            open,
        };
        if self.depth.get() == 0 {
            self.mount(mount)
        } else {
            // Called from inside GPUI (e.g. a click handler that creates a
            // window): finish once the current GPUI update has unwound.
            self.mounts.borrow_mut().push_back(mount);
            self.waker.wake();
            Ok(())
        }
    }

    fn mount(&self, mount: Mount) -> Result<(), GpuiError> {
        let Mount {
            inner,
            options,
            open,
        } = mount;
        // A deferred mount can outlive its window: Tauri may have destroyed it
        // (or already processed `Destroyed`) since `attach` queued the mount.
        // Getters fail once Tauri has dropped the native window.
        if inner.closed.get() || inner.tauri_window.inner_size().is_err() {
            self.surfaces.borrow_mut().remove(&inner.label);
            inner.destroy();
            return Err(GpuiError::NotEligible {
                label: inner.label.clone(),
                reason: "the window was destroyed before GPUI could be mounted",
            });
        }
        PENDING_SURFACE.with(|pending| *pending.borrow_mut() = Some(inner.clone()));
        let result = self.update(|cx| open(cx, options));
        PENDING_SURFACE.with(|pending| pending.borrow_mut().take());

        let error = match result {
            Ok(Ok(handle)) => {
                inner.gpui_handle.set(Some(handle));
                #[cfg(gpui_ios)]
                inner.set_insets(self.ios_insets());
                inner.force_present.set(true);
                inner.schedule_frame();
                return Ok(());
            }
            Ok(Err(error)) => GpuiError::PlatformInitialization(format!("{error:#}")),
            Err(error) => error,
        };
        self.surfaces.borrow_mut().remove(&inner.label);
        inner.destroy();
        Err(error)
    }

    fn surface_for(
        &self,
        window_id: TaoWindowId,
        context: &EventLoopIterationContext<'_, EventLoopMessage>,
    ) -> Option<Rc<WindowInner>> {
        if let Some(label) = self.tao_labels.borrow().get(&window_id) {
            return self.surfaces.borrow().get(label).cloned();
        }
        let id = context.window_id_map.get(&window_id)?;
        let windows = context.windows.0.try_borrow().ok()?;
        let label = windows.get(&id)?.label().to_string();
        drop(windows);
        let inner = self.surfaces.borrow().get(&label).cloned()?;
        self.tao_labels.borrow_mut().insert(window_id, label);
        Some(inner)
    }

    /// Feeds one TAO event to GPUI. Returns `true` when Tauri must not handle
    /// the event (GPUI vetoed a close request).
    pub(crate) fn handle_event(
        &self,
        event: &Event<'_, Message<EventLoopMessage>>,
        proxy: &EventLoopProxy<Message<EventLoopMessage>>,
        context: &EventLoopIterationContext<'_, EventLoopMessage>,
    ) -> bool {
        if !self.proxy_installed.replace(true) {
            let proxy = Mutex::new(proxy.clone());
            self.waker.set(Box::new(move || {
                let _ = lock(&proxy).send_event(Message::Task(Box::new(|| {})));
            }));
        }
        if self.depth.get() > 0 {
            // TAO never re-enters its callback, but be defensive.
            return false;
        }
        // On Android the GpuiView, not TAO, reports the surface and input.
        #[cfg(gpui_android)]
        if matches!(event, Event::WindowEvent { .. } | Event::RedrawRequested(_)) {
            return false;
        }

        match event {
            // GTK themes are application-wide: TAO reports the change once,
            // with a dummy window id.
            Event::WindowEvent {
                window_id,
                event: event @ WindowEvent::ThemeChanged(_),
                ..
            } if is_dummy(window_id) => {
                let surfaces: Vec<_> = self.surfaces.borrow().values().cloned().collect();
                let _guard = self.enter();
                for surface in surfaces {
                    events::dispatch(&surface, event);
                }
            }
            // Closing through the window manager.
            Event::WindowEvent {
                window_id,
                event: WindowEvent::CloseRequested,
                ..
            } => {
                if let Some(inner) = self.surface_for(*window_id, context) {
                    return self.veto_close(&inner);
                }
            }
            // `tauri::Window::close()`.
            Event::UserEvent(Message::Window(id, WindowMessage::Close)) => {
                let label = context
                    .windows
                    .0
                    .try_borrow()
                    .ok()
                    .and_then(|windows| Some(windows.get(id)?.label().to_string()));
                let inner = label.and_then(|label| self.surfaces.borrow().get(&label).cloned());
                if let Some(inner) = inner {
                    return self.veto_close(&inner);
                }
            }
            Event::WindowEvent {
                window_id, event, ..
            } => {
                let Some(inner) = self.surface_for(*window_id, context) else {
                    return false;
                };
                #[cfg(gpui_ios)]
                if self.ios_window_event(&inner, event) {
                    return false;
                }
                #[cfg(any(target_os = "linux", target_os = "freebsd"))]
                let rewritten;
                #[cfg(any(target_os = "linux", target_os = "freebsd"))]
                let event = match self.x11_window_event(&inner, event) {
                    x11::Rewrite::Keep => event,
                    x11::Rewrite::Drop => return false,
                    x11::Rewrite::Replace(event) => {
                        rewritten = event;
                        &rewritten
                    }
                };
                self.track_window_state(&inner, event);
                let destroyed = {
                    let _guard = self.enter();
                    events::dispatch(&inner, event)
                };
                if destroyed {
                    self.surfaces.borrow_mut().remove(&inner.label);
                    self.tao_labels.borrow_mut().remove(window_id);
                    self.forget_platform_refs(&inner);
                    let _guard = self.enter();
                    inner.destroy();
                }
            }
            Event::RedrawRequested(window_id) => {
                // The OS asked for a repaint (expose, resize, ...): present
                // even if GPUI has nothing new to render.
                if let Some(inner) = self.surface_for(*window_id, context) {
                    // Exposure also follows a restore TAO has no event for.
                    inner.window_mode_changed();
                    inner.force_present.set(true);
                    inner.schedule_frame();
                }
            }
            Event::MainEventsCleared | Event::RedrawEventsCleared => self.drain(),
            Event::LoopDestroyed => self.shutdown(),
            _ => {}
        }
        false
    }

    /// Consults GPUI's `on_window_should_close` before Tauri closes the window.
    fn veto_close(&self, inner: &WindowInner) -> bool {
        if inner.closed.get() {
            return false;
        }
        let _guard = self.enter();
        !inner.should_close()
    }

    fn track_window_state(&self, inner: &Rc<WindowInner>, event: &WindowEvent<'_>) {
        match event {
            WindowEvent::CursorEntered { .. } => {
                *self.platform.hovered_window.borrow_mut() = Some(inner.tauri_window.clone());
                // Cursor icons are per native window: the cached style
                // belongs to the previously hovered one.
                self.platform.cursor.reset();
            }
            WindowEvent::CursorLeft { .. } => self.unhover(inner),
            WindowEvent::Focused(true) => self.platform.active_window.set(inner.gpui_handle.get()),
            WindowEvent::Focused(false) => self.deactivate(inner),
            _ => {}
        }
    }

    /// Clears the platform's hovered window if it is `inner`.
    fn unhover(&self, inner: &WindowInner) {
        let mut hovered = self.platform.hovered_window.borrow_mut();
        if hovered.as_ref().is_some_and(|w| w.label() == inner.label) {
            *hovered = None;
        }
    }

    /// Clears the platform's active window if it is `inner`.
    fn deactivate(&self, inner: &WindowInner) {
        if self.platform.active_window.get() == inner.gpui_handle.get() {
            self.platform.active_window.set(None);
        }
    }

    fn forget_platform_refs(&self, inner: &WindowInner) {
        self.unhover(inner);
        self.deactivate(inner);
    }

    /// Runs queued GPUI work, finishes deferred attachments and delivers
    /// pending frame requests. Called once or twice per TAO iteration.
    fn drain(&self) {
        if self.depth.get() > 0 {
            return;
        }
        self.waker.clear();

        #[cfg(gpui_android)]
        self.pump_android();
        #[cfg(gpui_ios)]
        self.pump_ios();

        let start = Instant::now();
        {
            let _guard = self.enter();
            while let Some(runnable) = self.dispatcher.pop_main() {
                runnable.run();
                if start.elapsed() > TASK_BUDGET {
                    break;
                }
            }
        }

        loop {
            let mount = self.mounts.borrow_mut().pop_front();
            let Some(mount) = mount else { break };
            if let Err(error) = self.mount(mount) {
                log::error!("tauri-plugin-gpui: deferred GPUI attachment failed: {error}");
            }
        }

        let actions = std::mem::take(&mut *self.deferred.borrow_mut());
        for action in actions {
            action();
        }

        // iOS terminates apps that use the GPU in the background.
        #[cfg(gpui_ios)]
        let frames_allowed = !self.ios.background.get();
        #[cfg(not(gpui_ios))]
        let frames_allowed = true;
        let surfaces: Vec<_> = self.surfaces.borrow().values().cloned().collect();
        {
            let _guard = self.enter();
            for surface in &surfaces {
                if surface.closed.get() {
                    continue;
                }
                #[cfg(not(gpui_mobile))]
                surface.flush_file_drop();
                #[cfg(any(target_os = "linux", target_os = "freebsd"))]
                if let Some(ime) = &surface.ime {
                    ime.flush(surface);
                }
                #[cfg(any(target_os = "linux", target_os = "freebsd"))]
                if let Some(content) = &surface.wayland {
                    content.flush();
                }
                surface.flush_ime_commit();
                surface.refresh_window_mode();
                #[cfg(any(target_os = "linux", target_os = "freebsd"))]
                self.sync_x11(surface);
                // GPUI is told hidden windows get no frames; keep the request
                // pending until the window is visible again.
                if frames_allowed && surface.reported_visible.get() && surface.frame_pending.take()
                {
                    surface.request_frame();
                }
            }
        }
        let frames_pending = frames_allowed
            && surfaces
                .iter()
                .any(|s| s.reported_visible.get() && s.frame_pending.get());

        #[cfg(gpui_android)]
        self.sync_text_input();

        let more_work = self.dispatcher.has_main_work()
            || !self.mounts.borrow().is_empty()
            || !self.deferred.borrow().is_empty()
            || frames_pending;
        if more_work {
            self.waker.wake();
        }

        // Tell the keyboard about text GPUI changed on its own.
        #[cfg(gpui_ios)]
        crate::ios::sync();
    }

    /// Releases every surface while thread locals are still alive.
    fn shutdown(&self) {
        #[cfg(gpui_ios)]
        crate::ios::uninstall();
        let surfaces: Vec<_> = self.surfaces.borrow_mut().drain().map(|(_, s)| s).collect();
        self.tao_labels.borrow_mut().clear();
        let _guard = self.enter();
        for surface in surfaces {
            self.forget_platform_refs(&surface);
            surface.destroy();
        }
    }

    /// The attached surface of a Tauri window, if any.
    #[cfg(not(gpui_mobile))]
    pub(crate) fn surface(&self, label: &str) -> Option<Rc<WindowInner>> {
        self.surfaces.try_borrow().ok()?.get(label).cloned()
    }

    pub(crate) fn is_attached(&self, label: &str) -> bool {
        self.surfaces.borrow().contains_key(label)
    }
}