1
//! Timer callback information and utilities for azul-layout
2
//!
3
//! This module provides Timer, TimerCallbackInfo and related types for
4
//! managing timers that run on the main UI thread.
5

            
6
use core::ffi::c_void;
7

            
8
use azul_core::{
9
    callbacks::{TimerCallbackReturn, Update},
10
    dom::{DomId, OptionDomNodeId},
11
    geom::{LogicalPosition, LogicalSize, OptionLogicalPosition},
12
    id::NodeId,
13
    menu::Menu,
14
    refany::{OptionRefAny, RefAny},
15
    resources::ImageRef,
16
    task::{
17
        Duration, GetSystemTimeCallback, Instant, OptionDuration, OptionInstant, TerminateTimer,
18
        ThreadId, TimerId,
19
    },
20
    window::{KeyboardState, MouseState, WindowFlags},
21
};
22
use azul_css::AzString;
23

            
24
use crate::{
25
    callbacks::CallbackInfo,
26
    thread::Thread,
27
    window_state::{FullWindowState, WindowCreateOptions},
28
};
29

            
30
/// Default timer tick interval in milliseconds when no interval is configured.
31
const DEFAULT_TIMER_TICK_MS: u64 = 10;
32

            
33
/// Callback type for timers
34
pub type TimerCallbackType = extern "C" fn(
35
    /* timer internal refany */ RefAny,
36
    TimerCallbackInfo,
37
) -> TimerCallbackReturn;
38

            
39
/// Callback that runs on every frame on the main thread
40
#[repr(C)]
41
pub struct TimerCallback {
42
    pub cb: TimerCallbackType,
43
    /// For FFI: stores the foreign callable (e.g., `PyFunction`)
44
    /// Native Rust code sets this to None
45
    pub ctx: OptionRefAny,
46
}
47

            
48
impl TimerCallback {
49
89
    pub fn create(cb: TimerCallbackType) -> Self {
50
89
        Self {
51
89
            cb,
52
89
            ctx: OptionRefAny::None,
53
89
        }
54
89
    }
55
}
56

            
57
impl core::fmt::Debug for TimerCallback {
58
1
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
59
1
        write!(f, "TimerCallback {{ cb: {:p} }}", self.cb as *const ())
60
1
    }
61
}
62

            
63
impl Clone for TimerCallback {
64
19
    fn clone(&self) -> Self {
65
19
        Self {
66
19
            cb: self.cb,
67
19
            ctx: self.ctx.clone(),
68
19
        }
69
19
    }
70
}
71

            
72
impl From<TimerCallbackType> for TimerCallback {
73
73
    fn from(cb: TimerCallbackType) -> Self {
74
73
        Self {
75
73
            cb,
76
73
            ctx: OptionRefAny::None,
77
73
        }
78
73
    }
79
}
80

            
81
impl PartialEq for TimerCallback {
82
6
    fn eq(&self, other: &Self) -> bool {
83
6
        std::ptr::eq(self.cb as *const (), other.cb as *const ())
84
6
    }
85
}
86

            
87
impl Eq for TimerCallback {}
88

            
89
impl PartialOrd for TimerCallback {
90
1
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
91
1
        (self.cb as *const () as usize).partial_cmp(&(other.cb as *const () as usize))
92
1
    }
93
}
94

            
95
impl Ord for TimerCallback {
96
5
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
97
5
        (self.cb as *const () as usize).cmp(&(other.cb as *const () as usize))
98
5
    }
99
}
100

            
101
impl core::hash::Hash for TimerCallback {
102
2
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
103
2
        (self.cb as *const () as usize).hash(state);
104
2
    }
105
}
106

            
107
/// A `Timer` is a function that runs on every frame or at intervals.
108
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
109
#[repr(C)]
110
pub struct Timer {
111
    pub refany: RefAny,
112
    pub node_id: OptionDomNodeId,
113
    pub created: Instant,
114
    pub last_run: OptionInstant,
115
    pub run_count: usize,
116
    pub delay: OptionDuration,
117
    pub interval: OptionDuration,
118
    pub timeout: OptionDuration,
119
    pub callback: TimerCallback,
120
}
121

            
122
impl Timer {
123
74
    pub fn create<C: Into<TimerCallback>>(
124
74
        refany: RefAny,
125
74
        callback: C,
126
74
        get_system_time_fn: GetSystemTimeCallback,
127
74
    ) -> Self {
128
74
        Self {
129
74
            refany,
130
74
            node_id: None.into(),
131
74
            created: (get_system_time_fn.cb)(),
132
74
            run_count: 0,
133
74
            last_run: OptionInstant::None,
134
74
            delay: OptionDuration::None,
135
74
            interval: OptionDuration::None,
136
74
            timeout: OptionDuration::None,
137
74
            callback: callback.into(),
138
74
        }
139
74
    }
140

            
141
    /// How often, in REAL milliseconds, the platform layer should wake to service
142
    /// this timer.
143
    ///
144
    /// A `Duration::Tick` interval is a FRAME count, so it is converted at the
145
    /// nominal frame rate rather than passed through. Passing it through treated
146
    /// one tick as one millisecond, so a `5t` interval asked the OS to wake ~16x
147
    /// more often than the timer could possibly fire — a measurable idle burn for
148
    /// a timer that flips at most every 5 frames.
149
    #[must_use]
150
22
    pub const fn tick_millis(&self) -> u64 {
151
22
        match self.interval.as_ref() {
152
18
            Some(d) => d.as_millis_u64(),
153
4
            None => DEFAULT_TIMER_TICK_MS,
154
        }
155
22
    }
156

            
157
    #[must_use]
158
59
    pub fn is_about_to_finish(&self, instant_now: &Instant) -> bool {
159
59
        match self.timeout {
160
15
            OptionDuration::Some(timeout) => instant_now
161
15
                .duration_since(&self.created)
162
15
                .greater_than(&timeout),
163
44
            OptionDuration::None => false,
164
        }
165
59
    }
166

            
167
    #[must_use]
168
23
    pub fn instant_of_next_run(&self) -> Instant {
169
23
        let last_run = self.last_run.as_ref().map_or(&self.created, |s| s);
170

            
171
23
        last_run
172
23
            .clone()
173
23
            .add_optional_duration(self.delay.as_ref())
174
23
            .add_optional_duration(self.interval.as_ref())
175
23
    }
176

            
177
    #[inline]
178
    #[must_use]
179
12
    pub const fn with_delay(mut self, delay: Duration) -> Self {
180
12
        self.delay = OptionDuration::Some(delay);
181
12
        self
182
12
    }
183

            
184
    #[inline]
185
    #[must_use]
186
43
    pub const fn with_interval(mut self, interval: Duration) -> Self {
187
43
        self.interval = OptionDuration::Some(interval);
188
43
        self
189
43
    }
190

            
191
    #[inline]
192
    #[must_use]
193
14
    pub const fn with_timeout(mut self, timeout: Duration) -> Self {
194
14
        self.timeout = OptionDuration::Some(timeout);
195
14
        self
196
14
    }
197

            
198
    /// Invoke the timer callback and update internal state.
199
    ///
200
    /// Returns a `TimerCallbackReturn` with `DoNothing` + `Continue` if the timer
201
    /// is not ready to run yet (delay not elapsed for first run, or interval not
202
    /// elapsed for subsequent runs). Forces `Terminate` when the timeout expires.
203
125
    pub fn invoke(
204
125
        &mut self,
205
125
        callback_info: &CallbackInfo,
206
125
        get_system_time_fn: &GetSystemTimeCallback,
207
125
    ) -> TimerCallbackReturn {
208
125
        let now = (get_system_time_fn.cb)();
209

            
210
        // Check if timer should run based on last_run, delay, and interval
211
        //
212
        // Admission is unchanged (see the note at the comparison). What DID
213
        // change is what the met deadline is recorded as — the schedule is now
214
        // phase-accumulating rather than stamped from the arrival time.
215
125
        let mut phase_target: Option<Instant> = None;
216
125
        match self.last_run.as_ref() {
217
101
            Some(last_run) => {
218
                // Timer has run before - check interval
219
101
                if let OptionDuration::Some(interval) = self.interval {
220
99
                    let elapsed = now.duration_since(last_run);
221
                    // Nanoseconds: the one scale a Tick span and a System span
222
                    // can be compared on.
223
                    //
224
                    // NO early-fire tolerance. An interval means exactly that
225
                    // interval —
226
                    // `a_tick_interval_throttles_a_wall_clock_timer_at_the_converted_boundary`
227
                    // and `invoke_throttles_a_wall_clock_interval_on_a_tick_clock_at_the_exact_frame`
228
                    // both pin that boundary deliberately, and admitting a fire
229
                    // early would redefine "5 frames" as "4.94 frames". The
230
                    // half-rate pump that motivated a tolerance is addressed
231
                    // where it actually belongs: the scroll physics now
232
                    // integrates over the elapsed time it is given, so a
233
                    // doubled gap costs sample rate and nothing else.
234
99
                    let interval_ns = interval.as_nanos();
235
99
                    if elapsed.smaller_than(&interval) {
236
77
                        return TimerCallbackReturn {
237
77
                            should_update: Update::DoNothing,
238
77
                            should_terminate: TerminateTimer::Continue,
239
77
                        };
240
22
                    }
241
                    // PHASE-ACCUMULATING schedule: the next deadline is
242
                    // measured from the one just met, not from the moment this
243
                    // fire happened to arrive. Stamping the arrival time let
244
                    // every late delivery push the whole schedule later, so the
245
                    // period drifted and never recovered.
246
                    //
247
                    // Only while we are keeping up: if more than one interval
248
                    // has already elapsed the timer is behind (a stalled app, a
249
                    // debugger breakpoint), and accumulating from the old
250
                    // deadline would demand a burst of catch-up fires. Fall back
251
                    // to the arrival time and resynchronise.
252
22
                    if elapsed.as_nanos() < interval_ns.saturating_mul(2) {
253
20
                        phase_target = Some(last_run.add_optional_duration(Some(&interval)));
254
20
                    }
255
2
                }
256
            }
257
            None => {
258
                // Timer has never run - check delay (first run)
259
24
                if let OptionDuration::Some(delay) = self.delay {
260
7
                    if now.duration_since(&self.created).smaller_than(&delay) {
261
5
                        return TimerCallbackReturn {
262
5
                            should_update: Update::DoNothing,
263
5
                            should_terminate: TerminateTimer::Continue,
264
5
                        };
265
2
                    }
266
17
                }
267
            }
268
        }
269

            
270
43
        let is_about_to_finish = self.is_about_to_finish(&now);
271

            
272
        // Create a new TimerCallbackInfo wrapping the callback_info
273
        // CallbackInfo is Copy, so we can just copy it directly
274
43
        let mut timer_callback_info = TimerCallbackInfo {
275
43
            callback_info: *callback_info,
276
43
            node_id: self.node_id,
277
43
            frame_start: now.clone(),
278
43
            call_count: self.run_count,
279
43
            is_about_to_finish,
280
43
            _abi_ref: core::ptr::null(),
281
43
            _abi_mut: core::ptr::null_mut(),
282
43
        };
283

            
284
        // Time THIS app callback under its own resolved symbol name
285
        // (`cb:my_timer_fn`): the per-phase histogram then compares one
286
        // callback's cost across versions, and a slow one is named in the
287
        // slow-span WARN. Resolution is cached; recording-off is one atomic.
288
43
        let _cb_span = crate::probe::Probe::span_for_fn(self.callback.cb as usize);
289
43
        let mut result = (self.callback.cb)(self.refany.clone(), timer_callback_info);
290

            
291
43
        if is_about_to_finish {
292
1
            result.should_terminate = TerminateTimer::Terminate;
293
42
        }
294

            
295
43
        self.run_count += 1;
296
        // The deadline just met, when the schedule is being kept (see above);
297
        // otherwise the arrival time, which resynchronises.
298
43
        self.last_run = OptionInstant::Some(phase_target.unwrap_or(now));
299

            
300
43
        result
301
125
    }
302
}
303

            
304
impl Default for Timer {
305
21
    fn default() -> Self {
306
        extern "C" fn default_callback(_: RefAny, _: TimerCallbackInfo) -> TimerCallbackReturn {
307
            TimerCallbackReturn::terminate_unchanged()
308
        }
309

            
310
21
        const extern "C" fn default_time() -> Instant {
311
21
            Instant::Tick(azul_core::task::SystemTick { tick_counter: 0 })
312
21
        }
313

            
314
21
        let cb: TimerCallbackType = default_callback;
315
21
        Self::create(
316
21
            RefAny::new(()),
317
21
            cb,
318
21
            GetSystemTimeCallback { cb: default_time },
319
        )
320
21
    }
321
}
322

            
323
/// Information passed to timer callbacks.
324
///
325
/// This wraps `CallbackInfo` and adds timer-specific fields like `call_count` and `frame_start`.
326
/// `CallbackInfo` methods are available via explicit delegation methods below.
327
#[derive(Debug, Clone)]
328
#[repr(C)]
329
#[allow(clippy::pub_underscore_fields)] // _abi_ref/_abi_mut: intentional FFI/api.json ABI-stability
330
                                        // placeholder fields
331
pub struct TimerCallbackInfo {
332
    pub callback_info: CallbackInfo,
333
    pub node_id: OptionDomNodeId,
334
    pub frame_start: Instant,
335
    pub call_count: usize,
336
    pub is_about_to_finish: bool,
337
    pub _abi_ref: *const c_void,
338
    pub _abi_mut: *mut c_void,
339
}
340

            
341
impl TimerCallbackInfo {
342
    #[must_use]
343
2273
    pub const fn create(
344
2273
        callback_info: CallbackInfo,
345
2273
        node_id: OptionDomNodeId,
346
2273
        frame_start: Instant,
347
2273
        call_count: usize,
348
2273
        is_about_to_finish: bool,
349
2273
    ) -> Self {
350
2273
        Self {
351
2273
            callback_info,
352
2273
            node_id,
353
2273
            frame_start,
354
2273
            call_count,
355
2273
            is_about_to_finish,
356
2273
            _abi_ref: core::ptr::null(),
357
2273
            _abi_mut: core::ptr::null_mut(),
358
2273
        }
359
2273
    }
360

            
361
    #[must_use]
362
2
    pub fn get_attached_node_size(&self) -> Option<LogicalSize> {
363
2
        let node_id = self.node_id.into_option()?;
364
1
        self.callback_info.get_node_size(node_id)
365
2
    }
366

            
367
    #[must_use]
368
2
    pub fn get_attached_node_position(&self) -> Option<LogicalPosition> {
369
2
        let node_id = self.node_id.into_option()?;
370
1
        self.callback_info.get_node_position(node_id)
371
2
    }
372

            
373
    #[must_use]
374
1
    pub const fn get_callback_info(&self) -> &CallbackInfo {
375
1
        &self.callback_info
376
1
    }
377

            
378
2
    pub const fn get_callback_info_mut(&mut self) -> &mut CallbackInfo {
379
2
        &mut self.callback_info
380
2
    }
381

            
382
    // ==================== Delegated CallbackInfo methods ====================
383
    // These methods delegate to the inner callback_info to provide the same API
384
    // as CallbackInfo without using Deref (which causes issues with FFI codegen)
385

            
386
    /// Get the callable for FFI language bindings (Python, etc.)
387
    #[must_use]
388
2
    pub fn get_ctx(&self) -> OptionRefAny {
389
2
        self.callback_info.get_ctx()
390
2
    }
391

            
392
    /// Add a timer to this window (applied after callback returns)
393
1
    pub fn add_timer(&mut self, timer_id: TimerId, timer: Timer) {
394
1
        self.callback_info.add_timer(timer_id, timer);
395
1
    }
396

            
397
    /// Remove a timer from this window (applied after callback returns)
398
1
    pub fn remove_timer(&mut self, timer_id: TimerId) {
399
1
        self.callback_info.remove_timer(timer_id);
400
1
    }
401

            
402
    /// Add a thread to this window (applied after callback returns)
403
1
    pub fn add_thread(&mut self, thread_id: ThreadId, thread: Thread) {
404
1
        self.callback_info.add_thread(thread_id, thread);
405
1
    }
406

            
407
    /// Remove a thread from this window (applied after callback returns)
408
1
    pub fn remove_thread(&mut self, thread_id: ThreadId) {
409
1
        self.callback_info.remove_thread(thread_id);
410
1
    }
411

            
412
    /// Stop event propagation (applied after callback returns)
413
1
    pub fn stop_propagation(&mut self) {
414
1
        self.callback_info.stop_propagation();
415
1
    }
416

            
417
    /// Create a new window (applied after callback returns)
418
1
    pub fn create_window(&mut self, options: WindowCreateOptions) {
419
1
        self.callback_info.create_window(options);
420
1
    }
421

            
422
    /// Close the current window (applied after callback returns)
423
1
    pub fn close_window(&mut self) {
424
1
        self.callback_info.close_window();
425
1
    }
426

            
427
    /// Modify the window state (applied after callback returns)
428
1
    pub fn modify_window_state(&mut self, state: FullWindowState) {
429
1
        self.callback_info.modify_window_state(state);
430
1
    }
431

            
432
    /// Add an image to the image cache (applied after callback returns)
433
1
    pub fn add_image_to_cache(&mut self, id: AzString, image: ImageRef) {
434
1
        self.callback_info.add_image_to_cache(id, image);
435
1
    }
436

            
437
    /// Remove an image from the image cache (applied after callback returns)
438
1
    pub fn remove_image_from_cache(&mut self, id: AzString) {
439
1
        self.callback_info.remove_image_from_cache(id);
440
1
    }
441

            
442
    /// Re-render ALL image callbacks across all DOMs (applied after callback returns)
443
    ///
444
    /// This is the most efficient way to update animated GL textures from a timer.
445
    /// Triggers only texture re-rendering - no DOM rebuild or display list resubmission.
446
1
    pub fn update_all_image_callbacks(&mut self) {
447
1
        self.callback_info.update_all_image_callbacks();
448
1
    }
449

            
450
    /// Trigger re-rendering of a `VirtualView` (applied after callback returns)
451
1
    pub fn trigger_virtual_view_rerender(&mut self, dom_id: DomId, node_id: NodeId) {
452
1
        self.callback_info
453
1
            .trigger_virtual_view_rerender(dom_id, node_id);
454
1
    }
455

            
456
    /// Reload system fonts (applied after callback returns)
457
1
    pub fn reload_system_fonts(&mut self) {
458
1
        self.callback_info.reload_system_fonts();
459
1
    }
460

            
461
    /// Prevent the default action
462
1
    pub fn prevent_default(&mut self) {
463
1
        self.callback_info.prevent_default();
464
1
    }
465

            
466
    /// Open a menu
467
1
    pub fn open_menu(&mut self, menu: Menu) {
468
1
        self.callback_info.open_menu(menu);
469
1
    }
470

            
471
    /// Open a menu at a specific position
472
3
    pub fn open_menu_at(&mut self, menu: Menu, position: LogicalPosition) {
473
3
        self.callback_info.open_menu_at(menu, position);
474
3
    }
475

            
476
    /// Show a tooltip at the current cursor position
477
2
    pub fn show_tooltip(&mut self, text: AzString) {
478
2
        self.callback_info.show_tooltip(text);
479
2
    }
480

            
481
    /// Show a tooltip at a specific position
482
1
    pub fn show_tooltip_at(&mut self, text: AzString, position: LogicalPosition) {
483
1
        self.callback_info.show_tooltip_at(text, position);
484
1
    }
485

            
486
    /// Hide the currently displayed tooltip
487
1
    pub fn hide_tooltip(&mut self) {
488
1
        self.callback_info.hide_tooltip();
489
1
    }
490

            
491
    /// Open a menu positioned relative to the currently hit node
492
1
    pub fn open_menu_for_hit_node(&mut self, menu: Menu) -> bool {
493
1
        self.callback_info.open_menu_for_hit_node(menu)
494
1
    }
495

            
496
    /// Get current window flags
497
    #[must_use]
498
1
    pub const fn get_current_window_flags(&self) -> WindowFlags {
499
1
        self.callback_info.get_current_window_flags()
500
1
    }
501

            
502
    /// Get current keyboard state
503
    #[must_use]
504
1
    pub fn get_current_keyboard_state(&self) -> KeyboardState {
505
1
        self.callback_info.get_current_keyboard_state()
506
1
    }
507

            
508
    /// Get current mouse state
509
    #[must_use]
510
3
    pub const fn get_current_mouse_state(&self) -> MouseState {
511
3
        self.callback_info.get_current_mouse_state()
512
3
    }
513

            
514
    /// Get the cursor position relative to the hit node
515
    #[must_use]
516
2
    pub const fn get_cursor_relative_to_node(&self) -> azul_core::geom::OptionCursorNodePosition {
517
2
        self.callback_info.get_cursor_relative_to_node()
518
2
    }
519

            
520
    /// Get the cursor position relative to the viewport
521
    #[must_use]
522
1
    pub const fn get_cursor_relative_to_viewport(&self) -> OptionLogicalPosition {
523
1
        self.callback_info.get_cursor_relative_to_viewport()
524
1
    }
525

            
526
    /// Get the current cursor position
527
    #[must_use]
528
2
    pub fn get_cursor_position(&self) -> Option<LogicalPosition> {
529
2
        self.callback_info.get_cursor_position()
530
2
    }
531

            
532
    /// Get the current time (when the timer callback started)
533
    #[must_use]
534
12
    pub fn get_current_time(&self) -> Instant {
535
12
        self.frame_start.clone()
536
12
    }
537

            
538
    /// Check if any node in a specific DOM is focused
539
    #[must_use]
540
2
    pub fn is_dom_focused(&self, dom_id: DomId) -> bool {
541
2
        self.callback_info.is_dom_focused(dom_id)
542
2
    }
543

            
544
    /// Check if pen is in contact
545
    #[must_use]
546
1
    pub fn is_pen_in_contact(&self) -> bool {
547
1
        self.callback_info.is_pen_in_contact()
548
1
    }
549

            
550
    /// Check if pen eraser is active
551
    #[must_use]
552
1
    pub fn is_pen_eraser(&self) -> bool {
553
1
        self.callback_info.is_pen_eraser()
554
1
    }
555

            
556
    /// Check if pen barrel button is pressed
557
    #[must_use]
558
1
    pub fn is_pen_barrel_button_pressed(&self) -> bool {
559
1
        self.callback_info.is_pen_barrel_button_pressed()
560
1
    }
561

            
562
    /// Check if dragging is active
563
    #[must_use]
564
2
    pub const fn is_dragging(&self) -> bool {
565
2
        self.callback_info.get_current_mouse_state().left_down
566
2
    }
567

            
568
    /// Check if drag is active
569
    #[must_use]
570
2
    pub const fn is_drag_active(&self) -> bool {
571
2
        self.callback_info.get_current_mouse_state().left_down
572
2
    }
573

            
574
    /// Check if node drag is active
575
    #[must_use]
576
2
    pub const fn is_node_drag_active(&self) -> bool {
577
2
        self.callback_info.get_current_mouse_state().left_down
578
2
    }
579

            
580
    /// Check if file drag is active
581
    #[must_use]
582
1
    pub fn is_file_drag_active(&self) -> bool {
583
1
        self.callback_info.is_file_drag_active()
584
1
    }
585

            
586
    /// Check if there's sufficient history for gestures
587
    #[must_use]
588
1
    pub fn has_sufficient_history_for_gestures(&self) -> bool {
589
1
        self.callback_info.has_sufficient_history_for_gestures()
590
1
    }
591

            
592
    // ==================== Scroll Management (timer architecture) ====================
593

            
594
    /// Get a read-only snapshot of a scroll node's bounds and position.
595
    ///
596
    /// Timer callbacks use this to read current scroll state for physics calculation.
597
    #[must_use]
598
1053
    pub fn get_scroll_node_info(
599
1053
        &self,
600
1053
        dom_id: DomId,
601
1053
        node_id: NodeId,
602
1053
    ) -> Option<crate::managers::scroll_state::ScrollNodeInfo> {
603
1053
        self.callback_info.get_scroll_node_info(dom_id, node_id)
604
1053
    }
605

            
606
    /// The closest scrollable STRICT ancestor of a node — see
607
    /// [`CallbackInfo::find_scroll_parent`](crate::callbacks::CallbackInfo::find_scroll_parent).
608
    ///
609
    /// Used by the scroll physics timer to chain leftover momentum OUTWARDS.
610
    #[must_use]
611
2
    pub fn find_scroll_parent(&self, dom_id: DomId, node_id: NodeId) -> Option<NodeId> {
612
2
        self.callback_info.find_scroll_parent(dom_id, node_id)
613
2
    }
614

            
615
    /// The scroll box a node LIVES IN, itself included — see
616
    /// [`CallbackInfo::find_scroll_target`](crate::callbacks::CallbackInfo::find_scroll_target).
617
    ///
618
    /// Used by the auto-scroll timer to pick which container to scroll when
619
    /// the user drags beyond its edge.
620
    #[must_use]
621
    pub fn find_scroll_target(&self, dom_id: DomId, node_id: NodeId) -> Option<NodeId> {
622
        // Converted back to the internal `NodeId`: the public accessor returns
623
        // the FFI wrapper (`NodeHierarchyItemId`) so bindings can use it, while
624
        // this caller is the auto-scroll timer inside the engine and wants the
625
        // plain index it indexes with.
626
        self.callback_info
627
            .find_scroll_target(dom_id, node_id)
628
            .into_option()
629
            .and_then(|n| n.into_crate_internal())
630
    }
631

            
632
    /// Get the scroll input queue for consuming pending scroll inputs.
633
    ///
634
    /// The physics timer calls `take_all()` each tick to drain inputs
635
    /// recorded by platform event handlers.
636
    #[cfg(feature = "std")]
637
    #[must_use]
638
1
    pub fn get_scroll_input_queue(&self) -> crate::managers::scroll_state::ScrollInputQueue {
639
1
        self.callback_info.get_scroll_input_queue()
640
1
    }
641

            
642
    /// Scroll a node to a specific position (via transactional `CallbackChange`).
643
    ///
644
    /// This is the primary way for timer callbacks to update scroll positions.
645
    /// The change is applied after the callback returns.
646
120
    pub fn scroll_to(
647
120
        &mut self,
648
120
        dom_id: DomId,
649
120
        node_id: azul_core::styled_dom::NodeHierarchyItemId,
650
120
        position: LogicalPosition,
651
120
    ) {
652
120
        self.callback_info.scroll_to(dom_id, node_id, position);
653
120
    }
654

            
655
    /// Scroll to position without clamping (for rubber-banding/overscroll).
656
595
    pub fn scroll_to_unclamped(
657
595
        &mut self,
658
595
        dom_id: DomId,
659
595
        node_id: azul_core::styled_dom::NodeHierarchyItemId,
660
595
        position: LogicalPosition,
661
595
    ) {
662
595
        self.callback_info
663
595
            .scroll_to_unclamped(dom_id, node_id, position);
664
595
    }
665

            
666
    // Cursor blink timer methods
667

            
668
    /// Set cursor visibility state (for cursor blink timer)
669
2
    pub fn set_cursor_visibility(&mut self, visible: bool) {
670
2
        self.callback_info.set_cursor_visibility(visible);
671
2
    }
672

            
673
    /// Toggle cursor visibility (for cursor blink timer).
674
10
    pub fn set_cursor_visibility_toggle(&mut self) {
675
        use crate::callbacks::CallbackChange;
676
10
        self.callback_info
677
10
            .push_change(CallbackChange::ToggleCursorVisibility);
678
10
    }
679

            
680
    /// Reset cursor blink state on user input
681
1
    pub fn reset_cursor_blink(&mut self) {
682
1
        self.callback_info.reset_cursor_blink();
683
1
    }
684
}
685

            
686
/// Optional Timer type for API compatibility
687
#[derive(Debug, Clone)]
688
#[repr(C, u8)]
689
// FFI Option enum; boxing the Some variant would break the #[repr(C, u8)] C ABI / api.json.
690
#[allow(variant_size_differences)]
691
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
692
// disparity accepted
693
#[allow(clippy::large_enum_variant)]
694
pub enum OptionTimer {
695
    None,
696
    Some(Timer),
697
}
698

            
699
impl From<Option<Timer>> for OptionTimer {
700
2
    fn from(o: Option<Timer>) -> Self {
701
2
        o.map_or_else(|| Self::None, Self::Some)
702
2
    }
703
}
704

            
705
impl OptionTimer {
706
    #[must_use]
707
3
    pub fn into_option(self) -> Option<Timer> {
708
3
        match self {
709
2
            Self::None => None,
710
1
            Self::Some(t) => Some(t),
711
        }
712
3
    }
713
}
714

            
715
#[cfg(all(test, feature = "std"))]
716
#[allow(
717
    clippy::float_cmp,
718
    clippy::too_many_lines,
719
    clippy::unreadable_literal,
720
    clippy::cognitive_complexity
721
)]
722
mod autotest_generated {
723
    use std::{
724
        collections::BTreeMap,
725
        sync::{
726
            atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
727
            Arc, Mutex, MutexGuard, PoisonError,
728
        },
729
    };
730

            
731
    use azul_core::{
732
        dom::DomNodeId,
733
        gl::OptionGlContextPtr,
734
        hit_test::ScrollPosition,
735
        menu::MenuItemVec,
736
        resources::{RawImageFormat, RendererResources},
737
        styled_dom::NodeHierarchyItemId,
738
        task::{SystemTick, SystemTickDiff, SystemTimeDiff, ThreadReceiver},
739
        window::{MonitorVec, RawWindowHandle},
740
    };
741
    use azul_css::system::SystemStyle;
742
    use rust_fontconfig::FcFontCache;
743

            
744
    use super::*;
745
    #[cfg(feature = "icu")]
746
    use crate::icu::IcuLocalizerHandle;
747
    use crate::{
748
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
749
        thread::{ThreadCallbackType, ThreadSender},
750
        window::LayoutWindow,
751
    };
752

            
753
    // ------------------------------------------------------------------
754
    // Time helpers
755
    // ------------------------------------------------------------------
756

            
757
    /// A tick-based `Instant` — the only kind constructible without a real clock,
758
    /// and the only kind whose arithmetic is fully deterministic.
759
    fn tick(t: u64) -> Instant {
760
        Instant::Tick(SystemTick::new(t))
761
    }
762

            
763
    /// A tick-based `Duration`.
764
    const fn tick_dur(d: u64) -> Duration {
765
        Duration::Tick(SystemTickDiff { tick_diff: d })
766
    }
767

            
768
    /// A wall-clock-based `Duration` (deliberately the *wrong kind* to pair with
769
    /// a `Tick` instant — several tests below pin the saturating behaviour of
770
    /// exactly that mismatch).
771
    const fn sys_dur_millis(ms: u64) -> Duration {
772
        Duration::System(SystemTimeDiff::from_millis(ms))
773
    }
774

            
775
    /// Extract the tick counter, asserting the instant really is tick-based.
776
    fn tick_of(i: &Instant) -> u64 {
777
        match i {
778
            Instant::Tick(t) => t.tick_counter,
779
            Instant::System(_) => panic!("expected a Tick instant, got a System one"),
780
        }
781
    }
782

            
783
    // ------------------------------------------------------------------
784
    // Fake clock + recording callback
785
    //
786
    // `GetSystemTimeCallbackType` is a bare `extern "C" fn()` with no context
787
    // pointer, so the fake clock has to live in statics. Every test that touches
788
    // them takes `clock_guard()` first, which serialises them against the rest of
789
    // the (parallel) test binary.
790
    // ------------------------------------------------------------------
791

            
792
    static CLOCK_LOCK: Mutex<()> = Mutex::new(());
793
    static FAKE_TICK: AtomicU64 = AtomicU64::new(0);
794
    static CB_INVOCATIONS: AtomicUsize = AtomicUsize::new(0);
795
    static CB_SEEN_CALL_COUNT: AtomicUsize = AtomicUsize::new(0);
796
    static CB_SEEN_FRAME_START: AtomicU64 = AtomicU64::new(0);
797
    static CB_SEEN_ABOUT_TO_FINISH: AtomicBool = AtomicBool::new(false);
798
    static CB_RETURN_TERMINATE: AtomicBool = AtomicBool::new(false);
799

            
800
    /// Serialises access to the fake-clock / recorder statics. Ignores poisoning:
801
    /// a `#[should_panic]`-free suite still panics on assertion failure, and a
802
    /// poisoned lock must not cascade into unrelated test failures.
803
    fn clock_guard() -> MutexGuard<'static, ()> {
804
        let guard = CLOCK_LOCK.lock().unwrap_or_else(PoisonError::into_inner);
805
        FAKE_TICK.store(0, Ordering::SeqCst);
806
        CB_INVOCATIONS.store(0, Ordering::SeqCst);
807
        CB_SEEN_CALL_COUNT.store(0, Ordering::SeqCst);
808
        CB_SEEN_FRAME_START.store(0, Ordering::SeqCst);
809
        CB_SEEN_ABOUT_TO_FINISH.store(false, Ordering::SeqCst);
810
        CB_RETURN_TERMINATE.store(false, Ordering::SeqCst);
811
        guard
812
    }
813

            
814
    fn set_now(t: u64) {
815
        FAKE_TICK.store(t, Ordering::SeqCst);
816
    }
817

            
818
    extern "C" fn fake_clock() -> Instant {
819
        Instant::Tick(SystemTick::new(FAKE_TICK.load(Ordering::SeqCst)))
820
    }
821

            
822
    fn fake_clock_cb() -> GetSystemTimeCallback {
823
        GetSystemTimeCallback { cb: fake_clock }
824
    }
825

            
826
    /// Records everything the timer machinery handed it, and returns whatever
827
    /// `CB_RETURN_TERMINATE` currently says.
828
    extern "C" fn recording_cb(_data: RefAny, info: TimerCallbackInfo) -> TimerCallbackReturn {
829
        CB_INVOCATIONS.fetch_add(1, Ordering::SeqCst);
830
        CB_SEEN_CALL_COUNT.store(info.call_count, Ordering::SeqCst);
831
        CB_SEEN_ABOUT_TO_FINISH.store(info.is_about_to_finish, Ordering::SeqCst);
832
        if let Instant::Tick(t) = &info.frame_start {
833
            CB_SEEN_FRAME_START.store(t.tick_counter, Ordering::SeqCst);
834
        }
835
        TimerCallbackReturn {
836
            should_update: Update::DoNothing,
837
            should_terminate: if CB_RETURN_TERMINATE.load(Ordering::SeqCst) {
838
                TerminateTimer::Terminate
839
            } else {
840
                TerminateTimer::Continue
841
            },
842
        }
843
    }
844

            
845
    // Two callbacks with *different bodies* — identical bodies are legal prey for
846
    // identical-code folding, which would silently merge their addresses and make
847
    // the `TimerCallback` Eq/Ord/Hash tests below vacuous.
848
    extern "C" fn cb_alpha(_d: RefAny, _i: TimerCallbackInfo) -> TimerCallbackReturn {
849
        TimerCallbackReturn {
850
            should_update: Update::RefreshDom,
851
            should_terminate: TerminateTimer::Terminate,
852
        }
853
    }
854
    extern "C" fn cb_beta(_d: RefAny, _i: TimerCallbackInfo) -> TimerCallbackReturn {
855
        TimerCallbackReturn {
856
            should_update: Update::DoNothing,
857
            should_terminate: TerminateTimer::Continue,
858
        }
859
    }
860

            
861
    /// A timer created at tick `created`, driven by the fake clock.
862
    fn timer_at(created: u64, cb: TimerCallbackType) -> Timer {
863
        set_now(created);
864
        Timer::create(RefAny::new(0_usize), cb, fake_clock_cb())
865
    }
866

            
867
    // ------------------------------------------------------------------
868
    // CallbackInfo harness (mirrors the one in `scroll_timer.rs`)
869
    // ------------------------------------------------------------------
870

            
871
    struct Env<'a> {
872
        ref_data: &'a CallbackInfoRefData<'a>,
873
        changes: &'a Arc<Mutex<Vec<CallbackChange>>>,
874
    }
875

            
876
    impl Env<'_> {
877
        fn info(&self) -> CallbackInfo {
878
            self.info_with(OptionLogicalPosition::None, OptionLogicalPosition::None)
879
        }
880

            
881
        fn info_with(
882
            &self,
883
            cursor_relative_to_item: OptionLogicalPosition,
884
            cursor_in_viewport: OptionLogicalPosition,
885
        ) -> CallbackInfo {
886
            CallbackInfo::new(
887
                self.ref_data,
888
                self.changes,
889
                DomNodeId {
890
                    dom: DomId::ROOT_ID,
891
                    node: NodeHierarchyItemId::NONE,
892
                },
893
                cursor_relative_to_item,
894
                cursor_in_viewport,
895
            )
896
        }
897

            
898
        /// A `TimerCallbackInfo` with no attached node, frame_start = tick 0.
899
        fn timer_info(&self) -> TimerCallbackInfo {
900
            TimerCallbackInfo::create(self.info(), OptionDomNodeId::None, tick(0), 0, false)
901
        }
902

            
903
        fn take_changes(&self) -> Vec<CallbackChange> {
904
            self.changes
905
                .lock()
906
                .map(|mut c| core::mem::take(&mut *c))
907
                .unwrap_or_default()
908
        }
909

            
910
        /// Drain the log, asserting it holds exactly one change, and return it.
911
        fn take_one(&self) -> CallbackChange {
912
            let mut changes = self.take_changes();
913
            assert_eq!(changes.len(), 1, "expected exactly one change: {changes:?}");
914
            changes.remove(0)
915
        }
916
    }
917

            
918
    fn with_env<R>(f: impl FnOnce(&Env<'_>) -> R) -> R {
919
        with_env_cfg(false, OptionRefAny::None, f)
920
    }
921

            
922
    /// Builds a callback environment over an empty `LayoutWindow`. `left_down`
923
    /// drives the mouse state the drag predicates read; `ctx` is what `get_ctx`
924
    /// hands back to FFI bindings.
925
    fn with_env_cfg<R>(left_down: bool, ctx: OptionRefAny, f: impl FnOnce(&Env<'_>) -> R) -> R {
926
        let layout_window =
927
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
928
        let renderer_resources = RendererResources::default();
929
        let previous_window_state: Option<FullWindowState> = None;
930
        let mut current_window_state = FullWindowState::default();
931
        current_window_state.mouse_state.left_down = left_down;
932
        let gl_context = OptionGlContextPtr::None;
933
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
934
            BTreeMap::new();
935
        let window_handle = RawWindowHandle::Unsupported;
936
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
937

            
938
        let ref_data = CallbackInfoRefData {
939
            layout_window: &layout_window,
940
            renderer_resources: &renderer_resources,
941
            previous_window_state: &previous_window_state,
942
            current_window_state: &current_window_state,
943
            gl_context: &gl_context,
944
            current_scroll_manager: &scroll_states,
945
            current_window_handle: &window_handle,
946
            system_callbacks: &system_callbacks,
947
            system_style: Arc::new(SystemStyle::default()),
948
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
949
            #[cfg(feature = "icu")]
950
            icu_localizer: IcuLocalizerHandle::default(),
951
            ctx,
952
        };
953

            
954
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
955
        let env = Env {
956
            ref_data: &ref_data,
957
            changes: &changes,
958
        };
959
        f(&env)
960
    }
961

            
962
    fn empty_menu() -> Menu {
963
        Menu::create(MenuItemVec::from_const_slice(&[]))
964
    }
965

            
966
    // ==================================================================
967
    // Timer::create / Default — constructor invariants
968
    // ==================================================================
969

            
970
    #[test]
971
    fn timer_create_starts_completely_unarmed() {
972
        let _g = clock_guard();
973
        let t = timer_at(12_345, recording_cb as TimerCallbackType);
974

            
975
        assert_eq!(
976
            tick_of(&t.created),
977
            12_345,
978
            "created must come from the clock"
979
        );
980
        assert_eq!(t.run_count, 0);
981
        assert_eq!(t.last_run, OptionInstant::None);
982
        assert_eq!(t.delay, OptionDuration::None);
983
        assert_eq!(t.interval, OptionDuration::None);
984
        assert_eq!(t.timeout, OptionDuration::None);
985
        assert_eq!(t.node_id, OptionDomNodeId::None);
986
    }
987

            
988
    #[test]
989
    fn timer_create_at_max_tick_does_not_panic() {
990
        let _g = clock_guard();
991
        let t = timer_at(u64::MAX, recording_cb as TimerCallbackType);
992
        assert_eq!(tick_of(&t.created), u64::MAX);
993
        // Nothing is armed, so nothing can overflow off the end of time.
994
        assert!(!t.is_about_to_finish(&tick(u64::MAX)));
995
        assert_eq!(tick_of(&t.instant_of_next_run()), u64::MAX);
996
    }
997

            
998
    #[test]
999
    fn timer_default_is_a_zero_tick_timer() {
        let t = Timer::default();
        assert_eq!(tick_of(&t.created), 0);
        assert_eq!(t.run_count, 0);
        assert_eq!(t.last_run, OptionInstant::None);
        assert_eq!(t.tick_millis(), DEFAULT_TIMER_TICK_MS);
    }
    #[test]
    fn timer_clone_equals_original() {
        let _g = clock_guard();
        let t = timer_at(7, recording_cb as TimerCallbackType)
            .with_delay(tick_dur(1))
            .with_interval(tick_dur(2))
            .with_timeout(tick_dur(3));
        let c = t.clone();
        assert_eq!(t, c, "Clone must be value-preserving");
    }
    // ==================================================================
    // Timer::tick_millis — numeric limits / round-trip
    // ==================================================================
    #[test]
    fn tick_millis_falls_back_to_default_without_interval() {
        let _g = clock_guard();
        let t = timer_at(0, recording_cb as TimerCallbackType);
        assert_eq!(t.tick_millis(), DEFAULT_TIMER_TICK_MS);
        assert_eq!(t.tick_millis(), 10);
        // A delay/timeout must NOT be mistaken for an interval.
        let t = t.with_delay(tick_dur(999)).with_timeout(tick_dur(888));
        assert_eq!(t.tick_millis(), DEFAULT_TIMER_TICK_MS);
    }
    /// A tick interval is a FRAME count, so the platform wake-up interval it
    /// implies is `ticks / 60` seconds, not `ticks` milliseconds. The old
    /// pass-through made a `5t` timer ask the OS to wake every 5ms for a callback
    /// that can only fire every ~83ms.
    #[test]
    fn tick_millis_converts_tick_intervals_at_the_nominal_frame_rate() {
        let _g = clock_guard();
        for (raw, expected_ms) in [(0_u64, 0_u64), (1, 16), (5, 83), (60, 1_000), (600, 10_000)] {
            let t = timer_at(0, recording_cb as TimerCallbackType).with_interval(tick_dur(raw));
            assert_eq!(
                t.tick_millis(),
                expected_ms,
                "a {raw}-tick interval is {expected_ms}ms of wall clock"
            );
        }
    }
    /// `u64::MAX` ticks is ~9.7 billion years, which does NOT fit in `u64`
    /// milliseconds. The conversion must clamp — wrapping would turn "never" into
    /// some small interval and busy-wake the event loop forever.
    #[test]
    fn tick_millis_saturates_on_an_absurd_tick_interval_instead_of_wrapping() {
        let _g = clock_guard();
        let t = timer_at(0, recording_cb as TimerCallbackType).with_interval(tick_dur(u64::MAX));
        assert_eq!(t.tick_millis(), u64::MAX);
        // The largest tick interval that still converts without clamping.
        let fits = u64::MAX / 1000 * 60;
        let t = timer_at(0, recording_cb as TimerCallbackType).with_interval(tick_dur(fits));
        assert!(t.tick_millis() < u64::MAX, "{fits} ticks should not clamp");
    }
    #[test]
    fn tick_millis_system_interval_round_trips_whole_millis() {
        let _g = clock_guard();
        // from_millis -> millis() is an exact round-trip, even at u64::MAX
        // (secs*1000 + 615 lands exactly on u64::MAX without saturating).
        for ms in [0_u64, 1, 999, 1_000, 1_001, 86_400_000, u64::MAX] {
            let t =
                timer_at(0, recording_cb as TimerCallbackType).with_interval(sys_dur_millis(ms));
            assert_eq!(t.tick_millis(), ms, "millis {ms} must round-trip");
        }
    }
    #[test]
    fn tick_millis_saturates_instead_of_overflowing() {
        let _g = clock_guard();
        // secs::MAX * 1000 overflows u64 — `millis()` must saturate, not panic.
        let huge = Duration::System(SystemTimeDiff {
            secs: u64::MAX,
            nanos: 999_999_999,
        });
        let t = timer_at(0, recording_cb as TimerCallbackType).with_interval(huge);
        assert_eq!(t.tick_millis(), u64::MAX);
    }
    #[test]
    fn tick_millis_truncates_sub_millisecond_intervals_to_zero() {
        let _g = clock_guard();
        // A 999_999ns interval is a *sub-millisecond* tick request; it truncates
        // to 0, i.e. "tick as fast as possible", not to 1.
        let t = timer_at(0, recording_cb as TimerCallbackType)
            .with_interval(Duration::System(SystemTimeDiff::from_nanos(999_999)));
        assert_eq!(t.tick_millis(), 0);
    }
    // ==================================================================
    // Timer::is_about_to_finish — predicate boundaries
    // ==================================================================
    #[test]
    fn is_about_to_finish_is_false_without_a_timeout() {
        let _g = clock_guard();
        let t = timer_at(0, recording_cb as TimerCallbackType);
        assert!(!t.is_about_to_finish(&tick(0)));
        assert!(
            !t.is_about_to_finish(&tick(u64::MAX)),
            "no timeout = never finishes"
        );
    }
    #[test]
    fn is_about_to_finish_boundary_is_strictly_greater() {
        let _g = clock_guard();
        let t = timer_at(100, recording_cb as TimerCallbackType).with_timeout(tick_dur(50));
        assert!(!t.is_about_to_finish(&tick(149)), "1 tick early");
        // Elapsed == timeout is NOT "about to finish" — the comparison is `>`.
        assert!(!t.is_about_to_finish(&tick(150)), "exactly at the timeout");
        assert!(t.is_about_to_finish(&tick(151)), "1 tick past the timeout");
    }
    #[test]
    fn is_about_to_finish_saturates_when_the_clock_runs_backwards() {
        let _g = clock_guard();
        let t = timer_at(1_000, recording_cb as TimerCallbackType).with_timeout(tick_dur(10));
        // `now` older than `created`: duration_since saturates to 0 rather than
        // underflowing, so the timer is simply "not finished".
        assert!(!t.is_about_to_finish(&tick(0)));
    }
    #[test]
    fn is_about_to_finish_at_the_u64_ceiling() {
        let _g = clock_guard();
        let t = timer_at(0, recording_cb as TimerCallbackType);
        let max_timeout = t.clone().with_timeout(tick_dur(u64::MAX));
        assert!(
            !max_timeout.is_about_to_finish(&tick(u64::MAX)),
            "MAX elapsed is not > MAX timeout"
        );
        let near_max = t.with_timeout(tick_dur(u64::MAX - 1));
        assert!(near_max.is_about_to_finish(&tick(u64::MAX)));
    }
    /// A wall-clock timeout on a tick-driven timer must EXPIRE. `duration_since`
    /// yields a Tick duration, which is now compared against the System timeout
    /// on a canonical scale instead of saturating to `false`.
    ///
    /// The old saturating comparison made this timeout unexpirable — a timer
    /// created with a timeout silently became a timer with no timeout, and the
    /// only symptom was a callback that ran forever.
    #[test]
    fn is_about_to_finish_expires_a_wall_clock_timeout_on_a_tick_clock() {
        let _g = clock_guard();
        // 1ms at 60Hz is less than one frame, so the FIRST tick already exceeds it.
        let t = timer_at(0, recording_cb as TimerCallbackType).with_timeout(sys_dur_millis(1));
        assert!(!t.is_about_to_finish(&tick(0)), "no time has passed yet");
        assert!(t.is_about_to_finish(&tick(1)));
        assert!(t.is_about_to_finish(&tick(u64::MAX)));
        // A one-second timeout takes 60 whole frames, and expires strictly after.
        let t = timer_at(0, recording_cb as TimerCallbackType).with_timeout(sys_dur_millis(1_000));
        assert!(!t.is_about_to_finish(&tick(59)), "1 frame early");
        assert!(!t.is_about_to_finish(&tick(60)), "exactly at the timeout");
        assert!(t.is_about_to_finish(&tick(61)), "1 frame past the timeout");
    }
    // ==================================================================
    // Timer::instant_of_next_run — getter invariants
    // ==================================================================
    #[test]
    fn instant_of_next_run_is_created_when_nothing_is_armed() {
        let _g = clock_guard();
        let t = timer_at(42, recording_cb as TimerCallbackType);
        assert_eq!(tick_of(&t.instant_of_next_run()), 42);
    }
    #[test]
    fn instant_of_next_run_prefers_last_run_over_created() {
        let _g = clock_guard();
        let mut t = timer_at(100, recording_cb as TimerCallbackType).with_interval(tick_dur(7));
        assert_eq!(
            tick_of(&t.instant_of_next_run()),
            107,
            "no run yet: created + interval"
        );
        t.last_run = OptionInstant::Some(tick(500));
        assert_eq!(
            tick_of(&t.instant_of_next_run()),
            507,
            "after a run: last_run + interval"
        );
    }
    #[test]
    fn instant_of_next_run_sums_delay_and_interval() {
        let _g = clock_guard();
        // NOTE: when BOTH are set, the schedule point is `base + delay + interval`
        // — the delay is re-added on every subsequent run, even though `invoke`
        // only gates the *first* run on the delay. Pinned here as current
        // behaviour; see the report.
        let mut t = timer_at(100, recording_cb as TimerCallbackType)
            .with_delay(tick_dur(5))
            .with_interval(tick_dur(7));
        assert_eq!(tick_of(&t.instant_of_next_run()), 112);
        t.last_run = OptionInstant::Some(tick(200));
        assert_eq!(tick_of(&t.instant_of_next_run()), 212);
    }
    #[test]
    fn instant_of_next_run_saturates_at_the_end_of_time() {
        let _g = clock_guard();
        let t = timer_at(u64::MAX, recording_cb as TimerCallbackType)
            .with_delay(tick_dur(u64::MAX))
            .with_interval(tick_dur(u64::MAX));
        // Three MAXes added together: saturating_add, not an overflow panic.
        assert_eq!(tick_of(&t.instant_of_next_run()), u64::MAX);
    }
    /// System durations on a Tick instant are CONVERTED to whole frames, not
    /// dropped. Dropping them made `instant_of_next_run == created`, i.e. the
    /// timer claimed to be due immediately and stayed that way forever, which is
    /// how a unit mismatch turned into a scheduling bug with no error.
    #[test]
    fn instant_of_next_run_converts_wall_clock_delays_to_whole_frames() {
        let _g = clock_guard();
        let t = timer_at(42, recording_cb as TimerCallbackType)
            .with_delay(sys_dur_millis(1_000))
            .with_interval(sys_dur_millis(1_000));
        // 1000ms is 60 frames; delay + interval is 120.
        assert_eq!(tick_of(&t.instant_of_next_run()), 42 + 120);
    }
    /// A sub-frame wall-clock interval rounds DOWN to zero frames on a tick
    /// clock. That is the truthful answer at one-frame resolution — but it does
    /// mean such a timer is always due, so it is pinned here deliberately rather
    /// than rounded up to 1 to make something happen.
    #[test]
    fn instant_of_next_run_rounds_a_sub_frame_interval_down_to_zero_ticks() {
        let _g = clock_guard();
        let t = timer_at(42, recording_cb as TimerCallbackType).with_interval(sys_dur_millis(1));
        assert_eq!(tick_of(&t.instant_of_next_run()), 42);
    }
    // ==================================================================
    // with_delay / with_interval / with_timeout — builder invariants
    // ==================================================================
    #[test]
    fn with_setters_are_independent_and_preserve_the_rest() {
        let _g = clock_guard();
        let t = timer_at(9, recording_cb as TimerCallbackType)
            .with_delay(tick_dur(1))
            .with_interval(tick_dur(2))
            .with_timeout(tick_dur(3));
        assert_eq!(t.delay, OptionDuration::Some(tick_dur(1)));
        assert_eq!(t.interval, OptionDuration::Some(tick_dur(2)));
        assert_eq!(t.timeout, OptionDuration::Some(tick_dur(3)));
        // The builders must not disturb identity/progress fields.
        assert_eq!(tick_of(&t.created), 9);
        assert_eq!(t.run_count, 0);
        assert_eq!(t.last_run, OptionInstant::None);
    }
    #[test]
    fn with_setters_are_last_write_wins() {
        let _g = clock_guard();
        let t = timer_at(0, recording_cb as TimerCallbackType)
            .with_delay(tick_dur(1))
            .with_delay(tick_dur(2))
            .with_interval(tick_dur(3))
            .with_interval(tick_dur(4))
            .with_timeout(tick_dur(5))
            .with_timeout(tick_dur(6));
        assert_eq!(t.delay, OptionDuration::Some(tick_dur(2)));
        assert_eq!(t.interval, OptionDuration::Some(tick_dur(4)));
        assert_eq!(t.timeout, OptionDuration::Some(tick_dur(6)));
    }
    #[test]
    fn with_setters_accept_extreme_durations() {
        let _g = clock_guard();
        let t = timer_at(0, recording_cb as TimerCallbackType)
            .with_delay(tick_dur(0))
            .with_interval(tick_dur(u64::MAX))
            .with_timeout(Duration::max());
        assert_eq!(t.delay, OptionDuration::Some(tick_dur(0)));
        assert_eq!(t.tick_millis(), u64::MAX);
        // Duration::max() is a System duration -> never expires on a tick clock.
        assert!(!t.is_about_to_finish(&tick(u64::MAX)));
    }
    // ==================================================================
    // TimerCallback — identity, ordering, hashing
    // ==================================================================
    #[test]
    fn timer_callback_create_has_no_ffi_ctx() {
        let cb = TimerCallback::create(cb_alpha as TimerCallbackType);
        assert_eq!(cb.ctx, OptionRefAny::None);
        // `create` and the `From` impl must agree.
        let from: TimerCallback = (cb_alpha as TimerCallbackType).into();
        assert_eq!(cb, from);
    }
    #[test]
    fn timer_callback_identity_is_by_function_pointer() {
        let a1 = TimerCallback::create(cb_alpha as TimerCallbackType);
        let a2 = TimerCallback::create(cb_alpha as TimerCallbackType);
        let b = TimerCallback::create(cb_beta as TimerCallbackType);
        assert_eq!(a1, a2, "same fn -> equal");
        assert_ne!(a1, b, "different fn -> not equal");
        assert_eq!(a1, a1.clone(), "Clone preserves identity");
    }
    #[test]
    fn timer_callback_ord_and_hash_agree_with_eq() {
        use std::{
            collections::hash_map::DefaultHasher,
            hash::{Hash, Hasher},
        };
        fn hash_of(cb: &TimerCallback) -> u64 {
            let mut h = DefaultHasher::new();
            cb.hash(&mut h);
            h.finish()
        }
        let a = TimerCallback::create(cb_alpha as TimerCallbackType);
        let a2 = a.clone();
        let b = TimerCallback::create(cb_beta as TimerCallbackType);
        assert_eq!(a.cmp(&a2), core::cmp::Ordering::Equal);
        assert_eq!(hash_of(&a), hash_of(&a2), "Eq values must hash equal");
        // Ord must be antisymmetric and consistent with partial_cmp.
        assert_eq!(a.cmp(&b), a.partial_cmp(&b).unwrap());
        assert_eq!(a.cmp(&b).reverse(), b.cmp(&a));
        assert_ne!(
            a.cmp(&b),
            core::cmp::Ordering::Equal,
            "distinct fns must order strictly"
        );
    }
    #[test]
    fn timer_callback_debug_does_not_panic() {
        let s = format!("{:?}", TimerCallback::create(cb_alpha as TimerCallbackType));
        assert!(s.starts_with("TimerCallback"), "got {s}");
    }
    // ==================================================================
    // OptionTimer — round-trip
    // ==================================================================
    #[test]
    fn option_timer_round_trips_both_variants() {
        let _g = clock_guard();
        assert!(OptionTimer::None.into_option().is_none());
        assert!(OptionTimer::from(None).into_option().is_none());
        let t = timer_at(3, recording_cb as TimerCallbackType).with_interval(tick_dur(4));
        let round_tripped = OptionTimer::from(Some(t.clone()))
            .into_option()
            .expect("Some must survive the round-trip");
        assert_eq!(round_tripped, t, "encode == decode");
    }
    // ==================================================================
    // TimerCallbackInfo::create + getters
    // ==================================================================
    #[test]
    fn timer_callback_info_create_preserves_extremes() {
        with_env(|env| {
            let info = TimerCallbackInfo::create(
                env.info(),
                OptionDomNodeId::None,
                tick(u64::MAX),
                usize::MAX,
                true,
            );
            assert_eq!(info.call_count, usize::MAX, "no wrap at usize::MAX");
            assert!(info.is_about_to_finish);
            assert_eq!(tick_of(&info.frame_start), u64::MAX);
            assert!(info._abi_ref.is_null());
            assert!(info._abi_mut.is_null());
            let zero =
                TimerCallbackInfo::create(env.info(), OptionDomNodeId::None, tick(0), 0, false);
            assert_eq!(zero.call_count, 0);
            assert!(!zero.is_about_to_finish);
            assert_eq!(tick_of(&zero.frame_start), 0);
        });
    }
    #[test]
    fn get_current_time_returns_frame_start_verbatim() {
        with_env(|env| {
            for t in [0_u64, 1, u64::MAX] {
                let info =
                    TimerCallbackInfo::create(env.info(), OptionDomNodeId::None, tick(t), 0, false);
                assert_eq!(info.get_current_time(), tick(t));
            }
        });
    }
    #[test]
    fn attached_node_queries_are_none_without_an_attached_node() {
        with_env(|env| {
            let info = env.timer_info();
            assert!(info.get_attached_node_size().is_none());
            assert!(info.get_attached_node_position().is_none());
        });
    }
    #[test]
    fn attached_node_queries_are_none_for_a_bogus_node() {
        with_env(|env| {
            // Largest node index that survives the +1 encoding, in a DOM that
            // doesn't exist, on a window with no layout results at all.
            let bogus = DomNodeId {
                dom: DomId { inner: usize::MAX },
                node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(usize::MAX - 1))),
            };
            let info = TimerCallbackInfo::create(
                env.info(),
                OptionDomNodeId::Some(bogus),
                tick(0),
                0,
                false,
            );
            assert!(
                info.get_attached_node_size().is_none(),
                "must not panic or index OOB"
            );
            assert!(info.get_attached_node_position().is_none());
        });
    }
    #[test]
    fn get_callback_info_and_mut_alias_the_same_inner_info() {
        with_env(|env| {
            let mut info = env.timer_info();
            let addr_shared = std::ptr::from_ref(info.get_callback_info());
            let addr_mut = std::ptr::from_mut(info.get_callback_info_mut()).cast_const();
            assert!(
                std::ptr::eq(addr_shared, addr_mut),
                "both must alias the inner CallbackInfo"
            );
            // A change pushed through the &mut view lands in the shared log.
            info.get_callback_info_mut().prevent_default();
            assert!(matches!(env.take_one(), CallbackChange::PreventDefault));
        });
    }
    #[test]
    fn get_ctx_is_none_for_native_rust_callbacks() {
        with_env(|env| {
            assert_eq!(env.timer_info().get_ctx(), OptionRefAny::None);
        });
    }
    #[test]
    fn get_ctx_hands_back_the_ffi_callable() {
        let ctx = RefAny::new(0xDEAD_BEEF_u32);
        with_env_cfg(false, OptionRefAny::Some(ctx.clone()), |env| {
            let got = env
                .timer_info()
                .get_ctx()
                .into_option()
                .expect("ctx must survive");
            assert_eq!(got, ctx, "get_ctx must hand back the same RefAny");
        });
    }
    // ==================================================================
    // Delegated mutators — every one must land in the transaction log
    // ==================================================================
    #[test]
    fn add_and_remove_timer_push_the_matching_changes() {
        let _g = clock_guard();
        with_env(|env| {
            let mut info = env.timer_info();
            let id = TimerId { id: usize::MAX };
            info.add_timer(id, timer_at(1, recording_cb as TimerCallbackType));
            let CallbackChange::AddTimer { timer_id, timer } = env.take_one() else {
                panic!("expected AddTimer");
            };
            assert_eq!(timer_id, id);
            assert_eq!(
                tick_of(&timer.created),
                1,
                "the timer must be stored verbatim"
            );
            info.remove_timer(TimerId { id: 0 });
            let CallbackChange::RemoveTimer { timer_id } = env.take_one() else {
                panic!("expected RemoveTimer");
            };
            assert_eq!(
                timer_id.id, 0,
                "id 0 (a reserved system id) is still accepted"
            );
        });
    }
    #[test]
    fn add_and_remove_thread_push_the_matching_changes() {
        extern "C" fn noop_worker(_d: RefAny, _s: ThreadSender, _r: ThreadReceiver) {}
        with_env(|env| {
            let mut info = env.timer_info();
            let id = ThreadId::unique();
            let thread = Thread::create(
                RefAny::new(0_usize),
                RefAny::new(0_usize),
                noop_worker as ThreadCallbackType,
            );
            info.add_thread(id, thread);
            let CallbackChange::AddThread { thread_id, .. } = env.take_one() else {
                panic!("expected AddThread");
            };
            assert_eq!(thread_id, id);
            info.remove_thread(id);
            let CallbackChange::RemoveThread { thread_id } = env.take_one() else {
                panic!("expected RemoveThread");
            };
            assert_eq!(thread_id, id);
        });
    }
    #[test]
    fn nullary_mutators_push_exactly_one_change_each_in_order() {
        with_env(|env| {
            let mut info = env.timer_info();
            info.stop_propagation();
            info.prevent_default();
            info.close_window();
            info.hide_tooltip();
            info.reload_system_fonts();
            info.update_all_image_callbacks();
            info.reset_cursor_blink();
            info.set_cursor_visibility_toggle();
            let changes = env.take_changes();
            assert_eq!(
                changes.len(),
                8,
                "one change per call, no drops: {changes:?}"
            );
            assert!(matches!(changes[0], CallbackChange::StopPropagation));
            assert!(matches!(changes[1], CallbackChange::PreventDefault));
            assert!(matches!(changes[2], CallbackChange::CloseWindow));
            assert!(matches!(changes[3], CallbackChange::HideTooltip));
            assert!(matches!(changes[4], CallbackChange::ReloadSystemFonts));
            assert!(matches!(
                changes[5],
                CallbackChange::UpdateAllImageCallbacks
            ));
            assert!(matches!(changes[6], CallbackChange::ResetCursorBlink));
            assert!(matches!(changes[7], CallbackChange::ToggleCursorVisibility));
        });
    }
    #[test]
    fn set_cursor_visibility_records_both_polarities() {
        with_env(|env| {
            let mut info = env.timer_info();
            info.set_cursor_visibility(true);
            info.set_cursor_visibility(false);
            let changes = env.take_changes();
            assert_eq!(changes.len(), 2);
            let visibilities: Vec<bool> = changes
                .iter()
                .map(|c| match c {
                    CallbackChange::SetCursorVisibility { visible } => *visible,
                    other => panic!("expected SetCursorVisibility, got {other:?}"),
                })
                .collect();
            assert_eq!(visibilities, vec![true, false]);
        });
    }
    #[test]
    fn create_window_and_modify_window_state_push_changes() {
        with_env(|env| {
            let mut info = env.timer_info();
            info.create_window(WindowCreateOptions::default());
            assert!(matches!(
                env.take_one(),
                CallbackChange::CreateNewWindow { .. }
            ));
            info.modify_window_state(FullWindowState::default());
            assert!(matches!(
                env.take_one(),
                CallbackChange::ModifyWindowState { .. }
            ));
        });
    }
    #[test]
    fn image_cache_mutators_accept_degenerate_and_unicode_ids() {
        with_env(|env| {
            let mut info = env.timer_info();
            // A 0x0 null image with an empty tag is degenerate but legal.
            let img = ImageRef::null_image(0, 0, RawImageFormat::RGBA8, Vec::new());
            let id: AzString = String::new().into();
            info.add_image_to_cache(id.clone(), img);
            let CallbackChange::AddImageToCache { id: got, .. } = env.take_one() else {
                panic!("expected AddImageToCache");
            };
            assert_eq!(got, id, "an empty id is passed through, not rejected");
            // Embedded NUL, an RTL override and astral-plane chars must survive
            // the AzString round-trip byte-for-byte.
            let nasty: AzString = String::from("🚀\u{0}\u{202E}id\u{1F600}").into();
            info.remove_image_from_cache(nasty.clone());
            let CallbackChange::RemoveImageFromCache { id: got } = env.take_one() else {
                panic!("expected RemoveImageFromCache");
            };
            assert_eq!(got.as_str(), nasty.as_str());
        });
    }
    #[test]
    fn trigger_virtual_view_rerender_accepts_out_of_range_ids() {
        with_env(|env| {
            let mut info = env.timer_info();
            info.trigger_virtual_view_rerender(
                DomId { inner: usize::MAX },
                NodeId::new(usize::MAX),
            );
            let CallbackChange::UpdateVirtualView { dom_id, node_id } = env.take_one() else {
                panic!("expected UpdateVirtualView");
            };
            // Recorded verbatim — validation happens when the change is applied,
            // not here, and neither id may overflow on the way in.
            assert_eq!(dom_id.inner, usize::MAX);
            assert_eq!(node_id, NodeId::new(usize::MAX));
        });
    }
    #[test]
    fn open_menu_has_no_position_and_open_menu_at_carries_one() {
        with_env(|env| {
            let mut info = env.timer_info();
            info.open_menu(empty_menu());
            let CallbackChange::OpenMenu { position, .. } = env.take_one() else {
                panic!("expected OpenMenu");
            };
            assert!(position.is_none(), "open_menu must defer to menu.position");
            info.open_menu_at(empty_menu(), LogicalPosition::new(-1.5, 2.5));
            let CallbackChange::OpenMenu { position, .. } = env.take_one() else {
                panic!("expected OpenMenu");
            };
            let p = position.expect("open_menu_at must pin a position");
            assert_eq!((p.x, p.y), (-1.5, 2.5), "negative coordinates are legal");
        });
    }
    #[test]
    fn open_menu_at_passes_non_finite_coordinates_through_unchanged() {
        with_env(|env| {
            let mut info = env.timer_info();
            info.open_menu_at(empty_menu(), LogicalPosition::new(f32::NAN, f32::INFINITY));
            let CallbackChange::OpenMenu { position, .. } = env.take_one() else {
                panic!("expected OpenMenu");
            };
            let p = position.expect("position must be recorded");
            // No clamping/sanitising at this layer — but it must not panic either.
            assert!(p.x.is_nan());
            assert!(p.y.is_infinite() && p.y.is_sign_positive());
            info.open_menu_at(empty_menu(), LogicalPosition::new(f32::MAX, f32::MIN));
            let CallbackChange::OpenMenu { position, .. } = env.take_one() else {
                panic!("expected OpenMenu");
            };
            let p = position.expect("position must be recorded");
            assert_eq!((p.x, p.y), (f32::MAX, f32::MIN));
        });
    }
    #[test]
    fn open_menu_for_hit_node_is_false_and_silent_without_a_hit_node() {
        with_env(|env| {
            let mut info = env.timer_info();
            // Hit node is NONE and the window has no layout results: the menu has
            // nothing to anchor to.
            assert!(!info.open_menu_for_hit_node(empty_menu()));
            assert!(
                env.take_changes().is_empty(),
                "a failed anchor must not queue a half-open menu"
            );
        });
    }
    #[test]
    fn show_tooltip_falls_back_to_the_origin_without_a_cursor() {
        with_env(|env| {
            let mut info = env.timer_info();
            info.show_tooltip(String::from("hi").into());
            let CallbackChange::ShowTooltip { text, position } = env.take_one() else {
                panic!("expected ShowTooltip");
            };
            assert_eq!(text.as_str(), "hi");
            assert_eq!((position.x, position.y), (0.0, 0.0), "no cursor -> origin");
        });
    }
    #[test]
    fn show_tooltip_uses_the_viewport_cursor_when_there_is_one() {
        with_env(|env| {
            let cursor = LogicalPosition::new(3.0, 4.0);
            let mut info = TimerCallbackInfo::create(
                env.info_with(
                    OptionLogicalPosition::None,
                    OptionLogicalPosition::Some(cursor),
                ),
                OptionDomNodeId::None,
                tick(0),
                0,
                false,
            );
            info.show_tooltip(String::from("t").into());
            let CallbackChange::ShowTooltip { position, .. } = env.take_one() else {
                panic!("expected ShowTooltip");
            };
            assert_eq!((position.x, position.y), (3.0, 4.0));
        });
    }
    #[test]
    fn show_tooltip_at_records_empty_text_and_non_finite_positions() {
        with_env(|env| {
            let mut info = env.timer_info();
            info.show_tooltip_at(String::new().into(), LogicalPosition::new(f32::NAN, -0.0));
            let CallbackChange::ShowTooltip { text, position } = env.take_one() else {
                panic!("expected ShowTooltip");
            };
            assert_eq!(text.as_str(), "", "empty tooltip text is not rejected");
            assert!(position.x.is_nan());
            assert!(position.y.is_sign_negative());
        });
    }
    // ==================================================================
    // Scroll delegation — numeric edges
    // ==================================================================
    #[test]
    fn scroll_to_and_unclamped_differ_only_in_the_clamp_flag() {
        with_env(|env| {
            let mut info = env.timer_info();
            let node = NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(0)));
            let pos = LogicalPosition::new(10.0, 20.0);
            info.scroll_to(DomId::ROOT_ID, node, pos);
            info.scroll_to_unclamped(DomId::ROOT_ID, node, pos);
            let changes = env.take_changes();
            assert_eq!(changes.len(), 2);
            let flags: Vec<bool> = changes
                .iter()
                .map(|c| match c {
                    CallbackChange::ScrollTo {
                        dom_id,
                        node_id,
                        position,
                        unclamped,
                    } => {
                        assert_eq!(*dom_id, DomId::ROOT_ID);
                        assert_eq!(*node_id, node);
                        assert_eq!((position.x, position.y), (10.0, 20.0));
                        *unclamped
                    }
                    other => panic!("expected ScrollTo, got {other:?}"),
                })
                .collect();
            assert_eq!(flags, vec![false, true], "only the overscroll flag differs");
        });
    }
    #[test]
    fn scroll_to_records_zero_negative_and_non_finite_positions() {
        with_env(|env| {
            let mut info = env.timer_info();
            let node = NodeHierarchyItemId::NONE;
            for pos in [
                LogicalPosition::new(0.0, 0.0),
                LogicalPosition::new(-1.0, -f32::MAX),
                LogicalPosition::new(f32::MAX, f32::INFINITY),
            ] {
                info.scroll_to(DomId::ROOT_ID, node, pos);
                let CallbackChange::ScrollTo { position, .. } = env.take_one() else {
                    panic!("expected ScrollTo");
                };
                assert_eq!(
                    position.x.to_bits(),
                    pos.x.to_bits(),
                    "x must be recorded bit-exact"
                );
                assert_eq!(
                    position.y.to_bits(),
                    pos.y.to_bits(),
                    "y must be recorded bit-exact"
                );
            }
            // NaN separately — it is never == to itself.
            info.scroll_to_unclamped(
                DomId { inner: usize::MAX },
                node,
                LogicalPosition::new(f32::NAN, f32::NAN),
            );
            let CallbackChange::ScrollTo {
                position,
                unclamped,
                ..
            } = env.take_one()
            else {
                panic!("expected ScrollTo");
            };
            assert!(
                position.x.is_nan() && position.y.is_nan(),
                "NaN is passed through, not zeroed"
            );
            assert!(unclamped);
        });
    }
    #[test]
    fn scroll_queries_are_none_on_an_empty_window() {
        with_env(|env| {
            let info = env.timer_info();
            assert!(info
                .get_scroll_node_info(DomId::ROOT_ID, NodeId::new(0))
                .is_none());
            assert!(
                info.get_scroll_node_info(DomId { inner: usize::MAX }, NodeId::new(usize::MAX))
                    .is_none(),
                "an out-of-range dom/node must return None, not panic"
            );
            assert!(info
                .find_scroll_parent(DomId::ROOT_ID, NodeId::new(0))
                .is_none());
            assert!(info
                .find_scroll_parent(DomId { inner: usize::MAX }, NodeId::new(usize::MAX))
                .is_none());
        });
    }
    #[test]
    fn scroll_input_queue_starts_empty_and_draining_is_idempotent() {
        with_env(|env| {
            let info = env.timer_info();
            let queue = info.get_scroll_input_queue();
            assert!(queue.take_all().is_empty());
            assert!(
                queue.take_all().is_empty(),
                "draining twice must stay empty"
            );
        });
    }
    // ==================================================================
    // Predicates / state getters
    // ==================================================================
    #[test]
    fn the_three_drag_predicates_are_aliases_of_left_down() {
        for left_down in [false, true] {
            with_env_cfg(left_down, OptionRefAny::None, |env| {
                let info = env.timer_info();
                assert_eq!(info.get_current_mouse_state().left_down, left_down);
                assert_eq!(info.is_dragging(), left_down);
                assert_eq!(info.is_drag_active(), left_down);
                assert_eq!(info.is_node_drag_active(), left_down);
            });
        }
    }
    #[test]
    fn pen_predicates_are_false_without_a_pen() {
        with_env(|env| {
            let info = env.timer_info();
            assert!(!info.is_pen_in_contact());
            assert!(!info.is_pen_eraser());
            assert!(!info.is_pen_barrel_button_pressed());
        });
    }
    #[test]
    fn drag_and_gesture_predicates_are_false_on_a_fresh_window() {
        with_env(|env| {
            let info = env.timer_info();
            assert!(!info.is_file_drag_active());
            assert!(!info.has_sufficient_history_for_gestures());
        });
    }
    #[test]
    fn is_dom_focused_is_false_for_every_dom_when_nothing_is_focused() {
        with_env(|env| {
            let info = env.timer_info();
            assert!(!info.is_dom_focused(DomId::ROOT_ID));
            assert!(!info.is_dom_focused(DomId { inner: usize::MAX }));
        });
    }
    #[test]
    fn window_state_getters_mirror_the_current_window_state() {
        with_env(|env| {
            let info = env.timer_info();
            let default_state = FullWindowState::default();
            assert_eq!(info.get_current_window_flags(), default_state.flags);
            assert_eq!(
                info.get_current_keyboard_state(),
                default_state.keyboard_state
            );
            assert_eq!(info.get_current_mouse_state(), default_state.mouse_state);
        });
    }
    #[test]
    fn cursor_getters_round_trip_including_nan() {
        with_env(|env| {
            let info = env.timer_info();
            assert!(info.get_cursor_position().is_none());
            assert_eq!(
                info.get_cursor_relative_to_viewport(),
                OptionLogicalPosition::None
            );
            assert!(info.get_cursor_relative_to_node().is_none());
            let viewport = LogicalPosition::new(f32::NAN, 7.5);
            let relative = LogicalPosition::new(-3.0, f32::INFINITY);
            let info = TimerCallbackInfo::create(
                env.info_with(
                    OptionLogicalPosition::Some(relative),
                    OptionLogicalPosition::Some(viewport),
                ),
                OptionDomNodeId::None,
                tick(0),
                0,
                false,
            );
            let got = info.get_cursor_position().expect("cursor must be Some");
            assert!(got.x.is_nan() && got.y == 7.5);
            let node_rel = info
                .get_cursor_relative_to_node()
                .into_option()
                .expect("relative cursor must be Some");
            assert_eq!(node_rel.x, -3.0);
            assert!(node_rel.y.is_infinite());
        });
    }
    // ==================================================================
    // Timer::invoke — the scheduling state machine
    // ==================================================================
    #[test]
    fn invoke_does_not_run_the_callback_before_the_delay_elapses() {
        let _g = clock_guard();
        with_env(|env| {
            let mut t = timer_at(0, recording_cb as TimerCallbackType).with_delay(tick_dur(100));
            let info = env.info();
            set_now(99);
            let r = t.invoke(&info, &fake_clock_cb());
            assert_eq!(
                CB_INVOCATIONS.load(Ordering::SeqCst),
                0,
                "callback must not fire early"
            );
            assert_eq!(r.should_update, Update::DoNothing);
            assert_eq!(r.should_terminate, TerminateTimer::Continue);
            // A skipped tick must leave the timer's progress untouched.
            assert_eq!(t.run_count, 0);
            assert_eq!(t.last_run, OptionInstant::None);
            // The boundary is inclusive: elapsed == delay runs.
            set_now(100);
            let r = t.invoke(&info, &fake_clock_cb());
            assert_eq!(CB_INVOCATIONS.load(Ordering::SeqCst), 1);
            assert_eq!(r.should_terminate, TerminateTimer::Continue);
            assert_eq!(t.run_count, 1);
            assert_eq!(t.last_run, OptionInstant::Some(tick(100)));
        });
    }
    #[test]
    fn invoke_gates_subsequent_runs_on_the_interval() {
        let _g = clock_guard();
        with_env(|env| {
            let mut t = timer_at(0, recording_cb as TimerCallbackType).with_interval(tick_dur(10));
            let info = env.info();
            // No delay -> the first invoke runs immediately.
            let r = t.invoke(&info, &fake_clock_cb());
            assert_eq!(CB_INVOCATIONS.load(Ordering::SeqCst), 1);
            assert_eq!(r.should_terminate, TerminateTimer::Continue);
            assert_eq!(t.run_count, 1);
            set_now(9);
            let r = t.invoke(&info, &fake_clock_cb());
            assert_eq!(
                CB_INVOCATIONS.load(Ordering::SeqCst),
                1,
                "1 tick short of the interval"
            );
            assert_eq!(r.should_update, Update::DoNothing);
            assert_eq!(t.run_count, 1, "a skipped tick must not count as a run");
            set_now(10);
            let _ = t.invoke(&info, &fake_clock_cb());
            assert_eq!(CB_INVOCATIONS.load(Ordering::SeqCst), 2);
            assert_eq!(t.run_count, 2);
            assert_eq!(t.last_run, OptionInstant::Some(tick(10)));
        });
    }
    /// A LATE fire must not push the whole schedule later.
    ///
    /// `last_run` used to be stamped with the arrival time, so a periodic timer
    /// that was delivered late never recovered its phase: every late tick moved
    /// the next deadline out by the same lateness, and the period drifted. It
    /// now records the DEADLINE THAT WAS MET, so the schedule self-corrects.
    #[test]
    fn invoke_keeps_its_phase_when_a_fire_arrives_late() {
        let _g = clock_guard();
        with_env(|env| {
            let mut t = timer_at(0, recording_cb as TimerCallbackType).with_interval(tick_dur(10));
            let info = env.info();
            // First run establishes the schedule at t=0.
            let _ = t.invoke(&info, &fake_clock_cb());
            assert_eq!(t.last_run, OptionInstant::Some(tick(0)));
            // The 10-tick deadline is delivered 3 ticks LATE.
            set_now(13);
            let _ = t.invoke(&info, &fake_clock_cb());
            assert_eq!(CB_INVOCATIONS.load(Ordering::SeqCst), 2);
            assert_eq!(
                t.last_run,
                OptionInstant::Some(tick(10)),
                "the met DEADLINE is recorded, not the arrival time",
            );
            // Because the phase was kept, the next deadline is 20 — not 23.
            set_now(20);
            let _ = t.invoke(&info, &fake_clock_cb());
            assert_eq!(
                CB_INVOCATIONS.load(Ordering::SeqCst),
                3,
                "the schedule self-corrects instead of drifting by the lateness",
            );
        });
    }
    /// …but a timer that has fallen MORE than one interval behind resynchronises.
    ///
    /// Accumulating from a long-stale deadline (a suspended app, a debugger
    /// breakpoint) would demand a burst of catch-up fires to work off the debt.
    #[test]
    fn invoke_resynchronises_after_falling_far_behind() {
        let _g = clock_guard();
        with_env(|env| {
            let mut t = timer_at(0, recording_cb as TimerCallbackType).with_interval(tick_dur(10));
            let info = env.info();
            let _ = t.invoke(&info, &fake_clock_cb());
            // Five intervals of nothing.
            set_now(50);
            let _ = t.invoke(&info, &fake_clock_cb());
            assert_eq!(
                t.last_run,
                OptionInstant::Some(tick(50)),
                "a long stall resyncs to now rather than queueing catch-up fires",
            );
        });
    }
    #[test]
    fn invoke_hands_the_callback_the_run_count_and_frame_start() {
        let _g = clock_guard();
        with_env(|env| {
            let mut t = timer_at(0, recording_cb as TimerCallbackType);
            let info = env.info();
            set_now(5);
            let _ = t.invoke(&info, &fake_clock_cb());
            assert_eq!(
                CB_SEEN_CALL_COUNT.load(Ordering::SeqCst),
                0,
                "first run is call 0"
            );
            assert_eq!(
                CB_SEEN_FRAME_START.load(Ordering::SeqCst),
                5,
                "frame_start == now"
            );
            assert!(!CB_SEEN_ABOUT_TO_FINISH.load(Ordering::SeqCst));
            set_now(6);
            let _ = t.invoke(&info, &fake_clock_cb());
            assert_eq!(
                CB_SEEN_CALL_COUNT.load(Ordering::SeqCst),
                1,
                "run_count increments by 1"
            );
            assert_eq!(CB_SEEN_FRAME_START.load(Ordering::SeqCst), 6);
        });
    }
    #[test]
    fn invoke_forces_terminate_once_the_timeout_expires() {
        let _g = clock_guard();
        with_env(|env| {
            let mut t = timer_at(0, recording_cb as TimerCallbackType).with_timeout(tick_dur(5));
            let info = env.info();
            // The callback insists on Continue...
            CB_RETURN_TERMINATE.store(false, Ordering::SeqCst);
            set_now(5);
            let r = t.invoke(&info, &fake_clock_cb());
            assert_eq!(
                r.should_terminate,
                TerminateTimer::Continue,
                "elapsed == timeout: alive"
            );
            assert!(!CB_SEEN_ABOUT_TO_FINISH.load(Ordering::SeqCst));
            set_now(6);
            let r = t.invoke(&info, &fake_clock_cb());
            // ...but the timeout overrides it, and the callback is told so.
            assert!(
                CB_SEEN_ABOUT_TO_FINISH.load(Ordering::SeqCst),
                "last-call flag must be set"
            );
            assert_eq!(r.should_terminate, TerminateTimer::Terminate);
            assert_eq!(
                CB_INVOCATIONS.load(Ordering::SeqCst),
                2,
                "the final run still happens"
            );
        });
    }
    #[test]
    fn invoke_honours_a_callback_requested_terminate() {
        let _g = clock_guard();
        with_env(|env| {
            let mut t = timer_at(0, recording_cb as TimerCallbackType);
            let info = env.info();
            CB_RETURN_TERMINATE.store(true, Ordering::SeqCst);
            let r = t.invoke(&info, &fake_clock_cb());
            assert_eq!(r.should_terminate, TerminateTimer::Terminate);
            // Termination is the caller's job; invoke still records the run.
            assert_eq!(t.run_count, 1);
            assert_eq!(t.last_run, OptionInstant::Some(tick(0)));
        });
    }
    #[test]
    fn invoke_skips_deterministically_when_the_clock_runs_backwards() {
        let _g = clock_guard();
        with_env(|env| {
            let mut t = timer_at(0, recording_cb as TimerCallbackType).with_interval(tick_dur(10));
            t.last_run = OptionInstant::Some(tick(1_000));
            let info = env.info();
            // now(0) is *older* than last_run(1000): duration_since saturates to 0,
            // 0 < 10, so the tick is skipped — no panic, no spurious run.
            set_now(0);
            let r = t.invoke(&info, &fake_clock_cb());
            assert_eq!(CB_INVOCATIONS.load(Ordering::SeqCst), 0);
            assert_eq!(r.should_terminate, TerminateTimer::Continue);
            assert_eq!(t.run_count, 0);
            assert_eq!(
                t.last_run,
                OptionInstant::Some(tick(1_000)),
                "last_run is untouched"
            );
        });
    }
    /// A wall-clock interval on a tick-driven clock must THROTTLE, at the exact
    /// frame the interval converts to.
    ///
    /// It used to run on every single invoke: the Tick-vs-System comparison
    /// saturated to `false`, so the "not yet" branch was never taken and the
    /// interval was silently a no-op. A 60-second timer fired at 60Hz.
    #[test]
    fn invoke_throttles_a_wall_clock_interval_on_a_tick_clock_at_the_exact_frame() {
        let _g = clock_guard();
        with_env(|env| {
            // 60_000ms is exactly 3600 frames at 60Hz.
            let mut t = timer_at(0, recording_cb as TimerCallbackType)
                .with_interval(sys_dur_millis(60_000));
            let info = env.info();
            // First invoke has no `last_run`, so only the (absent) delay gates it.
            let _ = t.invoke(&info, &fake_clock_cb());
            assert_eq!(CB_INVOCATIONS.load(Ordering::SeqCst), 1);
            set_now(1);
            let _ = t.invoke(&info, &fake_clock_cb());
            assert_eq!(
                CB_INVOCATIONS.load(Ordering::SeqCst),
                1,
                "a 60s interval must not fire one frame later"
            );
            // One frame BEFORE the interval: still nothing.
            set_now(3_599);
            let _ = t.invoke(&info, &fake_clock_cb());
            assert_eq!(
                CB_INVOCATIONS.load(Ordering::SeqCst),
                1,
                "frame 3599 is early"
            );
            // Exactly at the interval: fires, because the gate is `elapsed < interval`.
            set_now(3_600);
            let _ = t.invoke(&info, &fake_clock_cb());
            assert_eq!(
                CB_INVOCATIONS.load(Ordering::SeqCst),
                2,
                "frame 3600 is the flip"
            );
            assert_eq!(t.run_count, 2);
        });
    }
    // ==================================================================
    // The `t` (tick) unit, end to end through Timer::invoke
    //
    // These are the tests the CSS `t` unit exists for: advance the clock by an
    // EXACT number of frames and assert the callback fired on that frame and no
    // other. Nothing here can be perturbed by how fast the machine is.
    // ==================================================================
    /// A tick interval on a tick clock fires on exactly the Nth frame — not N-1,
    /// not N+1. This is the off-by-one detector: with a millisecond interval the
    /// boundary frame is whatever rounding produced, and a one-frame error hides
    /// inside the jitter.
    #[test]
    fn invoke_with_a_tick_interval_fires_on_exactly_the_nth_frame() {
        let _g = clock_guard();
        with_env(|env| {
            let mut t = timer_at(0, recording_cb as TimerCallbackType).with_interval(tick_dur(5));
            let info = env.info();
            // Frame 0: first run (no last_run, no delay).
            let _ = t.invoke(&info, &fake_clock_cb());
            assert_eq!(CB_INVOCATIONS.load(Ordering::SeqCst), 1);
            assert_eq!(t.last_run, OptionInstant::Some(tick(0)));
            // Frames 1..=4 are all early. Stepping one frame at a time is the
            // point: a boundary that is off by one shows up as a count mismatch
            // on a specific frame, not as a flaky total.
            for frame in 1..=4 {
                set_now(frame);
                let _ = t.invoke(&info, &fake_clock_cb());
                assert_eq!(
                    CB_INVOCATIONS.load(Ordering::SeqCst),
                    1,
                    "frame {frame} is inside the 5-frame interval and must not fire"
                );
            }
            // Frame 5 is the flip.
            set_now(5);
            let _ = t.invoke(&info, &fake_clock_cb());
            assert_eq!(
                CB_INVOCATIONS.load(Ordering::SeqCst),
                2,
                "frame 5 must fire"
            );
            assert_eq!(CB_SEEN_FRAME_START.load(Ordering::SeqCst), 5);
            assert_eq!(t.last_run, OptionInstant::Some(tick(5)));
            // ...and frame 6 is early again for the NEXT interval.
            set_now(6);
            let _ = t.invoke(&info, &fake_clock_cb());
            assert_eq!(
                CB_INVOCATIONS.load(Ordering::SeqCst),
                2,
                "frame 6 restarts the wait"
            );
            set_now(10);
            let _ = t.invoke(&info, &fake_clock_cb());
            assert_eq!(
                CB_INVOCATIONS.load(Ordering::SeqCst),
                3,
                "frame 10 is the second flip"
            );
        });
    }
    /// A `1t` interval fires on every single frame and never skips one — the
    /// degenerate case the unit has to get right for per-frame animation.
    #[test]
    fn a_one_tick_interval_fires_on_every_frame() {
        let _g = clock_guard();
        with_env(|env| {
            let mut t = timer_at(0, recording_cb as TimerCallbackType).with_interval(tick_dur(1));
            let info = env.info();
            for frame in 0..=10 {
                set_now(frame);
                let _ = t.invoke(&info, &fake_clock_cb());
                assert_eq!(
                    CB_INVOCATIONS.load(Ordering::SeqCst),
                    (frame + 1) as usize,
                    "every frame up to {frame} must have fired exactly once"
                );
            }
        });
    }
    /// A tick DELAY gates the first run on exactly the Nth frame, the same way a
    /// tick interval gates the rest.
    #[test]
    fn a_tick_delay_gates_the_first_run_on_exactly_the_nth_frame() {
        let _g = clock_guard();
        with_env(|env| {
            let mut t = timer_at(0, recording_cb as TimerCallbackType).with_delay(tick_dur(3));
            let info = env.info();
            for frame in 0..=2 {
                set_now(frame);
                let _ = t.invoke(&info, &fake_clock_cb());
                assert_eq!(
                    CB_INVOCATIONS.load(Ordering::SeqCst),
                    0,
                    "frame {frame} is inside the 3-frame delay"
                );
            }
            set_now(3);
            let _ = t.invoke(&info, &fake_clock_cb());
            assert_eq!(
                CB_INVOCATIONS.load(Ordering::SeqCst),
                1,
                "frame 3 is the first run"
            );
        });
    }
    /// A tick interval on a WALL-CLOCK timer converts, so a `5t` CSS interval
    /// behaves on a desktop shell exactly as it does on a tick clock: 5 frames is
    /// 83.33ms, so 83ms is early and 84ms fires.
    ///
    /// This is the direction that used to be broken the OTHER way round — the
    /// mismatched comparison never took the "not yet" branch, so a `5t` interval
    /// on a real shell fired on every wake of the platform loop.
    ///
    /// Driven by the injectable clock (frozen, then advanced by an exact number
    /// of milliseconds), so it is a wall-clock path with no wall-clock jitter.
    #[cfg(feature = "std")]
    #[test]
    fn a_tick_interval_throttles_a_wall_clock_timer_at_the_converted_boundary() {
        use azul_core::task::{
            advance_test_clock_ms, freeze_test_clock, get_system_time_libstd, reset_test_clock,
        };
        let _g = clock_guard();
        reset_test_clock();
        freeze_test_clock();
        let real_clock = GetSystemTimeCallback {
            cb: get_system_time_libstd,
        };
        with_env(|env| {
            let mut t = Timer::create(
                RefAny::new(0_usize),
                recording_cb as TimerCallbackType,
                real_clock,
            )
            .with_interval(tick_dur(5));
            let info = env.info();
            // The first invoke has no `last_run`, so only the (absent) delay
            // gates it: it runs at +0ms and arms the interval.
            let _ = t.invoke(&info, &real_clock);
            assert_eq!(CB_INVOCATIONS.load(Ordering::SeqCst), 1);
            assert!(
                matches!(t.last_run, OptionInstant::Some(Instant::System(_))),
                "this timer must really be running on the wall clock"
            );
            // 5 frames is 83.333ms, so 83ms is still inside the interval.
            let _ = advance_test_clock_ms(83);
            let _ = t.invoke(&info, &real_clock);
            assert_eq!(
                CB_INVOCATIONS.load(Ordering::SeqCst),
                1,
                "83ms is less than 5 frames (83.33ms) and must not fire"
            );
            // ...and one more millisecond is past it.
            let _ = advance_test_clock_ms(1);
            let _ = t.invoke(&info, &real_clock);
            assert_eq!(
                CB_INVOCATIONS.load(Ordering::SeqCst),
                2,
                "84ms is past 5 frames and must fire"
            );
        });
        reset_test_clock();
    }
    #[test]
    fn invoke_at_the_end_of_time_does_not_panic() {
        let _g = clock_guard();
        with_env(|env| {
            let mut t = timer_at(u64::MAX, recording_cb as TimerCallbackType)
                .with_delay(tick_dur(u64::MAX))
                .with_interval(tick_dur(u64::MAX))
                .with_timeout(tick_dur(u64::MAX));
            let info = env.info();
            set_now(u64::MAX);
            // elapsed = 0, delay = MAX -> 0 < MAX -> skipped, no overflow anywhere.
            let r = t.invoke(&info, &fake_clock_cb());
            assert_eq!(CB_INVOCATIONS.load(Ordering::SeqCst), 0);
            assert_eq!(r.should_terminate, TerminateTimer::Continue);
            assert_eq!(t.run_count, 0);
        });
    }
}