Skip to main content

BoundScriptDocument

Struct BoundScriptDocument 

Source
pub struct BoundScriptDocument<G, H>
where G: TypedNativeGuest, H: NativeHost<Guest = G> + 'static,
{ /* private fields */ }
Expand description

A script document backed by an actual guest and host supplied by its caller.

H is retained as the host’s concrete type for API clarity. The host is owned behind the engine-neutral NativeHost boundary once attached.

Implementations§

Source§

impl<G, H> BoundScriptDocument<G, H>
where G: TypedNativeGuest, H: NativeHost<Guest = G> + 'static,

Source

pub fn new_bound( html: Arc<str>, config: DocumentConfig, host: H, ) -> Result<Self, String>

Parse HTML and bind a real host before returning an executable document.

Examples found in repository?
examples/native_document.rs (lines 362-366)
234fn main() {
235    let trace = Rc::new(RefCell::new(Vec::new()));
236    let html = Arc::from(
237        "<output id=subject>pending</output><template><script src='inert.js'>inert</script></template><script nomodule src='legacy.js'>inert</script><script type=application/json>inert</script><script>paint()</script><script src='data:text/javascript,paint()'></script>",
238    );
239    let mut page = Page::from_html(html, DocumentConfig::default()).expect("parse fixture");
240    assert_eq!(
241        blitz_script::external_script_urls(&page.inner()),
242        vec![Url::parse("data:text/javascript,paint()").unwrap()]
243    );
244    assert!(
245        page.execute_scripts().is_err(),
246        "unbound execution must fail"
247    );
248    page.attach_native_host(guest(&trace, true))
249        .expect("bind compiled guest");
250    page.storage_set("seed", 8).expect("seed before scripts");
251    page.execute_scripts().expect("execute compiled fixture");
252    page.execute_scripts().expect("bootstrap is idempotent");
253    let subject = page.inner().query_selector("#subject").unwrap().unwrap();
254    assert_eq!(
255        page.inner().get_node(subject).unwrap().text_content(),
256        "9",
257        "rendered-bootstrap"
258    );
259    assert_eq!(
260        &*trace.borrow(),
261        &["install", "execute", "execute", "ready"],
262        "script-order-and-inert-subtrees"
263    );
264    page.handle_ui_event(UiEvent::AppleStandardKeybinding("selectAll:".into()));
265    page.set_page_visible(false);
266    page.freeze();
267    assert!(!page.poll(None), "frozen guest must not run");
268    page.resume();
269    page.finish_restore();
270    let wakes = Arc::new(WakeCount(AtomicUsize::new(0)));
271    let waker = std::task::Waker::from(Arc::clone(&wakes));
272    assert!(page.poll(Some(Context::from_waker(&waker))));
273    assert_eq!(
274        wakes.0.load(Ordering::Relaxed),
275        1,
276        "document-waker-propagation"
277    );
278    assert!(page.poll_for_settle(None, false));
279    assert!(page.poll_for_settle(None, true));
280    assert_eq!(
281        &trace.borrow()[4..],
282        &[
283            "event",
284            "visibility",
285            "freeze",
286            "resume",
287            "restore",
288            "poll",
289            "jobs",
290            "timers"
291        ],
292        "lifecycle-and-timer-policy"
293    );
294    assert_eq!(page.storage_get("seed").unwrap(), Some(8));
295    page.storage_remove("seed").unwrap();
296    assert_eq!(page.storage_get("seed").unwrap(), None);
297    page.storage_set("seed", 3).unwrap();
298    page.storage_clear().unwrap();
299    assert_eq!(page.storage_get("seed").unwrap(), None);
300
301    page.with_guest_mut(|guest, document| {
302        assert!(guest.storage.is_empty());
303        assert_eq!(document.query_selector("#subject").unwrap(), Some(subject));
304    })
305    .unwrap();
306    let hook_order = Rc::new(RefCell::new(Vec::new()));
307    let nested_installed = Rc::new(Cell::new(false));
308    let retire = Rc::new(Cell::new(false));
309    let hook_wakes = Rc::new(Cell::new(0));
310    for index in [1, 2] {
311        let order = Rc::clone(&hook_order);
312        let installed = Rc::clone(&nested_installed);
313        let retire = Rc::clone(&retire);
314        let wakes = Rc::clone(&hook_wakes);
315        page.add_poll_hook(Box::new(move |document, context| {
316            order.borrow_mut().push(index);
317            if context.is_some() {
318                wakes.set(wakes.get() + 1);
319            }
320            if index == 1 && !installed.replace(true) {
321                let nested_order = Rc::clone(&order);
322                (document as &mut dyn std::any::Any)
323                    .downcast_mut::<Page>()
324                    .unwrap()
325                    .add_poll_hook(Box::new(move |_, _| {
326                        nested_order.borrow_mut().push(3);
327                        false
328                    }))
329                    .unwrap();
330            }
331            if index == 1 && retire.get() {
332                document.prepare_teardown();
333            }
334            index == 1
335        }))
336        .unwrap();
337    }
338    assert!(page.poll(None));
339    assert_eq!(&*hook_order.borrow(), &[1, 2]);
340    assert!(page.poll_for_settle(Some(Context::from_waker(&waker)), false));
341    assert_eq!(&*hook_order.borrow(), &[1, 2, 1, 2, 3]);
342    assert_eq!(hook_wakes.get(), 2);
343    retire.set(true);
344    assert!(!page.poll(None));
345    assert_eq!(&*hook_order.borrow(), &[1, 2, 1, 2, 3, 1]);
346    assert!(page.guest().is_none());
347    assert!(page.add_poll_hook(Box::new(|_, _| true)).is_err());
348    page.prepare_teardown();
349    let calls = trace.borrow().len();
350    assert!(!page.poll(None));
351    assert!(page.execute_scripts().is_err());
352    assert!(page.storage_set("seed", 1).is_err());
353    page.handle_ui_event(UiEvent::AppleStandardKeybinding("selectAll:".into()));
354    assert_eq!(trace.borrow().len(), calls, "retired-guest-entry");
355    drop(page);
356    assert_eq!(
357        trace.borrow().iter().filter(|&&v| v == "teardown").count(),
358        1
359    );
360    assert_eq!(trace.borrow().last(), Some(&"dispose"));
361    let drop_trace = Rc::new(RefCell::new(Vec::new()));
362    let page = Page::new_bound(
363        Arc::from("<p>plain</p>"),
364        DocumentConfig::default(),
365        guest(&drop_trace, true),
366    )
367    .unwrap();
368    drop(page);
369    assert_eq!(
370        &*drop_trace.borrow(),
371        &["install", "teardown", "dispose"],
372        "drop-cleanup"
373    );
374    #[cfg(feature = "intl")]
375    {
376        let mut page = Page::new_bound(
377            Arc::from("<script>paint()</script>"),
378            DocumentConfig::default(),
379            guest(&drop_trace, false),
380        )
381        .unwrap();
382        assert!(page.execute_scripts().unwrap_err().contains("Intl"));
383    }
384    println!(
385        "PASS bound document driver: compiled fixture, DOM, storage, lifecycle and teardown; no JavaScript engine claimed"
386    );
387}
Source

pub fn new_bound_with_fetcher<F>( html: Arc<str>, config: DocumentConfig, host: H, fetcher: F, ) -> Result<Self, String>
where F: ScriptFetcher,

Variant of new_bound with an embedder-provided external script fetcher.

Source

pub fn last_error(&self) -> Option<&str>

Return the most recent error from a Document callback, if any.

Source

pub fn take_last_error(&mut self) -> Option<String>

Drain a callback failure so an application can publish it once.

Source

pub fn add_poll_hook(&mut self, hook: DocumentPollHook) -> Result<(), String>

Add a poll hook without replacing hooks already registered.

Examples found in repository?
examples/native_document.rs (lines 315-335)
234fn main() {
235    let trace = Rc::new(RefCell::new(Vec::new()));
236    let html = Arc::from(
237        "<output id=subject>pending</output><template><script src='inert.js'>inert</script></template><script nomodule src='legacy.js'>inert</script><script type=application/json>inert</script><script>paint()</script><script src='data:text/javascript,paint()'></script>",
238    );
239    let mut page = Page::from_html(html, DocumentConfig::default()).expect("parse fixture");
240    assert_eq!(
241        blitz_script::external_script_urls(&page.inner()),
242        vec![Url::parse("data:text/javascript,paint()").unwrap()]
243    );
244    assert!(
245        page.execute_scripts().is_err(),
246        "unbound execution must fail"
247    );
248    page.attach_native_host(guest(&trace, true))
249        .expect("bind compiled guest");
250    page.storage_set("seed", 8).expect("seed before scripts");
251    page.execute_scripts().expect("execute compiled fixture");
252    page.execute_scripts().expect("bootstrap is idempotent");
253    let subject = page.inner().query_selector("#subject").unwrap().unwrap();
254    assert_eq!(
255        page.inner().get_node(subject).unwrap().text_content(),
256        "9",
257        "rendered-bootstrap"
258    );
259    assert_eq!(
260        &*trace.borrow(),
261        &["install", "execute", "execute", "ready"],
262        "script-order-and-inert-subtrees"
263    );
264    page.handle_ui_event(UiEvent::AppleStandardKeybinding("selectAll:".into()));
265    page.set_page_visible(false);
266    page.freeze();
267    assert!(!page.poll(None), "frozen guest must not run");
268    page.resume();
269    page.finish_restore();
270    let wakes = Arc::new(WakeCount(AtomicUsize::new(0)));
271    let waker = std::task::Waker::from(Arc::clone(&wakes));
272    assert!(page.poll(Some(Context::from_waker(&waker))));
273    assert_eq!(
274        wakes.0.load(Ordering::Relaxed),
275        1,
276        "document-waker-propagation"
277    );
278    assert!(page.poll_for_settle(None, false));
279    assert!(page.poll_for_settle(None, true));
280    assert_eq!(
281        &trace.borrow()[4..],
282        &[
283            "event",
284            "visibility",
285            "freeze",
286            "resume",
287            "restore",
288            "poll",
289            "jobs",
290            "timers"
291        ],
292        "lifecycle-and-timer-policy"
293    );
294    assert_eq!(page.storage_get("seed").unwrap(), Some(8));
295    page.storage_remove("seed").unwrap();
296    assert_eq!(page.storage_get("seed").unwrap(), None);
297    page.storage_set("seed", 3).unwrap();
298    page.storage_clear().unwrap();
299    assert_eq!(page.storage_get("seed").unwrap(), None);
300
301    page.with_guest_mut(|guest, document| {
302        assert!(guest.storage.is_empty());
303        assert_eq!(document.query_selector("#subject").unwrap(), Some(subject));
304    })
305    .unwrap();
306    let hook_order = Rc::new(RefCell::new(Vec::new()));
307    let nested_installed = Rc::new(Cell::new(false));
308    let retire = Rc::new(Cell::new(false));
309    let hook_wakes = Rc::new(Cell::new(0));
310    for index in [1, 2] {
311        let order = Rc::clone(&hook_order);
312        let installed = Rc::clone(&nested_installed);
313        let retire = Rc::clone(&retire);
314        let wakes = Rc::clone(&hook_wakes);
315        page.add_poll_hook(Box::new(move |document, context| {
316            order.borrow_mut().push(index);
317            if context.is_some() {
318                wakes.set(wakes.get() + 1);
319            }
320            if index == 1 && !installed.replace(true) {
321                let nested_order = Rc::clone(&order);
322                (document as &mut dyn std::any::Any)
323                    .downcast_mut::<Page>()
324                    .unwrap()
325                    .add_poll_hook(Box::new(move |_, _| {
326                        nested_order.borrow_mut().push(3);
327                        false
328                    }))
329                    .unwrap();
330            }
331            if index == 1 && retire.get() {
332                document.prepare_teardown();
333            }
334            index == 1
335        }))
336        .unwrap();
337    }
338    assert!(page.poll(None));
339    assert_eq!(&*hook_order.borrow(), &[1, 2]);
340    assert!(page.poll_for_settle(Some(Context::from_waker(&waker)), false));
341    assert_eq!(&*hook_order.borrow(), &[1, 2, 1, 2, 3]);
342    assert_eq!(hook_wakes.get(), 2);
343    retire.set(true);
344    assert!(!page.poll(None));
345    assert_eq!(&*hook_order.borrow(), &[1, 2, 1, 2, 3, 1]);
346    assert!(page.guest().is_none());
347    assert!(page.add_poll_hook(Box::new(|_, _| true)).is_err());
348    page.prepare_teardown();
349    let calls = trace.borrow().len();
350    assert!(!page.poll(None));
351    assert!(page.execute_scripts().is_err());
352    assert!(page.storage_set("seed", 1).is_err());
353    page.handle_ui_event(UiEvent::AppleStandardKeybinding("selectAll:".into()));
354    assert_eq!(trace.borrow().len(), calls, "retired-guest-entry");
355    drop(page);
356    assert_eq!(
357        trace.borrow().iter().filter(|&&v| v == "teardown").count(),
358        1
359    );
360    assert_eq!(trace.borrow().last(), Some(&"dispose"));
361    let drop_trace = Rc::new(RefCell::new(Vec::new()));
362    let page = Page::new_bound(
363        Arc::from("<p>plain</p>"),
364        DocumentConfig::default(),
365        guest(&drop_trace, true),
366    )
367    .unwrap();
368    drop(page);
369    assert_eq!(
370        &*drop_trace.borrow(),
371        &["install", "teardown", "dispose"],
372        "drop-cleanup"
373    );
374    #[cfg(feature = "intl")]
375    {
376        let mut page = Page::new_bound(
377            Arc::from("<script>paint()</script>"),
378            DocumentConfig::default(),
379            guest(&drop_trace, false),
380        )
381        .unwrap();
382        assert!(page.execute_scripts().unwrap_err().contains("Intl"));
383    }
384    println!(
385        "PASS bound document driver: compiled fixture, DOM, storage, lifecycle and teardown; no JavaScript engine claimed"
386    );
387}
Source

pub fn guest(&self) -> Option<&G>

Borrow the native guest while the document is live and attached.

Examples found in repository?
examples/native_document.rs (line 346)
234fn main() {
235    let trace = Rc::new(RefCell::new(Vec::new()));
236    let html = Arc::from(
237        "<output id=subject>pending</output><template><script src='inert.js'>inert</script></template><script nomodule src='legacy.js'>inert</script><script type=application/json>inert</script><script>paint()</script><script src='data:text/javascript,paint()'></script>",
238    );
239    let mut page = Page::from_html(html, DocumentConfig::default()).expect("parse fixture");
240    assert_eq!(
241        blitz_script::external_script_urls(&page.inner()),
242        vec![Url::parse("data:text/javascript,paint()").unwrap()]
243    );
244    assert!(
245        page.execute_scripts().is_err(),
246        "unbound execution must fail"
247    );
248    page.attach_native_host(guest(&trace, true))
249        .expect("bind compiled guest");
250    page.storage_set("seed", 8).expect("seed before scripts");
251    page.execute_scripts().expect("execute compiled fixture");
252    page.execute_scripts().expect("bootstrap is idempotent");
253    let subject = page.inner().query_selector("#subject").unwrap().unwrap();
254    assert_eq!(
255        page.inner().get_node(subject).unwrap().text_content(),
256        "9",
257        "rendered-bootstrap"
258    );
259    assert_eq!(
260        &*trace.borrow(),
261        &["install", "execute", "execute", "ready"],
262        "script-order-and-inert-subtrees"
263    );
264    page.handle_ui_event(UiEvent::AppleStandardKeybinding("selectAll:".into()));
265    page.set_page_visible(false);
266    page.freeze();
267    assert!(!page.poll(None), "frozen guest must not run");
268    page.resume();
269    page.finish_restore();
270    let wakes = Arc::new(WakeCount(AtomicUsize::new(0)));
271    let waker = std::task::Waker::from(Arc::clone(&wakes));
272    assert!(page.poll(Some(Context::from_waker(&waker))));
273    assert_eq!(
274        wakes.0.load(Ordering::Relaxed),
275        1,
276        "document-waker-propagation"
277    );
278    assert!(page.poll_for_settle(None, false));
279    assert!(page.poll_for_settle(None, true));
280    assert_eq!(
281        &trace.borrow()[4..],
282        &[
283            "event",
284            "visibility",
285            "freeze",
286            "resume",
287            "restore",
288            "poll",
289            "jobs",
290            "timers"
291        ],
292        "lifecycle-and-timer-policy"
293    );
294    assert_eq!(page.storage_get("seed").unwrap(), Some(8));
295    page.storage_remove("seed").unwrap();
296    assert_eq!(page.storage_get("seed").unwrap(), None);
297    page.storage_set("seed", 3).unwrap();
298    page.storage_clear().unwrap();
299    assert_eq!(page.storage_get("seed").unwrap(), None);
300
301    page.with_guest_mut(|guest, document| {
302        assert!(guest.storage.is_empty());
303        assert_eq!(document.query_selector("#subject").unwrap(), Some(subject));
304    })
305    .unwrap();
306    let hook_order = Rc::new(RefCell::new(Vec::new()));
307    let nested_installed = Rc::new(Cell::new(false));
308    let retire = Rc::new(Cell::new(false));
309    let hook_wakes = Rc::new(Cell::new(0));
310    for index in [1, 2] {
311        let order = Rc::clone(&hook_order);
312        let installed = Rc::clone(&nested_installed);
313        let retire = Rc::clone(&retire);
314        let wakes = Rc::clone(&hook_wakes);
315        page.add_poll_hook(Box::new(move |document, context| {
316            order.borrow_mut().push(index);
317            if context.is_some() {
318                wakes.set(wakes.get() + 1);
319            }
320            if index == 1 && !installed.replace(true) {
321                let nested_order = Rc::clone(&order);
322                (document as &mut dyn std::any::Any)
323                    .downcast_mut::<Page>()
324                    .unwrap()
325                    .add_poll_hook(Box::new(move |_, _| {
326                        nested_order.borrow_mut().push(3);
327                        false
328                    }))
329                    .unwrap();
330            }
331            if index == 1 && retire.get() {
332                document.prepare_teardown();
333            }
334            index == 1
335        }))
336        .unwrap();
337    }
338    assert!(page.poll(None));
339    assert_eq!(&*hook_order.borrow(), &[1, 2]);
340    assert!(page.poll_for_settle(Some(Context::from_waker(&waker)), false));
341    assert_eq!(&*hook_order.borrow(), &[1, 2, 1, 2, 3]);
342    assert_eq!(hook_wakes.get(), 2);
343    retire.set(true);
344    assert!(!page.poll(None));
345    assert_eq!(&*hook_order.borrow(), &[1, 2, 1, 2, 3, 1]);
346    assert!(page.guest().is_none());
347    assert!(page.add_poll_hook(Box::new(|_, _| true)).is_err());
348    page.prepare_teardown();
349    let calls = trace.borrow().len();
350    assert!(!page.poll(None));
351    assert!(page.execute_scripts().is_err());
352    assert!(page.storage_set("seed", 1).is_err());
353    page.handle_ui_event(UiEvent::AppleStandardKeybinding("selectAll:".into()));
354    assert_eq!(trace.borrow().len(), calls, "retired-guest-entry");
355    drop(page);
356    assert_eq!(
357        trace.borrow().iter().filter(|&&v| v == "teardown").count(),
358        1
359    );
360    assert_eq!(trace.borrow().last(), Some(&"dispose"));
361    let drop_trace = Rc::new(RefCell::new(Vec::new()));
362    let page = Page::new_bound(
363        Arc::from("<p>plain</p>"),
364        DocumentConfig::default(),
365        guest(&drop_trace, true),
366    )
367    .unwrap();
368    drop(page);
369    assert_eq!(
370        &*drop_trace.borrow(),
371        &["install", "teardown", "dispose"],
372        "drop-cleanup"
373    );
374    #[cfg(feature = "intl")]
375    {
376        let mut page = Page::new_bound(
377            Arc::from("<script>paint()</script>"),
378            DocumentConfig::default(),
379            guest(&drop_trace, false),
380        )
381        .unwrap();
382        assert!(page.execute_scripts().unwrap_err().contains("Intl"));
383    }
384    println!(
385        "PASS bound document driver: compiled fixture, DOM, storage, lifecycle and teardown; no JavaScript engine claimed"
386    );
387}
Source

pub fn guest_mut(&mut self) -> Option<&mut G>

Mutably borrow the native guest while the document is live and attached.

Source

pub fn with_guest_mut<R>( &mut self, callback: impl FnOnce(&mut G, &mut BaseDocument) -> R, ) -> Result<R, String>

Run a callback with mutable access to the guest and its document.

Examples found in repository?
examples/native_document.rs (lines 301-304)
234fn main() {
235    let trace = Rc::new(RefCell::new(Vec::new()));
236    let html = Arc::from(
237        "<output id=subject>pending</output><template><script src='inert.js'>inert</script></template><script nomodule src='legacy.js'>inert</script><script type=application/json>inert</script><script>paint()</script><script src='data:text/javascript,paint()'></script>",
238    );
239    let mut page = Page::from_html(html, DocumentConfig::default()).expect("parse fixture");
240    assert_eq!(
241        blitz_script::external_script_urls(&page.inner()),
242        vec![Url::parse("data:text/javascript,paint()").unwrap()]
243    );
244    assert!(
245        page.execute_scripts().is_err(),
246        "unbound execution must fail"
247    );
248    page.attach_native_host(guest(&trace, true))
249        .expect("bind compiled guest");
250    page.storage_set("seed", 8).expect("seed before scripts");
251    page.execute_scripts().expect("execute compiled fixture");
252    page.execute_scripts().expect("bootstrap is idempotent");
253    let subject = page.inner().query_selector("#subject").unwrap().unwrap();
254    assert_eq!(
255        page.inner().get_node(subject).unwrap().text_content(),
256        "9",
257        "rendered-bootstrap"
258    );
259    assert_eq!(
260        &*trace.borrow(),
261        &["install", "execute", "execute", "ready"],
262        "script-order-and-inert-subtrees"
263    );
264    page.handle_ui_event(UiEvent::AppleStandardKeybinding("selectAll:".into()));
265    page.set_page_visible(false);
266    page.freeze();
267    assert!(!page.poll(None), "frozen guest must not run");
268    page.resume();
269    page.finish_restore();
270    let wakes = Arc::new(WakeCount(AtomicUsize::new(0)));
271    let waker = std::task::Waker::from(Arc::clone(&wakes));
272    assert!(page.poll(Some(Context::from_waker(&waker))));
273    assert_eq!(
274        wakes.0.load(Ordering::Relaxed),
275        1,
276        "document-waker-propagation"
277    );
278    assert!(page.poll_for_settle(None, false));
279    assert!(page.poll_for_settle(None, true));
280    assert_eq!(
281        &trace.borrow()[4..],
282        &[
283            "event",
284            "visibility",
285            "freeze",
286            "resume",
287            "restore",
288            "poll",
289            "jobs",
290            "timers"
291        ],
292        "lifecycle-and-timer-policy"
293    );
294    assert_eq!(page.storage_get("seed").unwrap(), Some(8));
295    page.storage_remove("seed").unwrap();
296    assert_eq!(page.storage_get("seed").unwrap(), None);
297    page.storage_set("seed", 3).unwrap();
298    page.storage_clear().unwrap();
299    assert_eq!(page.storage_get("seed").unwrap(), None);
300
301    page.with_guest_mut(|guest, document| {
302        assert!(guest.storage.is_empty());
303        assert_eq!(document.query_selector("#subject").unwrap(), Some(subject));
304    })
305    .unwrap();
306    let hook_order = Rc::new(RefCell::new(Vec::new()));
307    let nested_installed = Rc::new(Cell::new(false));
308    let retire = Rc::new(Cell::new(false));
309    let hook_wakes = Rc::new(Cell::new(0));
310    for index in [1, 2] {
311        let order = Rc::clone(&hook_order);
312        let installed = Rc::clone(&nested_installed);
313        let retire = Rc::clone(&retire);
314        let wakes = Rc::clone(&hook_wakes);
315        page.add_poll_hook(Box::new(move |document, context| {
316            order.borrow_mut().push(index);
317            if context.is_some() {
318                wakes.set(wakes.get() + 1);
319            }
320            if index == 1 && !installed.replace(true) {
321                let nested_order = Rc::clone(&order);
322                (document as &mut dyn std::any::Any)
323                    .downcast_mut::<Page>()
324                    .unwrap()
325                    .add_poll_hook(Box::new(move |_, _| {
326                        nested_order.borrow_mut().push(3);
327                        false
328                    }))
329                    .unwrap();
330            }
331            if index == 1 && retire.get() {
332                document.prepare_teardown();
333            }
334            index == 1
335        }))
336        .unwrap();
337    }
338    assert!(page.poll(None));
339    assert_eq!(&*hook_order.borrow(), &[1, 2]);
340    assert!(page.poll_for_settle(Some(Context::from_waker(&waker)), false));
341    assert_eq!(&*hook_order.borrow(), &[1, 2, 1, 2, 3]);
342    assert_eq!(hook_wakes.get(), 2);
343    retire.set(true);
344    assert!(!page.poll(None));
345    assert_eq!(&*hook_order.borrow(), &[1, 2, 1, 2, 3, 1]);
346    assert!(page.guest().is_none());
347    assert!(page.add_poll_hook(Box::new(|_, _| true)).is_err());
348    page.prepare_teardown();
349    let calls = trace.borrow().len();
350    assert!(!page.poll(None));
351    assert!(page.execute_scripts().is_err());
352    assert!(page.storage_set("seed", 1).is_err());
353    page.handle_ui_event(UiEvent::AppleStandardKeybinding("selectAll:".into()));
354    assert_eq!(trace.borrow().len(), calls, "retired-guest-entry");
355    drop(page);
356    assert_eq!(
357        trace.borrow().iter().filter(|&&v| v == "teardown").count(),
358        1
359    );
360    assert_eq!(trace.borrow().last(), Some(&"dispose"));
361    let drop_trace = Rc::new(RefCell::new(Vec::new()));
362    let page = Page::new_bound(
363        Arc::from("<p>plain</p>"),
364        DocumentConfig::default(),
365        guest(&drop_trace, true),
366    )
367    .unwrap();
368    drop(page);
369    assert_eq!(
370        &*drop_trace.borrow(),
371        &["install", "teardown", "dispose"],
372        "drop-cleanup"
373    );
374    #[cfg(feature = "intl")]
375    {
376        let mut page = Page::new_bound(
377            Arc::from("<script>paint()</script>"),
378            DocumentConfig::default(),
379            guest(&drop_trace, false),
380        )
381        .unwrap();
382        assert!(page.execute_scripts().unwrap_err().contains("Intl"));
383    }
384    println!(
385        "PASS bound document driver: compiled fixture, DOM, storage, lifecycle and teardown; no JavaScript engine claimed"
386    );
387}
Source

pub fn storage_get(&mut self, key: &str) -> Result<Option<G::Value>, String>

Read a native guest storage value.

Examples found in repository?
examples/native_document.rs (line 294)
234fn main() {
235    let trace = Rc::new(RefCell::new(Vec::new()));
236    let html = Arc::from(
237        "<output id=subject>pending</output><template><script src='inert.js'>inert</script></template><script nomodule src='legacy.js'>inert</script><script type=application/json>inert</script><script>paint()</script><script src='data:text/javascript,paint()'></script>",
238    );
239    let mut page = Page::from_html(html, DocumentConfig::default()).expect("parse fixture");
240    assert_eq!(
241        blitz_script::external_script_urls(&page.inner()),
242        vec![Url::parse("data:text/javascript,paint()").unwrap()]
243    );
244    assert!(
245        page.execute_scripts().is_err(),
246        "unbound execution must fail"
247    );
248    page.attach_native_host(guest(&trace, true))
249        .expect("bind compiled guest");
250    page.storage_set("seed", 8).expect("seed before scripts");
251    page.execute_scripts().expect("execute compiled fixture");
252    page.execute_scripts().expect("bootstrap is idempotent");
253    let subject = page.inner().query_selector("#subject").unwrap().unwrap();
254    assert_eq!(
255        page.inner().get_node(subject).unwrap().text_content(),
256        "9",
257        "rendered-bootstrap"
258    );
259    assert_eq!(
260        &*trace.borrow(),
261        &["install", "execute", "execute", "ready"],
262        "script-order-and-inert-subtrees"
263    );
264    page.handle_ui_event(UiEvent::AppleStandardKeybinding("selectAll:".into()));
265    page.set_page_visible(false);
266    page.freeze();
267    assert!(!page.poll(None), "frozen guest must not run");
268    page.resume();
269    page.finish_restore();
270    let wakes = Arc::new(WakeCount(AtomicUsize::new(0)));
271    let waker = std::task::Waker::from(Arc::clone(&wakes));
272    assert!(page.poll(Some(Context::from_waker(&waker))));
273    assert_eq!(
274        wakes.0.load(Ordering::Relaxed),
275        1,
276        "document-waker-propagation"
277    );
278    assert!(page.poll_for_settle(None, false));
279    assert!(page.poll_for_settle(None, true));
280    assert_eq!(
281        &trace.borrow()[4..],
282        &[
283            "event",
284            "visibility",
285            "freeze",
286            "resume",
287            "restore",
288            "poll",
289            "jobs",
290            "timers"
291        ],
292        "lifecycle-and-timer-policy"
293    );
294    assert_eq!(page.storage_get("seed").unwrap(), Some(8));
295    page.storage_remove("seed").unwrap();
296    assert_eq!(page.storage_get("seed").unwrap(), None);
297    page.storage_set("seed", 3).unwrap();
298    page.storage_clear().unwrap();
299    assert_eq!(page.storage_get("seed").unwrap(), None);
300
301    page.with_guest_mut(|guest, document| {
302        assert!(guest.storage.is_empty());
303        assert_eq!(document.query_selector("#subject").unwrap(), Some(subject));
304    })
305    .unwrap();
306    let hook_order = Rc::new(RefCell::new(Vec::new()));
307    let nested_installed = Rc::new(Cell::new(false));
308    let retire = Rc::new(Cell::new(false));
309    let hook_wakes = Rc::new(Cell::new(0));
310    for index in [1, 2] {
311        let order = Rc::clone(&hook_order);
312        let installed = Rc::clone(&nested_installed);
313        let retire = Rc::clone(&retire);
314        let wakes = Rc::clone(&hook_wakes);
315        page.add_poll_hook(Box::new(move |document, context| {
316            order.borrow_mut().push(index);
317            if context.is_some() {
318                wakes.set(wakes.get() + 1);
319            }
320            if index == 1 && !installed.replace(true) {
321                let nested_order = Rc::clone(&order);
322                (document as &mut dyn std::any::Any)
323                    .downcast_mut::<Page>()
324                    .unwrap()
325                    .add_poll_hook(Box::new(move |_, _| {
326                        nested_order.borrow_mut().push(3);
327                        false
328                    }))
329                    .unwrap();
330            }
331            if index == 1 && retire.get() {
332                document.prepare_teardown();
333            }
334            index == 1
335        }))
336        .unwrap();
337    }
338    assert!(page.poll(None));
339    assert_eq!(&*hook_order.borrow(), &[1, 2]);
340    assert!(page.poll_for_settle(Some(Context::from_waker(&waker)), false));
341    assert_eq!(&*hook_order.borrow(), &[1, 2, 1, 2, 3]);
342    assert_eq!(hook_wakes.get(), 2);
343    retire.set(true);
344    assert!(!page.poll(None));
345    assert_eq!(&*hook_order.borrow(), &[1, 2, 1, 2, 3, 1]);
346    assert!(page.guest().is_none());
347    assert!(page.add_poll_hook(Box::new(|_, _| true)).is_err());
348    page.prepare_teardown();
349    let calls = trace.borrow().len();
350    assert!(!page.poll(None));
351    assert!(page.execute_scripts().is_err());
352    assert!(page.storage_set("seed", 1).is_err());
353    page.handle_ui_event(UiEvent::AppleStandardKeybinding("selectAll:".into()));
354    assert_eq!(trace.borrow().len(), calls, "retired-guest-entry");
355    drop(page);
356    assert_eq!(
357        trace.borrow().iter().filter(|&&v| v == "teardown").count(),
358        1
359    );
360    assert_eq!(trace.borrow().last(), Some(&"dispose"));
361    let drop_trace = Rc::new(RefCell::new(Vec::new()));
362    let page = Page::new_bound(
363        Arc::from("<p>plain</p>"),
364        DocumentConfig::default(),
365        guest(&drop_trace, true),
366    )
367    .unwrap();
368    drop(page);
369    assert_eq!(
370        &*drop_trace.borrow(),
371        &["install", "teardown", "dispose"],
372        "drop-cleanup"
373    );
374    #[cfg(feature = "intl")]
375    {
376        let mut page = Page::new_bound(
377            Arc::from("<script>paint()</script>"),
378            DocumentConfig::default(),
379            guest(&drop_trace, false),
380        )
381        .unwrap();
382        assert!(page.execute_scripts().unwrap_err().contains("Intl"));
383    }
384    println!(
385        "PASS bound document driver: compiled fixture, DOM, storage, lifecycle and teardown; no JavaScript engine claimed"
386    );
387}
Source

pub fn storage_set(&mut self, key: &str, value: G::Value) -> Result<(), String>

Write a native guest storage value.

Examples found in repository?
examples/native_document.rs (line 250)
234fn main() {
235    let trace = Rc::new(RefCell::new(Vec::new()));
236    let html = Arc::from(
237        "<output id=subject>pending</output><template><script src='inert.js'>inert</script></template><script nomodule src='legacy.js'>inert</script><script type=application/json>inert</script><script>paint()</script><script src='data:text/javascript,paint()'></script>",
238    );
239    let mut page = Page::from_html(html, DocumentConfig::default()).expect("parse fixture");
240    assert_eq!(
241        blitz_script::external_script_urls(&page.inner()),
242        vec![Url::parse("data:text/javascript,paint()").unwrap()]
243    );
244    assert!(
245        page.execute_scripts().is_err(),
246        "unbound execution must fail"
247    );
248    page.attach_native_host(guest(&trace, true))
249        .expect("bind compiled guest");
250    page.storage_set("seed", 8).expect("seed before scripts");
251    page.execute_scripts().expect("execute compiled fixture");
252    page.execute_scripts().expect("bootstrap is idempotent");
253    let subject = page.inner().query_selector("#subject").unwrap().unwrap();
254    assert_eq!(
255        page.inner().get_node(subject).unwrap().text_content(),
256        "9",
257        "rendered-bootstrap"
258    );
259    assert_eq!(
260        &*trace.borrow(),
261        &["install", "execute", "execute", "ready"],
262        "script-order-and-inert-subtrees"
263    );
264    page.handle_ui_event(UiEvent::AppleStandardKeybinding("selectAll:".into()));
265    page.set_page_visible(false);
266    page.freeze();
267    assert!(!page.poll(None), "frozen guest must not run");
268    page.resume();
269    page.finish_restore();
270    let wakes = Arc::new(WakeCount(AtomicUsize::new(0)));
271    let waker = std::task::Waker::from(Arc::clone(&wakes));
272    assert!(page.poll(Some(Context::from_waker(&waker))));
273    assert_eq!(
274        wakes.0.load(Ordering::Relaxed),
275        1,
276        "document-waker-propagation"
277    );
278    assert!(page.poll_for_settle(None, false));
279    assert!(page.poll_for_settle(None, true));
280    assert_eq!(
281        &trace.borrow()[4..],
282        &[
283            "event",
284            "visibility",
285            "freeze",
286            "resume",
287            "restore",
288            "poll",
289            "jobs",
290            "timers"
291        ],
292        "lifecycle-and-timer-policy"
293    );
294    assert_eq!(page.storage_get("seed").unwrap(), Some(8));
295    page.storage_remove("seed").unwrap();
296    assert_eq!(page.storage_get("seed").unwrap(), None);
297    page.storage_set("seed", 3).unwrap();
298    page.storage_clear().unwrap();
299    assert_eq!(page.storage_get("seed").unwrap(), None);
300
301    page.with_guest_mut(|guest, document| {
302        assert!(guest.storage.is_empty());
303        assert_eq!(document.query_selector("#subject").unwrap(), Some(subject));
304    })
305    .unwrap();
306    let hook_order = Rc::new(RefCell::new(Vec::new()));
307    let nested_installed = Rc::new(Cell::new(false));
308    let retire = Rc::new(Cell::new(false));
309    let hook_wakes = Rc::new(Cell::new(0));
310    for index in [1, 2] {
311        let order = Rc::clone(&hook_order);
312        let installed = Rc::clone(&nested_installed);
313        let retire = Rc::clone(&retire);
314        let wakes = Rc::clone(&hook_wakes);
315        page.add_poll_hook(Box::new(move |document, context| {
316            order.borrow_mut().push(index);
317            if context.is_some() {
318                wakes.set(wakes.get() + 1);
319            }
320            if index == 1 && !installed.replace(true) {
321                let nested_order = Rc::clone(&order);
322                (document as &mut dyn std::any::Any)
323                    .downcast_mut::<Page>()
324                    .unwrap()
325                    .add_poll_hook(Box::new(move |_, _| {
326                        nested_order.borrow_mut().push(3);
327                        false
328                    }))
329                    .unwrap();
330            }
331            if index == 1 && retire.get() {
332                document.prepare_teardown();
333            }
334            index == 1
335        }))
336        .unwrap();
337    }
338    assert!(page.poll(None));
339    assert_eq!(&*hook_order.borrow(), &[1, 2]);
340    assert!(page.poll_for_settle(Some(Context::from_waker(&waker)), false));
341    assert_eq!(&*hook_order.borrow(), &[1, 2, 1, 2, 3]);
342    assert_eq!(hook_wakes.get(), 2);
343    retire.set(true);
344    assert!(!page.poll(None));
345    assert_eq!(&*hook_order.borrow(), &[1, 2, 1, 2, 3, 1]);
346    assert!(page.guest().is_none());
347    assert!(page.add_poll_hook(Box::new(|_, _| true)).is_err());
348    page.prepare_teardown();
349    let calls = trace.borrow().len();
350    assert!(!page.poll(None));
351    assert!(page.execute_scripts().is_err());
352    assert!(page.storage_set("seed", 1).is_err());
353    page.handle_ui_event(UiEvent::AppleStandardKeybinding("selectAll:".into()));
354    assert_eq!(trace.borrow().len(), calls, "retired-guest-entry");
355    drop(page);
356    assert_eq!(
357        trace.borrow().iter().filter(|&&v| v == "teardown").count(),
358        1
359    );
360    assert_eq!(trace.borrow().last(), Some(&"dispose"));
361    let drop_trace = Rc::new(RefCell::new(Vec::new()));
362    let page = Page::new_bound(
363        Arc::from("<p>plain</p>"),
364        DocumentConfig::default(),
365        guest(&drop_trace, true),
366    )
367    .unwrap();
368    drop(page);
369    assert_eq!(
370        &*drop_trace.borrow(),
371        &["install", "teardown", "dispose"],
372        "drop-cleanup"
373    );
374    #[cfg(feature = "intl")]
375    {
376        let mut page = Page::new_bound(
377            Arc::from("<script>paint()</script>"),
378            DocumentConfig::default(),
379            guest(&drop_trace, false),
380        )
381        .unwrap();
382        assert!(page.execute_scripts().unwrap_err().contains("Intl"));
383    }
384    println!(
385        "PASS bound document driver: compiled fixture, DOM, storage, lifecycle and teardown; no JavaScript engine claimed"
386    );
387}
Source

pub fn storage_remove(&mut self, key: &str) -> Result<(), String>

Examples found in repository?
examples/native_document.rs (line 295)
234fn main() {
235    let trace = Rc::new(RefCell::new(Vec::new()));
236    let html = Arc::from(
237        "<output id=subject>pending</output><template><script src='inert.js'>inert</script></template><script nomodule src='legacy.js'>inert</script><script type=application/json>inert</script><script>paint()</script><script src='data:text/javascript,paint()'></script>",
238    );
239    let mut page = Page::from_html(html, DocumentConfig::default()).expect("parse fixture");
240    assert_eq!(
241        blitz_script::external_script_urls(&page.inner()),
242        vec![Url::parse("data:text/javascript,paint()").unwrap()]
243    );
244    assert!(
245        page.execute_scripts().is_err(),
246        "unbound execution must fail"
247    );
248    page.attach_native_host(guest(&trace, true))
249        .expect("bind compiled guest");
250    page.storage_set("seed", 8).expect("seed before scripts");
251    page.execute_scripts().expect("execute compiled fixture");
252    page.execute_scripts().expect("bootstrap is idempotent");
253    let subject = page.inner().query_selector("#subject").unwrap().unwrap();
254    assert_eq!(
255        page.inner().get_node(subject).unwrap().text_content(),
256        "9",
257        "rendered-bootstrap"
258    );
259    assert_eq!(
260        &*trace.borrow(),
261        &["install", "execute", "execute", "ready"],
262        "script-order-and-inert-subtrees"
263    );
264    page.handle_ui_event(UiEvent::AppleStandardKeybinding("selectAll:".into()));
265    page.set_page_visible(false);
266    page.freeze();
267    assert!(!page.poll(None), "frozen guest must not run");
268    page.resume();
269    page.finish_restore();
270    let wakes = Arc::new(WakeCount(AtomicUsize::new(0)));
271    let waker = std::task::Waker::from(Arc::clone(&wakes));
272    assert!(page.poll(Some(Context::from_waker(&waker))));
273    assert_eq!(
274        wakes.0.load(Ordering::Relaxed),
275        1,
276        "document-waker-propagation"
277    );
278    assert!(page.poll_for_settle(None, false));
279    assert!(page.poll_for_settle(None, true));
280    assert_eq!(
281        &trace.borrow()[4..],
282        &[
283            "event",
284            "visibility",
285            "freeze",
286            "resume",
287            "restore",
288            "poll",
289            "jobs",
290            "timers"
291        ],
292        "lifecycle-and-timer-policy"
293    );
294    assert_eq!(page.storage_get("seed").unwrap(), Some(8));
295    page.storage_remove("seed").unwrap();
296    assert_eq!(page.storage_get("seed").unwrap(), None);
297    page.storage_set("seed", 3).unwrap();
298    page.storage_clear().unwrap();
299    assert_eq!(page.storage_get("seed").unwrap(), None);
300
301    page.with_guest_mut(|guest, document| {
302        assert!(guest.storage.is_empty());
303        assert_eq!(document.query_selector("#subject").unwrap(), Some(subject));
304    })
305    .unwrap();
306    let hook_order = Rc::new(RefCell::new(Vec::new()));
307    let nested_installed = Rc::new(Cell::new(false));
308    let retire = Rc::new(Cell::new(false));
309    let hook_wakes = Rc::new(Cell::new(0));
310    for index in [1, 2] {
311        let order = Rc::clone(&hook_order);
312        let installed = Rc::clone(&nested_installed);
313        let retire = Rc::clone(&retire);
314        let wakes = Rc::clone(&hook_wakes);
315        page.add_poll_hook(Box::new(move |document, context| {
316            order.borrow_mut().push(index);
317            if context.is_some() {
318                wakes.set(wakes.get() + 1);
319            }
320            if index == 1 && !installed.replace(true) {
321                let nested_order = Rc::clone(&order);
322                (document as &mut dyn std::any::Any)
323                    .downcast_mut::<Page>()
324                    .unwrap()
325                    .add_poll_hook(Box::new(move |_, _| {
326                        nested_order.borrow_mut().push(3);
327                        false
328                    }))
329                    .unwrap();
330            }
331            if index == 1 && retire.get() {
332                document.prepare_teardown();
333            }
334            index == 1
335        }))
336        .unwrap();
337    }
338    assert!(page.poll(None));
339    assert_eq!(&*hook_order.borrow(), &[1, 2]);
340    assert!(page.poll_for_settle(Some(Context::from_waker(&waker)), false));
341    assert_eq!(&*hook_order.borrow(), &[1, 2, 1, 2, 3]);
342    assert_eq!(hook_wakes.get(), 2);
343    retire.set(true);
344    assert!(!page.poll(None));
345    assert_eq!(&*hook_order.borrow(), &[1, 2, 1, 2, 3, 1]);
346    assert!(page.guest().is_none());
347    assert!(page.add_poll_hook(Box::new(|_, _| true)).is_err());
348    page.prepare_teardown();
349    let calls = trace.borrow().len();
350    assert!(!page.poll(None));
351    assert!(page.execute_scripts().is_err());
352    assert!(page.storage_set("seed", 1).is_err());
353    page.handle_ui_event(UiEvent::AppleStandardKeybinding("selectAll:".into()));
354    assert_eq!(trace.borrow().len(), calls, "retired-guest-entry");
355    drop(page);
356    assert_eq!(
357        trace.borrow().iter().filter(|&&v| v == "teardown").count(),
358        1
359    );
360    assert_eq!(trace.borrow().last(), Some(&"dispose"));
361    let drop_trace = Rc::new(RefCell::new(Vec::new()));
362    let page = Page::new_bound(
363        Arc::from("<p>plain</p>"),
364        DocumentConfig::default(),
365        guest(&drop_trace, true),
366    )
367    .unwrap();
368    drop(page);
369    assert_eq!(
370        &*drop_trace.borrow(),
371        &["install", "teardown", "dispose"],
372        "drop-cleanup"
373    );
374    #[cfg(feature = "intl")]
375    {
376        let mut page = Page::new_bound(
377            Arc::from("<script>paint()</script>"),
378            DocumentConfig::default(),
379            guest(&drop_trace, false),
380        )
381        .unwrap();
382        assert!(page.execute_scripts().unwrap_err().contains("Intl"));
383    }
384    println!(
385        "PASS bound document driver: compiled fixture, DOM, storage, lifecycle and teardown; no JavaScript engine claimed"
386    );
387}
Source

pub fn storage_clear(&mut self) -> Result<(), String>

Examples found in repository?
examples/native_document.rs (line 298)
234fn main() {
235    let trace = Rc::new(RefCell::new(Vec::new()));
236    let html = Arc::from(
237        "<output id=subject>pending</output><template><script src='inert.js'>inert</script></template><script nomodule src='legacy.js'>inert</script><script type=application/json>inert</script><script>paint()</script><script src='data:text/javascript,paint()'></script>",
238    );
239    let mut page = Page::from_html(html, DocumentConfig::default()).expect("parse fixture");
240    assert_eq!(
241        blitz_script::external_script_urls(&page.inner()),
242        vec![Url::parse("data:text/javascript,paint()").unwrap()]
243    );
244    assert!(
245        page.execute_scripts().is_err(),
246        "unbound execution must fail"
247    );
248    page.attach_native_host(guest(&trace, true))
249        .expect("bind compiled guest");
250    page.storage_set("seed", 8).expect("seed before scripts");
251    page.execute_scripts().expect("execute compiled fixture");
252    page.execute_scripts().expect("bootstrap is idempotent");
253    let subject = page.inner().query_selector("#subject").unwrap().unwrap();
254    assert_eq!(
255        page.inner().get_node(subject).unwrap().text_content(),
256        "9",
257        "rendered-bootstrap"
258    );
259    assert_eq!(
260        &*trace.borrow(),
261        &["install", "execute", "execute", "ready"],
262        "script-order-and-inert-subtrees"
263    );
264    page.handle_ui_event(UiEvent::AppleStandardKeybinding("selectAll:".into()));
265    page.set_page_visible(false);
266    page.freeze();
267    assert!(!page.poll(None), "frozen guest must not run");
268    page.resume();
269    page.finish_restore();
270    let wakes = Arc::new(WakeCount(AtomicUsize::new(0)));
271    let waker = std::task::Waker::from(Arc::clone(&wakes));
272    assert!(page.poll(Some(Context::from_waker(&waker))));
273    assert_eq!(
274        wakes.0.load(Ordering::Relaxed),
275        1,
276        "document-waker-propagation"
277    );
278    assert!(page.poll_for_settle(None, false));
279    assert!(page.poll_for_settle(None, true));
280    assert_eq!(
281        &trace.borrow()[4..],
282        &[
283            "event",
284            "visibility",
285            "freeze",
286            "resume",
287            "restore",
288            "poll",
289            "jobs",
290            "timers"
291        ],
292        "lifecycle-and-timer-policy"
293    );
294    assert_eq!(page.storage_get("seed").unwrap(), Some(8));
295    page.storage_remove("seed").unwrap();
296    assert_eq!(page.storage_get("seed").unwrap(), None);
297    page.storage_set("seed", 3).unwrap();
298    page.storage_clear().unwrap();
299    assert_eq!(page.storage_get("seed").unwrap(), None);
300
301    page.with_guest_mut(|guest, document| {
302        assert!(guest.storage.is_empty());
303        assert_eq!(document.query_selector("#subject").unwrap(), Some(subject));
304    })
305    .unwrap();
306    let hook_order = Rc::new(RefCell::new(Vec::new()));
307    let nested_installed = Rc::new(Cell::new(false));
308    let retire = Rc::new(Cell::new(false));
309    let hook_wakes = Rc::new(Cell::new(0));
310    for index in [1, 2] {
311        let order = Rc::clone(&hook_order);
312        let installed = Rc::clone(&nested_installed);
313        let retire = Rc::clone(&retire);
314        let wakes = Rc::clone(&hook_wakes);
315        page.add_poll_hook(Box::new(move |document, context| {
316            order.borrow_mut().push(index);
317            if context.is_some() {
318                wakes.set(wakes.get() + 1);
319            }
320            if index == 1 && !installed.replace(true) {
321                let nested_order = Rc::clone(&order);
322                (document as &mut dyn std::any::Any)
323                    .downcast_mut::<Page>()
324                    .unwrap()
325                    .add_poll_hook(Box::new(move |_, _| {
326                        nested_order.borrow_mut().push(3);
327                        false
328                    }))
329                    .unwrap();
330            }
331            if index == 1 && retire.get() {
332                document.prepare_teardown();
333            }
334            index == 1
335        }))
336        .unwrap();
337    }
338    assert!(page.poll(None));
339    assert_eq!(&*hook_order.borrow(), &[1, 2]);
340    assert!(page.poll_for_settle(Some(Context::from_waker(&waker)), false));
341    assert_eq!(&*hook_order.borrow(), &[1, 2, 1, 2, 3]);
342    assert_eq!(hook_wakes.get(), 2);
343    retire.set(true);
344    assert!(!page.poll(None));
345    assert_eq!(&*hook_order.borrow(), &[1, 2, 1, 2, 3, 1]);
346    assert!(page.guest().is_none());
347    assert!(page.add_poll_hook(Box::new(|_, _| true)).is_err());
348    page.prepare_teardown();
349    let calls = trace.borrow().len();
350    assert!(!page.poll(None));
351    assert!(page.execute_scripts().is_err());
352    assert!(page.storage_set("seed", 1).is_err());
353    page.handle_ui_event(UiEvent::AppleStandardKeybinding("selectAll:".into()));
354    assert_eq!(trace.borrow().len(), calls, "retired-guest-entry");
355    drop(page);
356    assert_eq!(
357        trace.borrow().iter().filter(|&&v| v == "teardown").count(),
358        1
359    );
360    assert_eq!(trace.borrow().last(), Some(&"dispose"));
361    let drop_trace = Rc::new(RefCell::new(Vec::new()));
362    let page = Page::new_bound(
363        Arc::from("<p>plain</p>"),
364        DocumentConfig::default(),
365        guest(&drop_trace, true),
366    )
367    .unwrap();
368    drop(page);
369    assert_eq!(
370        &*drop_trace.borrow(),
371        &["install", "teardown", "dispose"],
372        "drop-cleanup"
373    );
374    #[cfg(feature = "intl")]
375    {
376        let mut page = Page::new_bound(
377            Arc::from("<script>paint()</script>"),
378            DocumentConfig::default(),
379            guest(&drop_trace, false),
380        )
381        .unwrap();
382        assert!(page.execute_scripts().unwrap_err().contains("Intl"));
383    }
384    println!(
385        "PASS bound document driver: compiled fixture, DOM, storage, lifecycle and teardown; no JavaScript engine claimed"
386    );
387}
Source§

impl<G, H> BoundScriptDocument<G, H>
where G: NativeDocumentRuntime, H: NativeHost<Guest = G> + 'static,

Source

pub fn eval(&mut self, source: &str) -> Result<(), String>

Evaluate source through the bound native guest.

Source

pub fn eval_named(&mut self, source: &str, name: &str) -> Result<(), String>

Evaluate named source through the bound native guest.

Source

pub fn eval_json(&mut self, source: &str) -> Result<Value, String>

Evaluate source and return its JSON-compatible result.

Source

pub fn has_pending_jobs(&self) -> bool

Whether the live guest reports pending jobs for this document.

Source

pub fn pending_task_count(&self) -> u64

Return the live guest’s pending task count.

Source

pub fn diagnostic_batch( &self, console_after: u64, errors_after: u64, limit: usize, ) -> Result<DiagnosticBatch, String>

Return a bounded batch of diagnostics from the bound guest.

Source

pub fn dispatch_dom_event(&mut self, event: DomEvent) -> Result<(), String>

Dispatch a DOM event through the bound native guest.

Source

pub fn handle_pointer_move_to_node( &mut self, event: BlitzPointerEvent, node: NodeId, ) -> Result<(), String>

Move pointer state to a caller-resolved node through the bound guest.

Source

pub fn handle_ui_event_to_node( &mut self, event: UiEvent, node: NodeId, ) -> Result<(), String>

Dispatch UI input to a caller-resolved node through the bound guest.

Source

pub fn dispatch_node_event( &mut self, node: NodeId, name: &str, ) -> Result<bool, String>

Dispatch a named event at a node through the bound guest.

Source

pub fn set_ipc_handler( &mut self, handler: Box<dyn Fn(String)>, ) -> Result<(), String>

Install an IPC handler through the bound native guest.

Trait Implementations§

Source§

impl<G, H> Document for BoundScriptDocument<G, H>
where G: TypedNativeGuest, H: NativeHost<Guest = G> + 'static,

Source§

fn inner(&self) -> DocGuard<'_>

Source§

fn inner_mut(&mut self) -> DocGuardMut<'_>

Source§

fn handle_ui_event(&mut self, event: UiEvent)

Update the Document in response to a UiEvent (click, keypress, etc)
Source§

fn poll(&mut self, context: Option<Context<'_>>) -> bool

Poll any pending async operations, and flush changes to the underlying BaseDocument
Source§

fn poll_for_settle( &mut self, context: Option<Context<'_>>, run_timers: bool, ) -> bool

Drain immediate work for a host’s settle loop. Read more
Source§

fn prepare_teardown(&mut self)

Revoke child work before ownership is dropped. Completion is separate.
Source§

fn dispose(self: Box<Self>) -> Arc<Teardown> ⓘ

Source§

fn set_page_visible(&mut self, visible: bool)

Source§

fn freeze(&mut self)

Source§

fn finish_restore(&mut self)

Source§

fn resume(&mut self)

Source§

fn id(&self) -> usize

Get the Document’s id
Source§

impl<G, H> Drop for BoundScriptDocument<G, H>
where G: TypedNativeGuest, H: NativeHost<Guest = G> + 'static,

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl<G, H> NativeHostDocumentBackend for BoundScriptDocument<G, H>
where G: TypedNativeGuest, H: NativeHost<Guest = G> + 'static,

Source§

type Host = H

The engine-specific host owned by this backend after attachment.
Source§

fn attach_native_host(&mut self, host: Self::Host) -> Result<(), String>

Attach host to this document before executing its scripts. Read more
Source§

impl<G, H> ScriptDocumentBackend for BoundScriptDocument<G, H>
where G: TypedNativeGuest, H: NativeHost<Guest = G> + 'static,

Auto Trait Implementations§

§

impl<G, H> !Freeze for BoundScriptDocument<G, H>

§

impl<G, H> !RefUnwindSafe for BoundScriptDocument<G, H>

§

impl<G, H> !Send for BoundScriptDocument<G, H>

§

impl<G, H> !Sync for BoundScriptDocument<G, H>

§

impl<G, H> !UnwindSafe for BoundScriptDocument<G, H>

§

impl<G, H> Forget for BoundScriptDocument<G, H>

§

impl<G, H> Move for BoundScriptDocument<G, H>

§

impl<G, H> Unpin for BoundScriptDocument<G, H>

§

impl<G, H> UnsafeUnpin for BoundScriptDocument<G, H>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> MaybeBoxed<Box<T>> for T

Source§

fn maybe_boxed(self) -> Box<T>

Convert
Source§

impl<T> MaybeBoxed<T> for T

Source§

fn maybe_boxed(self) -> T

Convert
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.