Skip to main content

egui_pop_views/viewer/
embed.rs

1//! The viewer's YouTube page (ADR 0017): a YouTube link played in a web view,
2//! through an [`EmbedBackend`].
3//!
4//! The backend is wry over WebKitGTK with the `webview` feature on Linux, none
5//! elsewhere or without it (YouTube links then open outside, as any web video;
6//! the policy asks [`Viewer::plays_web_video`]). What is here knows nothing of
7//! wry, so a host can give its own web view and a test a pretend one.
8//!
9//! - **What loads**: YouTube's privacy-enhanced player,
10//!   `https://www.youtube-nocookie.com/embed/<id>`, as the page itself, its
11//!   request carrying a `Referer` that names the application, as YouTube's
12//!   Required Minimum Functionality asks of desktop applications:
13//!   `https://<app id>/` ([`referrer_for`], the id of
14//!   `AppBuilder::app_id`), or the [`ViewerPlugin`](super::ViewerPlugin)'s
15//!   [`embed_referrer`](super::ViewerPlugin::embed_referrer). Without either,
16//!   YouTube links open outside. Nothing else loads in it: a link the player
17//!   follows (its title, "Watch on YouTube") goes through the links service,
18//!   outside.
19//! - **Its size**: YouTube's player needs at least [`MIN_PLAYER`] pixels each
20//!   way ([`fits_player`]). A panel smaller than that shows a card with Open
21//!   outside in place of the web view, which opens (from the start) once the
22//!   panel is large enough again; a window of its own is kept at least that
23//!   large by the backend.
24//! - **Nothing over it**: the page draws nothing on the player's place but a
25//!   background and a word under the web view, which covers them.
26//! - **Where**: inside the panel when the panel is in the main window and that
27//!   window is an X11 one (a child window over the panel's rectangle, following
28//!   it as it moves and resizes); in a window of its own otherwise (Wayland, a
29//!   detached panel). A child web view is a native window above egui: egui's
30//!   popups over the panel are drawn under it.
31//! - **Its loop**: a web view needs its toolkit's loop turned on the interface's
32//!   thread; the page asks for a pass every [`PUMP`] while a web view is open and
33//!   turns that loop once per pass, without blocking.
34//! - **Stopping**: leaving the page closes the web view. So does a panel no
35//!   longer drawn (closed, or a tab behind another), or the user closing its own
36//!   window: drawing the page again opens it again, from the start.
37//! - **On the bus** (ADR 0029): the web view is a native window of the
38//!   registry (`web-view:<n>`, [`WEB_VIEW_PREFIX`]), owned by the viewer, a
39//!   child of the window its page is drawn in. It opens by its `pop.window.open`
40//!   (`AppHandle::request_native_open`), asked before the backend is, and each
41//!   place it is dropped (its page left or hidden, a panel too small, a
42//!   failure, its own window closed, its page drawn in another window) asks
43//!   its `pop.window.close`. The viewer's local listener on `pop.window.close`
44//!   ([`WEB_VIEW_LISTENER`]) drops it in that call, on the interface's thread:
45//!   its window closing closes it first (`parent-closed`), none left behind.
46
47use std::sync::Arc;
48use std::time::Duration;
49
50use egui::{Align2, Rect, Sense, Ui, vec2};
51use egui_pop_api::AppHandle;
52use egui_pop_api::bus::bus_contract::{ListenOpts, Point as _};
53use egui_pop_api::bus::{CHILDREN, FOCUS, Reason, WindowClose, WindowKind, WindowRequest};
54use egui_pop_api::links::{self, How, Request, Source};
55use egui_pop_api::strings as api_txt;
56use egui_pop_core::icon::{Icon, Size, Tone};
57use egui_pop_core::lock;
58use egui_pop_core::strings::{tr, tr_args, tr_with};
59use egui_pop_core::theme::Tokens;
60use serde_json::{Value as Json, json};
61
62use super::{Failure, PLUGIN, Status, Viewer};
63use crate::strings as txt;
64
65/// The `Referer` the web view sent before it named the application.
66#[deprecated(
67    since = "0.4.2",
68    note = "the `Referer` names the application (`referrer_for`, `AppBuilder::app_id`): YouTube's terms rule out a shared one"
69)]
70pub const DEFAULT_REFERRER: &str = "https://localhost/";
71/// The smallest side of YouTube's player, in its own (CSS) pixels: its
72/// Required Minimum Functionality asks for a viewport of at least 200 by 200.
73pub const MIN_PLAYER: f32 = 200.0;
74/// How often the web view's loop is turned while it is open.
75pub const PUMP: Duration = Duration::from_millis(15);
76/// The viewer's local listener on `pop.window.close`: the web view of that
77/// native window is dropped, whoever asked (its page left, its window
78/// closing, among others).
79pub const WEB_VIEW_LISTENER: &str = "pop.viewer.web_view";
80/// A web view's id in the registry: `web-view:<n>`.
81pub const WEB_VIEW_PREFIX: &str = "web-view:";
82/// The application's passes without the page before its panel counts as
83/// hidden: a pass may run before the panel is drawn in it.
84const HIDDEN_PASSES: u32 = 3;
85
86/// The player's address for a YouTube video: the privacy-enhanced host, the
87/// video starting on its own.
88pub fn embed_url(id: &str) -> String {
89    format!("https://www.youtube-nocookie.com/embed/{id}?autoplay=1&playsinline=1&rel=0")
90}
91
92/// The `Referer` naming the application of id `app_id` (`org.example.App`),
93/// as YouTube asks of an application: an `https` URL whose domain is the
94/// application's id, `https://org.example.app/`. None for an empty id or one
95/// that cannot be a domain name.
96pub fn referrer_for(app_id: &str) -> Option<String> {
97    let id = app_id.trim();
98    let valid = !id.is_empty()
99        && !id.starts_with('.')
100        && !id.ends_with('.')
101        && !id.contains("..")
102        && id
103            .chars()
104            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_'));
105    valid.then(|| format!("https://{}/", id.to_ascii_lowercase()))
106}
107
108/// Whether a player of `physical` pixels meets YouTube's minimum
109/// ([`MIN_PLAYER`] each way). `native_pixels_per_point` is the system's
110/// scale: the web view's pixels are the window's physical pixels divided by
111/// it, so a 2x screen needs 400 physical pixels. Both counts must reach the
112/// minimum.
113pub fn fits_player(physical: egui::Vec2, native_pixels_per_point: f32) -> bool {
114    let scale = native_pixels_per_point.max(1.0);
115    physical.min_elem() / scale >= MIN_PLAYER
116}
117
118/// Where a web view goes.
119#[derive(Clone, Copy, Debug, PartialEq)]
120pub struct Placement {
121    /// In the window's physical pixels, from its inner top-left corner.
122    pub rect: Rect,
123    /// The main window's X11 id when the page is drawn in it: the web view is
124    /// made its child. None: a window of its own.
125    pub parent_x11: Option<u64>,
126}
127
128/// What a backend is asked to open.
129#[derive(Clone, Debug)]
130pub struct EmbedRequest {
131    /// The page to load ([`embed_url`]).
132    pub url: String,
133    /// The `Referer` its request carries.
134    pub referrer: String,
135    /// The title of its own window, when it has one.
136    pub title: String,
137    pub place: Placement,
138    /// For the backend to ask for a pass.
139    pub egui: egui::Context,
140}
141
142/// A web view open. A failure's text is shown on the error page.
143pub trait Embedded: Send {
144    /// Moves and sizes it (a child; its own window ignores this).
145    fn place(&mut self, place: &Placement) -> Result<(), String>;
146    /// Turns the web view's loop once, without blocking.
147    fn pump(&mut self) -> Result<(), String>;
148    /// Whether it is in a window of its own.
149    fn own_window(&self) -> bool;
150    /// Whether the user closed its own window.
151    fn closed(&self) -> bool;
152    /// The addresses it was asked to go to and did not: opened outside, through
153    /// the links service.
154    fn take_links(&mut self) -> Vec<String>;
155}
156
157/// What opens web views for the viewer ([`ViewerPlugin::web_video`](super::ViewerPlugin::web_video)).
158pub trait EmbedBackend: Send + Sync {
159    /// Its name, in `viewer.state`.
160    fn name(&self) -> &str;
161    /// Whether a web view opened at `place` sits over the panel, so that the
162    /// panel's place is the player's size (checked against [`MIN_PLAYER`]);
163    /// false: a window of its own, which the backend keeps at least
164    /// [`MIN_PLAYER`] each way. By default: a child of an X11 window.
165    fn in_panel(&self, place: &Placement) -> bool {
166        place.parent_x11.is_some()
167    }
168    /// A web view loading the request's page, or why not. It closes when
169    /// dropped.
170    fn open(&self, request: &EmbedRequest) -> Result<Box<dyn Embedded>, String>;
171}
172
173/// The backend of this build.
174pub(super) fn default_backend() -> Option<Arc<dyn EmbedBackend>> {
175    #[cfg(all(feature = "webview", target_os = "linux"))]
176    {
177        Some(Arc::new(super::wry_view::Wry))
178    }
179    #[cfg(not(all(feature = "webview", target_os = "linux")))]
180    {
181        None
182    }
183}
184
185/// The YouTube page's state.
186struct Session {
187    target: String,
188    id: String,
189    /// None before the page is first drawn, while its panel is hidden, and
190    /// once its own window was closed.
191    view: Option<Box<dyn Embedded>>,
192    own_window: bool,
193    /// The user closed its own window: it opens again on a click only.
194    closed: bool,
195    /// Its native window's registry id, from its `pop.window.open` until its
196    /// `pop.window.close`.
197    bus: Option<String>,
198    /// The registry window it is a child of.
199    parent: Option<String>,
200    /// Passes since the page was last drawn.
201    unseen: u32,
202    /// The panel is too small for the player: the card shows.
203    small: bool,
204}
205
206/// The viewer's web view state: the backend, the referrer, the page.
207pub(super) struct Embed {
208    backend: Option<Arc<dyn EmbedBackend>>,
209    /// None: the application has no id, YouTube links open outside.
210    referrer: Option<String>,
211    session: Option<Session>,
212    /// The last web view's number in the registry.
213    opened: u64,
214}
215
216impl Embed {
217    pub(super) fn new(backend: Option<Arc<dyn EmbedBackend>>) -> Self {
218        Self {
219            backend,
220            referrer: None,
221            session: None,
222            opened: 0,
223        }
224    }
225
226    pub(super) fn set_backend(&mut self, backend: Option<Arc<dyn EmbedBackend>>) {
227        self.backend = backend;
228    }
229
230    pub(super) fn has_backend(&self) -> bool {
231        self.backend.is_some()
232    }
233
234    pub(super) fn set_referrer(&mut self, referrer: Option<String>) {
235        self.referrer = referrer;
236    }
237}
238
239impl Viewer {
240    /// Whether YouTube links open here: a web view backend is there, and a
241    /// `Referer` naming the application (its id, or
242    /// [`ViewerPlugin::embed_referrer`](super::ViewerPlugin::embed_referrer)).
243    pub fn plays_web_video(&self) -> bool {
244        let e = lock(&self.embed);
245        e.backend.is_some() && e.referrer.is_some()
246    }
247
248    /// Replaces what opens web views (none: YouTube links open outside).
249    pub fn set_embed_backend(&self, backend: Option<Arc<dyn EmbedBackend>>) {
250        lock(&self.embed).set_backend(backend);
251    }
252
253    /// Shows the YouTube page; its web view opens when the page is drawn.
254    pub(super) fn open_embed(&self, app: &AppHandle, target: &str, id: String) {
255        lock(&self.embed).session = Some(Session {
256            target: target.to_string(),
257            id: id.clone(),
258            view: None,
259            own_window: false,
260            closed: false,
261            bus: None,
262            parent: None,
263            unseen: 0,
264            small: false,
265        });
266        let page = Arc::new(super::Page {
267            target: target.to_string(),
268            content: super::Content::YouTube(id),
269            html: false,
270            dropped: Vec::new(),
271        });
272        {
273            let mut i = lock(&self.inner);
274            i.status = Status::Shown(page);
275            i.restore = None;
276            i.scroll_to = None;
277            i.find.matches.clear();
278            i.find.at = 0;
279        }
280        app.publish(
281            PLUGIN.as_str(),
282            None,
283            "viewer.shown",
284            json!({ "target": target, "kind": "youtube" }),
285        );
286    }
287
288    /// Leaves the YouTube page: the web view closes, by its `pop.window.close`
289    /// for `reason`.
290    pub(super) fn stop_embed(&self, app: &AppHandle, reason: Reason) {
291        self.close_web_view(app, reason);
292        let session = lock(&self.embed).session.take();
293        drop(session);
294    }
295
296    fn embed_failed(&self, app: &AppHandle, target: &str, detail: &str) {
297        self.stop_embed(app, Reason::System);
298        self.fail(app, target, Failure::Playback, detail);
299    }
300
301    /// Asks the `pop.window.close` of the web view's native window, if one is
302    /// open: the viewer's listener drops the view in that call. Whether a
303    /// view was open.
304    fn close_web_view(&self, app: &AppHandle, reason: Reason) -> bool {
305        let (window, parent, had) = {
306            let e = lock(&self.embed);
307            let Some(s) = e.session.as_ref() else {
308                return false;
309            };
310            let Some(window) = s.bus.clone() else {
311                return false;
312            };
313            (window, s.parent.clone(), s.view.is_some())
314        };
315        let mut req = WindowRequest::new(window, WindowKind::Native, PLUGIN.as_str(), reason);
316        req.parent = parent;
317        if !app.request_window_close(req) {
318            log::warn!(target: "egui_pop", "viewer: the web view's `pop.window.close` did not close it");
319        }
320        had
321    }
322
323    /// [`WEB_VIEW_LISTENER`] on a native window closing: the web view of that
324    /// window, if it is this page's, is dropped in this call.
325    fn drop_on_close(&self, req: &WindowRequest, did: &mut Vec<String>) {
326        let dropped = {
327            let mut e = lock(&self.embed);
328            let Some(s) = e.session.as_mut() else {
329                return;
330            };
331            if s.bus.as_deref() != Some(req.window.as_str()) {
332                return;
333            }
334            s.bus = None;
335            s.parent = None;
336            s.view.take()
337        };
338        let had = dropped.is_some();
339        drop(dropped);
340        if had {
341            did.push(format!(
342                "{WEB_VIEW_LISTENER}: web view closed ({})",
343                req.reason.as_str()
344            ));
345        }
346    }
347
348    /// Once per pass of the application: turns the web view's loop, opens
349    /// outside what it was asked to go to, closes it when its page is no
350    /// longer drawn.
351    pub(super) fn embed_pass(&self, app: &AppHandle) {
352        let (failed, links, hidden, user_closed) = {
353            let mut e = lock(&self.embed);
354            let Some(s) = e.session.as_mut() else {
355                return;
356            };
357            let Some(view) = s.view.as_mut() else {
358                return;
359            };
360            s.unseen += 1;
361            if s.unseen >= HIDDEN_PASSES {
362                (None, Vec::new(), true, false)
363            } else {
364                let failed = view.pump().err().map(|e| (s.target.clone(), e));
365                let links = view.take_links();
366                let user_closed = failed.is_none() && view.closed();
367                if user_closed {
368                    s.closed = true;
369                }
370                (failed, links, false, user_closed)
371            }
372        };
373        if hidden {
374            self.close_web_view(app, Reason::Command);
375            app.publish(PLUGIN.as_str(), None, "viewer.embed_stopped", json!({}));
376            return;
377        }
378        if user_closed {
379            self.close_web_view(app, Reason::User);
380        }
381        for url in links {
382            links::open(
383                app,
384                Request::new(&url).source(Source::Content).how(How::Outside),
385            );
386        }
387        if let Some((target, e)) = failed {
388            return self.embed_failed(app, &target, &e);
389        }
390        if lock(&self.embed)
391            .session
392            .as_ref()
393            .is_some_and(|s| s.view.is_some())
394        {
395            app.egui().request_repaint_after(PUMP);
396        }
397    }
398
399    /// The page is drawn at `place`: its web view opened (again) or moved
400    /// there. False: the panel is too small for the player (the card shows,
401    /// the web view is closed).
402    fn embed_in_view(
403        &self,
404        app: &AppHandle,
405        place: Placement,
406        parent: String,
407        native_ppp: f32,
408    ) -> bool {
409        // Drawn in another window: closed there, opened again in this one.
410        let moved = lock(&self.embed)
411            .session
412            .as_ref()
413            .is_some_and(|s| s.bus.is_some() && s.parent.as_deref() != Some(parent.as_str()));
414        if moved {
415            self.close_web_view(app, Reason::Command);
416        }
417        let open = {
418            let mut e = lock(&self.embed);
419            let referrer = e.referrer.clone();
420            let backend = e.backend.clone();
421            let Some(s) = e.session.as_mut() else {
422                return true;
423            };
424            s.unseen = 0;
425            let in_panel = backend.as_ref().is_some_and(|b| b.in_panel(&place));
426            let small = in_panel && !fits_player(place.rect.size(), native_ppp);
427            let was_small = std::mem::replace(&mut s.small, small);
428            if small {
429                let target = s.target.clone();
430                drop(e);
431                let had = self.close_web_view(app, Reason::Command);
432                if !was_small {
433                    app.publish(
434                        PLUGIN.as_str(),
435                        None,
436                        "viewer.embed_too_small",
437                        json!({ "target": target, "closed": had }),
438                    );
439                }
440                return false;
441            }
442            match s.view.as_mut() {
443                Some(view) => {
444                    if let Err(err) = view.place(&place) {
445                        Some(Err((s.target.clone(), err)))
446                    } else {
447                        None
448                    }
449                }
450                None if s.closed => None,
451                None => Some(Ok((s.target.clone(), s.id.clone(), referrer, backend))),
452            }
453        };
454        match open {
455            None => {}
456            Some(Err((target, e))) => self.embed_failed(app, &target, &e),
457            Some(Ok((target, id, referrer, backend))) => {
458                let Some(backend) = backend else {
459                    self.embed_failed(app, &target, "this application has no web view");
460                    return true;
461                };
462                let Some(referrer) = referrer else {
463                    self.embed_failed(app, &target, "this application has no id to give YouTube");
464                    return true;
465                };
466                // Its native window first: the registry holds it before the
467                // backend is asked.
468                let window = {
469                    let mut e = lock(&self.embed);
470                    e.opened += 1;
471                    format!("{WEB_VIEW_PREFIX}{}", e.opened)
472                };
473                let req = WindowRequest::new(
474                    window.clone(),
475                    WindowKind::Native,
476                    PLUGIN.as_str(),
477                    Reason::Command,
478                )
479                .parent(parent.clone());
480                if !app.request_native_open(req) {
481                    self.embed_failed(app, &target, "its window could not open");
482                    return true;
483                }
484                if let Some(s) = lock(&self.embed).session.as_mut() {
485                    s.bus = Some(window);
486                    s.parent = Some(parent);
487                }
488                let request = EmbedRequest {
489                    url: embed_url(&id),
490                    referrer,
491                    title: format!("YouTube: {id}"),
492                    place,
493                    egui: app.egui(),
494                };
495                match backend.open(&request) {
496                    Ok(view) => {
497                        let mut e = lock(&self.embed);
498                        let kept = match e.session.as_mut() {
499                            Some(s) if s.bus.is_some() => {
500                                s.own_window = view.own_window();
501                                s.view = Some(view);
502                                None
503                            }
504                            // Closed while it opened: it goes.
505                            _ => Some(view),
506                        };
507                        drop(e);
508                        drop(kept);
509                        app.publish(
510                            PLUGIN.as_str(),
511                            None,
512                            "viewer.embed_opened",
513                            json!({ "target": target, "own_window": place.parent_x11.is_none() }),
514                        );
515                        app.egui().request_repaint_after(PUMP);
516                    }
517                    Err(e) => self.embed_failed(app, &target, &e),
518                }
519            }
520        }
521        true
522    }
523
524    /// Opens again the web view whose own window the user closed.
525    pub fn embed_reopen(&self, app: &AppHandle) {
526        if let Some(s) = lock(&self.embed).session.as_mut() {
527            s.closed = false;
528        }
529        app.egui().request_repaint();
530    }
531
532    /// What the page holds, for `viewer.state`: null without a YouTube page.
533    pub(super) fn embed_state(&self) -> Json {
534        let e = lock(&self.embed);
535        let Some(s) = e.session.as_ref() else {
536            return Json::Null;
537        };
538        json!({
539            "backend": e.backend.as_ref().map(|b| b.name().to_string()),
540            "id": s.id,
541            "url": embed_url(&s.id),
542            "referrer": e.referrer,
543            "open": s.view.is_some(),
544            "own_window": s.own_window,
545            "closed": s.closed,
546            "too_small": s.small,
547            "min": MIN_PLAYER,
548        })
549    }
550}
551
552/// Draws the page: the web view's place, 16:9 in the panel and at least
553/// [`MIN_PLAYER`] tall when the panel allows, the web view put over it (or a
554/// word saying it is in its own window); a card with Open outside when the
555/// panel is too small for the player. True: Open outside was clicked.
556pub(super) fn draw(ui: &mut Ui, app: &AppHandle, v: &Viewer) -> bool {
557    let ctx = ui.ctx().clone();
558    let (id, own_window, closed) = {
559        let e = lock(&v.embed);
560        let Some(s) = e.session.as_ref() else {
561            return false;
562        };
563        (s.id.clone(), s.own_window && s.view.is_some(), s.closed)
564    };
565    let width = ui.available_width();
566    let height = (width * 9.0 / 16.0)
567        .max(MIN_PLAYER)
568        .min(ui.available_height())
569        .max(1.0);
570    // Where the place will be, decided before it is laid out: a panel too
571    // small gets the card in its stead.
572    let rect = Rect::from_min_size(ui.cursor().min, vec2(width, height));
573    let visible = ui.clip_rect().intersect(rect);
574    let ppp = ctx.pixels_per_point();
575    let in_main = ctx.viewport_id() == egui::ViewportId::ROOT;
576    let place = Placement {
577        rect: Rect::from_min_max(
578            (visible.min.to_vec2() * ppp).to_pos2(),
579            (visible.max.to_vec2() * ppp).to_pos2(),
580        ),
581        parent_x11: in_main
582            .then(|| egui_pop_api::frame::x11_window(&ctx))
583            .flatten(),
584    };
585    let native = ctx.native_pixels_per_point().unwrap_or(1.0);
586    let parent = app.registry_window_of(ctx.viewport_id());
587    if !v.embed_in_view(app, place, parent, native) {
588        return too_small(ui, &place, native);
589    }
590    let (rect, response) = ui.allocate_exact_size(vec2(width, height), Sense::hover());
591    egui_pop_core::a11y::name(
592        &response,
593        egui::Role::Image,
594        &tr_args(&ctx, &txt::VIEWER_VIDEO_PICTURE, &[("name", &id)]),
595    );
596    // Under the web view, which covers it: nothing is drawn over the player.
597    let painter = ui.painter_at(rect);
598    painter.rect_filled(rect, 0.0, ui.visuals().extreme_bg_color);
599    let text = if own_window || closed {
600        tr(&ctx, &txt::VIEWER_EMBED_OWN_WINDOW)
601    } else {
602        tr(&ctx, &txt::VIEWER_VIDEO_LOADING)
603    };
604    // Wrapped to the place's width: a narrow panel keeps the whole sentence.
605    let galley = ui.painter().layout(
606        text,
607        egui::TextStyle::Body.resolve(ui.style()),
608        ui.visuals().weak_text_color(),
609        (rect.width() - 2.0 * ui.spacing().item_spacing.x).max(1.0),
610    );
611    let at = Align2::CENTER_CENTER
612        .anchor_size(rect.center(), galley.size())
613        .min;
614    painter.galley(at, galley, ui.visuals().weak_text_color());
615    if closed && ui.button(tr(&ctx, &txt::VIEWER_EMBED_SHOW)).clicked() {
616        v.embed_reopen(app);
617    }
618    false
619}
620
621/// The card in place of a player the panel is too small for: why, and Open
622/// outside. True: Open outside was clicked.
623fn too_small(ui: &mut Ui, place: &Placement, native: f32) -> bool {
624    let ctx = ui.ctx().clone();
625    let t = Tokens::of(&ctx);
626    let size = place.rect.size() / native.max(1.0);
627    ui.add_space(t.space.m);
628    ui.horizontal(|ui| {
629        ui.add(Icon::Info.size(Size::Inline).tone(Tone::Info));
630        ui.strong(tr(&ctx, &txt::VIEWER_EMBED_TOO_SMALL));
631    });
632    ui.weak(tr_with(
633        &ctx,
634        &txt::VIEWER_EMBED_TOO_SMALL_DETAIL,
635        &[
636            ("min", MIN_PLAYER.round().into()),
637            ("width", size.x.max(0.0).round().into()),
638            ("height", size.y.max(0.0).round().into()),
639        ],
640    ));
641    ui.add_space(t.space.s);
642    ui.button(tr(&ctx, &api_txt::LINKS_OPEN_OUTSIDE)).clicked()
643}
644
645/// Registers the viewer's [`WEB_VIEW_LISTENER`] on `pop.window.close`, replacing
646/// that of an earlier connection: a local listener, run on this (the
647/// interface's) thread, as a web view is dropped on the thread it was made
648/// on.
649pub(super) fn listen(app: &AppHandle, viewer: &Arc<Viewer>) {
650    let bus = app.bus();
651    bus.unlisten(&WindowClose::ID, WEB_VIEW_LISTENER);
652    let weak = Arc::downgrade(viewer);
653    let listened = bus.listen_local::<WindowClose>(
654        WEB_VIEW_LISTENER,
655        ListenOpts::new()
656            .owner(PLUGIN.as_str())
657            .after(CHILDREN)
658            .before(FOCUS),
659        move |req, did| {
660            if req.window.starts_with(WEB_VIEW_PREFIX)
661                && let Some(v) = weak.upgrade()
662            {
663                v.drop_on_close(req, did);
664            }
665            Ok(())
666        },
667    );
668    if let Err(e) = listened {
669        log::error!(target: "egui_pop", "{e}");
670    }
671}
672
673/// Takes the viewer's listener off the bus.
674pub(super) fn unlisten(app: &AppHandle) {
675    app.bus().unlisten(&WindowClose::ID, WEB_VIEW_LISTENER);
676}