sim-logic 0.1.0

A code-first application and logic layer for Sim;Engine
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
//! Keyboard/focus collection uses the exact field-based host dispatch path.
//! Winit's private KeyEvent fields are not fabricated or accessed unsafely.

use std::{error::Error, time::Duration};

use sim_engine::LogicalViewport;
use winit::event::MouseButton as PlatformMouseButton;

use super::*;
use crate::{
    app::{AppConfig, Application},
    input::{
        ALL_PHYSICAL_KEYS, ActionEdge, FrameInput, InputCancellationReason, InputControl,
        MouseButton, PointerSample,
    },
    resources::AppResMut,
    system::Stage,
    visual::ActiveCamera2d,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum TestAction {
    Activate,
}

#[derive(Default, Clone)]
struct Observed {
    edges: Vec<ActionEdge<TestAction>>,
    held: bool,
    pointer: Option<PointerSample>,
}

fn observe(input: FrameInput<TestAction>, mut observed: AppResMut<Observed>) {
    observed.edges.clear();
    observed.edges.extend(input.edges());
    observed.held = input.held(TestAction::Activate);
    observed.pointer = input.pointer();
}

fn host(limit: usize) -> Result<DesktopHost<TestAction>, Box<dyn Error>> {
    let mut application = Application::new(AppConfig::default())?;
    for key in ALL_PHYSICAL_KEYS {
        application.bind_key(key, TestAction::Activate)?;
    }
    for button in [MouseButton::Left, MouseButton::Right, MouseButton::Middle] {
        application.bind_mouse_button(button, TestAction::Activate)?;
    }
    application.register_app_resource(Observed::default())?;
    application.add_system(Stage::FrameUpdate, observe);
    let camera = ActiveCamera2d::centered(1.0)?;
    let initial = application.register_world("desktop-input-provenance", move |world| {
        world.spawn(camera)?;
        Ok(())
    })?;
    let mut host = DesktopHost::new(
        application.build_headless(initial)?,
        DesktopConfig::default(),
        limit,
        frame_budget(FrameLimits::default()),
        ThreeDRenderLimits::default(),
    );
    host.pointer_geometry = DesktopPointerGeometry::new(PhysicalSize::new(800, 600), 1.0)?;
    Ok(host)
}

fn advance(host: &mut DesktopHost<TestAction>) -> Result<Observed, Box<dyn Error>> {
    assert_eq!(host.input_failure, None);
    let outcome = advance_shared_core(
        &mut host.runner,
        FrameRequest::new(
            Duration::from_millis(20),
            &host.pending_events,
            LogicalViewport::new(800.0, 600.0)?,
        ),
    );
    let FrameOutcome::Advanced(report) = outcome else {
        return Err("desktop input frame should advance".into());
    };
    assert!(report.failure().is_none());
    host.pending_events.clear();
    host.runner
        .app_resource::<Observed>()
        .cloned()
        .ok_or_else(|| "missing input observations".into())
}

#[test]
fn focus_boundary_expansion_and_cancellation_order_belong_to_shared_core()
-> Result<(), Box<dyn Error>> {
    let mut host = host(ALL_PHYSICAL_KEYS.len() + 5)?;
    host.collect_cursor(PhysicalPosition::new(25.0, 35.0))?;
    for key in ALL_PHYSICAL_KEYS.into_iter().rev() {
        host.collect_physical_key(key, ButtonState::Pressed);
    }
    for button in [
        PlatformMouseButton::Middle,
        PlatformMouseButton::Right,
        PlatformMouseButton::Left,
    ] {
        host.collect_mouse_button(button, ElementState::Pressed);
    }
    let before_boundary = host.pending_events.len();
    host.collect_focus_loss();
    assert_eq!(host.pending_events.len(), before_boundary + 1);
    assert_eq!(host.pending_events.last(), Some(&InputEvent::FocusLost));
    assert!(host.held_keys.iter().all(|held| !held));

    let observed = advance(&mut host)?;
    assert!(!observed.held);
    assert_eq!(observed.pointer, None);
    let releases = observed
        .edges
        .iter()
        .filter(|edge| edge.state() == ButtonState::Released)
        .collect::<Vec<_>>();
    let expected = ALL_PHYSICAL_KEYS
        .into_iter()
        .map(InputControl::Key)
        .chain(
            [MouseButton::Left, MouseButton::Right, MouseButton::Middle]
                .map(InputControl::MouseButton),
        )
        .collect::<Vec<_>>();
    assert_eq!(
        releases
            .iter()
            .map(|edge| edge.control())
            .collect::<Vec<_>>(),
        expected
    );
    for edge in releases {
        assert!(edge.is_cancelled());
        assert_eq!(
            edge.cancellation_reason(),
            Some(InputCancellationReason::FocusLost)
        );
        assert_eq!(edge.pointer(), None);
    }

    host.collect_focus_loss();
    let observed = advance(&mut host)?;
    assert!(observed.edges.is_empty());
    assert!(!observed.held);
    Ok(())
}

#[test]
fn synthetic_release_before_focus_loss_does_not_hide_cancellation() -> Result<(), Box<dyn Error>> {
    let mut host = host(2)?;
    host.collect_key(
        PhysicalKey::Code(KeyCode::KeyW),
        ElementState::Pressed,
        false,
        false,
    );
    host.collect_key(
        PhysicalKey::Code(KeyCode::KeyW),
        ElementState::Released,
        true,
        false,
    );
    assert_eq!(host.pending_events.len(), 1);
    assert!(host.held_keys[physical_key_index(PhysicalKeyCode::KeyW)]);
    host.collect_focus_loss();

    let observed = advance(&mut host)?;
    assert_eq!(observed.edges.len(), 2);
    assert_eq!(observed.edges[0].state(), ButtonState::Pressed);
    assert!(!observed.edges[0].is_cancelled());
    assert_eq!(observed.edges[1].state(), ButtonState::Released);
    assert_eq!(
        observed.edges[1].cancellation_reason(),
        Some(InputCancellationReason::FocusLost)
    );
    assert!(!observed.held);
    Ok(())
}

#[test]
fn focus_return_ignores_restoration_and_repeat_until_a_fresh_press() -> Result<(), Box<dyn Error>> {
    let mut host = host(4)?;
    host.collect_key(
        PhysicalKey::Code(KeyCode::KeyW),
        ElementState::Pressed,
        false,
        false,
    );
    host.collect_focus_loss();
    assert!(!advance(&mut host)?.held);

    host.collect_key(
        PhysicalKey::Code(KeyCode::KeyW),
        ElementState::Pressed,
        true,
        false,
    );
    host.collect_key(
        PhysicalKey::Code(KeyCode::KeyW),
        ElementState::Pressed,
        false,
        true,
    );
    host.collect_key(
        PhysicalKey::Code(KeyCode::KeyW),
        ElementState::Pressed,
        true,
        true,
    );
    assert!(host.pending_events.is_empty());
    assert!(!host.held_keys[physical_key_index(PhysicalKeyCode::KeyW)]);
    assert!(advance(&mut host)?.edges.is_empty());

    // Releasing the original physically held key after return does not emit a
    // second release. The next genuine non-repeat press starts a new action.
    host.collect_key(
        PhysicalKey::Code(KeyCode::KeyW),
        ElementState::Released,
        false,
        false,
    );
    assert!(advance(&mut host)?.edges.is_empty());
    host.collect_key(
        PhysicalKey::Code(KeyCode::KeyW),
        ElementState::Pressed,
        false,
        false,
    );
    let observed = advance(&mut host)?;
    assert!(observed.held);
    assert_eq!(observed.edges.len(), 1);
    assert_eq!(
        observed.edges[0].control(),
        InputControl::Key(PhysicalKeyCode::KeyW)
    );
    assert!(!observed.edges[0].is_cancelled());
    Ok(())
}

#[test]
fn synthetic_events_repeated_presses_and_unmapped_keys_use_no_queue_capacity()
-> Result<(), Box<dyn Error>> {
    let mut host = host(0)?;
    for state in [ElementState::Pressed, ElementState::Released] {
        for repeat in [false, true] {
            host.collect_key(PhysicalKey::Code(KeyCode::KeyW), state, true, repeat);
        }
    }
    host.collect_key(
        PhysicalKey::Code(KeyCode::KeyW),
        ElementState::Pressed,
        false,
        true,
    );
    host.collect_key(
        PhysicalKey::Code(KeyCode::MediaPlayPause),
        ElementState::Pressed,
        false,
        false,
    );
    assert!(host.pending_events.is_empty());
    assert_eq!(host.input_failure, None);
    assert!(host.held_keys.iter().all(|held| !held));
    Ok(())
}

#[test]
fn repeat_flag_does_not_suppress_an_ordinary_key_release() -> Result<(), Box<dyn Error>> {
    let mut host = host(2)?;
    host.collect_key(
        PhysicalKey::Code(KeyCode::KeyW),
        ElementState::Pressed,
        false,
        false,
    );
    host.collect_key(
        PhysicalKey::Code(KeyCode::KeyW),
        ElementState::Released,
        false,
        true,
    );
    let observed = advance(&mut host)?;
    assert_eq!(observed.edges.len(), 2);
    assert_eq!(observed.edges[1].state(), ButtonState::Released);
    assert!(!observed.edges[1].is_cancelled());
    assert!(!observed.held);
    Ok(())
}

#[test]
fn focus_clears_stationary_pointer_before_resize_and_scale_updates() -> Result<(), Box<dyn Error>> {
    let mut host = host(4)?;
    host.collect_cursor(PhysicalPosition::new(200.0, 100.0))?;
    host.collect_focus_loss();
    let boundary_count = host.pending_events.len();
    host.collect_resize(PhysicalSize::new(1200, 800))?;
    host.collect_scale_factor(2.0)?;
    assert_eq!(host.pending_events.len(), boundary_count);
    assert_eq!(advance(&mut host)?.pointer, None);
    host.collect_cursor(PhysicalPosition::new(300.0, 200.0))?;
    let observed = advance(&mut host)?;
    let pointer = observed
        .pointer
        .ok_or("fresh motion should restore a pointer sample")?;
    assert_eq!(
        pointer.position(),
        sim_engine::LogicalScreenPosition::new(150.0, 100.0)
    );
    Ok(())
}

#[test]
fn rejected_focus_boundary_preserves_local_state_and_overflow_remains_sticky()
-> Result<(), Box<dyn Error>> {
    let mut host = host(3)?;
    host.collect_cursor(PhysicalPosition::new(10.0, 20.0))?;
    host.collect_physical_key(PhysicalKeyCode::KeyW, ButtonState::Pressed);
    host.collect_mouse_button(PlatformMouseButton::Left, ElementState::Pressed);
    let keys = host.held_keys;
    let geometry = host.pointer_geometry;
    let pending = host.pending_events.clone();
    host.collect_focus_loss();
    assert_eq!(host.input_failure, Some(InputBufferFailure::Limit));
    assert_eq!(host.held_keys, keys);
    assert_eq!(host.pointer_geometry, geometry);
    assert_eq!(host.pending_events, pending);

    // Even apparent room cannot recover a queue that lost an earlier event.
    host.pending_events.pop();
    let pending = host.pending_events.clone();
    for failure in [InputBufferFailure::Limit, InputBufferFailure::Allocation] {
        host.input_failure = Some(failure);
        host.collect_focus_loss();
        host.collect_physical_key(PhysicalKeyCode::KeyW, ButtonState::Released);
        host.collect_pointer_left();
        host.collect_cursor(PhysicalPosition::new(70.0, 80.0))?;
        host.collect_resize(PhysicalSize::new(1000, 700))?;
        host.collect_scale_factor(2.0)?;
        assert_eq!(host.input_failure, Some(failure));
        assert_eq!(host.held_keys, keys);
        assert_eq!(host.pointer_geometry, geometry);
        assert_eq!(host.pending_events, pending);
    }
    Ok(())
}

#[test]
fn rejected_pointer_events_do_not_publish_proposed_geometry() -> Result<(), Box<dyn Error>> {
    for change in 0..4 {
        let mut host = host(2)?;
        host.collect_cursor(PhysicalPosition::new(10.0, 20.0))?;
        host.collect_physical_key(PhysicalKeyCode::KeyW, ButtonState::Pressed);
        let geometry = host.pointer_geometry;
        let pending = host.pending_events.clone();
        match change {
            0 => host.collect_cursor(PhysicalPosition::new(70.0, 80.0))?,
            1 => host.collect_pointer_left(),
            2 => host.collect_resize(PhysicalSize::new(1000, 700))?,
            _ => host.collect_scale_factor(2.0)?,
        }
        assert_eq!(host.input_failure, Some(InputBufferFailure::Limit));
        assert_eq!(host.pointer_geometry, geometry);
        assert_eq!(host.pending_events, pending);
    }
    Ok(())
}

#[test]
fn rejected_key_press_or_release_preserves_adapter_held_state() -> Result<(), Box<dyn Error>> {
    let mut pressed = host(0)?;
    pressed.collect_key(
        PhysicalKey::Code(KeyCode::KeyW),
        ElementState::Pressed,
        false,
        false,
    );
    assert!(!pressed.held_keys[physical_key_index(PhysicalKeyCode::KeyW)]);
    assert_eq!(pressed.input_failure, Some(InputBufferFailure::Limit));

    let mut released = host(1)?;
    released.collect_key(
        PhysicalKey::Code(KeyCode::KeyW),
        ElementState::Pressed,
        false,
        false,
    );
    released.collect_key(
        PhysicalKey::Code(KeyCode::KeyW),
        ElementState::Released,
        false,
        false,
    );
    assert!(released.held_keys[physical_key_index(PhysicalKeyCode::KeyW)]);
    assert_eq!(released.input_failure, Some(InputBufferFailure::Limit));
    Ok(())
}

#[test]
fn relative_motion_coalesces_only_adjacent_samples_under_one_queue_slot()
-> Result<(), Box<dyn Error>> {
    let mut host = host(3)?;
    let motion = InputEvent::relative_pointer_motion(RelativePointerMotion::new(0.5, -0.25)?);
    for _ in 0..2000 {
        assert!(host.collect_input(motion));
    }
    assert_eq!(
        host.pending_events,
        [InputEvent::relative_pointer_motion(
            RelativePointerMotion::new(1000.0, -500.0)?
        )]
    );
    host.collect_mouse_button(PlatformMouseButton::Left, ElementState::Pressed);
    assert!(host.collect_input(motion));
    assert_eq!(host.pending_events.len(), 3);
    assert!(matches!(
        host.pending_events[1],
        InputEvent::MouseButton { .. }
    ));
    assert!(host.collect_input(motion));
    assert_eq!(host.pending_events.len(), 3);
    assert_eq!(
        host.pending_events[2],
        InputEvent::relative_pointer_motion(RelativePointerMotion::new(1.0, -0.5)?)
    );
    Ok(())
}

#[test]
fn relative_motion_overflow_is_sticky_and_preserves_accepted_tail() -> Result<(), Box<dyn Error>> {
    let mut host = host(1)?;
    let limit = InputEvent::relative_pointer_motion(RelativePointerMotion::new(
        RelativePointerMotion::MAX_DISPLACEMENT,
        0.0,
    )?);
    assert!(host.collect_input(limit));
    let extra = InputEvent::relative_pointer_motion(RelativePointerMotion::new(1.0, 0.0)?);
    assert!(!host.collect_input(extra));
    assert_eq!(host.pending_events, [limit]);
    assert_eq!(
        host.input_failure,
        Some(InputBufferFailure::RelativeMotion(
            RelativePointerMotionError::OutOfRange
        ))
    );
    assert!(!host.collect_input(InputEvent::FocusLost));
    assert_eq!(host.pending_events, [limit]);
    Ok(())
}

#[test]
fn uncaptured_global_device_motion_never_enters_the_window_queue() -> Result<(), Box<dyn Error>> {
    let mut host = host(1)?;
    host.collect_relative_motion((12.0, 4.0))?;
    host.capture.set_focused(true);
    host.collect_relative_motion((15.0, -3.0))?;
    host.collect_relative_motion((f64::NAN, f64::INFINITY))?;
    assert!(host.pending_events.is_empty());
    assert_eq!(host.input_failure, None);
    Ok(())
}

#[test]
fn capture_change_invalidates_old_position_before_click_without_fresh_motion()
-> Result<(), Box<dyn Error>> {
    for (before, after) in [(false, true), (true, false)] {
        let mut host = host(8)?;
        host.collect_cursor(PhysicalPosition::new(100.0, 120.0))?;
        assert!(advance(&mut host)?.pointer.is_some());
        host.collect_capture_change(before, after);
        assert_eq!(host.pending_events, [InputEvent::PointerLeft]);
        // A resize must not revive the pre-capture physical sample either.
        host.collect_resize(PhysicalSize::new(900, 650))?;
        assert_eq!(host.pending_events, [InputEvent::PointerLeft]);
        host.collect_mouse_button(PlatformMouseButton::Left, ElementState::Pressed);
        host.collect_mouse_button(PlatformMouseButton::Left, ElementState::Released);
        let no_motion = advance(&mut host)?;
        assert_eq!(no_motion.pointer, None);
        assert_eq!(no_motion.edges.len(), 2);
        assert!(no_motion.edges.iter().all(|edge| edge.pointer().is_none()));

        host.collect_cursor(PhysicalPosition::new(420.0, 250.0))?;
        host.collect_mouse_button(PlatformMouseButton::Left, ElementState::Pressed);
        let fresh = advance(&mut host)?;
        assert_eq!(fresh.edges.len(), 1);
        assert_eq!(fresh.edges[0].pointer(), fresh.pointer);
        assert_eq!(
            fresh.pointer.ok_or("fresh absolute sample")?.position(),
            sim_engine::LogicalScreenPosition::new(420.0, 250.0)
        );
    }
    Ok(())
}

#[test]
fn unchanged_capture_does_not_cancel_input_but_ownership_change_cancels_a_held_gesture()
-> Result<(), Box<dyn Error>> {
    let mut host = host(4)?;
    host.collect_cursor(PhysicalPosition::new(100.0, 120.0))?;
    host.collect_mouse_button(PlatformMouseButton::Left, ElementState::Pressed);
    assert!(advance(&mut host)?.held);
    for captured in [false, true] {
        host.collect_capture_change(captured, captured);
        assert!(host.pending_events.is_empty());
    }
    host.collect_capture_change(true, false);
    let cancelled = advance(&mut host)?;
    assert!(!cancelled.held);
    assert_eq!(cancelled.pointer, None);
    assert_eq!(cancelled.edges.len(), 1);
    assert_eq!(
        cancelled.edges[0].cancellation_reason(),
        Some(InputCancellationReason::PointerLeft)
    );
    Ok(())
}