Skip to main content

sk_tree/
pointer_lock.rs

1//! The Pointer Lock API. One document, so one lock: an element, held in the window that paints it.
2//!
3//! JS asks ([`sk_pointer_lock_request`], [`sk_pointer_lock_exit`]); each window's frame settles what
4//! was asked of it against the platform ([`tick`]) and tells the document with
5//! `pointerlockchange` / `pointerlockerror` (`a` = the request settled, 0 for none). Escape
6//! ([`intercept_escape`]), losing focus, removing the element, a reload and closing the window let
7//! go. After the user lets go, only a newer gesture locks again (Chromium's rule).
8//!
9//! `SK_POINTER_LOCK=fake` simulates the lock in gpui without touching the cursor and counts every
10//! window as focused (tests); `deny` refuses every request.
11
12use std::cell::{Cell, RefCell};
13use std::collections::HashMap;
14use std::ffi::c_void;
15use std::time::{Duration, Instant};
16
17use gpui::{App, KeystrokeEvent, PointerLockError, VnPointerLock, Window};
18use sk_runtime::host::{self, global, Settler};
19use sk_runtime::redjs::webapi::util::*;
20use sk_runtime::{host_fn, JsRuntime};
21
22use crate::native_dom;
23
24use crate::tree::{self, Kind};
25use crate::windows::{self, WinKey};
26use crate::EventPayload;
27
28/// Transient activation's lifespan (Chromium's).
29const ACTIVATION: Duration = Duration::from_secs(5);
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32enum Mode {
33    System,
34    Simulated,
35    Denied,
36}
37
38fn mode() -> Mode {
39    thread_local! { static MODE: Cell<Option<Mode>> = const { Cell::new(None) }; }
40    MODE.with(|m| {
41        *m.get().get_or_insert_with(|| {
42            match std::env::var("SK_POINTER_LOCK")
43                .ok()
44                .as_deref()
45                .map(str::trim)
46            {
47                Some(v) if v.eq_ignore_ascii_case("fake") => Mode::Simulated,
48                Some(v) if v.eq_ignore_ascii_case("deny") => Mode::Denied,
49                _ => Mode::System,
50            }
51        })
52    })
53}
54
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56enum Refusal {
57    Unsupported,
58    Refused,
59    Denied,
60}
61
62impl From<PointerLockError> for Refusal {
63    fn from(e: PointerLockError) -> Self {
64        match e {
65            PointerLockError::Unsupported => Refusal::Unsupported,
66            PointerLockError::Refused => Refusal::Refused,
67        }
68    }
69}
70
71/// What the state machine needs from one window and the tree.
72trait Host {
73    fn window(&self) -> WinKey;
74    fn focused(&self) -> bool;
75    fn lock(&mut self, unadjusted: bool) -> Result<(), Refusal>;
76    fn unlock(&mut self);
77    fn locked(&self) -> bool;
78    /// The window painting `element`; `None` when it is no connected element.
79    fn window_of(&self, element: u32) -> Option<WinKey>;
80}
81
82#[derive(Clone, Debug, PartialEq, Eq)]
83enum Note {
84    /// `pointerlockchange`, settling request `request` (0: none).
85    Change { request: u32 },
86    Error {
87        request: u32,
88        name: &'static str,
89        message: &'static str,
90    },
91}
92
93#[derive(Clone, Copy, Debug, PartialEq, Eq)]
94struct Held {
95    element: u32,
96    window: WinKey,
97    unadjusted: bool,
98}
99
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101enum Op {
102    Request {
103        id: u32,
104        element: u32,
105        unadjusted: bool,
106        /// The gesture the request was made under, if one was still active.
107        gesture: Option<u64>,
108    },
109    Exit,
110}
111
112#[derive(Default)]
113struct State {
114    held: Option<Held>,
115    ops: Vec<Op>,
116    next_id: u32,
117    gestures: u64,
118    gesture_at: Option<Instant>,
119    /// The gesture count when the user let go: a new lock needs a later gesture.
120    released_after: Option<u64>,
121    /// Windows whose system lock outlived its document (a reload).
122    unlock_owed: Vec<WinKey>,
123    /// Changes for a window that can no longer tell (it closed).
124    owed: Vec<Note>,
125}
126
127impl State {
128    fn note_gesture(&mut self, now: Instant) {
129        self.gestures += 1;
130        self.gesture_at = Some(now);
131    }
132
133    fn active_gesture(&self, now: Instant) -> Option<u64> {
134        let at = self.gesture_at?;
135        (now.saturating_duration_since(at) <= ACTIVATION).then_some(self.gestures)
136    }
137
138    fn request(&mut self, element: u32, unadjusted: bool, now: Instant) -> u32 {
139        self.next_id = self.next_id.wrapping_add(1).max(1);
140        let id = self.next_id;
141        self.ops.push(Op::Request {
142            id,
143            element,
144            unadjusted,
145            gesture: self.active_gesture(now),
146        });
147        id
148    }
149
150    fn exit(&mut self) {
151        self.ops.push(Op::Exit);
152    }
153
154    fn held_in(&self, window: WinKey) -> Option<Held> {
155        self.held.filter(|h| h.window == window)
156    }
157
158    fn release_by_user(&mut self, host: &mut dyn Host) -> Option<Note> {
159        self.held_in(host.window())?;
160        host.unlock();
161        self.held = None;
162        self.released_after = Some(self.gestures);
163        Some(Note::Change { request: 0 })
164    }
165
166    fn tick(&mut self, host: &mut dyn Host) -> Vec<Note> {
167        let here = host.window();
168        let mut notes = std::mem::take(&mut self.owed);
169        if let Some(at) = self.unlock_owed.iter().position(|&w| w == here) {
170            self.unlock_owed.swap_remove(at);
171            if self.held_in(here).is_none() {
172                host.unlock();
173            }
174        }
175        if let Some(held) = self.held_in(here) {
176            if !host.locked() || !host.focused() {
177                notes.extend(self.release_by_user(host));
178            } else if host.window_of(held.element) != Some(here) {
179                host.unlock();
180                self.held = None;
181                notes.push(Note::Change { request: 0 });
182            }
183        }
184        for op in std::mem::take(&mut self.ops) {
185            match op {
186                Op::Request {
187                    id,
188                    element,
189                    unadjusted,
190                    gesture,
191                } => match host.window_of(element) {
192                    None => notes.push(Note::Error {
193                        request: id,
194                        name: "WrongDocumentError",
195                        message: "The element is not connected to the document.",
196                    }),
197                    Some(w) if w != here => self.ops.push(op),
198                    Some(_) => self.grant(host, id, element, unadjusted, gesture, &mut notes),
199                },
200                Op::Exit => match self.held {
201                    Some(held) if held.window == here => {
202                        host.unlock();
203                        self.held = None;
204                        notes.push(Note::Change { request: 0 });
205                    }
206                    Some(_) => self.ops.push(op),
207                    None => {}
208                },
209            }
210        }
211        notes
212    }
213
214    fn grant(
215        &mut self,
216        host: &mut dyn Host,
217        id: u32,
218        element: u32,
219        unadjusted: bool,
220        gesture: Option<u64>,
221        notes: &mut Vec<Note>,
222    ) {
223        let here = host.window();
224        let error = |name, message| Note::Error {
225            request: id,
226            name,
227            message,
228        };
229        if !host.focused() {
230            return notes.push(error(
231                "WrongDocumentError",
232                "Pointer lock needs the window to be focused.",
233            ));
234        }
235        let current = self.held_in(here);
236        if current.is_none() {
237            let Some(gesture) = gesture else {
238                return notes.push(error(
239                    "NotAllowedError",
240                    "requestPointerLock() needs a user gesture: call it from a click or key \
241                     press handler.",
242                ));
243            };
244            if self.released_after.is_some_and(|after| gesture <= after) {
245                return notes.push(error(
246                    "NotAllowedError",
247                    "The user released the pointer lock: requesting it again needs a new user \
248                     gesture.",
249                ));
250            }
251        }
252        if let Some(other) = self.held.filter(|h| h.window != here) {
253            self.unlock_owed.push(other.window);
254            self.held = None;
255            notes.push(Note::Change { request: 0 });
256        }
257        if current.is_some_and(|held| held.unadjusted == unadjusted) {
258            self.held = Some(Held {
259                element,
260                window: here,
261                unadjusted,
262            });
263            return notes.push(Note::Change { request: id });
264        }
265        match host.lock(unadjusted) {
266            Ok(()) => {
267                self.held = Some(Held {
268                    element,
269                    window: here,
270                    unadjusted,
271                });
272                notes.push(Note::Change { request: id });
273            }
274            Err(refusal) => {
275                if current.is_some() {
276                    self.held = None;
277                    notes.push(Note::Change { request: 0 });
278                }
279                notes.push(match refusal {
280                    Refusal::Unsupported if unadjusted => error(
281                        "NotSupportedError",
282                        "unadjustedMovement is not supported on this platform.",
283                    ),
284                    Refusal::Unsupported => error(
285                        "NotSupportedError",
286                        "Pointer lock is not supported on this platform.",
287                    ),
288                    Refusal::Refused => {
289                        error("NotAllowedError", "The system refused to lock the pointer.")
290                    }
291                    Refusal::Denied => error(
292                        "NotAllowedError",
293                        "Pointer lock is off for this process (SK_POINTER_LOCK=deny).",
294                    ),
295                });
296            }
297        }
298    }
299
300    fn window_closed(&mut self, window: WinKey) {
301        self.unlock_owed.retain(|&w| w != window);
302        if self.held_in(window).is_some() {
303            self.held = None;
304            self.owed.push(Note::Change { request: 0 });
305        }
306    }
307
308    /// The document went away (a reload): its lock with it, without events.
309    fn navigated(&mut self) {
310        if let Some(held) = self.held.take() {
311            self.unlock_owed.push(held.window);
312        }
313        self.ops.clear();
314        self.owed.clear();
315        self.released_after = None;
316    }
317}
318
319thread_local! {
320    static STATE: RefCell<State> = RefCell::new(State::default());
321    /// The promise each unsettled `requestPointerLock()` returned.
322    static PENDING: RefCell<HashMap<u32, Settler>> = RefCell::new(HashMap::new());
323}
324
325fn with_state<R>(f: impl FnOnce(&mut State) -> R) -> R {
326    STATE.with(|s| f(&mut s.borrow_mut()))
327}
328
329struct WindowHost<'a> {
330    window: &'a mut Window,
331    mode: Mode,
332}
333
334impl Host for WindowHost<'_> {
335    fn window(&self) -> WinKey {
336        windows::key(self.window)
337    }
338
339    fn focused(&self) -> bool {
340        self.mode == Mode::Simulated || self.window.is_window_active()
341    }
342
343    fn lock(&mut self, unadjusted: bool) -> Result<(), Refusal> {
344        let how = match self.mode {
345            Mode::Denied => return Err(Refusal::Denied),
346            Mode::Simulated => VnPointerLock::Simulated,
347            Mode::System => VnPointerLock::System { unadjusted },
348        };
349        Ok(self.window.vn_lock_pointer(how)?)
350    }
351
352    fn unlock(&mut self) {
353        self.window.vn_unlock_pointer();
354    }
355
356    fn locked(&self) -> bool {
357        self.window.vn_pointer_locked()
358    }
359
360    fn window_of(&self, element: u32) -> Option<WinKey> {
361        tree::read_tree(|t| {
362            let element_here = t.node(element).is_some_and(|n| n.kind == Kind::Element)
363                && crate::fullscreen::connected(t, element);
364            element_here.then(|| windows::window_of_node_in(t, element))
365        })
366    }
367}
368
369/// The element holding the lock in `window`, while connected: where its mouse events go.
370pub(crate) fn target_in(window: &Window) -> Option<u32> {
371    let held = with_state(|s| s.held_in(windows::key(window)))?;
372    let connected = tree::read_tree(|t| crate::fullscreen::connected(t, held.element));
373    connected.then_some(held.element)
374}
375
376/// A press or a key press: transient activation, as far as the lock is concerned.
377pub(crate) fn note_gesture() {
378    with_state(|s| s.note_gesture(Instant::now()));
379}
380
381/// Settles this window's requests and notices a lock the platform, the focus or the tree let go.
382pub(crate) fn tick(window: &mut Window, cx: &mut App) {
383    let idle = with_state(|s| {
384        s.held.is_none() && s.ops.is_empty() && s.owed.is_empty() && s.unlock_owed.is_empty()
385    });
386    if idle {
387        return;
388    }
389    let notes = with_state(|s| {
390        s.tick(&mut WindowHost {
391            window,
392            mode: mode(),
393        })
394    });
395    deliver(notes, window, cx);
396}
397
398/// Escape releases the lock before anything else hears the key, and nothing on the page does.
399/// Every other key press counts as a gesture.
400pub fn intercept_escape(event: &KeystrokeEvent, window: &mut Window, cx: &mut App) {
401    let key = event.keystroke.key.as_str();
402    if key != "escape" {
403        if !matches!(
404            key,
405            "shift" | "control" | "alt" | "platform" | "function" | "capslock"
406        ) {
407            note_gesture();
408        }
409        return;
410    }
411    let released = with_state(|s| {
412        s.release_by_user(&mut WindowHost {
413            window,
414            mode: mode(),
415        })
416    });
417    let Some(note) = released else {
418        return;
419    };
420    crate::render::claim_key_event(window);
421    cx.stop_propagation();
422    deliver(vec![note], window, cx);
423}
424
425pub(crate) fn window_closed(window: WinKey) {
426    with_state(|s| s.window_closed(window));
427}
428
429/// The document went away: its requests are never answered.
430pub fn navigated() {
431    with_state(State::navigated);
432    let abandoned: Vec<Settler> =
433        PENDING.with(|p| p.borrow_mut().drain().map(|(_, s)| s).collect());
434    if !abandoned.is_empty() {
435        JsRuntime::try_with(|rt| {
436            for s in abandoned {
437                unsafe { s.abandon(rt.raw()) };
438            }
439        });
440    }
441}
442
443/// Fires each note's event at the document, then settles the request it answers.
444fn deliver(notes: Vec<Note>, window: &mut Window, cx: &mut App) {
445    for note in notes {
446        let code = match note {
447            Note::Change { .. } => tree::EV_POINTERLOCKCHANGE,
448            Note::Error { .. } => tree::EV_POINTERLOCKERROR,
449        };
450        crate::off_input(|| {
451            crate::render::js_dispatch_app(0, code, &EventPayload::default(), window, cx)
452        });
453        JsRuntime::try_with(|rt| unsafe { settle(rt.raw(), &note) });
454    }
455}
456
457unsafe fn settle(g: *mut c_void, note: &Note) {
458    let request = match *note {
459        Note::Change { request } | Note::Error { request, .. } => request,
460    };
461    let Some(settler) = PENDING.with(|p| p.borrow_mut().remove(&request)) else {
462        return;
463    };
464    match *note {
465        Note::Change { .. } => settler.resolve(g, UNDEF),
466        Note::Error { name, message, .. } => settler.reject(g, host::error(g, name, message)),
467    }
468}
469
470host_fn!(fn request_pointer_lock(g, args) {
471    let options = args.arg(0).0;
472    let unadjusted = is_cell(options) && unsafe { host::truthy(g, get(g, options, "unadjustedMovement")) };
473    let element = unsafe { native_dom::node_id(g, args.this().0) }.unwrap_or(0);
474    let id = with_state(|s| s.request(element, unadjusted, Instant::now()));
475    tree::with_tree(|t| t.mark_dirty());
476    let (promise, settler) = unsafe { host::deferred(g) };
477    PENDING.with(|p| p.borrow_mut().insert(id, settler));
478    promise
479});
480
481host_fn!(fn exit_pointer_lock(_g, _args) {
482    with_state(State::exit);
483    tree::with_tree(|t| t.mark_dirty());
484    UNDEF
485});
486
487host_fn!(fn pointer_lock_element(g, _args) {
488    let held = with_state(|s| s.held);
489    let element = held
490        .filter(|h| tree::read_tree(|t| crate::fullscreen::connected(t, h.element)))
491        .map_or(0, |h| h.element);
492    unsafe { native_dom::node_by_id(g, element) }
493});
494
495pub(crate) fn install(rt: &JsRuntime) {
496    unsafe {
497        let g = rt.raw();
498        native_dom::method(
499            g,
500            native_dom::proto(g, "Element"),
501            "requestPointerLock",
502            0,
503            request_pointer_lock,
504        );
505        let document = get(g, global(g), "document");
506        native_dom::method(g, document, "exitPointerLock", 0, exit_pointer_lock);
507        native_dom::accessor(
508            g,
509            document,
510            "pointerLockElement",
511            pointer_lock_element,
512            None,
513        );
514    }
515}
516
517#[cfg(test)]
518mod tests {
519    use super::*;
520    use std::collections::HashMap;
521
522    const W: WinKey = 7;
523    const OTHER: WinKey = 8;
524
525    struct Fake {
526        window: WinKey,
527        focused: bool,
528        locked: bool,
529        refuse: Option<Refusal>,
530        unadjusted_supported: bool,
531        elements: HashMap<u32, WinKey>,
532        calls: Vec<String>,
533    }
534
535    impl Fake {
536        fn new() -> Self {
537            Fake {
538                window: W,
539                focused: true,
540                locked: false,
541                refuse: None,
542                unadjusted_supported: true,
543                elements: HashMap::from([(1, W), (2, W), (3, OTHER)]),
544                calls: Vec::new(),
545            }
546        }
547    }
548
549    impl Host for Fake {
550        fn window(&self) -> WinKey {
551            self.window
552        }
553        fn focused(&self) -> bool {
554            self.focused
555        }
556        fn lock(&mut self, unadjusted: bool) -> Result<(), Refusal> {
557            self.calls.push(format!("lock {unadjusted}"));
558            if let Some(r) = self.refuse {
559                return Err(r);
560            }
561            if unadjusted && !self.unadjusted_supported {
562                return Err(Refusal::Unsupported);
563            }
564            self.locked = true;
565            Ok(())
566        }
567        fn unlock(&mut self) {
568            self.calls.push("unlock".into());
569            self.locked = false;
570        }
571        fn locked(&self) -> bool {
572            self.locked
573        }
574        fn window_of(&self, element: u32) -> Option<WinKey> {
575            self.elements.get(&element).copied()
576        }
577    }
578
579    fn gestured() -> (State, Instant) {
580        let mut s = State::default();
581        let now = Instant::now();
582        s.note_gesture(now);
583        (s, now)
584    }
585
586    fn change(request: u32) -> Note {
587        Note::Change { request }
588    }
589
590    fn error_name(note: &Note) -> &'static str {
591        match note {
592            Note::Error { name, .. } => name,
593            Note::Change { .. } => panic!("expected an error, got {note:?}"),
594        }
595    }
596
597    #[test]
598    fn a_request_under_a_gesture_locks_and_exit_releases() {
599        let (mut s, now) = gestured();
600        let mut host = Fake::new();
601        let id = s.request(1, false, now);
602        assert!(
603            s.held.is_none(),
604            "nothing happens before the window's frame"
605        );
606        assert_eq!(s.tick(&mut host), vec![change(id)]);
607        assert_eq!(s.held.map(|h| h.element), Some(1));
608        assert!(host.locked);
609
610        s.exit();
611        assert_eq!(s.tick(&mut host), vec![change(0)]);
612        assert!(s.held.is_none() && !host.locked);
613        s.exit();
614        assert_eq!(s.tick(&mut host), vec![], "exiting when unlocked is silent");
615    }
616
617    #[test]
618    fn a_request_without_a_gesture_or_focus_fails() {
619        let mut s = State::default();
620        let mut host = Fake::new();
621        s.request(1, false, Instant::now());
622        let notes = s.tick(&mut host);
623        assert_eq!(notes.len(), 1);
624        assert_eq!(error_name(&notes[0]), "NotAllowedError");
625
626        let (mut s, now) = gestured();
627        host.focused = false;
628        let id2 = s.request(1, false, now);
629        let notes = s.tick(&mut host);
630        assert!(
631            matches!(notes[..], [Note::Error { request, name: "WrongDocumentError", .. }] if request == id2)
632        );
633        assert!(host.calls.is_empty(), "the platform is never asked");
634    }
635
636    #[test]
637    fn a_gesture_expires() {
638        let mut s = State::default();
639        let then = Instant::now();
640        s.note_gesture(then);
641        s.request(1, false, then + ACTIVATION + Duration::from_millis(1));
642        let notes = s.tick(&mut Fake::new());
643        assert_eq!(error_name(&notes[0]), "NotAllowedError");
644    }
645
646    #[test]
647    fn escape_releases_and_the_next_request_needs_a_new_gesture() {
648        let (mut s, now) = gestured();
649        let mut host = Fake::new();
650        s.request(1, false, now);
651        s.tick(&mut host);
652
653        assert_eq!(s.release_by_user(&mut host), Some(change(0)));
654        assert!(!host.locked);
655        assert_eq!(s.release_by_user(&mut host), None, "nothing to release");
656
657        s.request(1, false, now);
658        let notes = s.tick(&mut host);
659        assert_eq!(error_name(&notes[0]), "NotAllowedError");
660
661        s.note_gesture(now);
662        let id = s.request(1, false, now);
663        assert_eq!(s.tick(&mut host), vec![change(id)]);
664    }
665
666    #[test]
667    fn losing_focus_or_the_platform_lock_releases_as_the_user() {
668        let (mut s, now) = gestured();
669        let mut host = Fake::new();
670        s.request(1, false, now);
671        s.tick(&mut host);
672        host.focused = false;
673        assert_eq!(s.tick(&mut host), vec![change(0)]);
674        assert!(!host.locked && s.held.is_none());
675
676        host.focused = true;
677        s.note_gesture(now);
678        s.request(1, false, now);
679        s.tick(&mut host);
680        host.locked = false;
681        assert_eq!(s.tick(&mut host), vec![change(0)]);
682        assert_eq!(s.released_after, Some(s.gestures));
683    }
684
685    #[test]
686    fn removing_the_element_releases_without_needing_a_new_gesture() {
687        let (mut s, now) = gestured();
688        let mut host = Fake::new();
689        s.request(1, false, now);
690        s.tick(&mut host);
691        host.elements.remove(&1);
692        assert_eq!(s.tick(&mut host), vec![change(0)]);
693        assert!(!host.locked);
694        assert_eq!(s.released_after, None);
695    }
696
697    #[test]
698    fn a_detached_element_is_a_wrong_document() {
699        let (mut s, now) = gestured();
700        s.request(99, false, now);
701        let notes = s.tick(&mut Fake::new());
702        assert_eq!(error_name(&notes[0]), "WrongDocumentError");
703    }
704
705    #[test]
706    fn moving_the_lock_to_another_element_needs_no_gesture_or_platform_call() {
707        let (mut s, now) = gestured();
708        let mut host = Fake::new();
709        s.request(1, false, now);
710        s.tick(&mut host);
711        let later = now + ACTIVATION * 2;
712        let id = s.request(2, false, later);
713        assert_eq!(s.tick(&mut host), vec![change(id)]);
714        assert_eq!(s.held.map(|h| h.element), Some(2));
715        assert_eq!(host.calls, vec!["lock false"]);
716
717        let id = s.request(2, true, later);
718        assert_eq!(s.tick(&mut host), vec![change(id)]);
719        assert_eq!(host.calls, vec!["lock false", "lock true"]);
720    }
721
722    #[test]
723    fn platform_refusals_name_their_reason() {
724        let cases = [
725            (Some(Refusal::Refused), false, "NotAllowedError"),
726            (Some(Refusal::Denied), false, "NotAllowedError"),
727            (Some(Refusal::Unsupported), false, "NotSupportedError"),
728            (None, true, "NotSupportedError"),
729        ];
730        for (refuse, unadjusted, name) in cases {
731            let (mut s, now) = gestured();
732            let mut host = Fake::new();
733            host.refuse = refuse;
734            host.unadjusted_supported = false;
735            s.request(1, unadjusted, now);
736            let notes = s.tick(&mut host);
737            assert_eq!(
738                error_name(&notes[0]),
739                name,
740                "{refuse:?} unadjusted={unadjusted}"
741            );
742            assert!(s.held.is_none());
743        }
744    }
745
746    #[test]
747    fn a_failed_mode_change_loses_the_lock_it_had() {
748        let (mut s, now) = gestured();
749        let mut host = Fake::new();
750        host.unadjusted_supported = false;
751        s.request(1, false, now);
752        s.tick(&mut host);
753        s.request(1, true, now);
754        let notes = s.tick(&mut host);
755        assert_eq!(notes[0], change(0));
756        assert_eq!(error_name(&notes[1]), "NotSupportedError");
757        assert!(s.held.is_none());
758    }
759
760    #[test]
761    fn a_request_waits_for_the_window_painting_its_element() {
762        let (mut s, now) = gestured();
763        let mut here = Fake::new();
764        let id = s.request(3, false, now);
765        assert_eq!(s.tick(&mut here), vec![]);
766        let mut there = Fake::new();
767        there.window = OTHER;
768        assert_eq!(s.tick(&mut there), vec![change(id)]);
769        assert_eq!(s.held.map(|h| h.window), Some(OTHER));
770
771        s.exit();
772        assert_eq!(s.tick(&mut here), vec![]);
773        assert_eq!(s.tick(&mut there), vec![change(0)]);
774    }
775
776    #[test]
777    fn closing_the_window_tells_the_document_at_the_next_frame() {
778        let (mut s, now) = gestured();
779        let mut host = Fake::new();
780        s.request(1, false, now);
781        s.tick(&mut host);
782        s.window_closed(W);
783        assert!(s.held.is_none());
784        let mut other = Fake::new();
785        other.window = OTHER;
786        assert_eq!(s.tick(&mut other), vec![change(0)]);
787    }
788
789    fn js(src: &str) -> String {
790        JsRuntime::with(|rt| {
791            let v = rt
792                .ctx()
793                .eval(src)
794                .unwrap_or_else(|e| panic!("{src}: {e:?}"));
795            rt.ctx().to_rust_string(v).unwrap()
796        })
797    }
798
799    #[test]
800    fn request_pointer_lock_is_a_promise_the_settling_note_answers() {
801        sk_runtime::testing::on_js_thread(|| {
802            JsRuntime::with(|rt| {
803                native_dom::install(rt);
804                install(rt);
805            });
806            with_state(|s| *s = State::default());
807            let el = tree::with_tree(|t| {
808                let root = t.create_root();
809                let tag = t.intern("canvas");
810                let el = t.create_element(tag);
811                t.insert(el, root, 0);
812                el
813            });
814            js(&format!(
815                "globalThis.canvas = Object.create(HTMLElement.prototype); canvas.__skId = {el}; \
816                 __sk_set_node_lookup((id) => (id === {el} ? canvas : undefined)); globalThis.seen = []; \
817                 canvas.requestPointerLock({{ unadjustedMovement: true }}).then(() => seen.push('locked')); \
818                 canvas.requestPointerLock().catch((e) => seen.push(`${{e instanceof DOMException}} ${{e.name}}: ${{e.message}}`)); \
819                 Object.create(HTMLElement.prototype).requestPointerLock(); ''"
820            ));
821            let requests: Vec<(u32, u32, bool)> = with_state(|s| {
822                s.ops
823                    .iter()
824                    .filter_map(|op| match *op {
825                        Op::Request {
826                            id,
827                            element,
828                            unadjusted,
829                            ..
830                        } => Some((id, element, unadjusted)),
831                        Op::Exit => None,
832                    })
833                    .collect()
834            });
835            let [(first, a, true), (second, b, false), (_, 0, false)] = requests[..] else {
836                panic!("{requests:?}");
837            };
838            assert_eq!((a, b), (el, el));
839            assert_eq!(js("String(document.pointerLockElement)"), "null");
840
841            with_state(|s| {
842                s.held = Some(Held {
843                    element: el,
844                    window: W,
845                    unadjusted: true,
846                });
847            });
848            JsRuntime::with(|rt| unsafe {
849                settle(
850                    rt.raw(),
851                    &Note::Error {
852                        request: second,
853                        name: "WrongDocumentError",
854                        message: "Not here.",
855                    },
856                );
857                settle(rt.raw(), &Note::Change { request: first });
858                settle(rt.raw(), &Note::Change { request: first });
859            });
860            assert_eq!(js("String(document.pointerLockElement === canvas)"), "true");
861            js("''");
862            assert_eq!(
863                js("seen.join('|')"),
864                "true WrongDocumentError: Not here.|locked"
865            );
866
867            js("document.exitPointerLock()");
868            assert!(with_state(|s| s.ops.contains(&Op::Exit)));
869            navigated();
870            assert!(
871                PENDING.with(|p| p.borrow().is_empty()),
872                "a reload forgets every request"
873            );
874        });
875    }
876
877    #[test]
878    fn a_reload_drops_the_lock_silently_and_its_window_unlocks() {
879        let (mut s, now) = gestured();
880        let mut host = Fake::new();
881        s.request(1, false, now);
882        s.tick(&mut host);
883        s.request(2, false, now);
884        s.navigated();
885        assert_eq!(s.tick(&mut host), vec![]);
886        assert!(!host.locked);
887        assert_eq!(host.calls, vec!["lock false", "unlock"]);
888    }
889}