bezel-browser 0.2.3

A platform webview hosted in a gpui window
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
use crate::{LoadState, host::Surface};
use gpui::{AnyWindowHandle, App, Bounds, FocusHandle, Keystroke, Pixels, RenderImage, Window};
use std::{
    cell::{Cell, RefCell},
    sync::Arc,
};

#[cfg_attr(target_os = "macos", path = "page/macos.rs")]
#[cfg_attr(target_os = "windows", path = "page/windows.rs")]
#[cfg_attr(target_os = "linux", path = "page/linux.rs")]
#[cfg_attr(
    not(any(target_os = "macos", target_os = "windows", target_os = "linux")),
    path = "page/stub.rs"
)]
mod platform;

/// Sent from the page's callbacks to the view.
#[cfg_attr(
    not(any(target_os = "macos", target_os = "windows", target_os = "linux")),
    allow(dead_code)
)]
pub(crate) enum Report {
    Pressed,
    /// A key the page took that the keymap binds.
    #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
    Key(Keystroke),
    /// The page moved its own history; its URL is read back from the page.
    Moved,
    Load(LoadState, String),
    Title(String),
    /// The page asked for a window of its own, for this URL.
    Opened(String),
    /// A still of the page, taken for a cover; `None` if the capture failed.
    Still(Option<Arc<RenderImage>>),
}

/// Whether something is painted over the page.
enum Cover {
    Off,
    /// The page is still up while its still is taken. A parked page captures
    /// blank.
    Capturing,
    /// The page is parked, and the still, if any, is painted in its place.
    On(Option<Arc<RenderImage>>),
}

/// Edits a WKWebView takes as responder actions (`copy:`, `paste:`) and only
/// through them: without an Edit menu, cmd-c in the page copies nothing.
#[derive(Clone, Copy)]
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) enum Edit {
    Copy,
    Cut,
    Paste,
    SelectAll,
    Undo,
    Redo,
}

pub(crate) struct Page {
    /// What the page is built with; unread once it is built.
    #[cfg_attr(
        not(any(target_os = "macos", target_os = "windows", target_os = "linux")),
        allow(dead_code)
    )]
    url: RefCell<String>,
    #[cfg_attr(
        not(any(target_os = "macos", target_os = "windows", target_os = "linux")),
        allow(dead_code)
    )]
    pub(crate) user_agent: RefCell<Option<String>>,
    #[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
    view: std::cell::OnceCell<Option<wry::WebView>>,
    /// Where the page last sat; `None` before the first paint and while parked.
    placed: Cell<Option<Bounds<Pixels>>>,
    /// The window the page is in; `None` before the first paint.
    window: Cell<Option<AnyWindowHandle>>,
    owner: Cell<u64>,
    cover: RefCell<Cover>,
    /// A still painted before the page was uncovered, to free from the atlas.
    dropped: RefCell<Option<Arc<RenderImage>>>,
    pub(crate) focus: FocusHandle,
    #[cfg_attr(
        not(any(target_os = "macos", target_os = "windows", target_os = "linux")),
        allow(dead_code)
    )]
    reports: async_channel::Sender<Report>,
    #[cfg_attr(
        not(any(target_os = "macos", target_os = "windows", target_os = "linux")),
        allow(dead_code)
    )]
    platform: platform::State,
}

impl Page {
    /// Whether the view binds the edit keys to [`Edit`]s.
    pub(crate) const BINDS_EDITS: bool = platform::BINDS_EDITS;

    pub(crate) fn new(
        url: String,
        focus: FocusHandle,
        reports: async_channel::Sender<Report>,
        cx: &App,
    ) -> Self {
        Self {
            url: RefCell::new(url),
            user_agent: RefCell::new(None),
            #[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
            view: std::cell::OnceCell::new(),
            placed: Cell::new(None),
            window: Cell::new(None),
            owner: Cell::new(0),
            cover: RefCell::new(Cover::Off),
            dropped: RefCell::new(None),
            focus,
            reports,
            platform: platform::State::new(cx),
        }
    }
}

impl Surface for Page {
    fn focus(&self) -> Option<&FocusHandle> {
        Some(&self.focus)
    }

    fn owner(&self) -> &Cell<u64> {
        &self.owner
    }

    fn place(&self, bounds: Bounds<Pixels>, window: &Window) {
        Page::place(self, bounds, window);
    }

    fn park(&self) {
        Page::park(self);
    }

    fn cover(&self) {
        if !matches!(*self.cover.borrow(), Cover::Off) {
            return;
        }
        if self.placed.get().is_some() && self.capture() {
            *self.cover.borrow_mut() = Cover::Capturing;
        } else {
            Page::park(self);
            *self.cover.borrow_mut() = Cover::On(None);
        }
    }

    fn still(&self) -> Option<Arc<RenderImage>> {
        match &*self.cover.borrow() {
            Cover::On(still) => still.clone(),
            Cover::Off | Cover::Capturing => None,
        }
    }

    fn take_dropped(&self) -> Option<Arc<RenderImage>> {
        self.dropped.take()
    }
}

impl Page {
    /// Parks the page for the still if it is still covered.
    pub(crate) fn captured(&self, still: Option<Arc<RenderImage>>) {
        if matches!(*self.cover.borrow(), Cover::Capturing) {
            Page::park(self);
            *self.cover.borrow_mut() = Cover::On(still);
        }
    }

    /// The window the page is in; `None` before the first paint.
    pub(crate) fn window(&self) -> Option<AnyWindowHandle> {
        self.window.get()
    }

    /// Run before the page is placed.
    fn uncover(&self) {
        if let Cover::On(still) = self.cover.replace(Cover::Off) {
            *self.dropped.borrow_mut() = still;
        }
    }
}

#[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
impl Page {
    /// Where a parked page waits. Hidden alone, a WKWebView stays registered as
    /// a drag destination over its last rect and takes every drag that crosses
    /// it.
    const PARKED: f64 = -20_000.0;

    /// Run in the main frame, where wry defines `window.ipc`.
    const MOVED: &str = "(() => {
        const moved = () => window.ipc.postMessage('moved');
        for (const name of ['pushState', 'replaceState']) {
            const original = history[name];
            history[name] = function (...args) {
                const result = original.apply(this, args);
                moved();
                return result;
            };
        }
        addEventListener('popstate', moved);
        addEventListener('hashchange', moved);
    })();";

    fn place(&self, bounds: Bounds<Pixels>, window: &Window) {
        self.uncover();
        let view = self.view.get_or_init(|| self.build(bounds, window));
        let Some(view) = view else { return };
        if self.window.get() != Some(window.window_handle()) {
            self.give_keys();
            self.platform.parked();
            if !platform::reparent(view, window) {
                return;
            }
            self.window.set(Some(window.window_handle()));
            self.placed.set(None);
        }
        let placed = self.placed.get();
        if placed == Some(bounds) {
            return;
        }
        let _ = view.set_bounds(rect(bounds));
        let _ = view.set_visible(true);
        self.placed.set(Some(bounds));
        if placed.is_none() && self.focus.is_focused(window) {
            self.take_keys();
        }
    }

    fn build(&self, bounds: Bounds<Pixels>, window: &Window) -> Option<wry::WebView> {
        let url = self.url.borrow();
        let (ipc, loads, titles, opened) = (
            self.reports.clone(),
            self.reports.clone(),
            self.reports.clone(),
            self.reports.clone(),
        );
        let builder = wry::WebViewBuilder::new()
            .with_url(url.as_str())
            .with_bounds(rect(bounds))
            .with_initialization_script(Self::MOVED)
            .with_ipc_handler(move |request| {
                let report = match request.body().as_str() {
                    "moved" => Report::Moved,
                    _ => return,
                };
                let _ = ipc.try_send(report);
            })
            .with_on_page_load_handler(move |event, url| {
                let state = match event {
                    wry::PageLoadEvent::Started => LoadState::Started,
                    wry::PageLoadEvent::Finished => LoadState::Finished,
                };
                let _ = loads.try_send(Report::Load(state, url));
            })
            .with_document_title_changed_handler(move |title| {
                let _ = titles.try_send(Report::Title(title));
            })
            .with_new_window_req_handler(move |url, _| {
                let _ = opened.try_send(Report::Opened(url));
                wry::NewWindowResponse::Deny
            });
        let user_agent = self
            .user_agent
            .borrow()
            .clone()
            .or_else(platform::default_user_agent);
        let builder = match user_agent {
            Some(user_agent) => builder.with_user_agent(user_agent),
            None => builder,
        };
        let view = platform::build(builder, window)?
            .inspect_err(|error| tracing::warn!(%error, url = %url, "webview: build"))
            .ok()?;
        self.platform.attach(&view, &self.reports);
        self.window.set(Some(window.window_handle()));
        Some(view)
    }

    fn built(&self) -> Option<&wry::WebView> {
        self.view.get()?.as_ref()
    }

    /// Whether a still was asked for; it arrives as [`Report::Still`].
    fn capture(&self) -> bool {
        let Some(view) = self.built() else {
            return false;
        };
        let reports = self.reports.clone();
        platform::capture(view, move |still| {
            let _ = reports.try_send(Report::Still(still));
        })
    }

    pub(crate) fn start(window: &Window, cx: &mut App) {
        platform::start(window, cx);
    }

    pub(crate) fn watch_keys(&self, window: &Window) {
        self.platform.watch_keys(window);
    }

    pub(crate) fn back(&self) {
        if let Some(view) = self.built() {
            platform::back(view);
        }
    }

    pub(crate) fn forward(&self) {
        if let Some(view) = self.built() {
            platform::forward(view);
        }
    }

    /// Whether the page, or a view inside it, holds keyboard focus.
    pub(crate) fn holds_keys(&self) -> bool {
        self.built()
            .is_some_and(|view| self.platform.holds_keys(view))
    }

    pub(crate) fn edit(&self, edit: Edit) {
        if self.holds_keys() {
            platform::edit(edit);
        }
    }

    pub(crate) fn load(&self, url: String) {
        match self.built() {
            Some(view) => {
                let _ = view.load_url(&url);
            }
            None => *self.url.borrow_mut() = url,
        }
    }

    pub(crate) fn reload(&self) {
        if let Some(view) = self.built() {
            let _ = view.reload();
        }
    }

    pub(crate) fn location(&self) -> Option<String> {
        self.built()?.url().ok()
    }

    /// Whether the script was handed to the page.
    pub(crate) fn eval(&self, script: &str, done: impl Fn(String) + Send + 'static) -> bool {
        self.built()
            .is_some_and(|view| view.evaluate_script_with_callback(script, done).is_ok())
    }

    pub(crate) fn take_keys(&self) {
        let Some(view) = self.built() else {
            return;
        };
        if self.placed.get().is_some() && !platform::closed(view) {
            let _ = view.focus();
        }
    }

    /// Hands keyboard focus back to gpui's view if the page holds it.
    pub(crate) fn give_keys(&self) {
        if let Some(view) = self.built()
            && self.holds_keys()
        {
            platform::give_keys(view);
        }
    }

    fn park(&self) {
        let Some(view) = self.built() else {
            return;
        };
        let Some(bounds) = self.placed.take() else {
            return;
        };
        self.give_keys();
        self.platform.parked();
        let _ = view.set_visible(false);
        if platform::closed(view) {
            return;
        }
        // At its own size, so the page does not lay out again for a viewport
        // nobody sees.
        let _ = view.set_bounds(wry::Rect {
            position: wry::dpi::LogicalPosition::new(Self::PARKED, Self::PARKED).into(),
            ..rect(bounds)
        });
    }
}

#[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
fn rect(bounds: Bounds<Pixels>) -> wry::Rect {
    wry::Rect {
        position: wry::dpi::LogicalPosition::new(
            f64::from(f32::from(bounds.origin.x)),
            f64::from(f32::from(bounds.origin.y)),
        )
        .into(),
        size: wry::dpi::LogicalSize::new(
            f64::from(f32::from(bounds.size.width)),
            f64::from(f32::from(bounds.size.height)),
        )
        .into(),
    }
}