gpui-webview 0.9.0

WebView support for GPUI, based on Wry.
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
extern crate gpui_kit as gpui;

#[cfg(all(feature = "gpui-fast", target_os = "macos"))]
mod composition;
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;

#[cfg(all(feature = "gpui-fast", target_os = "macos"))]
use composition::NativeWebViewSurface;
#[cfg(all(feature = "gpui-fast", target_os = "linux"))]
use linux::NativeWebViewSurface;

use std::{cell::Cell, ops::Deref, rc::Rc};

use wry::Rect;

use gpui::{
    App, Bounds, ContentMask, DismissEvent, Element, ElementId, Entity, EventEmitter, FocusHandle,
    Focusable, GlobalElementId, Hitbox, InteractiveElement, IntoElement, LayoutId, MouseDownEvent,
    ParentElement as _, Pixels, Render, Size, Style, Styled as _, Window, canvas, div,
};

// `gpui-kit` selects the GPUI backend; this crate's `gpui-fast` feature only follows it, so
// the two must agree. A mismatch would otherwise keep the gpui-pre attachment on GPUI Fast.
const _: () = {
    assert!(
        !gpui::GPUI_FAST || cfg!(feature = "gpui-fast"),
        "gpui-kit is built with `gpui-fast`, but gpui-webview is not: enable the \
         `gpui-webview/gpui-fast` feature so the WebView uses GPUI Fast's window composition"
    );
    assert!(
        gpui::GPUI_FAST || !cfg!(feature = "gpui-fast"),
        "gpui-webview is built with `gpui-fast`, but gpui-kit is not: enable the \
         `gpui-kit/gpui-fast` feature, which selects the GPUI backend"
    );
};

/// An owned, UI-thread-local handle to the raw wry webview.
///
/// Cloning this handle prolongs the native webview's lifetime. Dropping the owning [`WebView`]
/// entity hides the child view, but final native destruction waits until all handle and frame
/// clones are dropped. All handles must be dropped before the parent window is destroyed.
#[derive(Clone)]
pub struct WebViewHandle(Rc<wry::WebView>);

impl WebViewHandle {
    /// Get the raw wry webview.
    pub fn raw(&self) -> &wry::WebView {
        &self.0
    }
}

/// A webview based on wry WebView.
///
/// With the `gpui-fast` feature, macOS and Linux host the native view in a window
/// composition surface, so deferred GPUI overlays render above the page. Without it, the
/// native view covers GPUI content in its bounds and extends past a container that clips it.
///
/// [experimental]
pub struct WebView {
    focus_handle: FocusHandle,
    webview: Rc<wry::WebView>,
    visible: Cell<bool>,
    bounds: Bounds<Pixels>,
    /// The page zoom the script asked for, before any display scale compensation.
    zoom: Cell<f64>,
    /// Whether the last geometry update failed, so each failure is logged once until it recovers.
    geometry_failed: Cell<bool>,
    #[cfg(all(feature = "gpui-fast", any(target_os = "macos", target_os = "linux")))]
    composition: Option<NativeWebViewSurface>,
    /// The GPUI scale factor the page zoom was last matched to.
    #[cfg(target_os = "linux")]
    scale_factor: Cell<f32>,
    /// The window-relative origin that page clicks are forwarded to GPUI from.
    #[cfg(target_os = "linux")]
    origin: Rc<Cell<gpui::Point<Pixels>>>,
}

impl Drop for WebView {
    fn drop(&mut self) {
        self.hide();
        #[cfg(all(feature = "gpui-fast", any(target_os = "macos", target_os = "linux")))]
        if let Some(surface) = self.composition.take() {
            surface.release(self.webview.clone());
        }
    }
}

impl WebView {
    /// Create a new WebView from a wry WebView.
    pub fn new(webview: wry::WebView, window: &mut Window, cx: &mut App) -> Self {
        let _ = webview.set_bounds(Rect::default());

        #[cfg(all(feature = "gpui-fast", target_os = "macos"))]
        let composition = match NativeWebViewSurface::new(&webview, window, cx) {
            Ok(surface) => Some(surface),
            Err(error) => {
                log::warn!("WebView composition unavailable: {error:#}");
                None
            }
        };
        #[cfg(target_os = "linux")]
        let origin = Rc::new(Cell::new(gpui::Point::default()));
        #[cfg(target_os = "linux")]
        linux::forward_mouse_down(&webview, origin.clone(), window, cx);
        #[cfg(target_os = "linux")]
        linux::match_scale_factor(&webview, window.scale_factor(), 1.0);
        #[cfg(not(any(all(feature = "gpui-fast", target_os = "macos"), target_os = "linux")))]
        let _ = window;

        Self {
            focus_handle: cx.focus_handle(),
            visible: Cell::new(true),
            bounds: Bounds::default(),
            zoom: Cell::new(1.0),
            geometry_failed: Cell::new(false),
            webview: Rc::new(webview),
            #[cfg(all(feature = "gpui-fast", target_os = "macos"))]
            composition,
            #[cfg(all(feature = "gpui-fast", target_os = "linux"))]
            composition: None,
            #[cfg(target_os = "linux")]
            scale_factor: Cell::new(window.scale_factor()),
            #[cfg(target_os = "linux")]
            origin,
        }
    }

    /// Build a webview as a child of `window`, performing the platform setup Wry requires.
    ///
    /// On Linux the window must run on X11 or XWayland: start the application with
    /// `gpui_kit::platform::linux(WindowingModes::X11)`. A Wayland window returns an error.
    /// This also initializes GTK and drives its main loop from GPUI. With the `gpui-fast` feature,
    /// the webview is built in a window composition surface so GPUI overlays can render above it.
    pub fn build(
        builder: wry::WebViewBuilder,
        window: &mut Window,
        cx: &mut App,
    ) -> wry::Result<Self> {
        #[cfg(target_os = "linux")]
        let webview = {
            let parent = linux::X11Parent::new(window)?;
            linux::ensure_gtk(cx)?;

            #[cfg(feature = "gpui-fast")]
            match NativeWebViewSurface::new(window, cx) {
                Ok(surface) => {
                    let webview = builder.build_as_child(&surface.parent()?)?;
                    let mut this = Self::new(webview, window, cx);
                    this.composition = Some(surface);
                    return Ok(this);
                }
                Err(error) => log::warn!("WebView composition unavailable: {error:#}"),
            }

            builder.build_as_child(&parent)?
        };
        #[cfg(not(target_os = "linux"))]
        let webview = builder.build_as_child(&*window)?;

        Ok(Self::new(webview, window, cx))
    }

    /// Set window-relative bounds, including offscreen loading bounds.
    /// With window composition, position the managed container and its child together.
    pub fn set_bounds(&self, bounds: Rect) -> wry::Result<()> {
        #[cfg(all(feature = "gpui-fast", any(target_os = "macos", target_os = "linux")))]
        if let Some(surface) = &self.composition {
            return surface
                .set_bounds(&self.webview, bounds)
                .map_err(|error| wry::Error::Io(std::io::Error::other(error)));
        }
        self.webview.set_bounds(bounds)
    }

    /// Apply full document bounds and an inherited clip without changing the DOM viewport.
    /// Empty clips hide the native surface while preserving the loaded document.
    /// Partial clipping requires native window composition; without it, the native view
    /// takes the full document bounds and extends past the clip.
    pub fn set_geometry(
        &self,
        document: Bounds<Pixels>,
        clip: Bounds<Pixels>,
    ) -> anyhow::Result<()> {
        let visible = document.intersect(&clip);
        if visible.is_empty() || !self.visible.get() {
            self.set_native_visible(false)?;
            #[cfg(all(feature = "gpui-fast", any(target_os = "macos", target_os = "linux")))]
            if let Some(surface) = &self.composition {
                // Hidden preparation still gives WebKit its real layout width.
                if self.visible.get() && !document.is_empty() {
                    surface.set_geometry(&self.webview, document, document)?;
                }
            }
            return Ok(());
        }
        #[cfg(all(feature = "gpui-fast", any(target_os = "macos", target_os = "linux")))]
        if let Some(surface) = &self.composition {
            surface.set_geometry(&self.webview, document, visible)?;
            surface.set_visible(true)?;
            self.webview.set_visible(true)?;
            return Ok(());
        }
        #[cfg(target_os = "linux")]
        let rect = linux::device_bounds(document, self.scale_factor.get());
        #[cfg(not(target_os = "linux"))]
        let rect = Rect {
            position: wry::dpi::LogicalPosition::new(
                f64::from(document.origin.x),
                f64::from(document.origin.y),
            )
            .into(),
            size: wry::dpi::LogicalSize::new(
                f64::from(document.size.width),
                f64::from(document.size.height),
            )
            .into(),
        };
        self.set_bounds(rect)?;
        self.set_native_visible(true)?;
        Ok(())
    }

    // Geometry can temporarily hide the native view without changing the caller's
    // visibility preference, so prepaint can retry when the view becomes unclipped.
    fn set_native_visible(&self, visible: bool) -> wry::Result<()> {
        self.webview.set_visible(visible)?;
        #[cfg(all(feature = "gpui-fast", any(target_os = "macos", target_os = "linux")))]
        if let Some(surface) = &self.composition {
            surface
                .set_visible(visible)
                .map_err(|error| wry::Error::Io(std::io::Error::other(error)))?;
        }
        Ok(())
    }

    /// Set visibility and report native errors without discarding the loaded page.
    pub fn set_visible(&self, visible: bool) -> wry::Result<()> {
        // A focus error must not leave a closing native view covering the window.
        let focus_result = if !visible && self.visible.get() {
            self.webview.focus_parent()
        } else {
            Ok(())
        };
        self.set_native_visible(visible)?;
        self.visible.set(visible);
        focus_result
    }

    /// Show the webview.
    pub fn show(&mut self) {
        let _ = self.set_visible(true);
    }

    /// Hide the webview.
    pub fn hide(&mut self) {
        let _ = self.set_visible(false);
    }

    /// Get whether the webview is visible.
    pub fn visible(&self) -> bool {
        self.visible.get()
    }

    /// Get the current bounds of the webview.
    pub fn bounds(&self) -> Bounds<Pixels> {
        self.bounds
    }

    /// Go back in the webview history.
    pub fn back(&mut self) -> anyhow::Result<()> {
        Ok(self.webview.evaluate_script("history.back();")?)
    }

    /// Go forward in the webview history.
    pub fn forward(&mut self) -> anyhow::Result<()> {
        Ok(self.webview.evaluate_script("history.forward();")?)
    }

    /// Load a URL in the webview.
    pub fn load_url(&mut self, url: &str) {
        let _ = self.webview.load_url(url);
    }

    /// Set the colour scheme the page sees in `prefers-color-scheme` and draws its
    /// native controls in. `Theme::Auto` follows the system again.
    ///
    /// On Linux this is GTK's process-wide `gtk-application-prefer-dark-theme`, so it
    /// applies to every webview in the application.
    pub fn set_theme(&self, theme: wry::Theme) -> wry::Result<()> {
        #[cfg(target_os = "linux")]
        linux::set_theme(theme);
        #[cfg(target_os = "macos")]
        macos::set_theme(&self.webview, theme);
        #[cfg(target_os = "windows")]
        wry::WebViewExtWindows::set_theme(&*self.webview, theme)?;
        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
        let _ = theme;
        Ok(())
    }

    /// Zoom the page, where `1.0` is its natural size. The engine scales the page
    /// itself, without the relayout and repaint a CSS `zoom` causes, and keeps the
    /// factor across navigations.
    pub fn set_zoom(&self, zoom: f64) -> wry::Result<()> {
        self.zoom.set(zoom);
        // WebKitGTK's zoom also makes up for the gap between GPUI's scale factor and
        // GTK's integer one, so the page zoom is applied on top of it.
        #[cfg(target_os = "linux")]
        linux::match_scale_factor(&self.webview, self.scale_factor.get(), zoom);
        #[cfg(not(target_os = "linux"))]
        self.webview.zoom(zoom)?;
        Ok(())
    }

    /// The page zoom last set with [`WebView::set_zoom`].
    pub fn zoom(&self) -> f64 {
        self.zoom.get()
    }

    /// Get the raw wry webview.
    pub fn raw(&self) -> &wry::WebView {
        &self.webview
    }

    /// Get an owned, UI-thread-local handle to the raw wry webview.
    pub fn handle(&self) -> WebViewHandle {
        WebViewHandle(self.webview.clone())
    }
}

impl Deref for WebView {
    type Target = wry::WebView;

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

impl Focusable for WebView {
    fn focus_handle(&self, _cx: &gpui::App) -> FocusHandle {
        self.focus_handle.clone()
    }
}

impl EventEmitter<DismissEvent> for WebView {}

impl Render for WebView {
    fn render(
        &mut self,
        window: &mut gpui::Window,
        cx: &mut gpui::Context<Self>,
    ) -> impl IntoElement {
        let view = cx.entity().clone();

        div()
            .track_focus(&self.focus_handle)
            .size_full()
            .child({
                let view = cx.entity().clone();
                canvas(
                    move |bounds, _, cx| view.update(cx, |r, _| r.bounds = bounds),
                    |_, _, _, _| {},
                )
                .absolute()
                .size_full()
            })
            .child(WebViewElement::new(self.webview.clone(), view, window, cx))
    }
}

/// A webview element can display a wry webview.
pub struct WebViewElement {
    parent: Entity<WebView>,
    view: Rc<wry::WebView>,
}

impl WebViewElement {
    /// Create a new webview element from a wry WebView.
    pub fn new(
        view: Rc<wry::WebView>,
        parent: Entity<WebView>,
        _window: &mut Window,
        _cx: &mut App,
    ) -> Self {
        Self { view, parent }
    }
}

impl IntoElement for WebViewElement {
    type Element = WebViewElement;

    fn into_element(self) -> Self::Element {
        self
    }
}

impl Element for WebViewElement {
    type RequestLayoutState = ();
    type PrepaintState = Option<Hitbox>;

    fn id(&self) -> Option<ElementId> {
        None
    }

    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
        None
    }

    fn request_layout(
        &mut self,
        _: Option<&GlobalElementId>,
        _: Option<&gpui::InspectorElementId>,
        window: &mut Window,
        cx: &mut App,
    ) -> (LayoutId, Self::RequestLayoutState) {
        let style = Style {
            size: Size::full(),
            flex_shrink: 1.,
            ..Default::default()
        };

        // If the parent view is no longer visible, we don't need to layout the webview
        let id = window.request_layout(style, [], cx);
        (id, ())
    }

    fn prepaint(
        &mut self,
        _: Option<&GlobalElementId>,
        _: Option<&gpui::InspectorElementId>,
        bounds: Bounds<Pixels>,
        _: &mut Self::RequestLayoutState,
        window: &mut Window,
        cx: &mut App,
    ) -> Self::PrepaintState {
        if !self.parent.read(cx).visible() {
            return None;
        }

        let parent = self.parent.read(cx);
        #[cfg(all(feature = "gpui-fast", any(target_os = "macos", target_os = "linux")))]
        if let Some(surface) = &parent.composition {
            surface.set_scale_factor(window.scale_factor());
        }
        #[cfg(target_os = "linux")]
        if parent.scale_factor.replace(window.scale_factor()) != window.scale_factor() {
            linux::match_scale_factor(&parent.webview, window.scale_factor(), parent.zoom.get());
        }
        #[cfg(target_os = "linux")]
        parent.origin.set(bounds.origin);
        let clip = window.content_mask().bounds;
        if let Err(error) = parent.set_geometry(bounds, clip) {
            if !parent.geometry_failed.replace(true) {
                log::warn!("WebView geometry update failed: {error:#}");
            }
            let _ = parent.set_native_visible(false);
            return None;
        }
        parent.geometry_failed.set(false);
        let visible = bounds.intersect(&clip);
        if visible.is_empty() {
            return None;
        }

        // The native view covers this area, so GPUI content below it must not receive input.
        Some(window.insert_hitbox(visible, gpui::HitboxBehavior::BlockMouse))
    }

    fn paint(
        &mut self,
        _: Option<&GlobalElementId>,
        _: Option<&gpui::InspectorElementId>,
        bounds: Bounds<Pixels>,
        _: &mut Self::RequestLayoutState,
        hitbox: &mut Self::PrepaintState,
        window: &mut Window,
        _: &mut App,
    ) {
        let bounds = hitbox.clone().map(|h| h.bounds).unwrap_or(bounds);
        window.with_content_mask(Some(ContentMask { bounds }), |window| {
            let webview = self.view.clone();
            window.on_mouse_event(move |event: &MouseDownEvent, _, _, _| {
                if !bounds.contains(&event.position) {
                    // Click white space to blur the input focus
                    let _ = webview.focus_parent();
                }
            });
        });
    }
}