Skip to main content

sk_tree/
iframe.rs

1//! `<iframe>`: a document in a platform webview, drawn into the element's box.
2//!
3//! This module knows the tree (which `<iframe>` nodes exist, where their boxes are, how document
4//! events become JS events), not the webview: a [`Backend`] does, registered with [`set_backend`].
5//! With none (Linux, no WebView2 runtime, tests) every `src` is answered with `error`.
6//!
7//! A document exists while the element is CONNECTED and has a `src`/`srcdoc`. Attribute writes and
8//! insertion/removal [`note`] the node; [`tick`] reconciles each (create, navigate, drop). Moving
9//! the element keeps the frame: the node id is its identity. Backend events arrive on the UI thread
10//! outside any gpui frame, so the [`Sink`] queues and [`tick`] dispatches `load`/`error`/`message`.
11
12use std::cell::RefCell;
13use std::collections::{HashMap, HashSet, VecDeque};
14use std::rc::Rc;
15
16use gpui::{App, Bounds, Pixels, Window};
17
18use crate::tree::{self, Tree};
19use crate::EventPayload;
20
21#[derive(Clone, Debug, Default, PartialEq)]
22pub struct FrameAttrs {
23    pub src: Option<String>,
24    /// An inline document; wins over `src` when present, as in HTML.
25    pub srcdoc: Option<String>,
26    pub sandbox: Option<String>,
27    pub allow: Option<String>,
28    pub referrer_policy: Option<String>,
29    pub name: Option<String>,
30    pub allow_fullscreen: bool,
31}
32
33impl FrameAttrs {
34    fn has_document(&self) -> bool {
35        self.srcdoc.is_some() || self.src.is_some()
36    }
37
38    fn key(&self) -> &str {
39        self.src.as_deref().unwrap_or("about:srcdoc")
40    }
41}
42
43#[derive(Clone, Copy, Debug, PartialEq)]
44pub struct Placement {
45    pub bounds: [f32; 4],
46    pub clip: [f32; 4],
47    /// Corner radii of the box, top-left clockwise.
48    pub radii: [f32; 4],
49    pub scale: f32,
50    pub opacity: f32,
51}
52
53#[derive(Clone, Debug, PartialEq)]
54pub enum FrameEvent {
55    Loaded,
56    Failed(String),
57    /// `window.parent.postMessage(..)` in the document: the sender's serialized origin (`"null"`
58    /// for an opaque one) and the payload's wire text.
59    Message {
60        origin: String,
61        wire: String,
62    },
63    Cursor(gpui::CursorStyle),
64    /// `Tab` (`forward`) or `Shift-Tab` went past the document's last or first focusable element.
65    FocusOut {
66        forward: bool,
67    },
68}
69
70/// Callable from the UI thread at any time; never re-enters JS — the event is queued for the next
71/// [`tick`].
72#[derive(Clone)]
73pub struct Sink {
74    node: u32,
75    wake: Rc<dyn Fn()>,
76}
77
78impl Sink {
79    pub fn send(&self, event: FrameEvent) {
80        EVENTS.with(|q| q.borrow_mut().push_back((self.node, event)));
81        (self.wake)();
82    }
83}
84
85/// A pointer event over the visible part of the document's box.
86#[derive(Clone, Copy, Debug, PartialEq)]
87pub struct PointerInput {
88    pub kind: PointerKind,
89    /// Device pixels from the box's top-left corner.
90    pub x: f32,
91    pub y: f32,
92    /// Buttons held: 1 left, 2 right, 4 middle.
93    pub buttons: u8,
94    pub shift: bool,
95    pub control: bool,
96}
97
98#[derive(Clone, Copy, Debug, PartialEq)]
99pub enum PointerKind {
100    Move,
101    /// 0 left, 1 middle, 2 right — the DOM's `button`.
102    Down(u8),
103    Up(u8),
104    /// Device pixels to scroll by, x then y, positive down and right.
105    Wheel(f32, f32),
106    Leave,
107}
108
109pub trait Frame {
110    fn navigate(&mut self, attrs: &FrameAttrs);
111    /// Deliver a message to the document's `window`.
112    fn post(&mut self, wire: &str, target_origin: &str);
113    /// Show the document at `placement`, or hide it (`None`: not painted this frame).
114    fn place(&mut self, placement: Option<Placement>);
115    /// Re-parent to `window`; the document goes with it and is not reloaded.
116    fn rehome(&mut self, window: &mut Window);
117    /// Give the document the keyboard focus, or take it back.
118    fn focus(&mut self, on: bool);
119    fn pointer(&mut self, input: PointerInput);
120}
121
122pub trait Backend {
123    /// Cheap: asked by `skFeatures.iframe` on every read.
124    fn supported(&self) -> bool;
125    fn create(
126        &self,
127        node: u32,
128        sink: Sink,
129        window: &mut Window,
130        cx: &mut App,
131    ) -> Option<Box<dyn Frame>>;
132}
133
134struct Live {
135    frame: Box<dyn Frame>,
136    attrs: FrameAttrs,
137    win: crate::windows::WinKey,
138    answered: bool,
139    placed: Option<Placement>,
140    cursor: gpui::CursorStyle,
141}
142
143/// How many documents may be open at once in the process.
144pub const MAX_FRAMES: usize = 8;
145
146thread_local! {
147    static BACKEND: RefCell<Option<Rc<dyn Backend>>> = const { RefCell::new(None) };
148    static WAKE: RefCell<Rc<dyn Fn()>> = RefCell::new(Rc::new(|| {}));
149    static NOTED: RefCell<HashSet<u32>> = RefCell::new(HashSet::new());
150    static WAITING: RefCell<HashSet<u32>> = RefCell::new(HashSet::new());
151    static FRAMES: RefCell<HashMap<u32, Live>> = RefCell::new(HashMap::new());
152    static EVENTS: RefCell<VecDeque<(u32, FrameEvent)>> = const { RefCell::new(VecDeque::new()) };
153    static PAINTED: RefCell<HashSet<u32>> = RefCell::new(HashSet::new());
154    static DREW: RefCell<Vec<crate::windows::WinKey>> = const { RefCell::new(Vec::new()) };
155    static REFUSED: RefCell<HashMap<u32, FrameAttrs>> = RefCell::new(HashMap::new());
156    static UNAVAILABLE: std::cell::Cell<Option<&'static str>> = const { std::cell::Cell::new(None) };
157}
158
159/// Why `<iframe>` has no backend, as the console and the `error` event say it.
160pub fn set_unavailable(reason: &'static str) {
161    UNAVAILABLE.with(|u| u.set(Some(reason)));
162}
163
164/// The host's reason, when it gave one: the build left the webview out.
165pub(crate) fn unavailable() -> Option<&'static str> {
166    UNAVAILABLE.with(std::cell::Cell::get)
167}
168
169pub fn set_backend(backend: Rc<dyn Backend>, wake: Rc<dyn Fn()>) {
170    BACKEND.with(|b| *b.borrow_mut() = Some(backend));
171    WAKE.with(|w| *w.borrow_mut() = wake);
172}
173
174pub fn supported() -> bool {
175    BACKEND.with(|b| b.borrow().as_ref().is_some_and(|b| b.supported()))
176}
177
178pub(crate) fn is_frame_attr(name: &str) -> bool {
179    matches!(
180        name,
181        "src" | "srcdoc" | "sandbox" | "allow" | "referrerpolicy" | "name" | "allowfullscreen"
182    )
183}
184
185pub(crate) fn note(id: u32) {
186    NOTED.with(|n| n.borrow_mut().insert(id));
187}
188
189pub(crate) fn note_structure() {
190    let waiting: Vec<u32> = WAITING.with(|w| w.borrow().iter().copied().collect());
191    let live: Vec<u32> = FRAMES.with(|f| f.borrow().keys().copied().collect());
192    if waiting.is_empty() && live.is_empty() {
193        return;
194    }
195    NOTED.with(|n| n.borrow_mut().extend(waiting.into_iter().chain(live)));
196}
197
198fn attrs_of(t: &Tree, id: u32) -> FrameAttrs {
199    let get = |name: &str| t.prop(id, name).map(str::to_string);
200    FrameAttrs {
201        src: get("src"),
202        srcdoc: get("srcdoc"),
203        sandbox: get("sandbox"),
204        allow: get("allow"),
205        referrer_policy: get("referrerpolicy"),
206        name: get("name"),
207        allow_fullscreen: t.prop(id, "allowfullscreen").is_some(),
208    }
209}
210
211fn connected(t: &Tree, id: u32) -> bool {
212    let mut at = id;
213    for _ in 0..4096 {
214        let Some(node) = t.node(at) else { return false };
215        if node.parent == 0 {
216            return t.name(node.tag) == "root";
217        }
218        at = node.parent;
219    }
220    false
221}
222
223#[derive(Debug, PartialEq)]
224enum Step {
225    Drop,
226    Wait,
227    Show(FrameAttrs),
228}
229
230fn step(t: &Tree, id: u32) -> Step {
231    let Some(node) = t.node(id) else {
232        return Step::Drop;
233    };
234    if t.name(node.tag) != "iframe" {
235        return Step::Drop;
236    }
237    let attrs = attrs_of(t, id);
238    if !attrs.has_document() {
239        return Step::Drop;
240    }
241    if connected(t, id) {
242        Step::Show(attrs)
243    } else {
244        Step::Wait
245    }
246}
247
248pub(crate) fn tick(window: &mut Window, cx: &mut App) {
249    let noted: Vec<u32> = NOTED.with(|n| n.borrow_mut().drain().collect());
250    let win = crate::windows::key(window);
251    for id in noted {
252        match tree::read_tree(|t| step(t, id)) {
253            Step::Drop => {
254                WAITING.with(|w| w.borrow_mut().remove(&id));
255                REFUSED.with(|r| r.borrow_mut().remove(&id));
256                drop(FRAMES.with(|f| f.borrow_mut().remove(&id)));
257            }
258            Step::Wait => {
259                WAITING.with(|w| w.borrow_mut().insert(id));
260                drop(FRAMES.with(|f| f.borrow_mut().remove(&id)));
261            }
262            Step::Show(attrs) => {
263                WAITING.with(|w| w.borrow_mut().remove(&id));
264                show(id, attrs, win, window, cx);
265            }
266        }
267    }
268    place_all(win);
269    sync_focus(win, window);
270    deliver(window, cx);
271}
272
273fn show(
274    id: u32,
275    attrs: FrameAttrs,
276    win: crate::windows::WinKey,
277    window: &mut Window,
278    cx: &mut App,
279) {
280    let backend = BACKEND
281        .with(|b| b.borrow().clone())
282        .filter(|b| b.supported());
283    let Some(backend) = backend else {
284        let again = REFUSED.with(|r| r.borrow().get(&id) == Some(&attrs));
285        if !again {
286            let reason = unavailable().unwrap_or("no webview backend on this system");
287            crate::render::warn_compat(
288                "iframe-unavailable",
289                &format!("<iframe> shows nothing: {reason}"),
290            );
291            EVENTS.with(|q| {
292                q.borrow_mut()
293                    .push_back((id, FrameEvent::Failed(reason.into())))
294            });
295            REFUSED.with(|r| r.borrow_mut().insert(id, attrs));
296        }
297        return;
298    };
299    let existing = FRAMES.with(|f| {
300        f.borrow()
301            .get(&id)
302            .map(|l| (l.attrs == attrs, l.win == win))
303    });
304    match existing {
305        Some((true, _)) => {}
306        Some((false, _)) => FRAMES.with(|f| {
307            if let Some(live) = f.borrow_mut().get_mut(&id) {
308                live.frame.navigate(&attrs);
309                live.attrs = attrs;
310                live.answered = false;
311            }
312        }),
313        None if FRAMES.with(|f| f.borrow().len()) >= MAX_FRAMES => {
314            // One more would cost the ones that are running.
315            let again = REFUSED.with(|r| r.borrow().get(&id) == Some(&attrs));
316            if !again {
317                EVENTS.with(|q| {
318                    q.borrow_mut().push_back((
319                        id,
320                        FrameEvent::Failed(format!(
321                            "{MAX_FRAMES} documents are already open; this one was not loaded"
322                        )),
323                    ))
324                });
325                REFUSED.with(|r| r.borrow_mut().insert(id, attrs));
326            }
327        }
328        None => {
329            REFUSED.with(|r| r.borrow_mut().remove(&id));
330            let sink = Sink {
331                node: id,
332                wake: WAKE.with(|w| w.borrow().clone()),
333            };
334            match backend.create(id, sink, window, cx) {
335                Some(mut frame) => {
336                    frame.navigate(&attrs);
337                    FRAMES.with(|f| {
338                        f.borrow_mut().insert(
339                            id,
340                            Live {
341                                frame,
342                                attrs,
343                                win,
344                                answered: false,
345                                placed: None,
346                                cursor: gpui::CursorStyle::Arrow,
347                            },
348                        )
349                    });
350                }
351                None => EVENTS.with(|q| {
352                    q.borrow_mut().push_back((
353                        id,
354                        FrameEvent::Failed("the webview could not be created".into()),
355                    ))
356                }),
357            }
358        }
359    }
360}
361
362/// Hides each frame of this window that the last paint did not reach (`display: none`, culled, scrolled out).
363fn place_all(win: crate::windows::WinKey) {
364    let drew = DREW.with(|d| {
365        let mut d = d.borrow_mut();
366        let before = d.len();
367        d.retain(|w| *w != win);
368        d.len() != before
369    });
370    if !drew {
371        return;
372    }
373    let seen: HashSet<u32> = PAINTED.with(|p| std::mem::take(&mut *p.borrow_mut()));
374    FRAMES.with(|f| {
375        for (id, live) in f.borrow_mut().iter_mut() {
376            if live.win == win && !seen.contains(id) && live.placed.is_some() {
377                live.frame.place(None);
378                live.placed = None;
379            }
380        }
381    });
382    PAINTED.with(|p| {
383        let mut p = p.borrow_mut();
384        for id in seen {
385            if FRAMES.with(|f| f.borrow().get(&id).is_some_and(|l| l.win != win)) {
386                p.insert(id);
387            }
388        }
389    });
390}
391
392/// `win` is building the element tree of a draw: the paint that follows reaches every iframe that
393/// is on screen in it.
394pub(crate) fn drawing(win: crate::windows::WinKey) {
395    DREW.with(|d| {
396        let mut d = d.borrow_mut();
397        if !d.contains(&win) {
398            d.push(win);
399        }
400    });
401}
402
403/// The element is painted in `window`: its document follows it there.
404pub(crate) fn painted_in(id: u32, window: &mut Window) {
405    let win = crate::windows::key(window);
406    FRAMES.with(|f| {
407        if let Some(live) = f.borrow_mut().get_mut(&id) {
408            live.frame.rehome(window);
409            if live.win != win {
410                live.win = win;
411                live.placed = None;
412            }
413        }
414    });
415}
416
417pub(crate) fn cursor(id: u32) -> Option<gpui::CursorStyle> {
418    FRAMES.with(|f| f.borrow().get(&id).map(|l| l.cursor))
419}
420
421/// Told to the frame at once, so the document moves in the frame its box does.
422pub(crate) fn placed(id: u32, placement: Placement) {
423    PAINTED.with(|p| p.borrow_mut().insert(id));
424    FRAMES.with(|f| {
425        if let Some(live) = f.borrow_mut().get_mut(&id) {
426            if live.placed != Some(placement) {
427                live.frame.place(Some(placement));
428                live.placed = Some(placement);
429            }
430        }
431    });
432}
433
434fn deliver(window: &mut Window, cx: &mut App) {
435    loop {
436        let Some((id, event)) = EVENTS.with(|q| q.borrow_mut().pop_front()) else {
437            break;
438        };
439        let key = FRAMES.with(|f| f.borrow().get(&id).map(|l| l.attrs.key().to_string()));
440        let key =
441            key.or_else(|| REFUSED.with(|r| r.borrow().get(&id).map(|a| a.key().to_string())));
442        let Some(key) = key else { continue };
443        match event {
444            FrameEvent::Loaded | FrameEvent::Failed(_) => {
445                let first = FRAMES.with(|f| match f.borrow_mut().get_mut(&id) {
446                    Some(live) => !std::mem::replace(&mut live.answered, true),
447                    None => true,
448                });
449                if !first {
450                    continue;
451                }
452                let code = if matches!(event, FrameEvent::Loaded) {
453                    tree::EV_LOAD
454                } else {
455                    tree::EV_ERROR
456                };
457                if let FrameEvent::Failed(why) = &event {
458                    crate::log::record("warn", format!("<iframe> {key}: {why}"));
459                }
460                let payload = EventPayload {
461                    key: Some(&key),
462                    ..Default::default()
463                };
464                crate::render::js_dispatch_app(id, code, &payload, window, cx);
465            }
466            FrameEvent::Cursor(style) => {
467                let changed = FRAMES.with(|f| match f.borrow_mut().get_mut(&id) {
468                    Some(live) => std::mem::replace(&mut live.cursor, style) != style,
469                    None => false,
470                });
471                if changed {
472                    window.refresh();
473                }
474            }
475            FrameEvent::FocusOut { forward } => {
476                let before = window.focused(cx);
477                if forward {
478                    window.focus_next(cx);
479                } else {
480                    window.focus_prev(cx);
481                }
482                // Nothing else takes the focus: the keys go back to the document, which starts over.
483                if window.focused(cx) == before {
484                    focus(id, true);
485                }
486            }
487            FrameEvent::Message { origin, wire } => {
488                let text = message_key(&origin, &wire);
489                let payload = EventPayload {
490                    key: Some(&text),
491                    ..Default::default()
492                };
493                crate::render::js_dispatch_app(id, tree::EV_MESSAGE, &payload, window, cx);
494            }
495        }
496    }
497}
498
499/// `{"o": origin, "d": wire}` — `wire` is already JSON text.
500fn message_key(origin: &str, wire: &str) -> String {
501    let mut out = String::with_capacity(wire.len() + origin.len() + 16);
502    out.push_str("{\"o\":\"");
503    for c in origin.chars() {
504        match c {
505            '"' => out.push_str("\\\""),
506            '\\' => out.push_str("\\\\"),
507            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
508            c => out.push(c),
509        }
510    }
511    out.push_str("\",\"d\":");
512    out.push_str(wire);
513    out.push('}');
514    out
515}
516
517pub(crate) fn post(id: u32, wire: &str, target_origin: &str) {
518    FRAMES.with(|f| {
519        if let Some(live) = f.borrow_mut().get_mut(&id) {
520            live.frame.post(wire, target_origin);
521        }
522    });
523}
524
525pub(crate) fn focus(id: u32, on: bool) {
526    FRAMES.with(|f| {
527        if let Some(live) = f.borrow_mut().get_mut(&id) {
528            live.frame.focus(on);
529        }
530    });
531}
532
533pub(crate) fn pointer(
534    id: u32,
535    kind: PointerKind,
536    at: (f32, f32),
537    buttons: u8,
538    shift: bool,
539    control: bool,
540) {
541    FRAMES.with(|f| {
542        if let Some(live) = f.borrow_mut().get_mut(&id) {
543            // Not painted: there is no box to be relative to.
544            let Some(place) = live.placed else { return };
545            let input = PointerInput {
546                kind,
547                x: at.0 - place.bounds[0],
548                y: at.1 - place.bounds[1],
549                buttons,
550                shift,
551                control,
552            };
553            live.frame.pointer(input);
554        }
555    });
556}
557
558thread_local! {
559    static FOCUSED: RefCell<HashMap<crate::windows::WinKey, u32>> = RefCell::new(HashMap::new());
560}
561
562/// The keyboard follows the app's focus: while an `<iframe>` is the window's focused node (press,
563/// `Tab`, `el.focus()`) its document has the keys; when focus moves on, the window has them back.
564fn sync_focus(win: crate::windows::WinKey, window: &Window) {
565    let had = FOCUSED.with(|f| f.borrow().get(&win).copied().unwrap_or(0));
566    if !window.is_window_active() {
567        if had != 0 {
568            FOCUSED.with(|f| f.borrow_mut().remove(&win));
569        }
570        return;
571    }
572    let node = crate::windows::focused_node(win);
573    let want = if has_document(node) { node } else { 0 };
574    if want == had {
575        return;
576    }
577    if want != 0 {
578        focus(want, true);
579    } else {
580        focus(had, false);
581    }
582    FOCUSED.with(|f| {
583        let mut f = f.borrow_mut();
584        if want == 0 {
585            f.remove(&win)
586        } else {
587            f.insert(win, want)
588        };
589    });
590}
591
592/// Is an element of the app fullscreen? Then Escape is the app's even while a document has the
593/// keyboard: it leaves fullscreen and the document does not hear it, as in a browser.
594pub fn fullscreen_active() -> bool {
595    tree::read_tree(|t| crate::fullscreen::current(t).is_some())
596}
597
598pub(crate) fn has_document(id: u32) -> bool {
599    FRAMES.with(|f| f.borrow().contains_key(&id))
600}
601
602pub(crate) fn gc(live: impl Fn(u32) -> bool) {
603    drop(FRAMES.with(|f| {
604        let mut f = f.borrow_mut();
605        let gone: Vec<u32> = f.keys().copied().filter(|&id| !live(id)).collect();
606        gone.into_iter()
607            .filter_map(|id| f.remove(&id))
608            .collect::<Vec<_>>()
609    }));
610    WAITING.with(|w| w.borrow_mut().retain(|&id| live(id)));
611    REFUSED.with(|r| r.borrow_mut().retain(|&id, _| live(id)));
612    PAINTED.with(|p| p.borrow_mut().retain(|&id| live(id)));
613}
614
615/// A window closed: its documents go, and their elements load anew if painted again elsewhere.
616pub(crate) fn forget_window(win: crate::windows::WinKey) {
617    let gone: Vec<Live> = FRAMES.with(|f| {
618        let mut f = f.borrow_mut();
619        let ids: Vec<u32> = f
620            .iter()
621            .filter(|(_, l)| l.win == win)
622            .map(|(id, _)| *id)
623            .collect();
624        ids.into_iter().filter_map(|id| f.remove(&id)).collect()
625    });
626    drop(gone);
627    FOCUSED.with(|f| f.borrow_mut().remove(&win));
628    DREW.with(|d| d.borrow_mut().retain(|w| *w != win));
629}
630
631pub fn shutdown() {
632    drop(FRAMES.with(|f| std::mem::take(&mut *f.borrow_mut())));
633    EVENTS.with(|q| q.borrow_mut().clear());
634}
635
636pub(crate) fn placement(
637    bounds: Bounds<Pixels>,
638    mask: Bounds<Pixels>,
639    radii: [f32; 4],
640    scale: f32,
641    opacity: f32,
642) -> Placement {
643    let rect = |b: Bounds<Pixels>| {
644        [
645            f32::from(b.origin.x) * scale,
646            f32::from(b.origin.y) * scale,
647            f32::from(b.size.width) * scale,
648            f32::from(b.size.height) * scale,
649        ]
650    };
651    Placement {
652        bounds: rect(bounds),
653        clip: rect(bounds.intersect(&mask)),
654        radii: radii.map(|r| r * scale),
655        scale,
656        opacity,
657    }
658}
659
660#[cfg(test)]
661mod tests {
662    use super::*;
663    use crate::tree::{read_tree, with_tree};
664
665    struct FakeFrame(u32, Rc<RefCell<Vec<String>>>);
666
667    impl Frame for FakeFrame {
668        fn navigate(&mut self, attrs: &FrameAttrs) {
669            self.1
670                .borrow_mut()
671                .push(format!("navigate {} {}", self.0, attrs.key()));
672        }
673        fn post(&mut self, wire: &str, target: &str) {
674            self.1
675                .borrow_mut()
676                .push(format!("post {} {wire} {target}", self.0));
677        }
678        fn place(&mut self, placement: Option<Placement>) {
679            self.1
680                .borrow_mut()
681                .push(format!("place {} {}", self.0, placement.is_some()));
682        }
683        fn rehome(&mut self, _: &mut Window) {}
684        fn focus(&mut self, on: bool) {
685            self.1.borrow_mut().push(format!("focus {} {on}", self.0));
686        }
687        fn pointer(&mut self, input: PointerInput) {
688            self.1
689                .borrow_mut()
690                .push(format!("pointer {} {:?}", self.0, input.kind));
691        }
692    }
693
694    impl Drop for FakeFrame {
695        fn drop(&mut self) {
696            self.1.borrow_mut().push(format!("drop {}", self.0));
697        }
698    }
699
700    fn iframe(src: Option<&str>, attach: bool) -> u32 {
701        with_tree(|t| {
702            let root = t.create_root();
703            let tag = t.intern("iframe");
704            let el = t.create_element(tag);
705            if let Some(src) = src {
706                let key = t.intern("src");
707                t.set_prop(el, key, Some(src.into()));
708            }
709            if attach {
710                t.insert(el, root, 0);
711            }
712            el
713        })
714    }
715
716    #[test]
717    fn a_document_needs_a_connected_element_with_a_src() {
718        let loose = iframe(Some("/game.html"), false);
719        assert_eq!(read_tree(|t| step(t, loose)), Step::Wait);
720        let empty = iframe(None, true);
721        assert_eq!(read_tree(|t| step(t, empty)), Step::Drop);
722        let ready = iframe(Some("/game.html"), true);
723        assert!(
724            matches!(read_tree(|t| step(t, ready)), Step::Show(a) if a.src.as_deref() == Some("/game.html"))
725        );
726        assert_eq!(read_tree(|t| step(t, 999_999)), Step::Drop);
727    }
728
729    #[test]
730    fn srcdoc_is_a_document_without_a_src() {
731        let el = iframe(None, true);
732        with_tree(|t| {
733            let key = t.intern("srcdoc");
734            t.set_prop(el, key, Some("<p>hi</p>".into()));
735        });
736        let Step::Show(attrs) = read_tree(|t| step(t, el)) else {
737            panic!("srcdoc alone is a document")
738        };
739        assert_eq!(attrs.key(), "about:srcdoc");
740    }
741
742    #[test]
743    fn a_message_key_is_json_with_the_wire_embedded() {
744        assert_eq!(
745            message_key("null", "[\"o\",[]]"),
746            "{\"o\":\"null\",\"d\":[\"o\",[]]}"
747        );
748        assert_eq!(
749            message_key("a\"b\\c", "1"),
750            "{\"o\":\"a\\\"b\\\\c\",\"d\":1}"
751        );
752    }
753
754    #[test]
755    fn a_frame_is_placed_once_per_change_and_hidden_when_not_painted() {
756        let log = Rc::new(RefCell::new(Vec::new()));
757        let id = 77_001;
758        FRAMES.with(|f| {
759            f.borrow_mut().insert(
760                id,
761                Live {
762                    frame: Box::new(FakeFrame(id, log.clone())),
763                    attrs: FrameAttrs::default(),
764                    win: 5,
765                    answered: false,
766                    placed: None,
767                    cursor: gpui::CursorStyle::Arrow,
768                },
769            )
770        });
771        let at = Placement {
772            bounds: [0.0, 0.0, 10.0, 10.0],
773            clip: [0.0, 0.0, 10.0, 10.0],
774            radii: [0.0; 4],
775            scale: 1.0,
776            opacity: 1.0,
777        };
778        drawing(5);
779        placed(id, at);
780        placed(id, at);
781        place_all(5);
782        drawing(5);
783        placed(id, at);
784        place_all(5);
785        place_all(5);
786        // A draw that did not reach it hides it.
787        drawing(5);
788        place_all(5);
789        post(id, "1", "*");
790        gc(|_| false);
791        assert_eq!(
792            *log.borrow(),
793            [
794                "place 77001 true",
795                "place 77001 false",
796                "post 77001 1 *",
797                "drop 77001"
798            ],
799            "same place: no call; not painted: hidden; gone: dropped"
800        );
801    }
802
803    #[test]
804    fn a_placement_is_in_device_pixels_and_clipped() {
805        use gpui::{point, px, size};
806        let bounds = Bounds {
807            origin: point(px(10.0), px(20.0)),
808            size: size(px(100.0), px(50.0)),
809        };
810        let mask = Bounds {
811            origin: point(px(0.0), px(0.0)),
812            size: size(px(60.0), px(40.0)),
813        };
814        let p = placement(bounds, mask, [4.0; 4], 2.0, 0.5);
815        assert_eq!(p.bounds, [20.0, 40.0, 200.0, 100.0]);
816        assert_eq!(p.clip, [20.0, 40.0, 100.0, 40.0]);
817        assert_eq!(p.radii, [8.0; 4]);
818    }
819}