bezel-browser 0.2.21

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
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
use crate::{ConsoleMessage, DataStore, LoadState, host::Surface};
use gpui::{AnyWindowHandle, App, Bounds, FocusHandle, Keystroke, Pixels, RenderImage, Window};
use std::{
    cell::{Cell, RefCell},
    rc::Rc,
    sync::Arc,
};

#[cfg_attr(target_os = "macos", path = "page/macos.rs")]
#[cfg_attr(target_os = "windows", path = "page/windows.rs")]
#[cfg_attr(
    not(any(target_os = "macos", target_os = "windows")),
    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")), 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),
    Console(ConsoleMessage),
    /// A still of the page, taken for a cover; `None` if the capture failed.
    Still(Option<Arc<RenderImage>>),
    /// The page was built, or failed to be, after the paint that asked for it.
    Built,
}

/// 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")), allow(dead_code))]
    url: RefCell<String>,
    #[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))]
    pub(crate) user_agent: RefCell<Option<String>>,
    #[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))]
    pub(crate) store: RefCell<DataStore>,
    #[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))]
    pub(crate) console: Cell<bool>,
    #[cfg(feature = "inspector")]
    #[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))]
    pub(crate) inspector: Cell<bool>,
    #[cfg(any(target_os = "macos", target_os = "windows"))]
    view: std::cell::OnceCell<Option<wry::WebView>>,
    /// A build is on its way; see [`Page::request`].
    #[cfg(any(target_os = "macos", target_os = "windows"))]
    building: Cell<bool>,
    /// 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")), allow(dead_code))]
    reports: async_channel::Sender<Report>,
    #[cfg_attr(not(any(target_os = "macos", target_os = "windows")), 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),
            store: RefCell::new(DataStore::default()),
            console: Cell::new(false),
            #[cfg(feature = "inspector")]
            inspector: Cell::new(false),
            #[cfg(any(target_os = "macos", target_os = "windows"))]
            view: std::cell::OnceCell::new(),
            #[cfg(any(target_os = "macos", target_os = "windows"))]
            building: Cell::new(false),
            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(this: &Rc<Self>, bounds: Bounds<Pixels>, window: &mut Window, cx: &mut App) {
        Page::place(this, bounds, window, cx);
    }

    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"))]
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);
    })();";

    /// Run in every frame. wry defines `window.ipc` in the main frame only on
    /// macOS, so this posts to the handler behind it. Each message is
    /// `{level, text}` as JSON.
    // TODO: whether `chrome.webview` exists in a WebView2 iframe is unchecked.
    const CONSOLE: &str = "(() => {
        const handler = window.webkit?.messageHandlers?.ipc ?? window.chrome?.webview;
        if (!handler) return;
        const text = (value) => {
            if (typeof value === 'string') return value;
            if (value instanceof Error) return value.stack || String(value);
            try {
                return JSON.stringify(value) ?? String(value);
            } catch {
                return String(value);
            }
        };
        const send = (level, values) => {
            try {
                handler.postMessage(JSON.stringify({ level, text: values.map(text).join(' ') }));
            } catch {}
        };
        for (const level of ['debug', 'log', 'info', 'warn', 'error']) {
            const original = console[level];
            console[level] = function (...values) {
                send(level, values);
                return original.apply(this, values);
            };
        }
        addEventListener('error', (event) => send('error', [event.error ?? event.message]));
        addEventListener('unhandledrejection', (event) =>
            send('error', ['Uncaught (in promise)', event.reason]));
    })();";

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

    /// Builds the page in a task of its own, between gpui updates, and reports
    /// [`Report::Built`] when it lands. The page is built hidden and shown by
    /// the next [`Page::place`].
    ///
    /// On Windows wry starts WebView2 by pumping the thread's messages, and a
    /// message that enters gpui while the `App` is borrowed aborts the process.
    fn request(this: &Rc<Self>, bounds: Bounds<Pixels>, window: &mut Window, cx: &mut App) {
        if this.building.replace(true) {
            return;
        }
        let page = this.clone();
        window
            .spawn(cx, async move |cx| {
                let Ok((handle, parent)) =
                    cx.update(|window, _| (window.window_handle(), Parent::of(window)))
                else {
                    return;
                };
                let view = parent.and_then(|parent| page.build(bounds, &parent));
                if view.is_some() {
                    page.window.set(Some(handle));
                }
                let _ = page.view.set(view);
                let _ = page.reports.try_send(Report::Built);
            })
            .detach();
    }

    fn build(&self, bounds: Bounds<Pixels>, parent: &Parent) -> 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 store = self.store.borrow().clone();
        let directory = store.directory.filter(|_| !store.incognito);
        let view = with_context(directory, |context| {
            let builder = match context {
                Some(context) => wry::WebViewBuilder::new_with_web_context(context),
                None => wry::WebViewBuilder::new(),
            };
            let builder = builder
                .with_incognito(store.incognito)
                .with_url(url.as_str())
                .with_bounds(rect(bounds))
                .with_visible(false)
                .with_initialization_script(Self::MOVED)
                .with_ipc_handler(move |request| {
                    let report = match request.body().as_str() {
                        "moved" => Report::Moved,
                        body => match logged(body, request.uri().to_string()) {
                            Some(message) => Report::Console(message),
                            None => 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 builder = if self.console.get() {
                builder.with_initialization_script_for_main_only(Self::CONSOLE, false)
            } else {
                builder
            };
            #[cfg(feature = "inspector")]
            let builder = builder.with_devtools(self.inspector.get());
            let builder = platform::store(builder, store.identifier);
            builder
                .build_as_child(parent)
                .inspect_err(|error| tracing::warn!(%error, url = %url, "webview: build"))
                .ok()
        })?;
        self.platform.attach(&view, &self.reports);
        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 can step back and forward; `(false, false)` before
    /// it is built.
    pub(crate) fn history(&self) -> (bool, bool) {
        self.built().map_or((false, false), |view| {
            (
                view.can_go_back().unwrap_or(false),
                view.can_go_forward().unwrap_or(false),
            )
        })
    }

    /// 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 reload_bypassing_cache(&self) {
        if let Some(view) = self.built() {
            platform::reload_bypassing_cache(view);
        }
    }

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

    #[cfg(feature = "inspector")]
    pub(crate) fn open_inspector(&self) {
        if let Some(view) = self.built() {
            platform::open_inspector(view);
        }
    }

    /// 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)
        });
    }
}

/// The native window a page is built in, by its raw handle: the build runs
/// while gpui's `Window` is not borrowed.
#[cfg(any(target_os = "macos", target_os = "windows"))]
struct Parent(raw_window_handle::RawWindowHandle);

#[cfg(any(target_os = "macos", target_os = "windows"))]
impl Parent {
    fn of(window: &Window) -> Option<Self> {
        raw_window_handle::HasWindowHandle::window_handle(window)
            .ok()
            .map(|handle| Self(handle.as_raw()))
    }
}

#[cfg(any(target_os = "macos", target_os = "windows"))]
impl raw_window_handle::HasWindowHandle for Parent {
    fn window_handle(
        &self,
    ) -> Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError> {
        // SAFETY: read from a gpui window on this thread in the update just
        // before the build. On macOS nothing runs between the two. On Windows
        // the messages WebView2's start pumps can close the window, and a
        // destroyed HWND fails the build.
        Ok(unsafe { raw_window_handle::WindowHandle::borrow_raw(self.0) })
    }
}

/// A console message the [`Page::CONSOLE`] script posted from `source`.
#[cfg(any(target_os = "macos", target_os = "windows"))]
fn logged(body: &str, source: String) -> Option<ConsoleMessage> {
    #[derive(serde::Deserialize)]
    struct Logged {
        level: String,
        text: String,
    }
    let Logged { level, text } = serde_json::from_str(body).ok()?;
    use crate::ConsoleLevel;
    let level = match level.as_str() {
        "debug" => ConsoleLevel::Debug,
        "log" => ConsoleLevel::Log,
        "info" => ConsoleLevel::Info,
        "warn" => ConsoleLevel::Warn,
        "error" => ConsoleLevel::Error,
        _ => return None,
    };
    Some(ConsoleMessage {
        level,
        text,
        source,
    })
}

/// Runs `build` with the context for `directory`, or with none, which has wry
/// make the page its own.
#[cfg(any(target_os = "macos", target_os = "windows"))]
fn with_context<T>(
    directory: Option<std::path::PathBuf>,
    build: impl FnOnce(Option<&mut wry::WebContext>) -> T,
) -> T {
    match directory {
        Some(directory) => shared_context(Some(directory), |context| build(Some(context))),
        None => build(None),
    }
}

/// Runs `f` with the context for `directory`, `None` being the platform's
/// default store. A context lives as long as the thread: pages built with it
/// hold on to it.
#[cfg(any(target_os = "macos", target_os = "windows"))]
fn shared_context<T>(
    directory: Option<std::path::PathBuf>,
    f: impl FnOnce(&mut wry::WebContext) -> T,
) -> T {
    thread_local! {
        static CONTEXTS: RefCell<
            std::collections::HashMap<Option<std::path::PathBuf>, wry::WebContext>,
        > = RefCell::default();
    }
    CONTEXTS.with_borrow_mut(|contexts| {
        let context = contexts
            .entry(directory.clone())
            .or_insert_with(|| wry::WebContext::new(directory));
        f(context)
    })
}

/// Clears `store`, calling `done` with whether it was cleared.
pub(crate) fn clear_store(store: &DataStore, done: impl FnOnce(bool) + Send + 'static) {
    platform::clear_store(store, done);
}

/// Reports what `store` holds, calling `done` with `None` where the platform
/// cannot tell.
pub(crate) fn store_usage(
    store: &DataStore,
    done: impl FnOnce(Option<crate::Usage>) + Send + 'static,
) {
    platform::store_usage(store, done);
}

#[cfg(any(target_os = "macos", target_os = "windows"))]
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(),
    }
}

#[cfg(all(test, any(target_os = "macos", target_os = "windows")))]
mod tests {
    use super::logged;
    use crate::ConsoleLevel;

    #[test]
    fn reads_a_posted_message() {
        let message = logged(
            r#"{"level":"warn","text":"low disk"}"#,
            "https://a.test/".into(),
        );
        let message = message.expect("a console message");
        assert_eq!(message.level, ConsoleLevel::Warn);
        assert_eq!(message.text, "low disk");
        assert_eq!(message.source, "https://a.test/");
    }

    #[test]
    fn ignores_what_is_not_one() {
        assert!(logged("moved", String::new()).is_none());
        assert!(logged(r#"{"level":"trace","text":""}"#, String::new()).is_none());
    }
}