incular-runtime 0.1.1

Application runtime and scheduling foundations for Incular
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
//! High-level, in-process interaction and capture for Incular applications.
//!
//! The simulator is deliberately below the native desktop boundary. It sends
//! the same normalized [`InputEvent`] values that a platform adapter sends,
//! after resolving semantic labels to retained layout bounds. No OS cursor,
//! keyboard device, focus, or desktop screenshot API is involved.

use super::{Application, WindowHandle, profiling::GpuResourceSummary};
use incular_config::Constraints;
use incular_core::time::Instant;
use incular_core::{
    Code, InputEvent, KeyState, KeyboardEvent, KeyboardKey, Location, Modifiers, NamedKey, Offset,
    PointerPhase, Rect,
};
use incular_platform::WindowId;
use incular_semantics::SemanticActionKind;
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, mpsc};
use std::time::Duration;

const SIMULATION_REPLY_TIMEOUT: Duration = Duration::from_secs(30);
const MAX_SIMULATION_REQUESTS_PER_TURN: usize = 64;

/// A screenshot of an Incular window's rendered surface.
///
/// Pixels are tightly packed, top-to-bottom, straight-alpha RGBA8 values.
/// This is an application frame, not a capture of the desktop or another
/// application.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Screenshot {
    width: u32,
    height: u32,
    rgba8: Vec<u8>,
}

impl Screenshot {
    /// Creates a screenshot from tightly packed RGBA8 pixels.
    pub fn from_rgba8(width: u32, height: u32, rgba8: Vec<u8>) -> Result<Self, SimulationError> {
        let expected = usize::try_from(width)
            .ok()
            .and_then(|width| {
                usize::try_from(height)
                    .ok()
                    .and_then(|height| width.checked_mul(height))
            })
            .and_then(|pixels| pixels.checked_mul(4))
            .ok_or_else(|| {
                SimulationError::InvalidInput("screenshot dimensions overflow".into())
            })?;
        if expected == 0 || rgba8.len() != expected {
            return Err(SimulationError::InvalidInput(format!(
                "screenshot pixel length {} does not match {}x{} RGBA8",
                rgba8.len(),
                width,
                height
            )));
        }
        Ok(Self {
            width,
            height,
            rgba8,
        })
    }

    #[must_use]
    pub const fn width(&self) -> u32 {
        self.width
    }

    #[must_use]
    pub const fn height(&self) -> u32 {
        self.height
    }

    /// Returns the tightly packed RGBA8 pixel bytes.
    #[must_use]
    pub fn pixels(&self) -> &[u8] {
        &self.rgba8
    }

    /// Consumes the screenshot and returns its tightly packed RGBA8 pixels.
    #[must_use]
    pub fn into_pixels(self) -> Vec<u8> {
        self.rgba8
    }
}

/// Failure returned by an in-process simulation command.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum SimulationError {
    /// The target application's event loop is not running, has stopped, or
    /// the application was dropped before the request was serviced.
    #[error("the Incular simulation bridge is disconnected")]
    Disconnected,
    /// The target event loop did not service the request in time.
    #[error("the Incular simulation request timed out")]
    Timeout,
    /// The requested retained window no longer exists.
    #[error("simulation window {0} was not found")]
    WindowNotFound(WindowId),
    /// The requested retained window was closed while the command was queued.
    #[error("simulation window {0} was closed")]
    WindowClosed(WindowId),
    /// No semantic node with the requested exact label was found.
    #[error("no semantic element labeled {0:?} was found")]
    ElementNotFound(String),
    /// The command contained a value that cannot represent native input.
    #[error("invalid simulation input: {0}")]
    InvalidInput(String),
    /// The renderer could not produce a window frame for a capture request.
    #[error("window capture unavailable: {0}")]
    CaptureUnavailable(String),
    /// The runtime or renderer failed while servicing a frame request.
    #[error("simulation frame failed: {0}")]
    FrameFailed(String),
}

type Reply<T> = mpsc::SyncSender<Result<T, SimulationError>>;

pub(crate) enum SimulationRequest {
    Input {
        window_id: WindowId,
        event: InputEvent,
        reply: Reply<()>,
    },
    ClickAt {
        window_id: WindowId,
        position: Offset,
        reply: Reply<()>,
    },
    ClickLabel {
        window_id: WindowId,
        label: String,
        reply: Reply<()>,
    },
    WaitForFrame {
        window_id: WindowId,
        reply: Reply<()>,
    },
    Capture {
        window_id: WindowId,
        reply: Reply<Screenshot>,
    },
    GpuResources {
        window_id: WindowId,
        reply: Reply<GpuResourceSummary>,
    },
}

pub(crate) struct SimulationBridge {
    sender: mpsc::Sender<SimulationRequest>,
    wake: Mutex<Option<Arc<dyn super::RuntimeWake>>>,
    accepting: AtomicBool,
}

impl SimulationBridge {
    pub(crate) fn new(sender: mpsc::Sender<SimulationRequest>) -> Self {
        Self {
            sender,
            wake: Mutex::new(None),
            accepting: AtomicBool::new(true),
        }
    }

    fn enqueue(&self, request: SimulationRequest) -> Result<(), SimulationError> {
        if !self.accepting.load(Ordering::Acquire) {
            return Err(SimulationError::Disconnected);
        }
        self.sender
            .send(request)
            .map_err(|_| SimulationError::Disconnected)?;
        if let Some(wake) = self.wake.lock().expect("simulation wake mutex").as_ref() {
            wake.wake();
        }
        Ok(())
    }

    pub(crate) fn set_wake(&self, wake: Arc<dyn super::RuntimeWake>) {
        *self.wake.lock().expect("simulation wake mutex") = Some(wake);
    }

    pub(crate) fn stop(&self) {
        self.accepting.store(false, Ordering::Release);
    }
}

#[derive(Default)]
struct KeyboardState {
    modifiers: Modifiers,
    pressed: HashSet<Code>,
}

/// Owns per-window simulation waiter settlement: frame, capture, and
/// GPU-resource replies. Every settle path removes a window's waiters
/// before replying, so each waiter settles exactly once and window
/// close/shutdown settle all three kinds together. Frame failure leaves
/// GPU queries pending by design — they hold no frame debt and resolve
/// through maintenance, close, or shutdown instead.
#[derive(Default)]
pub(crate) struct SimulationWaiters {
    frame: HashMap<WindowId, Vec<mpsc::SyncSender<Result<(), SimulationError>>>>,
    capture: HashMap<WindowId, Vec<mpsc::SyncSender<Result<Screenshot, SimulationError>>>>,
    gpu: HashMap<WindowId, Vec<mpsc::SyncSender<Result<GpuResourceSummary, SimulationError>>>>,
}

impl SimulationWaiters {
    fn settle<T: Clone>(
        waiters: &mut HashMap<WindowId, Vec<mpsc::SyncSender<Result<T, SimulationError>>>>,
        window_id: WindowId,
        result: Result<T, SimulationError>,
    ) {
        if let Some(pending) = waiters.remove(&window_id) {
            for reply in pending {
                let _ = reply.send(result.clone());
            }
        }
    }

    /// Reports whether a simulator is waiting for the next presented frame.
    #[must_use]
    pub(crate) fn frame_pending(&self, window_id: WindowId) -> bool {
        self.frame
            .get(&window_id)
            .is_some_and(|waiters| !waiters.is_empty())
    }

    /// Reports whether a simulator is waiting for a capture.
    #[must_use]
    pub(crate) fn capture_pending(&self, window_id: WindowId) -> bool {
        self.capture
            .get(&window_id)
            .is_some_and(|waiters| !waiters.is_empty())
    }

    /// Registers a frame waiter enlisted by simulation request handling.
    pub(crate) fn insert_frame(
        &mut self,
        window_id: WindowId,
        reply: mpsc::SyncSender<Result<(), SimulationError>>,
    ) {
        self.frame.entry(window_id).or_default().push(reply);
    }

    /// Registers a capture waiter enlisted by simulation request handling.
    pub(crate) fn insert_capture(
        &mut self,
        window_id: WindowId,
        reply: mpsc::SyncSender<Result<Screenshot, SimulationError>>,
    ) {
        self.capture.entry(window_id).or_default().push(reply);
    }

    /// Registers a GPU-resource waiter enlisted by simulation request handling.
    pub(crate) fn insert_gpu(
        &mut self,
        window_id: WindowId,
        reply: mpsc::SyncSender<Result<GpuResourceSummary, SimulationError>>,
    ) {
        self.gpu.entry(window_id).or_default().push(reply);
    }

    /// Completes simulator waiters after the native renderer has presented a
    /// frame. `capture` is supplied only when a renderer serviced a pending
    /// capture request.
    pub(crate) fn complete_frame(
        &mut self,
        window_id: WindowId,
        presented: bool,
        capture: Option<Result<Screenshot, String>>,
    ) {
        if !presented {
            return;
        }
        Self::settle(&mut self.frame, window_id, Ok(()));
        let result = capture
            .map(|result| result.map_err(SimulationError::CaptureUnavailable))
            .unwrap_or_else(|| {
                Err(SimulationError::CaptureUnavailable(
                    "the renderer did not return a capture".into(),
                ))
            });
        Self::settle(&mut self.capture, window_id, result);
    }

    /// Fails simulator requests when a native frame cannot be produced.
    pub(crate) fn fail_frame(&mut self, window_id: WindowId, message: impl Into<String>) {
        let error = SimulationError::FrameFailed(message.into());
        Self::settle(&mut self.frame, window_id, Err(error.clone()));
        let capture_error = SimulationError::CaptureUnavailable(error.to_string());
        Self::settle(&mut self.capture, window_id, Err(capture_error));
    }

    /// Fails all three waiter kinds when a window closes or the
    /// application shuts down.
    pub(crate) fn fail_window(&mut self, window_id: WindowId) {
        let error = SimulationError::WindowClosed(window_id);
        Self::settle(&mut self.frame, window_id, Err(error.clone()));
        Self::settle(&mut self.capture, window_id, Err(error.clone()));
        // Resource queries hold no frame debt: closing settles them here,
        // through the same close/shutdown paths as every other waiter, so
        // no maintenance pass is needed to release them.
        Self::settle(&mut self.gpu, window_id, Err(error));
    }

    /// Completes pending GPU-resource waiters after the native adapter has
    /// snapshotted current residency. Never renders.
    pub(crate) fn complete_gpu(&mut self, window_id: WindowId, summary: GpuResourceSummary) {
        Self::settle(&mut self.gpu, window_id, Ok(summary));
    }

    /// Windows holding GPU-resource waiters, for liveness filtering by
    /// the caller: liveness lives in the window registry, not here.
    pub(crate) fn gpu_windows(&self) -> Vec<WindowId> {
        self.gpu.keys().copied().collect()
    }

    /// Releases one window's GPU-resource waiters for out-of-band
    /// settlement by the caller. Empty when nothing was pending.
    pub(crate) fn take_gpu_waiters(
        &mut self,
        window_id: WindowId,
    ) -> Vec<Reply<GpuResourceSummary>> {
        self.gpu.remove(&window_id).unwrap_or_default()
    }
}

/// A cloneable in-process controller for one Incular application window.
///
/// Calls block until the application's UI thread services the command. Use
/// this handle from a test/automation thread, not from an application build or
/// event callback, because those already run on the UI thread.
#[derive(Clone)]
pub struct Simulation {
    bridge: Arc<SimulationBridge>,
    window_id: WindowId,
    keyboard: Arc<Mutex<KeyboardState>>,
}

impl Simulation {
    pub(crate) fn new(bridge: Arc<SimulationBridge>, window_id: WindowId) -> Self {
        Self {
            bridge,
            window_id,
            keyboard: Arc::new(Mutex::new(KeyboardState::default())),
        }
    }

    /// Returns a controller targeting the window represented by `handle`.
    #[must_use]
    pub fn window(&self, handle: &WindowHandle) -> Self {
        self.for_window(handle.id())
    }

    /// Returns a controller targeting a known Incular window ID.
    #[must_use]
    pub fn for_window(&self, window_id: WindowId) -> Self {
        Self {
            bridge: self.bridge.clone(),
            window_id,
            keyboard: self.keyboard.clone(),
        }
    }

    #[must_use]
    pub const fn window_id(&self) -> WindowId {
        self.window_id
    }

    /// Returns the mouse command group for this window.
    #[must_use]
    pub fn mouse(&self) -> SimulationMouse {
        SimulationMouse {
            simulation: self.clone(),
        }
    }

    /// Returns the keyboard command group for this window.
    #[must_use]
    pub fn keyboard(&self) -> SimulationKeyboard {
        SimulationKeyboard {
            simulation: self.clone(),
        }
    }

    /// Clicks the first enabled semantic node whose label exactly matches
    /// `label`, using move → down → up through the ordinary pointer pipeline.
    pub fn click(&self, label: impl Into<String>) -> Result<(), SimulationError> {
        self.mouse().click(label)
    }

    pub fn click_at(&self, position: Offset) -> Result<(), SimulationError> {
        self.mouse().click_at(position)
    }

    pub fn move_mouse_to(&self, position: Offset) -> Result<(), SimulationError> {
        self.mouse().move_to(position)
    }

    pub fn scroll(&self, delta: Offset) -> Result<(), SimulationError> {
        self.mouse().scroll(delta)
    }

    pub fn key_down(&self, code: Code) -> Result<(), SimulationError> {
        self.keyboard().key_down(code)
    }

    pub fn key_up(&self, code: Code) -> Result<(), SimulationError> {
        self.keyboard().key_up(code)
    }

    pub fn press(&self, code: Code) -> Result<(), SimulationError> {
        self.keyboard().press(code)
    }

    pub fn press_key(&self, key: KeyboardKey, code: Code) -> Result<(), SimulationError> {
        self.keyboard().press_key(key, code)
    }

    pub fn type_text(&self, text: impl Into<String>) -> Result<(), SimulationError> {
        self.keyboard().type_text(text)
    }

    /// Waits until the next frame for this window has been presented.
    pub fn wait_for_frame(&self) -> Result<(), SimulationError> {
        self.request(|reply| SimulationRequest::WaitForFrame {
            window_id: self.window_id,
            reply,
        })
    }

    /// Requests and returns the next rendered frame for this window.
    pub fn capture(&self) -> Result<Screenshot, SimulationError> {
        self.request(|reply| SimulationRequest::Capture {
            window_id: self.window_id,
            reply,
        })
    }

    /// Reads the current GPU residency snapshot for this window's device
    /// without presenting a frame. Resolves once the native adapter's
    /// maintenance path fulfills it from current state.
    pub fn query_gpu_resources(&self) -> Result<GpuResourceSummary, SimulationError> {
        self.request(|reply| SimulationRequest::GpuResources {
            window_id: self.window_id,
            reply,
        })
    }

    /// Releases every modifier/key held by this simulation keyboard.
    pub fn release_all_keys(&self) -> Result<(), SimulationError> {
        self.keyboard().release_all()
    }

    fn request<T>(
        &self,
        build: impl FnOnce(Reply<T>) -> SimulationRequest,
    ) -> Result<T, SimulationError> {
        let (sender, receiver) = mpsc::sync_channel(1);
        self.bridge.enqueue(build(sender))?;
        match receiver.recv_timeout(SIMULATION_REPLY_TIMEOUT) {
            Ok(result) => result,
            Err(mpsc::RecvTimeoutError::Timeout) => Err(SimulationError::Timeout),
            Err(mpsc::RecvTimeoutError::Disconnected) => Err(SimulationError::Disconnected),
        }
    }

    fn input(&self, event: InputEvent) -> Result<(), SimulationError> {
        self.request(|reply| SimulationRequest::Input {
            window_id: self.window_id,
            event,
            reply,
        })
    }
}

/// Mouse/pointer operations for a [`Simulation`] window. Only the primary
/// pointer/left-button path is exposed here; multi-pointer tests can use the
/// lower-level runtime input API directly.
#[derive(Clone)]
pub struct SimulationMouse {
    simulation: Simulation,
}

impl SimulationMouse {
    pub fn move_to(&self, position: Offset) -> Result<(), SimulationError> {
        self.simulation.input(InputEvent::Pointer {
            phase: PointerPhase::Move,
            position,
        })
    }

    pub fn down(&self, position: Offset) -> Result<(), SimulationError> {
        self.simulation.input(InputEvent::Pointer {
            phase: PointerPhase::Down,
            position,
        })
    }

    pub fn up(&self, position: Offset) -> Result<(), SimulationError> {
        self.simulation.input(InputEvent::Pointer {
            phase: PointerPhase::Up,
            position,
        })
    }

    pub fn click(&self, label: impl Into<String>) -> Result<(), SimulationError> {
        self.simulation
            .request(|reply| SimulationRequest::ClickLabel {
                window_id: self.simulation.window_id,
                label: label.into(),
                reply,
            })
    }

    pub fn click_at(&self, position: Offset) -> Result<(), SimulationError> {
        self.simulation.request(|reply| SimulationRequest::ClickAt {
            window_id: self.simulation.window_id,
            position,
            reply,
        })
    }

    pub fn scroll(&self, delta: Offset) -> Result<(), SimulationError> {
        self.simulation.input(InputEvent::Scroll { delta })
    }
}

/// Keyboard operations for a [`Simulation`] window. Key events use Incular's
/// platform-neutral physical [`Code`] plus the logical key supplied to
/// [`Self::press_key`]. Text entry is a separate committed-text event, just as
/// it is for native IME-aware adapters.
#[derive(Clone)]
pub struct SimulationKeyboard {
    simulation: Simulation,
}

impl SimulationKeyboard {
    pub fn key_down(&self, code: Code) -> Result<(), SimulationError> {
        self.send_key(KeyState::Down, None, code)
    }

    pub fn key_up(&self, code: Code) -> Result<(), SimulationError> {
        self.send_key(KeyState::Up, None, code)
    }

    pub fn press(&self, code: Code) -> Result<(), SimulationError> {
        self.key_down(code)?;
        self.key_up(code)
    }

    pub fn press_key(&self, key: KeyboardKey, code: Code) -> Result<(), SimulationError> {
        self.send_key(KeyState::Down, Some(key.clone()), code)?;
        self.send_key(KeyState::Up, Some(key), code)
    }

    pub fn type_text(&self, text: impl Into<String>) -> Result<(), SimulationError> {
        let text = text.into();
        if text.chars().any(char::is_control) {
            return Err(SimulationError::InvalidInput(
                "type_text accepts printable committed text; use press for commands".into(),
            ));
        }
        self.simulation.input(InputEvent::Text(text))
    }

    pub fn release_all(&self) -> Result<(), SimulationError> {
        let pressed = self
            .simulation
            .keyboard
            .lock()
            .expect("simulation keyboard mutex")
            .pressed
            .iter()
            .copied()
            .collect::<Vec<_>>();
        for code in pressed {
            self.key_up(code)?;
        }
        Ok(())
    }

    fn send_key(
        &self,
        state: KeyState,
        explicit_key: Option<KeyboardKey>,
        code: Code,
    ) -> Result<(), SimulationError> {
        let (key, modifiers, location, repeat, was_pressed) = {
            let mut keyboard = self
                .simulation
                .keyboard
                .lock()
                .expect("simulation keyboard mutex");
            let was_pressed = keyboard.pressed.contains(&code);
            if state.is_down() {
                if let Some(modifier) = modifier_for_code(code) {
                    keyboard.modifiers.insert(modifier);
                }
                keyboard.pressed.insert(code);
            }
            let values = (
                explicit_key.unwrap_or_else(|| logical_key(code)),
                keyboard.modifiers,
                location_for_code(code),
                state.is_down() && was_pressed,
                was_pressed,
            );
            if state.is_up() {
                // Key-up carries the modifier as pressed, then the local
                // simulator state releases it after the event is delivered.
                keyboard.pressed.remove(&code);
                if let Some(modifier) = modifier_for_code(code) {
                    keyboard.modifiers.remove(modifier);
                }
            }
            values
        };
        let event = KeyboardEvent {
            state,
            key,
            code,
            location,
            modifiers,
            repeat,
            is_composing: false,
        };
        let result = self.simulation.input(InputEvent::Key(event));
        if result.is_err() {
            // Keep local key state usable after a disconnected/failed request.
            let mut keyboard = self
                .simulation
                .keyboard
                .lock()
                .expect("simulation keyboard mutex");
            if state.is_down() {
                if !was_pressed {
                    keyboard.pressed.remove(&code);
                }
            } else {
                keyboard.pressed.insert(code);
            }
            keyboard.modifiers = modifiers_for_pressed(&keyboard.pressed);
        }
        result
    }
}

fn modifier_for_code(code: Code) -> Option<Modifiers> {
    match code {
        Code::AltLeft | Code::AltRight => Some(Modifiers::ALT),
        Code::ControlLeft | Code::ControlRight => Some(Modifiers::CONTROL),
        Code::MetaLeft | Code::MetaRight => Some(Modifiers::META),
        Code::ShiftLeft | Code::ShiftRight => Some(Modifiers::SHIFT),
        _ => None,
    }
}

fn modifiers_for_pressed(pressed: &HashSet<Code>) -> Modifiers {
    pressed
        .iter()
        .fold(Modifiers::default(), |mut modifiers, code| {
            if let Some(modifier) = modifier_for_code(*code) {
                modifiers.insert(modifier);
            }
            modifiers
        })
}

fn location_for_code(code: Code) -> Location {
    match code {
        Code::AltLeft | Code::ControlLeft | Code::MetaLeft | Code::ShiftLeft => Location::Left,
        Code::AltRight | Code::ControlRight | Code::MetaRight | Code::ShiftRight => Location::Right,
        Code::NumpadEnter => Location::Numpad,
        _ => Location::Standard,
    }
}

fn logical_key(code: Code) -> KeyboardKey {
    let character = match code {
        Code::Backquote => Some("`"),
        Code::Backslash => Some("\\"),
        Code::BracketLeft => Some("["),
        Code::BracketRight => Some("]"),
        Code::Comma => Some(","),
        Code::Digit0 => Some("0"),
        Code::Digit1 => Some("1"),
        Code::Digit2 => Some("2"),
        Code::Digit3 => Some("3"),
        Code::Digit4 => Some("4"),
        Code::Digit5 => Some("5"),
        Code::Digit6 => Some("6"),
        Code::Digit7 => Some("7"),
        Code::Digit8 => Some("8"),
        Code::Digit9 => Some("9"),
        Code::Equal => Some("="),
        Code::KeyA => Some("a"),
        Code::KeyB => Some("b"),
        Code::KeyC => Some("c"),
        Code::KeyD => Some("d"),
        Code::KeyE => Some("e"),
        Code::KeyF => Some("f"),
        Code::KeyG => Some("g"),
        Code::KeyH => Some("h"),
        Code::KeyI => Some("i"),
        Code::KeyJ => Some("j"),
        Code::KeyK => Some("k"),
        Code::KeyL => Some("l"),
        Code::KeyM => Some("m"),
        Code::KeyN => Some("n"),
        Code::KeyO => Some("o"),
        Code::KeyP => Some("p"),
        Code::KeyQ => Some("q"),
        Code::KeyR => Some("r"),
        Code::KeyS => Some("s"),
        Code::KeyT => Some("t"),
        Code::KeyU => Some("u"),
        Code::KeyV => Some("v"),
        Code::KeyW => Some("w"),
        Code::KeyX => Some("x"),
        Code::KeyY => Some("y"),
        Code::KeyZ => Some("z"),
        Code::Minus => Some("-"),
        Code::Period => Some("."),
        Code::Quote => Some("'"),
        Code::Semicolon => Some(";"),
        Code::Slash => Some("/"),
        Code::Space => Some(" "),
        Code::Numpad0 => Some("0"),
        Code::Numpad1 => Some("1"),
        Code::Numpad2 => Some("2"),
        Code::Numpad3 => Some("3"),
        Code::Numpad4 => Some("4"),
        Code::Numpad5 => Some("5"),
        Code::Numpad6 => Some("6"),
        Code::Numpad7 => Some("7"),
        Code::Numpad8 => Some("8"),
        Code::Numpad9 => Some("9"),
        Code::NumpadAdd => Some("+"),
        Code::NumpadComma => Some(","),
        Code::NumpadDecimal => Some("."),
        Code::NumpadDivide => Some("/"),
        Code::NumpadEqual => Some("="),
        Code::NumpadMultiply | Code::NumpadStar => Some("*"),
        Code::NumpadSubtract => Some("-"),
        _ => None,
    };
    if let Some(character) = character {
        return KeyboardKey::Character(character.into());
    }
    let named = match code {
        Code::AltLeft | Code::AltRight => NamedKey::Alt,
        Code::CapsLock => NamedKey::CapsLock,
        Code::ControlLeft | Code::ControlRight => NamedKey::Control,
        Code::Enter | Code::NumpadEnter => NamedKey::Enter,
        Code::Escape => NamedKey::Escape,
        Code::MetaLeft | Code::MetaRight => NamedKey::Meta,
        Code::NumLock => NamedKey::NumLock,
        Code::ScrollLock => NamedKey::ScrollLock,
        Code::ShiftLeft | Code::ShiftRight => NamedKey::Shift,
        Code::Tab => NamedKey::Tab,
        Code::Backspace => NamedKey::Backspace,
        Code::Delete => NamedKey::Delete,
        Code::Insert => NamedKey::Insert,
        Code::PageDown => NamedKey::PageDown,
        Code::PageUp => NamedKey::PageUp,
        Code::ArrowDown => NamedKey::ArrowDown,
        Code::ArrowLeft => NamedKey::ArrowLeft,
        Code::ArrowRight => NamedKey::ArrowRight,
        Code::ArrowUp => NamedKey::ArrowUp,
        Code::End => NamedKey::End,
        Code::Home => NamedKey::Home,
        _ => NamedKey::Unidentified,
    };
    KeyboardKey::Named(named)
}

fn valid_offset(offset: Offset) -> Result<(), SimulationError> {
    if offset.x.is_finite() && offset.y.is_finite() {
        Ok(())
    } else {
        Err(SimulationError::InvalidInput(
            "pointer and scroll offsets must be finite".into(),
        ))
    }
}

impl Application {
    /// Services queued in-process simulation requests on the application UI
    /// thread. Native adapters call this from their event-loop wake path.
    pub fn process_simulation_requests(&mut self) {
        for _ in 0..MAX_SIMULATION_REQUESTS_PER_TURN {
            let request = match self.simulation_receiver.try_recv() {
                Ok(request) => request,
                Err(mpsc::TryRecvError::Empty | mpsc::TryRecvError::Disconnected) => break,
            };
            self.handle_simulation_request(request);
        }
    }

    fn handle_simulation_request(&mut self, request: SimulationRequest) {
        match request {
            SimulationRequest::Input {
                window_id,
                event,
                reply,
            } => {
                let result = self
                    .ensure_simulation_layout(window_id)
                    .and_then(|_| self.dispatch_simulation_input(window_id, event));
                let _ = reply.send(result);
            }
            SimulationRequest::ClickAt {
                window_id,
                position,
                reply,
            } => {
                let _ = reply.send(self.dispatch_simulation_click(window_id, position));
            }
            SimulationRequest::ClickLabel {
                window_id,
                label,
                reply,
            } => {
                let trigger = format!("click({label:?})");
                let result = self
                    .simulation_label_bounds(window_id, &label)
                    .and_then(|bounds| {
                        self.dispatch_simulation_click_prepared(
                            window_id,
                            bounds.center(),
                            &trigger,
                        )
                    });
                let _ = reply.send(result);
            }
            SimulationRequest::WaitForFrame { window_id, reply } => {
                if self.contains_window(window_id) {
                    let _ =
                        self.with_window_mut(window_id, |record| record.runtime.request_frame());
                    self.simulation_waiters.insert_frame(window_id, reply);
                } else {
                    let _ = reply.send(Err(SimulationError::WindowNotFound(window_id)));
                }
            }
            SimulationRequest::Capture { window_id, reply } => {
                if self.contains_window(window_id) {
                    let _ =
                        self.with_window_mut(window_id, |record| record.runtime.request_frame());
                    self.simulation_waiters.insert_capture(window_id, reply);
                } else {
                    let _ = reply.send(Err(SimulationError::WindowNotFound(window_id)));
                }
            }
            SimulationRequest::GpuResources { window_id, reply } => {
                // Deliberately no frame request: resource observation must
                // not present. The native adapter fulfills pending queries
                // from current state on its maintenance path.
                if self.contains_window(window_id) {
                    self.simulation_waiters.insert_gpu(window_id, reply);
                } else {
                    let _ = reply.send(Err(SimulationError::WindowNotFound(window_id)));
                }
            }
        }
    }

    fn dispatch_simulation_input(
        &mut self,
        window_id: WindowId,
        event: InputEvent,
    ) -> Result<(), SimulationError> {
        self.dispatch_simulation_input_with_trigger(window_id, event, None)
    }

    fn dispatch_simulation_input_with_trigger(
        &mut self,
        window_id: WindowId,
        event: InputEvent,
        trigger: Option<&str>,
    ) -> Result<(), SimulationError> {
        if let InputEvent::Pointer { position, .. } | InputEvent::PointerWithId { position, .. } =
            &event
        {
            valid_offset(*position)?;
        }
        if let InputEvent::Scroll { delta } = &event {
            valid_offset(*delta)?;
        }
        if !self.contains_window(window_id) {
            return Err(SimulationError::WindowNotFound(window_id));
        }
        let applied = self.with_window_mut(window_id, |record| {
            record.input_events = record.input_events.wrapping_add(1);
            let _ = match trigger {
                Some(trigger) => record.runtime.handle_input_with_trigger(event, trigger),
                None => {
                    record.runtime.tree().set_diagnostic_input_trigger(
                        Some("simulation::"),
                        &event,
                        super::diagnostic_input_trigger,
                    );
                    record.runtime.handle_input_timed(event)
                }
            };
        });
        applied
            .map(|_| ())
            .ok_or(SimulationError::WindowNotFound(window_id))
    }

    fn dispatch_simulation_click(
        &mut self,
        window_id: WindowId,
        position: Offset,
    ) -> Result<(), SimulationError> {
        valid_offset(position)?;
        self.ensure_simulation_layout(window_id)?;
        self.dispatch_simulation_click_prepared(
            window_id,
            position,
            &format!("click_at({:.1}, {:.1})", position.x, position.y),
        )
    }

    fn dispatch_simulation_click_prepared(
        &mut self,
        window_id: WindowId,
        position: Offset,
        trigger: &str,
    ) -> Result<(), SimulationError> {
        self.dispatch_simulation_input_with_trigger(
            window_id,
            InputEvent::Pointer {
                phase: PointerPhase::Move,
                position,
            },
            Some(trigger),
        )?;
        self.dispatch_simulation_input_with_trigger(
            window_id,
            InputEvent::Pointer {
                phase: PointerPhase::Down,
                position,
            },
            Some(trigger),
        )?;
        self.dispatch_simulation_input_with_trigger(
            window_id,
            InputEvent::Pointer {
                phase: PointerPhase::Up,
                position,
            },
            Some(trigger),
        )
    }

    fn ensure_simulation_layout(&mut self, window_id: WindowId) -> Result<(), SimulationError> {
        let diagnostics = self
            .window_diagnostics(window_id)
            .ok_or(SimulationError::WindowNotFound(window_id))?;
        if diagnostics.physical_size.is_zero() {
            return Err(SimulationError::FrameFailed(
                "the target window has a zero-sized surface".into(),
            ));
        }
        self.run_window_frame_at(
            window_id,
            Constraints::tight(diagnostics.logical_size),
            Instant::now(),
        )
        .map_err(|error| SimulationError::FrameFailed(format!("{error:?}")))?;
        // The preparation frame is not presented by this runtime-only step;
        // leave the native adapter a real redraw to present afterward.
        let _ = self.with_window_mut(window_id, |record| record.runtime.request_frame());
        Ok(())
    }

    fn simulation_label_bounds(
        &mut self,
        window_id: WindowId,
        label: &str,
    ) -> Result<Rect, SimulationError> {
        // Targets resolve through semantics, which a native host leaves off
        // until something needs them.
        self.set_semantics_enabled(window_id, true);
        self.ensure_simulation_layout(window_id)?;
        let viewport = self
            .window_diagnostics(window_id)
            .map(|diagnostics| Rect::from_origin_size(Offset::ZERO, diagnostics.logical_size))
            .ok_or(SimulationError::WindowNotFound(window_id))?;
        let result = self.registry.borrow().get(window_id).and_then(|record| {
            let mut fallback = None;
            record
                .runtime
                .tree()
                .semantics()
                .iter()
                .find_map(|(_, node)| {
                    if node.label.as_deref() != Some(label) || !node.state.enabled {
                        return None;
                    }
                    // Semantic trees can retain children just outside a
                    // viewport (especially sliver children). Resolve a
                    // pointer target only from the visible intersection so a
                    // simulation never reports a click that the pointer
                    // pipeline cannot receive.
                    let visible_bounds = node.bounds.intersection(viewport)?;
                    if visible_bounds.size.width <= 0.0 || visible_bounds.size.height <= 0.0 {
                        return None;
                    }
                    if node.actions.contains(&SemanticActionKind::Activate) {
                        return Some(visible_bounds);
                    }
                    fallback = Some(visible_bounds);
                    None
                })
                .or(fallback)
        });
        result.ok_or_else(|| SimulationError::ElementNotFound(label.to_owned()))
    }

    pub fn simulation_capture_pending(&self, window_id: WindowId) -> bool {
        self.simulation_waiters.capture_pending(window_id)
    }

    /// Returns the live windows with pending GPU-resource queries so the
    /// native adapter can fulfill them from current state without
    /// presenting. Live waiters stay queued until
    /// [`Self::complete_gpu_resource_query`] drains them; waiters for
    /// windows that no longer exist fail immediately instead of hanging
    /// the querier. Window close and application shutdown settle pending
    /// waiters through the shared close/shutdown cleanup, never through
    /// this method.
    pub fn take_gpu_resource_queries(&mut self) -> Vec<WindowId> {
        let mut live = Vec::new();
        for window_id in self.simulation_waiters.gpu_windows() {
            if self.contains_window(window_id) {
                live.push(window_id);
            } else {
                for reply in self.simulation_waiters.take_gpu_waiters(window_id) {
                    let _ = reply.send(Err(SimulationError::WindowNotFound(window_id)));
                }
            }
        }
        live
    }

    /// Completes pending GPU-resource waiters after the native adapter has
    /// snapshotted current residency. Never renders.
    pub fn complete_gpu_resource_query(
        &mut self,
        window_id: WindowId,
        summary: GpuResourceSummary,
    ) {
        self.simulation_waiters.complete_gpu(window_id, summary);
    }

    /// Reports whether a simulator is waiting for the next presented frame.
    #[must_use]
    pub fn simulation_frame_pending(&self, window_id: WindowId) -> bool {
        self.simulation_waiters.frame_pending(window_id)
    }

    /// Completes simulator waiters after the native renderer has presented a
    /// frame. `capture` is supplied only when a renderer serviced a pending
    /// capture request.
    pub fn complete_simulation_frame(
        &mut self,
        window_id: WindowId,
        presented: bool,
        capture: Option<Result<Screenshot, String>>,
    ) {
        self.simulation_waiters
            .complete_frame(window_id, presented, capture);
    }

    /// Fails simulator requests when a native frame cannot be produced.
    pub fn fail_simulation_frame(&mut self, window_id: WindowId, message: impl Into<String>) {
        self.simulation_waiters.fail_frame(window_id, message);
    }

    pub(crate) fn fail_simulation_window(&mut self, window_id: WindowId) {
        self.simulation_waiters.fail_window(window_id);
    }

    pub(crate) fn stop_simulation(&self) {
        self.simulation_bridge.stop();
    }
}

trait RectCenter {
    fn center(self) -> Offset;
}

impl RectCenter for Rect {
    fn center(self) -> Offset {
        Offset::new(
            self.origin.x + self.size.width * 0.5,
            self.origin.y + self.size.height * 0.5,
        )
    }
}

// Keep the imported input types intentionally visible in this module's API
// documentation and make accidental future requests for native IME payloads
// explicit at the type boundary.