1
//! Timer and thread management for asynchronous operations.
2
//!
3
//! This module provides:
4
//! - `TimerId` / `ThreadId`: Unique identifiers for timers and background threads
5
//! - `Instant` / `Duration`: Cross-platform time types (works on no_std with tick counters)
6
//! - `ThreadReceiver`: Channel for receiving messages from the main thread
7
//! - Callback types for thread communication and system time queries
8

            
9
#[cfg(not(feature = "std"))]
10
use alloc::string::{String, ToString};
11
use alloc::{
12
    boxed::Box,
13
    collections::btree_map::BTreeMap,
14
    sync::{Arc, Weak},
15
    vec::Vec,
16
};
17
use core::{
18
    ffi::c_void,
19
    fmt,
20
    mem::ManuallyDrop,
21
    sync::atomic::{AtomicU64, AtomicUsize, Ordering},
22
};
23
#[cfg(feature = "std")]
24
use std::sync::mpsc::{Receiver, Sender};
25
#[cfg(feature = "std")]
26
use std::sync::Mutex;
27
#[cfg(feature = "std")]
28
use std::thread::{self, JoinHandle};
29
#[cfg(feature = "std")]
30
use std::time::Duration as StdDuration;
31
#[cfg(feature = "std")]
32
use std::time::Instant as StdInstant;
33

            
34
use azul_css::{props::property::CssProperty, AzString};
35
use rust_fontconfig::FcFontCache;
36

            
37
use crate::{
38
    callbacks::{FocusTarget, TimerCallbackReturn, Update},
39
    dom::{DomId, DomNodeId, OptionDomNodeId},
40
    geom::{LogicalPosition, OptionLogicalPosition},
41
    gl::OptionGlContextPtr,
42
    hit_test::ScrollPosition,
43
    id::NodeId,
44
    refany::{OptionRefAny, RefAny},
45
    resources::{ImageCache, ImageMask, ImageRef},
46
    styled_dom::NodeHierarchyItemId,
47
    window::RawWindowHandle,
48
    FastBTreeSet, OrderedMap,
49
};
50

            
51
/// Should a timer terminate or not - used to remove active timers
52
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
53
#[repr(C)]
54
pub enum TerminateTimer {
55
    /// Remove the timer from the list of active timers
56
    Terminate,
57
    /// Do nothing and let the timers continue to run
58
    Continue,
59
}
60

            
61
// ============================================================================
62
// Reserved System Timer IDs (0x0000 - 0x00FF)
63
// ============================================================================
64
// User timers start at 0x0100 to avoid conflicts with system timers.
65
// These constants define well-known timer IDs for internal framework use.
66

            
67
/// Timer ID for cursor blinking in contenteditable elements (~530ms interval)
68
pub const CURSOR_BLINK_TIMER_ID: TimerId = TimerId { id: 0x0001 };
69
/// Timer ID for scroll momentum/inertia animation
70
pub const SCROLL_MOMENTUM_TIMER_ID: TimerId = TimerId { id: 0x0002 };
71
/// Timer ID for auto-scroll during drag operations near edges
72
pub const DRAG_AUTOSCROLL_TIMER_ID: TimerId = TimerId { id: 0x0003 };
73
/// Timer ID for tooltip show delay.
74
///
75
/// Started by the platform event loop when the hover target changes to a node
76
/// that advertises a tooltip source (`aria-label` / `alt` / `title`); fires
77
/// once after `SystemStyle::input_metrics.hover_time_ms` (`SPI_GETMOUSEHOVERTIME`
78
/// on Windows, default 400ms) and emits a `ShowTooltip` `CallbackChange`. The
79
/// timer is torn down on hover loss, which also emits `HideTooltip`.
80
///
81
/// Double-click detection used to live on a neighbouring reserved ID but is
82
/// now handled entirely by `GestureManager::detect_double_click`, so no
83
/// equivalent `DOUBLE_CLICK_TIMER_ID` exists.
84
pub const TOOLTIP_DELAY_TIMER_ID: TimerId = TimerId { id: 0x0004 };
85
/// Timer ID for the single-threaded capability pump (MWA-A1).
86
///
87
/// Armed by `sync_capability_pump_timer` whenever a capability source needs
88
/// polling or draining while the app is otherwise idle (gamepad listeners,
89
/// sensor listeners, an active geolocation subscription). Each tick wakes the
90
/// blocked platform loop; `invoke_expired_timers` then runs an event pass,
91
/// whose top-of-pass pump drains the async capability channels. There is NO
92
/// pump thread by design — a recurring shell timer is the only wake
93
/// mechanism, so the identical code path works on WASM (no threads).
94
pub const CAPABILITY_PUMP_TIMER_ID: TimerId = TimerId { id: 0x0005 };
95
/// Timer ID for the one-shot long-press wake-up (MWA-B12).
96
///
97
/// Armed on every `MouseDown` for the long-press threshold: a motionless
98
/// press generates no further events, so no pass would ever evaluate
99
/// `detect_long_press` — this timer wakes the loop exactly once at the
100
/// threshold, `invoke_expired_timers` runs an event pass, and the
101
/// detection fires (or doesn't — moved/released holds are no-ops).
102
pub const LONG_PRESS_TIMER_ID: TimerId = TimerId { id: 0x0006 };
103

            
104
/// Reserved timer ID for the caret / selection tween driver (~16ms).
105
///
106
/// Armed by the shared event dispatcher whenever a text tween is in flight; the
107
/// callback terminates itself the tick after the tween state goes idle.
108
pub const CARET_TWEEN_TIMER_ID: TimerId = TimerId { id: 0x0007 };
109

            
110
/// Reserved timer ID for the CSS animation frame driver (~16ms).
111
///
112
/// Armed by the shared event dispatcher whenever a CSS transition or keyframe
113
/// track is in flight (`LayoutWindow::needs_animation_frame`). Its callback is
114
/// an inert marker: when it expires, the dispatcher advances the animations by
115
/// the wall clock and schedules the frame, then disarms it once nothing moves.
116
/// The `WebRender` frame path ticks on its own; the CPU-rendered shells had no
117
/// driver at all, so a declared `animation` never ran there.
118
pub const CSS_ANIMATION_TIMER_ID: TimerId = TimerId { id: 0x0008 };
119

            
120
/// First available ID for user-defined timers
121
pub const USER_TIMER_ID_START: usize = 0x0100;
122

            
123
// User timers start at 0x0100 to avoid conflicts with reserved system timer IDs
124
static MAX_TIMER_ID: AtomicUsize = AtomicUsize::new(USER_TIMER_ID_START);
125

            
126
/// ID for uniquely identifying a timer
127
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
128
#[repr(C)]
129
pub struct TimerId {
130
    pub id: usize,
131
}
132

            
133
impl TimerId {
134
    /// Generates a new, unique `TimerId`.
135
    #[must_use]
136
536
    pub fn unique() -> Self {
137
536
        Self {
138
536
            id: MAX_TIMER_ID.fetch_add(1, Ordering::SeqCst),
139
536
        }
140
536
    }
141
}
142

            
143
impl_option!(
144
    TimerId,
145
    OptionTimerId,
146
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
147
);
148

            
149
impl_vec!(
150
    TimerId,
151
    TimerIdVec,
152
    TimerIdVecDestructor,
153
    TimerIdVecDestructorType,
154
    TimerIdVecSlice,
155
    OptionTimerId
156
);
157
impl_vec_debug!(TimerId, TimerIdVec);
158
impl_vec_clone!(TimerId, TimerIdVec, TimerIdVecDestructor);
159
impl_vec_partialeq!(TimerId, TimerIdVec);
160
impl_vec_partialord!(TimerId, TimerIdVec);
161

            
162
// Thread IDs 0-4 are reserved for internal framework use.
163
// User threads start at RESERVED_THREAD_ID_COUNT.
164
const RESERVED_THREAD_ID_COUNT: usize = 5;
165
static MAX_THREAD_ID: AtomicUsize = AtomicUsize::new(RESERVED_THREAD_ID_COUNT);
166

            
167
/// ID for uniquely identifying a background thread
168
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
169
#[repr(C)]
170
pub struct ThreadId {
171
    id: usize,
172
}
173

            
174
impl_option!(
175
    ThreadId,
176
    OptionThreadId,
177
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
178
);
179

            
180
impl_vec!(
181
    ThreadId,
182
    ThreadIdVec,
183
    ThreadIdVecDestructor,
184
    ThreadIdVecDestructorType,
185
    ThreadIdVecSlice,
186
    OptionThreadId
187
);
188
impl_vec_debug!(ThreadId, ThreadIdVec);
189
impl_vec_clone!(ThreadId, ThreadIdVec, ThreadIdVecDestructor);
190
impl_vec_partialeq!(ThreadId, ThreadIdVec);
191
impl_vec_partialord!(ThreadId, ThreadIdVec);
192

            
193
impl ThreadId {
194
    /// Generates a new, unique `ThreadId`.
195
    #[must_use]
196
1009
    pub fn unique() -> Self {
197
1009
        Self {
198
1009
            id: MAX_THREAD_ID.fetch_add(1, Ordering::SeqCst),
199
1009
        }
200
1009
    }
201
}
202

            
203
// Request ids start at 1: 0 is `RequestId::invalid()`, the never-matching
204
// sentinel an app can store before it has issued anything.
205
static NEXT_REQUEST_ID: AtomicU64 = AtomicU64::new(1);
206

            
207
/// Identifies one in-flight request created by a resumable API function.
208
///
209
/// Every request function (`FileDialog::open_file`, `FilePath::read_bytes`,
210
/// `HttpRequestConfig::http_get`, ...) returns one of these immediately and
211
/// resumes the caller later through its `ResumeCallback`. The id is a `u64`
212
/// on every target - it crosses to JavaScript as a `BigInt`, where a 32-bit
213
/// `usize` would not round-trip - and it is process-unique, never reused.
214
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
215
#[repr(C)]
216
pub struct RequestId {
217
    pub id: u64,
218
}
219

            
220
impl RequestId {
221
    /// A `RequestId` that never matches a real request - use it to initialise
222
    /// state before the first request has been issued.
223
    #[must_use]
224
1
    pub const fn invalid() -> Self {
225
1
        Self { id: 0 }
226
1
    }
227

            
228
    /// `true` for every id minted by [`RequestId::unique`], `false` only for
229
    /// [`RequestId::invalid`].
230
    #[must_use]
231
3
    pub const fn is_valid(&self) -> bool {
232
3
        self.id != 0
233
3
    }
234

            
235
    /// Mints the next process-unique id.
236
    #[must_use]
237
55
    pub fn unique() -> Self {
238
55
        Self {
239
55
            id: NEXT_REQUEST_ID.fetch_add(1, Ordering::SeqCst),
240
55
        }
241
55
    }
242
}
243

            
244
impl Default for RequestId {
245
    fn default() -> Self {
246
        Self::invalid()
247
    }
248
}
249

            
250
/// A point in time, either from the system clock or a tick counter.
251
///
252
/// Use `Instant::System` on platforms with std, `Instant::Tick` on `embedded/no_std`.
253
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
254
#[repr(C, u8)]
255
pub enum Instant {
256
    /// System time from `std::time::Instant` (requires "std" feature)
257
    System(InstantPtr),
258
    /// Tick-based time for embedded systems without a real-time clock
259
    Tick(SystemTick),
260
}
261

            
262
#[cfg(feature = "std")]
263
impl From<StdInstant> for Instant {
264
166781
    fn from(s: StdInstant) -> Self {
265
166781
        Self::System(s.into())
266
166781
    }
267
}
268

            
269
#[cfg(feature = "std")]
270
std::thread_local! {
271
    /// Injectable test-clock offset, in milliseconds, added to every
272
    /// `Instant::now()` **on this thread**.
273
    ///
274
    /// Driven by the E2E `tick_ms` op. Everything time-driven in the engine —
275
    /// scroll momentum, scrollbar fade, cursor blink, animations, timers —
276
    /// reads the clock through `Instant::now()` / `get_system_time_libstd()`,
277
    /// so advancing this offset moves all of them forward by exactly N ms
278
    /// WITHOUT sleeping. That is what makes "drive the animation to completion
279
    /// and assert it converges" deterministic instead of a `wait { ms }` race.
280
    ///
281
    /// Zero in production; only the debug-server `tick_ms` op ever writes it.
282
    ///
283
    /// # Why this is a thread-local and not a `static AtomicU64`
284
    ///
285
    /// It used to be process-global, which made the clock a shared mutable
286
    /// resource: every scenario that ticked had to run SERIALLY, or scenario
287
    /// A's `tick_ms` would shift scenario B's animations mid-frame. Since the
288
    /// corpus is dominated by idle/animation scenarios, that serialised
289
    /// essentially the whole suite.
290
    ///
291
    /// The read path is [`GetSystemTimeCallbackType`] — a bare
292
    /// `extern "C" fn() -> Instant` in the public C API — plus ~140 direct
293
    /// `Instant::now()` calls. Neither can carry a window, an app or a clock
294
    /// handle without either breaking the C ABI for every language binding or
295
    /// threading a time source through every call site including `no_std`
296
    /// ones. A thread-local is the narrowest scope a context-free C callback
297
    /// can read: it turns "the whole process" into "the thread that owns this
298
    /// scenario", which is exactly the ownership boundary the parallel E2E
299
    /// runner already establishes (one scenario runs start-to-finish on one
300
    /// worker thread). [`reset_test_clock`] makes that boundary explicit.
301
    static TEST_CLOCK_OFFSET_MS: core::cell::Cell<u64> = const { core::cell::Cell::new(0) };
302
}
303

            
304
/// Advance the injectable test clock by `ms` (E2E `tick_ms`), returning the new
305
/// offset. Affects only the CURRENT thread — see [`TEST_CLOCK_OFFSET_MS`].
306
#[cfg(feature = "std")]
307
#[must_use]
308
27286
pub fn advance_test_clock_ms(ms: u64) -> u64 {
309
27286
    TEST_CLOCK_OFFSET_MS.with(|c| {
310
27286
        let next = c.get().saturating_add(ms);
311
27286
        c.set(next);
312
27286
        next
313
27286
    })
314
27286
}
315

            
316
/// The current test-clock offset in ms (0 unless `tick_ms` was used on this
317
/// thread).
318
#[cfg(feature = "std")]
319
#[must_use]
320
135597
pub fn test_clock_offset_ms() -> u64 {
321
135597
    TEST_CLOCK_OFFSET_MS.with(core::cell::Cell::get)
322
135597
}
323

            
324
#[cfg(feature = "std")]
325
#[cfg(all(feature = "std", not(target_arch = "wasm32")))]
326
std::thread_local! {
327
    /// When set, this thread's clock is FROZEN at this instant: `Instant::now()`
328
    /// answers `base + TEST_CLOCK_OFFSET_MS` and real time does not flow into it
329
    /// at all. See [`freeze_test_clock`].
330
    static TEST_CLOCK_BASE: core::cell::Cell<Option<StdInstant>> =
331
        const { core::cell::Cell::new(None) };
332
}
333

            
334
/// Freeze this thread's clock, so engine time advances ONLY when a scenario says
335
/// it does (`tick_ms` / `wait`) and never because wall time passed.
336
///
337
/// Offsetting alone is not enough. `Instant::now()` was
338
/// `StdInstant::now() + offset`, so the REAL component still flowed and every
339
/// time-driven behaviour rode on however long the machine happened to take:
340
/// elapsed = (exact virtual) + (whatever this build, under this load, spent
341
/// computing). The E2E suite runs 8 scenarios per core, so that second term is
342
/// both large and variable, and an assertion on a blinking caret's phase would
343
/// flip between runs on a loaded runner while passing every time in isolation.
344
///
345
/// Frozen, engine time becomes a pure function of the ops a scenario executed —
346
/// identical on a debug build, a release build and a saturated CI box. That is
347
/// also what makes an off-by-one in animation timing *observable*: advance
348
/// exactly one interval and the frame either flipped or it did not, with no
349
/// jitter to hide behind.
350
///
351
/// This deliberately does NOT touch [`Instant::Tick`]. Interval constants are
352
/// built as `Duration::System` (e.g. the cursor blink in `text_edit`), and
353
/// `Duration::greater_than` compares only matching variants — handing the engine
354
/// `Tick` elapsed values against `System` intervals would mismatch and silently
355
/// answer "not yet" forever. Freezing keeps every existing comparison intact.
356
///
357
/// Idempotent: re-freezing an already-frozen clock keeps the original base, so
358
/// the offset stays the single source of elapsed time.
359
#[cfg(all(feature = "std", not(target_arch = "wasm32")))]
360
27020
pub fn freeze_test_clock() {
361
27020
    TEST_CLOCK_BASE.with(|c| {
362
27020
        if c.get().is_none() {
363
583
            c.set(Some(StdInstant::now()));
364
26503
        }
365
27020
    });
366
27020
}
367

            
368
/// Whether this thread's clock is frozen (see [`freeze_test_clock`]).
369
#[cfg(all(feature = "std", not(target_arch = "wasm32")))]
370
#[must_use]
371
3
pub fn test_clock_is_frozen() -> bool {
372
3
    TEST_CLOCK_BASE.with(core::cell::Cell::get).is_some()
373
3
}
374

            
375
/// Put this thread's test clock back on real time.
376
///
377
/// Worker threads are REUSED across scenarios, so without this the next
378
/// scenario scheduled onto this thread would inherit the previous one's
379
/// accumulated offset — the same cross-contamination the process-global
380
/// offset had, just at thread granularity. The E2E runner calls this at the
381
/// start of every scenario. Clears the freeze as well, so a scenario cannot
382
/// leave the next one's clock stopped.
383
#[cfg(all(feature = "std", not(target_arch = "wasm32")))]
384
118
pub fn reset_test_clock() {
385
118
    TEST_CLOCK_OFFSET_MS.with(|c| c.set(0));
386
118
    TEST_CLOCK_BASE.with(|c| c.set(None));
387
118
}
388

            
389
/// Monotonic frame counter, and the ONLY clock a wasm build has.
390
///
391
/// `std::time::Instant::now()` PANICS on wasm32-unknown-unknown, and
392
/// `#[cfg(feature = "std")]` does not exclude wasm here: azul-core is built with
393
/// `default = ["std"]` for the web target, so every `std` path is compiled in.
394
///
395
/// Answering `Tick(0)` forever would stop the panic and freeze every animation
396
/// instead — a silent stall, which is worse than a loud crash. So the web build
397
/// gets a real monotonic source: the browser drives redraw, each produced DOM
398
/// patch is one frame, and one frame is exactly what a `t` (tick) duration
399
/// counts. `AzStartup_buildPatch` calls [`advance_system_tick`] once per patch.
400
#[cfg(feature = "std")]
401
static SYSTEM_TICK: AtomicU64 = AtomicU64::new(0);
402

            
403
/// Advance the frame counter by one. Called once per produced frame by backends
404
/// that have no wall clock. Cheap enough to call unconditionally.
405
#[cfg(feature = "std")]
406
pub fn advance_system_tick() {
407
    SYSTEM_TICK.fetch_add(1, Ordering::Relaxed);
408
}
409

            
410
/// The current frame counter.
411
#[cfg(feature = "std")]
412
#[must_use]
413
pub fn system_tick_now() -> u64 {
414
    SYSTEM_TICK.load(Ordering::Relaxed)
415
}
416

            
417
/// `std::time::Instant::now()` shifted by the injectable test-clock offset, or —
418
/// when the clock is frozen — built from the frozen base so real time cannot
419
/// leak in.
420
///
421
/// NOT COMPILED on wasm32, where `std::time::Instant::now()` panics.
422
///
423
/// `web_lift` is deliberately NOT included here. That backend compiles natively
424
/// and is lifted to wasm afterwards, so `target_arch` reads `x86_64` — but the
425
/// lift walks the LLVM graph and auto-inserts calls out to JS for things like
426
/// time, so it supplies its own clock and does not want this arm disabled.
427
#[cfg(all(feature = "std", not(target_arch = "wasm32")))]
428
135568
fn std_now_with_test_offset() -> StdInstant {
429
135568
    let offset = test_clock_offset_ms();
430
135568
    if let Some(base) = TEST_CLOCK_BASE.with(core::cell::Cell::get) {
431
54514
        return base + core::time::Duration::from_millis(offset);
432
81054
    }
433
81054
    if offset == 0 {
434
81054
        StdInstant::now()
435
    } else {
436
        StdInstant::now() + core::time::Duration::from_millis(offset)
437
    }
438
135568
}
439

            
440
impl Instant {
441
    /// Returns the current system time.
442
    ///
443
    /// On systems with std, this uses `std::time::Instant::now()`.
444
    /// On `no_std` systems, this returns a zero tick.
445
    #[cfg(all(feature = "std", not(target_arch = "wasm32")))]
446
    #[must_use]
447
72649
    pub fn now() -> Self {
448
72649
        std_now_with_test_offset().into()
449
72649
    }
450

            
451
    /// Returns the current time on wasm32, which has no clock to read.
452
    ///
453
    /// `std::time::Instant::now()` panics on wasm32-unknown-unknown, and
454
    /// `#[cfg(feature = "std")]` does not exclude wasm here — azul-core is built
455
    /// with `default = ["std"]` for the web target, so the std path is compiled
456
    /// in and would trap on the first frame.
457
    ///
458
    /// This deliberately does NOT answer a constant `Tick(0)`. That stops the
459
    /// panic and freezes every animation instead, which is a silent stall — the
460
    /// worse failure of the two. The browser drives redraw and each produced DOM
461
    /// patch is one frame, so the frame counter IS the clock, and a frame is
462
    /// exactly what a `t` (tick) duration counts. Elapsed values come out as
463
    /// `Tick` and convert against `System` intervals through
464
    /// `Duration::as_nanos`, so `60t` compares equal to one second.
465
    #[cfg(all(feature = "std", target_arch = "wasm32"))]
466
    #[must_use]
467
    pub fn now() -> Self {
468
        Instant::Tick(SystemTick::new(system_tick_now()))
469
    }
470

            
471
    /// Returns the current system time (no_std fallback).
472
    #[cfg(not(feature = "std"))]
473
    pub fn now() -> Self {
474
        Instant::Tick(SystemTick::new(0))
475
    }
476

            
477
    /// Returns a number from 0.0 to 1.0 indicating the current
478
    /// linear interpolation value between (start, end)
479
    #[must_use]
480
16
    pub fn linear_interpolate(&self, mut start: Self, mut end: Self) -> f32 {
481
        use core::mem;
482

            
483
16
        if end < start {
484
2
            mem::swap(&mut start, &mut end);
485
14
        }
486

            
487
16
        if *self < start {
488
2
            return 0.0;
489
14
        }
490
14
        if *self > end {
491
3
            return 1.0;
492
11
        }
493

            
494
        // Zero-length interval: `duration_current / duration_total` would be
495
        // `0/0 = NaN`. Treat a collapsed interval as fully elapsed (1.0) rather
496
        // than propagating NaN into animation progress.
497
11
        if start == end {
498
3
            return 1.0;
499
8
        }
500

            
501
8
        let duration_total = end.duration_since(&start);
502
8
        let duration_current = self.duration_since(&start);
503

            
504
8
        let ratio = duration_current.div(&duration_total);
505
8
        if ratio.is_nan() {
506
2
            return 1.0;
507
6
        }
508
6
        ratio.clamp(0.0, 1.0)
509
16
    }
510

            
511
    /// Adds a duration to the instant.
512
    ///
513
    /// The duration's UNIT need not match the instant's: a `Tick` duration added
514
    /// to a `System` instant is converted at [`TICKS_PER_SECOND`], and a `System`
515
    /// duration added to a `Tick` instant is converted to whole ticks.
516
    ///
517
    /// # Why the mismatch is converted rather than dropped
518
    ///
519
    /// This used to return `self` unchanged for a unit mismatch, which turned a
520
    /// `Duration::Tick` interval on a wall-clock timer into a schedule point of
521
    /// `last_run + 0` — `Timer::instant_of_next_run` is literally
522
    /// `last_run + delay + interval`, so the timer reported itself permanently
523
    /// overdue and `LayoutWindow::time_until_next_timer_ms` answered `Some(0)`
524
    /// for it, i.e. "block for zero milliseconds" to any loop that consults it.
525
    ///
526
    /// `System + System` still overflow-panics on an absurd duration (that is
527
    /// `StdInstant`'s own behaviour, characterised in the tests); the tick arms
528
    /// saturate.
529
    #[must_use]
530
6931
    pub fn add_optional_duration(&self, duration: Option<&Duration>) -> Self {
531
6931
        duration.map_or_else(
532
290
            || self.clone(),
533
6641
            |d| match (self, d) {
534
6163
                (Self::System(i), Duration::System(d)) => {
535
                    #[cfg(feature = "std")]
536
                    {
537
6163
                        let s: StdInstant = i.clone().into();
538
6163
                        let d: StdDuration = (*d).into();
539
6163
                        let new: InstantPtr = (s + d).into();
540
6163
                        Self::System(new)
541
                    }
542
                    #[cfg(not(feature = "std"))]
543
                    {
544
                        // A `System` instant cannot be constructed on no_std, so
545
                        // this arm is unreachable in practice; return self rather
546
                        // than aborting.
547
                        let _ = (i, d);
548
                        self.clone()
549
                    }
550
                }
551
412
                (Self::Tick(s), Duration::Tick(d)) => Self::Tick(SystemTick {
552
412
                    // Saturate so a runaway tick delta cannot overflow-panic.
553
412
                    tick_counter: s.tick_counter.saturating_add(d.tick_diff),
554
412
                }),
555
                // System instant + Tick duration: convert the frame count to wall
556
                // time. Routed through the same `System + System` arm so the
557
                // overflow behaviour is identical for both units.
558
14
                (Self::System(_), Duration::Tick(_)) => self.add_optional_duration(Some(
559
14
                    &Duration::System(SystemTimeDiff::from_nanos_u128(d.as_nanos())),
560
14
                )),
561
                // Tick instant + System duration: convert to WHOLE ticks. A
562
                // sub-frame duration therefore advances nothing, which is the
563
                // truthful answer on a clock whose resolution is one frame.
564
52
                (Self::Tick(s), Duration::System(_)) => Self::Tick(SystemTick {
565
52
                    tick_counter: s.tick_counter.saturating_add(d.as_ticks()),
566
52
                }),
567
6641
            },
568
        )
569
6931
    }
570

            
571
    /// Converts to `std::time::Instant` (panics if Tick variant).
572
    #[cfg(feature = "std")]
573
    #[must_use]
574
2
    pub fn into_std_instant(self) -> StdInstant {
575
2
        match self {
576
1
            Self::System(s) => s.into(),
577
1
            Self::Tick(_) => unreachable!(),
578
        }
579
1
    }
580

            
581
    /// Calculates the duration since an earlier point in time.
582
    ///
583
    /// Saturates to a zero duration in the degenerate cases (earlier is actually
584
    /// *later* than `self`, or the two instants are of mismatched kinds) instead
585
    /// of panicking — this runs on the hot event-loop path and must not crash.
586
    #[must_use]
587
51036
    pub fn duration_since(&self, earlier: &Self) -> Duration {
588
51036
        match (earlier, self) {
589
47342
            (Self::System(prev), Self::System(now)) => {
590
                #[cfg(feature = "std")]
591
                {
592
47342
                    let prev_instant: StdInstant = prev.clone().into();
593
47342
                    let now_instant: StdInstant = now.clone().into();
594
                    // `saturating_duration_since` yields 0 if `prev` is later
595
                    // than `now` (monotonic-clock skew / reordered instants).
596
47342
                    Duration::System(now_instant.saturating_duration_since(prev_instant).into())
597
                }
598
                #[cfg(not(feature = "std"))]
599
                {
600
                    // Unreachable on no_std (no System instants); saturate to 0.
601
                    let _ = (prev, now);
602
                    Duration::Tick(SystemTickDiff { tick_diff: 0 })
603
                }
604
            }
605
            (
606
3617
                Self::Tick(SystemTick { tick_counter: prev }),
607
3617
                Self::Tick(SystemTick { tick_counter: now }),
608
3617
            ) => Duration::Tick(SystemTickDiff {
609
3617
                // Saturate: a "negative" span (prev > now) clamps to 0.
610
3617
                tick_diff: now.saturating_sub(*prev),
611
3617
            }),
612
            // Mismatched kinds: no meaningful span -> saturate to 0.
613
77
            _ => Duration::Tick(SystemTickDiff { tick_diff: 0 }),
614
        }
615
51036
    }
616
}
617

            
618
/// Tick-based timestamp for systems without a real-time clock.
619
///
620
/// Used on embedded systems where time is measured in frame ticks or cycles.
621
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
622
#[repr(C)]
623
pub struct SystemTick {
624
    pub tick_counter: u64,
625
}
626

            
627
impl SystemTick {
628
    /// Creates a new tick timestamp from a counter value.
629
    #[must_use]
630
128039
    pub const fn new(tick_counter: u64) -> Self {
631
128039
        Self { tick_counter }
632
128039
    }
633
}
634

            
635
/// FFI-safe wrapper around `std::time::Instant` with custom clone/drop callbacks.
636
///
637
/// Allows crossing FFI boundaries while maintaining proper memory management.
638
#[repr(C)]
639
pub struct InstantPtr {
640
    /// `ManuallyDrop` so the owned `Box` is freed ONLY when `run_destructor` is
641
    /// still set (see `Drop`). The codegen FFI wrappers (`AzTimerCallbackInfo`
642
    /// etc.) embed this by value AND have their own `Drop` that `drop_in_place`s
643
    /// the real type first; Rust's drop glue would then drop this `ptr` field a
644
    /// SECOND time on the same bytes. Gating the `Box` free on `run_destructor`
645
    /// (cleared by the first drop) makes that second drop a safe no-op. Layout is
646
    /// unchanged: `ManuallyDrop<Box<T>>` is one pointer, like the old `Box<T>`.
647
    #[cfg(feature = "std")]
648
    pub ptr: ManuallyDrop<Box<StdInstant>>,
649
    #[cfg(not(feature = "std"))]
650
    pub ptr: *const c_void,
651
    pub clone_fn: InstantPtrCloneCallback,
652
    pub destructor: InstantPtrDestructorCallback,
653
    pub run_destructor: bool,
654
}
655

            
656
pub type InstantPtrCloneCallbackType = extern "C" fn(*const InstantPtr) -> InstantPtr;
657
#[repr(C)]
658
pub struct InstantPtrCloneCallback {
659
    pub cb: InstantPtrCloneCallbackType,
660
}
661
impl_callback_simple!(InstantPtrCloneCallback);
662

            
663
pub type InstantPtrDestructorCallbackType = extern "C" fn(*mut InstantPtr);
664
#[repr(C)]
665
pub struct InstantPtrDestructorCallback {
666
    pub cb: InstantPtrDestructorCallbackType,
667
}
668
impl_callback_simple!(InstantPtrDestructorCallback);
669

            
670
// ----  LIBSTD implementation for InstantPtr BEGIN
671
#[cfg(feature = "std")]
672
impl fmt::Debug for InstantPtr {
673
1
    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
674
1
        write!(f, "{:?}", self.get())
675
1
    }
676
}
677

            
678
#[cfg(not(feature = "std"))]
679
impl core::fmt::Debug for InstantPtr {
680
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
681
        write!(f, "{:?}", self.ptr as usize)
682
    }
683
}
684

            
685
#[cfg(feature = "std")]
686
impl core::hash::Hash for InstantPtr {
687
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
688
        self.get().hash(state);
689
    }
690
}
691

            
692
#[cfg(not(feature = "std"))]
693
impl core::hash::Hash for InstantPtr {
694
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
695
        (self.ptr as usize).hash(state);
696
    }
697
}
698

            
699
#[cfg(feature = "std")]
700
impl PartialEq for InstantPtr {
701
38
    fn eq(&self, other: &Self) -> bool {
702
38
        self.get() == other.get()
703
38
    }
704
}
705

            
706
#[cfg(not(feature = "std"))]
707
impl PartialEq for InstantPtr {
708
    fn eq(&self, other: &InstantPtr) -> bool {
709
        (self.ptr as usize).eq(&(other.ptr as usize))
710
    }
711
}
712

            
713
impl Eq for InstantPtr {}
714

            
715
#[cfg(feature = "std")]
716
impl PartialOrd for InstantPtr {
717
13
    fn partial_cmp(&self, other: &Self) -> Option<::core::cmp::Ordering> {
718
13
        Some((self.get()).cmp(&(other.get())))
719
13
    }
720
}
721

            
722
#[cfg(not(feature = "std"))]
723
impl PartialOrd for InstantPtr {
724
    fn partial_cmp(&self, other: &Self) -> Option<::core::cmp::Ordering> {
725
        Some((self.ptr as usize).cmp(&(other.ptr as usize)))
726
    }
727
}
728

            
729
#[cfg(feature = "std")]
730
impl Ord for InstantPtr {
731
16478
    fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
732
16478
        (self.get()).cmp(&(other.get()))
733
16478
    }
734
}
735

            
736
#[cfg(not(feature = "std"))]
737
impl Ord for InstantPtr {
738
    fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
739
        (self.ptr as usize).cmp(&(other.ptr as usize))
740
    }
741
}
742

            
743
#[cfg(feature = "std")]
744
impl InstantPtr {
745
136910
    fn get(&self) -> StdInstant {
746
136910
        (**self.ptr)
747
136910
    }
748
}
749

            
750
impl Clone for InstantPtr {
751
167618
    fn clone(&self) -> Self {
752
167618
        (self.clone_fn.cb)(self)
753
167618
    }
754
}
755

            
756
#[cfg(feature = "std")]
757
167619
extern "C" fn std_instant_clone(ptr: *const InstantPtr) -> InstantPtr {
758
167619
    let az_instant_ptr = unsafe { &*ptr };
759
167619
    InstantPtr {
760
167619
        ptr: ManuallyDrop::new((*az_instant_ptr.ptr).clone()),
761
167619
        clone_fn: az_instant_ptr.clone_fn,
762
167619
        destructor: az_instant_ptr.destructor,
763
167619
        run_destructor: true,
764
167619
    }
765
167619
}
766

            
767
#[cfg(feature = "std")]
768
impl From<StdInstant> for InstantPtr {
769
172947
    fn from(s: StdInstant) -> Self {
770
172947
        Self {
771
172947
            ptr: ManuallyDrop::new(Box::new(s)),
772
172947
            clone_fn: InstantPtrCloneCallback {
773
172947
                cb: std_instant_clone,
774
172947
            },
775
172947
            destructor: InstantPtrDestructorCallback {
776
172947
                cb: std_instant_drop,
777
172947
            },
778
172947
            run_destructor: true,
779
172947
        }
780
172947
    }
781
}
782

            
783
#[cfg(feature = "std")]
784
impl From<InstantPtr> for StdInstant {
785
100848
    fn from(s: InstantPtr) -> Self {
786
100848
        s.get()
787
100848
    }
788
}
789

            
790
impl Drop for InstantPtr {
791
340566
    fn drop(&mut self) {
792
340566
        if self.run_destructor {
793
340566
            self.run_destructor = false;
794
340566
            (self.destructor.cb)(self);
795
            // Free the owned Box exactly once, here under the run_destructor guard.
796
            // A second drop on the same bytes (the codegen wrapper's field-drop after
797
            // its own `_delete` already ran the real drop) sees run_destructor=false
798
            // and skips this -> no double-free. (non-std `ptr` is a raw POD pointer
799
            // freed by the destructor callback above, so nothing to drop here.)
800
            // SAFETY: `run_destructor` is set false above, so this arm runs at
801
            // most once per InstantPtr value; the `Box` inside was never moved
802
            // out, so it is live and owned here and safe to drop exactly once.
803
            #[cfg(feature = "std")]
804
340566
            unsafe {
805
340566
                ManuallyDrop::drop(&mut self.ptr);
806
340566
            }
807
        }
808
340566
    }
809
}
810

            
811
#[cfg(feature = "std")]
812
340568
const extern "C" fn std_instant_drop(_: *mut InstantPtr) {}
813

            
814
// ----  LIBSTD implementation for InstantPtr END
815

            
816
/// A span of time, either from the system clock or as tick difference.
817
///
818
/// Mirrors `Instant` variants - System durations work with System instants,
819
/// Tick durations work with Tick instants.
820
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
821
#[repr(C, u8)]
822
pub enum Duration {
823
    /// System duration from `std::time::Duration` (requires "std" feature)
824
    System(SystemTimeDiff),
825
    /// Tick-based duration for embedded systems
826
    Tick(SystemTickDiff),
827
}
828

            
829
impl fmt::Display for Duration {
830
8
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
831
8
        match self {
832
            #[cfg(feature = "std")]
833
5
            Self::System(s) => {
834
5
                let s: StdDuration = (*s).into();
835
5
                write!(f, "{s:?}")
836
            }
837
            #[cfg(not(feature = "std"))]
838
            Duration::System(s) => write!(f, "({}s, {}ns)", s.secs, s.nanos),
839
3
            Self::Tick(tick) => write!(f, "{} ticks", tick.tick_diff),
840
        }
841
8
    }
842
}
843

            
844
#[cfg(feature = "std")]
845
impl From<StdDuration> for Duration {
846
12
    fn from(s: StdDuration) -> Self {
847
12
        Self::System(s.into())
848
12
    }
849
}
850

            
851
/// Nominal engine tick (frame) rate — the single exchange rate between
852
/// [`Duration::Tick`] (frames) and [`Duration::System`] (wall time).
853
///
854
/// Re-exported from `azul-css` so the CSS `t` unit and the engine's `Duration`
855
/// arithmetic cannot drift apart. See [`azul_css::props::basic::time::TICKS_PER_SECOND`].
856
pub use azul_css::props::basic::time::TICKS_PER_SECOND;
857

            
858
impl Duration {
859
    /// This duration on ONE canonical scale, in nanoseconds — the common ground
860
    /// on which a `Tick` span and a `System` span can be compared.
861
    ///
862
    /// `u128` because a `System` duration holds up to `u64::MAX` *seconds*
863
    /// (~1.8e28 ns), which does not fit `u64`. The tick conversion multiplies
864
    /// before it divides so whole seconds stay exact: `60t` is `1_000_000_000`ns,
865
    /// not `60 * 16_666_666 = 999_999_960`ns.
866
    ///
867
    /// Note this also normalises a DENORMALISED `SystemTimeDiff` (`nanos` past
868
    /// `1e9`) the same way `std::time::Duration::new` would — except it cannot
869
    /// panic on overflow while doing it.
870
    // `as u128` rather than `u128::from`: this is a `const fn` and `From` is not
871
    // const. Every one of these widenings is lossless.
872
    #[allow(clippy::cast_lossless)]
873
    #[must_use]
874
31474
    pub const fn as_nanos(&self) -> u128 {
875
31474
        match self {
876
29104
            Self::System(s) => (s.secs as u128) * (NANOS_PER_SEC as u128) + (s.nanos as u128),
877
2370
            Self::Tick(t) => {
878
2370
                (t.tick_diff as u128) * (NANOS_PER_SEC as u128) / (TICKS_PER_SECOND as u128)
879
            }
880
        }
881
31474
    }
882

            
883
    /// A wall-clock duration of `ms` whole milliseconds.
884
    #[must_use]
885
49358
    pub const fn from_millis(ms: u64) -> Self {
886
49358
        Self::System(SystemTimeDiff::from_millis(ms))
887
49358
    }
888

            
889
    /// A duration of `ticks` engine frames — the clockless unit, and what the
890
    /// CSS `t` unit becomes.
891
    #[must_use]
892
176
    pub const fn from_ticks(ticks: u64) -> Self {
893
176
        Self::Tick(SystemTickDiff { tick_diff: ticks })
894
176
    }
895

            
896
    /// This duration in whole ticks (frames), truncating toward zero.
897
    ///
898
    /// A sub-frame span is **zero** ticks, not one: "how many whole frames fit",
899
    /// never "round up so that something happens".
900
    // `as` casts: `const fn`, so `From`/`TryFrom` are unavailable. The widenings
901
    // are lossless and the u128 -> u64 narrowing is range-checked immediately
902
    // above it.
903
    #[allow(clippy::cast_lossless, clippy::cast_possible_truncation)]
904
    #[must_use]
905
52
    pub const fn as_ticks(&self) -> u64 {
906
52
        match self {
907
            Self::Tick(t) => t.tick_diff,
908
            Self::System(_) => {
909
52
                let ticks = self.as_nanos() * (TICKS_PER_SECOND as u128) / (NANOS_PER_SEC as u128);
910
52
                if ticks > u64::MAX as u128 {
911
1
                    u64::MAX
912
                } else {
913
51
                    ticks as u64
914
                }
915
            }
916
        }
917
52
    }
918

            
919
    /// This duration in whole milliseconds, truncating toward zero and
920
    /// saturating at `u64::MAX` rather than wrapping.
921
    // `as` casts: `const fn`, so `From`/`TryFrom` are unavailable. The u128 ->
922
    // u64 narrowing is range-checked immediately above it.
923
    #[allow(clippy::cast_lossless, clippy::cast_possible_truncation)]
924
    #[must_use]
925
2054
    pub const fn as_millis_u64(&self) -> u64 {
926
2054
        let ms = self.as_nanos() / (NANOS_PER_MILLI as u128);
927
2054
        if ms > u64::MAX as u128 {
928
99
            u64::MAX
929
        } else {
930
1955
            ms as u64
931
        }
932
2054
    }
933

            
934
    /// Returns the maximum possible duration.
935
    #[must_use]
936
18
    pub fn max() -> Self {
937
        #[cfg(feature = "std")]
938
        {
939
18
            Self::System(StdDuration::new(core::u64::MAX, NANOS_PER_SEC - 1).into())
940
        }
941
        #[cfg(not(feature = "std"))]
942
        {
943
            Duration::Tick(SystemTickDiff {
944
                tick_diff: u64::MAX,
945
            })
946
        }
947
18
    }
948

            
949
    /// Divides this duration by another, returning the ratio as f32.
950
    ///
951
    /// Same-unit division goes through the unit's own `div` so its exact
952
    /// floating-point result is unchanged. Cross-unit division falls back to the
953
    /// canonical nanosecond scale rather than returning `0.0` — a `0.0` ratio
954
    /// here means "animation is at 0% progress", which is a frozen animation, not
955
    /// an error anyone would notice.
956
    // the f64 ratio is intentionally narrowed to the f32 return type; the value
957
    // is a duration ratio, far inside f32's range.
958
    #[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
959
    #[must_use]
960
58607
    pub fn div(&self, other: &Self) -> f32 {
961
        use self::Duration::{System, Tick};
962
58607
        match (self, other) {
963
52182
            (System(s), System(s2)) => s.div(s2) as f32,
964
6348
            (Tick(t), Tick(t2)) => t.div(t2) as f32,
965
            // u128 -> f64 loses precision only past 2^53 ns (~104 days), and the
966
            // result is a ratio that is then narrowed to f32 anyway.
967
77
            _ => (self.as_nanos() as f64 / other.as_nanos() as f64) as f32,
968
        }
969
58607
    }
970

            
971
    /// Returns the smaller of two durations.
972
    #[must_use]
973
9
    pub const fn min(self, other: Self) -> Self {
974
9
        if self.smaller_than(&other) {
975
5
            self
976
        } else {
977
4
            other
978
        }
979
9
    }
980

            
981
    /// Returns true if self > other.
982
    ///
983
    /// Compares on the canonical nanosecond scale ([`Self::as_nanos`]), so a
984
    /// `Tick` span and a `System` span compare TRUTHFULLY against each other.
985
    ///
986
    /// # Why this is not "mismatched kinds saturate to false"
987
    ///
988
    /// It used to be. That made a unit mismatch invisible and permanent instead
989
    /// of loud: the engine's interval constants are `Duration::System` (the
990
    /// cursor blink, the scrollbar fade, the tooltip delay), so the moment a
991
    /// clock produced `Tick` elapsed values every one of those comparisons
992
    /// answered "not yet" — forever. Nothing panicked, nothing logged, the UI
993
    /// simply stopped animating. That is precisely the failure a clockless unit
994
    /// is supposed to make *catchable*, so the comparison has to be total.
995
    ///
996
    /// Three behaviours changed, all in the safe direction:
997
    ///
998
    /// 1. Cross-unit comparisons now answer, instead of always `false`.
999
    /// 2. On `no_std` the `System`/`System` arm used to be hardcoded `false` (there was no
    ///    `StdDuration` to defer to); it now compares properly.
    /// 3. A denormalised `SystemTimeDiff` whose `secs + nanos/1e9` overflows `u64` used to panic
    ///    inside `StdDuration::new`; `u128` nanoseconds cannot overflow.
    #[must_use]
472
    pub const fn greater_than(&self, other: &Self) -> bool {
472
        self.as_nanos() > other.as_nanos()
472
    }
    /// Returns true if self < other.
    ///
    /// Canonical-scale comparison; see [`Self::greater_than`] for why this is
    /// unit-aware rather than saturating to `false` on a unit mismatch.
    #[must_use]
518
    pub const fn smaller_than(&self, other: &Self) -> bool {
518
        self.as_nanos() < other.as_nanos()
518
    }
}
/// Represents a difference in ticks for systems that
/// don't support timing
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct SystemTickDiff {
    pub tick_diff: u64,
}
impl SystemTickDiff {
    /// Divide duration A by duration B.
    /// Returns `Inf` or `NaN` if `other` is zero.
    // tick counts -> f64 for the ratio; precision only degrades past 2^53 ticks.
    #[allow(clippy::cast_precision_loss)]
    #[must_use]
6354
    pub fn div(&self, other: &Self) -> f64 {
6354
        self.tick_diff as f64 / other.tick_diff as f64
6354
    }
}
/// Duration represented as seconds + nanoseconds (mirrors `std::time::Duration`).
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct SystemTimeDiff {
    pub secs: u64,
    pub nanos: u32,
}
impl SystemTimeDiff {
    /// Divide duration A by duration B.
    /// Returns `Inf` or `NaN` if `other` is zero.
    #[must_use]
52189
    pub fn div(&self, other: &Self) -> f64 {
52189
        self.as_secs_f64() / other.as_secs_f64()
52189
    }
    // secs (u64) -> f64 loses precision only past 2^53 seconds (~285M years).
    #[allow(clippy::cast_precision_loss)]
104385
    fn as_secs_f64(&self) -> f64 {
104385
        (self.secs as f64) + (f64::from(self.nanos) / f64::from(NANOS_PER_SEC))
104385
    }
}
#[cfg(feature = "std")]
impl From<StdDuration> for SystemTimeDiff {
47412
    fn from(d: StdDuration) -> Self {
47412
        Self {
47412
            secs: d.as_secs(),
47412
            nanos: d.subsec_nanos(),
47412
        }
47412
    }
}
#[cfg(feature = "std")]
impl From<SystemTimeDiff> for StdDuration {
6176
    fn from(d: SystemTimeDiff) -> Self {
6176
        Self::new(d.secs, d.nanos)
6176
    }
}
const MILLIS_PER_SEC: u64 = 1_000;
const NANOS_PER_MILLI: u32 = 1_000_000;
const NANOS_PER_SEC: u32 = 1_000_000_000;
impl SystemTimeDiff {
    /// Creates a duration from whole seconds.
    #[must_use]
12
    pub const fn from_secs(secs: u64) -> Self {
12
        Self { secs, nanos: 0 }
12
    }
    /// Creates a duration from milliseconds.
    #[must_use]
114661
    pub const fn from_millis(millis: u64) -> Self {
114661
        Self {
114661
            secs: millis / MILLIS_PER_SEC,
114661
            nanos: ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI,
114661
        }
114661
    }
    /// Creates a duration from nanoseconds.
    // const fn (no const TryFrom); `nanos % NANOS_PER_SEC` is always < 10^9, which
    // fits u32, so the narrowing cast cannot truncate.
    #[allow(clippy::cast_possible_truncation)]
    #[must_use]
14
    pub const fn from_nanos(nanos: u64) -> Self {
14
        Self {
14
            secs: nanos / (NANOS_PER_SEC as u64),
14
            nanos: (nanos % (NANOS_PER_SEC as u64)) as u32,
14
        }
14
    }
    /// Creates a duration from a `u128` nanosecond count, saturating at the
    /// largest representable duration instead of wrapping.
    ///
    /// Needed because [`Duration::as_nanos`] is `u128`: a tick count near
    /// `u64::MAX` converts to ~3e26 ns, far past what `u64` nanoseconds hold.
    // `nanos % NANOS_PER_SEC` is always < 10^9 and `secs` is range-checked above,
    // so neither narrowing cast can truncate. `as` widenings rather than `From`
    // because this is a `const fn`.
    #[allow(clippy::cast_possible_truncation, clippy::cast_lossless)]
    #[must_use]
14
    pub const fn from_nanos_u128(nanos: u128) -> Self {
14
        let secs = nanos / (NANOS_PER_SEC as u128);
14
        if secs > u64::MAX as u128 {
            Self {
                secs: u64::MAX,
                nanos: NANOS_PER_SEC - 1,
            }
        } else {
14
            Self {
14
                secs: secs as u64,
14
                nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
14
            }
        }
14
    }
    /// Adds two durations, returning None on overflow.
    #[must_use]
21
    pub const fn checked_add(self, rhs: Self) -> Option<Self> {
21
        if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
20
            let mut nanos = self.nanos + rhs.nanos;
20
            if nanos >= NANOS_PER_SEC {
7
                nanos -= NANOS_PER_SEC;
7
                if let Some(new_secs) = secs.checked_add(1) {
6
                    secs = new_secs;
6
                } else {
1
                    return None;
                }
13
            }
19
            Some(Self { secs, nanos })
        } else {
1
            None
        }
21
    }
    /// Returns the total duration in milliseconds.
    ///
    /// Saturates at `u64::MAX` instead of overflow-panicking for enormous
    /// `secs` values (`secs * 1000` overflows around ~1.8e16 seconds).
    #[must_use]
14
    pub const fn millis(&self) -> u64 {
14
        self.secs
14
            .saturating_mul(MILLIS_PER_SEC)
14
            .saturating_add((self.nanos / NANOS_PER_MILLI) as u64)
14
    }
    /// Converts to `std::time::Duration`.
    #[cfg(feature = "std")]
    #[must_use]
8
    pub fn get(&self) -> StdDuration {
8
        (*self).into()
8
    }
}
/// Bridge from the CSS-level duration to the engine-level one, preserving the
/// unit.
///
/// This is the join that makes a CSS `5t` mean five FRAMES all the way down to
/// the timer: `ms`/`s` become `Duration::System`, `t` becomes `Duration::Tick`.
/// Collapsing ticks to milliseconds here would put the wall clock back in the
/// path and make "advance exactly 5 ticks, assert the 5th frame flipped"
/// untestable again.
impl From<azul_css::props::basic::time::CssDuration> for Duration {
44
    fn from(d: azul_css::props::basic::time::CssDuration) -> Self {
        use azul_css::props::basic::time::CssDurationUnit;
44
        match d.unit {
22
            CssDurationUnit::Milliseconds => Self::from_millis(u64::from(d.inner)),
22
            CssDurationUnit::Ticks => Self::from_ticks(u64::from(d.inner)),
        }
44
    }
}
impl_option!(
    Instant,
    OptionInstant,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);
impl_option!(
    Duration,
    OptionDuration,
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);
#[allow(variant_size_differences)]
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
// disparity accepted
/// Message that can be sent from the main thread to the Thread using the `ThreadId`.
///
/// The thread can ignore the event.
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[repr(C, u8)]
pub enum ThreadSendMsg {
    /// The thread should terminate at the nearest
    TerminateThread,
    /// Next frame tick
    Tick,
    /// Custom data
    Custom(RefAny),
}
impl_option!(
    ThreadSendMsg,
    OptionThreadSendMsg,
    copy = false,
    [Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash]
);
/// Channel endpoint for receiving messages from the main thread in a background thread.
///
/// Thread-safe wrapper around the receiver end of a message channel.
#[derive(Debug)]
#[repr(C)]
pub struct ThreadReceiver {
    #[cfg(feature = "std")]
    pub ptr: Box<Arc<Mutex<ThreadReceiverInner>>>,
    #[cfg(not(feature = "std"))]
    pub ptr: *const c_void,
    pub run_destructor: bool,
    /// For FFI: stores the foreign callable (e.g., `PyFunction`)
    pub ctx: OptionRefAny,
}
impl Clone for ThreadReceiver {
1
    fn clone(&self) -> Self {
1
        Self {
1
            ptr: self.ptr.clone(),
1
            run_destructor: true,
1
            ctx: self.ctx.clone(),
1
        }
1
    }
}
impl Drop for ThreadReceiver {
820
    fn drop(&mut self) {
820
        self.run_destructor = false;
820
    }
}
impl ThreadReceiver {
    /// Creates a new receiver (no-op on no_std).
    #[cfg(not(feature = "std"))]
    pub fn new(_t: ThreadReceiverInner) -> Self {
        Self {
            ptr: core::ptr::null(),
            run_destructor: false,
            ctx: OptionRefAny::None,
        }
    }
    /// Creates a new receiver wrapping the inner channel.
    #[cfg(feature = "std")]
    #[must_use]
893
    pub fn new(t: ThreadReceiverInner) -> Self {
893
        Self {
893
            ptr: Box::new(Arc::new(Mutex::new(t))),
893
            run_destructor: true,
893
            ctx: OptionRefAny::None,
893
        }
893
    }
    /// Get the FFI context (e.g., Python callable)
    #[must_use]
4
    pub fn get_ctx(&self) -> OptionRefAny {
4
        self.ctx.clone()
4
    }
    /// Receives a message (returns None on no_std).
    #[cfg(not(feature = "std"))]
    pub fn recv(&mut self) -> OptionThreadSendMsg {
        None.into()
    }
    /// Receives a message from the main thread, if available.
    #[cfg(feature = "std")]
1199
    pub fn recv(&mut self) -> OptionThreadSendMsg {
1199
        let Some(ts) = self.ptr.lock().ok() else {
            return None.into();
        };
1199
        (ts.recv_fn.cb)(std::ptr::from_ref(ts.ptr.as_ref()) as *const c_void)
1199
    }
}
/// Inner receiver state containing the actual channel and callbacks.
#[derive(Debug)]
#[cfg_attr(not(feature = "std"), derive(PartialEq, PartialOrd, Eq, Ord))]
#[repr(C)]
pub struct ThreadReceiverInner {
    #[cfg(feature = "std")]
    pub ptr: Box<Receiver<ThreadSendMsg>>,
    #[cfg(not(feature = "std"))]
    pub ptr: *const c_void,
    pub recv_fn: ThreadRecvCallback,
    pub destructor: ThreadReceiverDestructorCallback,
}
#[cfg(not(feature = "std"))]
unsafe impl Send for ThreadReceiverInner {}
#[cfg(feature = "std")]
impl core::hash::Hash for ThreadReceiverInner {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        (std::ptr::from_ref(self.ptr.as_ref()) as usize).hash(state);
    }
}
#[cfg(feature = "std")]
impl PartialEq for ThreadReceiverInner {
    fn eq(&self, other: &Self) -> bool {
        std::ptr::eq(self.ptr.as_ref(), other.ptr.as_ref())
    }
}
#[cfg(feature = "std")]
impl Eq for ThreadReceiverInner {}
#[cfg(feature = "std")]
impl PartialOrd for ThreadReceiverInner {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(
            (std::ptr::from_ref(self.ptr.as_ref()) as usize)
                .cmp(&(std::ptr::from_ref(other.ptr.as_ref()) as usize)),
        )
    }
}
#[cfg(feature = "std")]
impl Ord for ThreadReceiverInner {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        (std::ptr::from_ref(self.ptr.as_ref()) as usize)
            .cmp(&(std::ptr::from_ref(other.ptr.as_ref()) as usize))
    }
}
impl Drop for ThreadReceiverInner {
893
    fn drop(&mut self) {
893
        (self.destructor.cb)(self);
893
    }
}
/// Get the current system type, equivalent to `std::time::Instant::now()`, except it
/// also works on systems that don't have a clock (such as embedded timers)
pub type GetSystemTimeCallbackType = extern "C" fn() -> Instant;
#[repr(C)]
pub struct GetSystemTimeCallback {
    pub cb: GetSystemTimeCallbackType,
}
impl_callback_simple!(GetSystemTimeCallback);
/// Default implementation that gets the current system time.
///
/// On WASM targets `std::time::Instant::now()` panics, so we fall back to
/// a zero-tick instant instead.
#[cfg(all(feature = "std", not(target_arch = "wasm32")))]
#[must_use]
62919
pub extern "C" fn get_system_time_libstd() -> Instant {
    // Honours the injectable E2E test clock (see TEST_CLOCK_OFFSET_MS).
62919
    std_now_with_test_offset().into()
62919
}
/// Fallback for WASM (where `Instant::now()` panics) and no-std targets.
#[cfg(any(not(feature = "std"), target_arch = "wasm32"))]
pub extern "C" fn get_system_time_libstd() -> Instant {
    Instant::Tick(SystemTick::new(0))
}
/// Callback to check if a thread has finished execution.
pub type CheckThreadFinishedCallbackType =
    extern "C" fn(/* dropcheck */ *const c_void) -> bool;
/// Wrapper for thread completion check callback.
#[repr(C)]
pub struct CheckThreadFinishedCallback {
    pub cb: CheckThreadFinishedCallbackType,
}
impl_callback_simple!(CheckThreadFinishedCallback);
/// Callback to send a message to a background thread.
pub type LibrarySendThreadMsgCallbackType =
    extern "C" fn(/* Sender<ThreadSendMsg> */ *const c_void, ThreadSendMsg) -> bool;
/// Wrapper for thread message send callback.
#[repr(C)]
pub struct LibrarySendThreadMsgCallback {
    pub cb: LibrarySendThreadMsgCallbackType,
}
impl_callback_simple!(LibrarySendThreadMsgCallback);
/// Callback for a running thread to receive messages from the main thread.
pub type ThreadRecvCallbackType =
    extern "C" fn(/* receiver.ptr */ *const c_void) -> OptionThreadSendMsg;
/// Wrapper for thread message receive callback.
#[repr(C)]
pub struct ThreadRecvCallback {
    pub cb: ThreadRecvCallbackType,
}
impl_callback_simple!(ThreadRecvCallback);
/// Callback to destroy a `ThreadReceiver`.
pub type ThreadReceiverDestructorCallbackType = extern "C" fn(*mut ThreadReceiverInner);
/// Wrapper for thread receiver destructor callback.
#[repr(C)]
pub struct ThreadReceiverDestructorCallback {
    pub cb: ThreadReceiverDestructorCallbackType,
}
impl_callback_simple!(ThreadReceiverDestructorCallback);
#[cfg(test)]
#[path = "task_test.rs"]
mod task_test;