1
//! Callback types for the Azul UI framework.
2
//!
3
//! This module defines the callback infrastructure used by the event system,
4
//! layout engine, and virtual view rendering. Key design patterns:
5
//!
6
//! - **Core vs Layout callback split**: `CoreCallbackType` and `CoreRenderImageCallbackType` store
7
//!   function pointers as `usize` to avoid circular dependencies between `azul-core` and
8
//!   `azul-layout`. The actual function pointer types are defined in `azul-layout` and transmuted
9
//!   at invocation time.
10
//!
11
//! - **FFI callable pattern**: Callback structs carry an optional `ctx: OptionRefAny` field that
12
//!   holds a foreign callable (e.g. a Python function object). The `extern "C"` trampoline stored
13
//!   in `cb` extracts both the user data and the foreign callable from `RefAny` and dispatches the
14
//!   call. Native Rust code sets `ctx` to `None`.
15
//!
16
//! - **Info structs**: `LayoutCallbackInfo`, `VirtualViewCallbackInfo`, and the layout-side
17
//!   `CallbackInfo` provide read-only access to framework resources (fonts, images, GL context,
18
//!   window size) during callback invocation.
19

            
20
#[cfg(not(feature = "std"))]
21
use alloc::string::ToString;
22
use alloc::{alloc::Layout, boxed::Box, collections::BTreeMap, sync::Arc, vec::Vec};
23
use core::{
24
    ffi::c_void,
25
    fmt,
26
    sync::atomic::{AtomicUsize, Ordering as AtomicOrdering},
27
};
28
#[cfg(feature = "std")]
29
use std::hash::Hash;
30

            
31
use azul_css::{
32
    css::{CssPath, CssPropertyValue},
33
    props::{
34
        basic::{
35
            AnimationInterpolationFunction, FontRef, InterpolateResolver, LayoutRect, LayoutSize,
36
        },
37
        property::{CssProperty, CssPropertyType},
38
    },
39
    system::SystemStyle,
40
    AzString,
41
};
42
use rust_fontconfig::{FcFontCache, OwnedFontSource};
43

            
44
use crate::{
45
    dom::{Dom, DomId, DomNodeId, EventFilter, OptionDom},
46
    geom::{
47
        LogicalPosition, LogicalRect, LogicalRectVec, LogicalSize, OptionLogicalPosition,
48
        PhysicalSize,
49
    },
50
    gl::OptionGlContextPtr,
51
    hit_test::OverflowingScrollNode,
52
    id::{NodeDataContainer, NodeDataContainerRef, NodeDataContainerRefMut, NodeId},
53
    prop_cache::CssPropertyCache,
54
    refany::{OptionRefAny, RefAny},
55
    resources::{
56
        DpiScaleFactor, FontInstanceKey, IdNamespace, ImageCache, ImageMask, ImageRef,
57
        RendererResources,
58
    },
59
    styled_dom::{NodeHierarchyItemId, NodeHierarchyItemVec, StyledNode, StyledNodeVec},
60
    task::{
61
        Duration as AzDuration, GetSystemTimeCallback, Instant as AzInstant, Instant,
62
        TerminateTimer, ThreadId, ThreadReceiver, ThreadSendMsg, TimerId,
63
    },
64
    window::{
65
        AzStringPair, KeyboardState, MouseState, OptionChar, RawWindowHandle, UpdateFocusWarning,
66
        WindowFlags, WindowFrame, WindowSize, WindowTheme,
67
    },
68
    FastBTreeSet, OrderedMap,
69
};
70

            
71
/// Specifies if the screen should be updated after the callback function has returned
72
#[repr(C)]
73
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
74
pub enum Update {
75
    /// The screen does not need to redraw after the callback has been called
76
    DoNothing,
77
    /// After the callback is called, the screen needs to redraw (`layout()` function being called
78
    /// again)
79
    RefreshDom,
80
    /// The layout has to be re-calculated for all windows
81
    RefreshDomAllWindows,
82
}
83

            
84
impl Update {
85
434
    pub fn max_self(&mut self, other: Self) {
86
434
        if (*self == Self::DoNothing && other != Self::DoNothing)
87
317
            || (*self == Self::RefreshDom && other == Self::RefreshDomAllWindows)
88
130
        {
89
130
            *self = other;
90
304
        }
91
434
    }
92
}
93

            
94
// -- layout callback
95

            
96
/// Callback function pointer (has to be a function pointer in
97
/// order to be compatible with C APIs later on).
98
///
99
/// IMPORTANT: The callback needs to deallocate the `RefAnyPtr` and `LayoutCallbackInfoPtr`,
100
/// otherwise that memory is leaked. If you use the official auto-generated
101
/// bindings, this is already done for you.
102
///
103
/// NOTE: The original callback was `fn(&self, LayoutCallbackInfo) -> Dom`
104
/// which then evolved to `fn(&RefAny, LayoutCallbackInfo) -> Dom`.
105
/// The indirection is necessary because of the memory management
106
/// around the C API
107
///
108
/// The memory management across the callback boundary is handled by
109
/// the caller (see `LayoutCallback` and `LayoutCallbackInfo`).
110
pub type LayoutCallbackType = extern "C" fn(RefAny, LayoutCallbackInfo) -> Dom;
111

            
112
1
extern "C" fn default_layout_callback(_: RefAny, _: LayoutCallbackInfo) -> Dom {
113
1
    Dom::create_body()
114
1
}
115

            
116
/// Wrapper around the layout callback
117
///
118
/// For FFI languages (Python, Java, etc.), the `RefAny` contains both:
119
/// - The user's application data
120
/// - The callback function object from the foreign language
121
///
122
/// The trampoline function (stored in `cb`) knows how to extract both
123
/// from the `RefAny` and invoke the foreign callback with the user data.
124
#[repr(C)]
125
pub struct LayoutCallback {
126
    pub cb: LayoutCallbackType,
127
    /// For FFI: stores the foreign callable (e.g., `PyFunction`)
128
    /// Native Rust code sets this to None
129
    pub ctx: OptionRefAny,
130
}
131

            
132
impl_callback!(LayoutCallback, LayoutCallbackType);
133

            
134
impl LayoutCallback {
135
3
    pub fn create<I: Into<Self>>(cb: I) -> Self {
136
3
        cb.into()
137
3
    }
138
}
139

            
140
// Host-invoker plumbing for managed-FFI bindings (Lua, Ruby, Perl, …):
141
// expands to a static `az_layout_callback_thunk` (the `cb` we hand to the
142
// framework when the host calls `LayoutCallback::create_from_host_handle`),
143
// an `AzLayoutCallback_createFromHostHandle` C-ABI export, plus the
144
// `AzApp_setLayoutCallbackInvoker` setter the host calls once at module
145
// load. See `crate::host_invoker` for the design.
146
crate::impl_managed_callback! {
147
    wrapper:        LayoutCallback,
148
    info_ty:        LayoutCallbackInfo,
149
    return_ty:      Dom,
150
    default_ret:    Dom::create_body(),
151
    invoker_static: LAYOUT_CALLBACK_INVOKER,
152
    invoker_ty:     AzLayoutCallbackInvoker,
153
    thunk_fn:       az_layout_callback_thunk,
154
    setter_fn:      AzApp_setLayoutCallbackInvoker,
155
    from_handle_fn: AzLayoutCallback_createFromHostHandle,
156
}
157

            
158
impl Default for LayoutCallback {
159
109859
    fn default() -> Self {
160
109859
        Self {
161
109859
            cb: default_layout_callback,
162
109859
            ctx: OptionRefAny::None,
163
109859
        }
164
109859
    }
165
}
166

            
167
// -- virtualized view callback
168

            
169
pub type VirtualViewCallbackType =
170
    extern "C" fn(RefAny, VirtualViewCallbackInfo) -> VirtualViewReturn;
171

            
172
/// Callback that, given a rectangle area on the screen, returns the DOM
173
/// appropriate for that bounds (useful for infinite lists)
174
#[repr(C)]
175
pub struct VirtualViewCallback {
176
    pub cb: VirtualViewCallbackType,
177
    /// For FFI: stores the foreign callable (e.g., `PyFunction`)
178
    /// Native Rust code sets this to None
179
    pub ctx: OptionRefAny,
180
}
181
impl_callback!(VirtualViewCallback, VirtualViewCallbackType);
182

            
183
// Host-invoker plumbing for VirtualViewCallback. See `crate::host_invoker`.
184
crate::impl_managed_callback! {
185
    wrapper:        VirtualViewCallback,
186
    info_ty:        VirtualViewCallbackInfo,
187
    return_ty:      VirtualViewReturn,
188
    default_ret:    VirtualViewReturn::default(),
189
    invoker_static: VIRTUAL_VIEW_CALLBACK_INVOKER,
190
    invoker_ty:     AzVirtualViewCallbackInvoker,
191
    thunk_fn:       az_virtual_view_callback_thunk,
192
    setter_fn:      AzApp_setVirtualViewCallbackInvoker,
193
    from_handle_fn: AzVirtualViewCallback_createFromHostHandle,
194
}
195

            
196
impl VirtualViewCallback {
197
1896
    pub fn create(cb: VirtualViewCallbackType) -> Self {
198
1896
        Self {
199
1896
            cb,
200
1896
            ctx: OptionRefAny::None,
201
1896
        }
202
1896
    }
203
}
204

            
205
// -- caret / selection tween callbacks (system text animations)
206
//
207
// The framework animates the caret and the selection highlight between their
208
// previous and current geometry ("tween"). The MATH of the tween is a user-
209
// replaceable C-ABI function set in `AppConfig.system_animations` (defaults
210
// below): the framework drives a short timer, computes the linear progress
211
// `t = elapsed / configured duration`, and calls the function to obtain the
212
// geometry to RENDER this frame. While a tween is in flight the caret blink
213
// is suppressed (the caret stays solid while it moves).
214

            
215
/// Inputs for one caret-tween evaluation.
216
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
217
#[repr(C)]
218
pub struct CaretTweenInfo {
219
    /// Caret rectangle the previous frame RENDERED (mid-flight retargets
220
    /// start from the interpolated position, not the old logical one).
221
    pub past: LogicalRect,
222
    /// Caret rectangle the current layout actually wants.
223
    pub current: LogicalRect,
224
    /// Linear time progress `0.0..=1.0` (elapsed / configured duration).
225
    /// Easing/curves are this function's job.
226
    pub t: f32,
227
}
228

            
229
/// Returns the caret rectangle to render at progress `info.t`.
230
pub type CaretTweenCallbackType = extern "C" fn(RefAny, CaretTweenInfo) -> LogicalRect;
231

            
232
/// User-settable caret tween interpolator (see [`CaretTweenInfo`]).
233
#[repr(C)]
234
pub struct CaretTweenCallback {
235
    pub cb: CaretTweenCallbackType,
236
    /// For FFI: stores the foreign callable (e.g., `PyFunction`)
237
    /// Native Rust code sets this to None
238
    pub ctx: OptionRefAny,
239
}
240
impl_callback!(CaretTweenCallback, CaretTweenCallbackType);
241

            
242
impl CaretTweenCallback {
243
1141
    pub fn create(cb: CaretTweenCallbackType) -> Self {
244
1141
        Self {
245
1141
            cb,
246
1141
            ctx: OptionRefAny::None,
247
1141
        }
248
1141
    }
249
}
250

            
251
/// Inputs for one selection-tween evaluation.
252
///
253
/// Carries the full PAST and CURRENT selection band geometry: all rectangles
254
/// of the selection highlight, in display-list order — spanning multiple
255
/// lines and, for a cross-block selection, multiple nodes.
256
#[derive(Debug, Clone, PartialEq, PartialOrd)]
257
#[repr(C)]
258
pub struct SelectionTweenInfo {
259
    /// Selection rectangles the previous frame RENDERED.
260
    pub past: LogicalRectVec,
261
    /// Selection rectangles the current layout actually wants.
262
    pub current: LogicalRectVec,
263
    /// Linear time progress `0.0..=1.0` (elapsed / configured duration).
264
    pub t: f32,
265
}
266

            
267
/// Returns the selection rectangles to render at progress `info.t`.
268
/// MUST return exactly `info.current.len()` rectangles — a mismatched
269
/// length makes the framework fall back to `info.current` unanimated.
270
pub type SelectionTweenCallbackType = extern "C" fn(RefAny, SelectionTweenInfo) -> LogicalRectVec;
271

            
272
/// User-settable selection tween interpolator (see [`SelectionTweenInfo`]).
273
#[repr(C)]
274
pub struct SelectionTweenCallback {
275
    pub cb: SelectionTweenCallbackType,
276
    /// For FFI: stores the foreign callable (e.g., `PyFunction`)
277
    /// Native Rust code sets this to None
278
    pub ctx: OptionRefAny,
279
}
280
impl_callback!(SelectionTweenCallback, SelectionTweenCallbackType);
281

            
282
impl SelectionTweenCallback {
283
1141
    pub fn create(cb: SelectionTweenCallbackType) -> Self {
284
1141
        Self {
285
1141
            cb,
286
1141
            ctx: OptionRefAny::None,
287
1141
        }
288
1141
    }
289
}
290

            
291
/// Trapezoidal velocity profile: velocity ramps up HARD over the first
292
/// `RAMP` of the duration, cruises at constant speed, and ramps down hard
293
/// over the last `RAMP` — a `/‾‾‾\` velocity curve. In position terms:
294
/// a brief quadratic ease-in, a LINEAR middle, a brief quadratic ease-out.
295
/// Chosen over ease-out-cubic for the caret/selection defaults: at the
296
/// very short default durations the motion should read as "barely
297
/// noticeable glide", not as a spring (user directive). Analytic integral,
298
/// exact — a cubic bezier cannot express the flat-velocity plateau.
299
#[inline]
300
2940
fn trapezoid_ease(t: f32) -> f32 {
301
    const RAMP: f32 = 0.25;
302
    // Peak velocity so the total distance integrates to exactly 1.
303
    const V: f32 = 1.0 / (1.0 - RAMP);
304
2940
    let t = t.clamp(0.0, 1.0);
305
2940
    if t < RAMP {
306
2796
        V * t * t / (2.0 * RAMP)
307
144
    } else if t <= 1.0 - RAMP {
308
108
        V * (RAMP / 2.0 + (t - RAMP))
309
    } else {
310
36
        let inv = 1.0 - t;
311
36
        1.0 - V * inv * inv / (2.0 * RAMP)
312
    }
313
2940
}
314

            
315
#[inline]
316
// Plain `a + (b - a) * e`, NOT mul_add: fused multiply-add changes f32
317
// results, and tween geometry must be bit-reproducible across builds (the
318
// e2e corpus pins pixel-exact frames).
319
#[allow(clippy::suboptimal_flops)]
320
3060
fn lerp_rect(from: LogicalRect, to: LogicalRect, e: f32) -> LogicalRect {
321
3060
    LogicalRect {
322
3060
        origin: LogicalPosition {
323
3060
            x: from.origin.x + (to.origin.x - from.origin.x) * e,
324
3060
            y: from.origin.y + (to.origin.y - from.origin.y) * e,
325
3060
        },
326
3060
        size: LogicalSize {
327
3060
            width: from.size.width + (to.size.width - from.size.width) * e,
328
3060
            height: from.size.height + (to.size.height - from.size.height) * e,
329
3060
        },
330
3060
    }
331
3060
}
332

            
333
/// Default caret tween: trapezoidal-velocity lerp of origin and size
334
/// (hard rise, linear cruise, hard fall — see [`trapezoid_ease`]).
335
#[must_use]
336
2772
pub extern "C" fn default_caret_tween(_data: RefAny, info: CaretTweenInfo) -> LogicalRect {
337
2772
    lerp_rect(info.past, info.current, trapezoid_ease(info.t))
338
2772
}
339

            
340
/// Default selection tween: trapezoidal-velocity lerp, rectangles paired by
341
/// the LINE they sit on — not by their position in the list.
342
///
343
/// Index pairing broke every UPWARD extension: growing the selection upward
344
/// prepends a rect, which shifts every later rect one slot, so each line lerped
345
/// from the geometry of the line ABOVE it and the whole band visibly slid.
346
/// Geometric pairing is stable under insertion at either end.
347
///
348
/// Rectangles with no counterpart on their line (a line the selection did not
349
/// cover before) appear at their final geometry immediately. Each past
350
/// rectangle is consumed at most once, so a line that bidi splits into several
351
/// rectangles still pairs one-to-one.
352
#[must_use]
353
168
pub extern "C" fn default_selection_tween(
354
168
    _data: RefAny,
355
168
    info: SelectionTweenInfo,
356
168
) -> LogicalRectVec {
357
168
    let e = trapezoid_ease(info.t);
358
168
    let past = info.past.as_ref();
359
168
    let mut taken = alloc::vec![false; past.len()];
360
168
    let out: Vec<LogicalRect> = info
361
168
        .current
362
168
        .as_ref()
363
168
        .iter()
364
564
        .map(|cur| {
365
564
            take_same_line_rect(past, &mut taken, *cur).map_or(*cur, |p| lerp_rect(p, *cur, e))
366
564
        })
367
168
        .collect();
368
168
    out.into()
369
168
}
370

            
371
/// The not-yet-consumed `past` rectangle sitting on the same line as `cur` —
372
/// the closest one vertically, ties to the earlier one — marked consumed.
373
/// `None` when no past rectangle shares that line.
374
///
375
/// "Same line" means the vertical CENTRES are within half the shorter
376
/// rectangle's height of each other: a line that shifted by a fraction of its
377
/// own height is still recognised (and glides there), a different line never
378
/// is. The test is a positive comparison, which NaN fails, so garbage geometry
379
/// pops instead of pairing wrongly.
380
564
fn take_same_line_rect(
381
564
    past: &[LogicalRect],
382
564
    taken: &mut [bool],
383
564
    cur: LogicalRect,
384
564
) -> Option<LogicalRect> {
385
564
    let cur_centre = cur.origin.y + cur.size.height / 2.0;
386
564
    let mut best: Option<(usize, f32)> = None;
387

            
388
1920
    for (i, p) in past.iter().enumerate() {
389
1920
        if taken.get(i).copied().unwrap_or(true) {
390
1320
            continue;
391
600
        }
392
600
        let dy = (p.origin.y + p.size.height / 2.0 - cur_centre).abs();
393
600
        let tolerance = p.size.height.min(cur.size.height) / 2.0;
394
600
        if dy <= tolerance && best.is_none_or(|(_, best_dy)| dy < best_dy) {
395
288
            best = Some((i, dy));
396
312
        }
397
    }
398

            
399
564
    let (idx, _) = best?;
400
288
    if let Some(slot) = taken.get_mut(idx) {
401
288
        *slot = true;
402
288
    }
403
288
    past.get(idx).copied()
404
564
}
405

            
406
/// Reason why a `VirtualView` callback is being invoked.
407
///
408
/// This helps the callback optimize its behavior based on why it's being called.
409
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
410
#[repr(C, u8)]
411
pub enum VirtualViewCallbackReason {
412
    /// Initial render - first time the `VirtualView` appears
413
    InitialRender,
414
    /// Parent DOM was recreated (cache invalidated)
415
    DomRecreated,
416
    /// Window/VirtualView bounds expanded beyond current `scroll_size`
417
    BoundsExpanded,
418
    /// Scroll position is near an edge (within `EDGE_THRESHOLD`, currently 200px)
419
    EdgeScrolled(EdgeType),
420
    /// Scroll position extends beyond current `scroll_size`
421
    ScrollBeyondContent,
422
}
423

            
424
/// Which edge triggered a scroll-based re-invocation
425
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
426
#[repr(C)]
427
pub enum EdgeType {
428
    Top,
429
    Bottom,
430
    Left,
431
    Right,
432
}
433

            
434
#[derive(Debug, Clone, Copy)]
435
#[repr(C)]
436
pub struct VirtualViewCallbackInfo {
437
    pub reason: VirtualViewCallbackReason,
438
    pub system_fonts: *const FcFontCache,
439
    pub image_cache: *const ImageCache,
440
    pub window_theme: WindowTheme,
441
    /// The window's CURRENT frame: normal, minimized, maximized, fullscreen.
442
    ///
443
    /// Here for the same reason `window_theme` is: a view whose content
444
    /// depends on a window-level fact should read that fact, not be handed a
445
    /// copy of it at build time and then kept in sync. The window control that
446
    /// has to draw "maximize" or "restore" is the case - a seeded copy is
447
    /// wrong the moment the window manager maximizes the window itself
448
    /// (super+up, edge snap, a tiling rule), which never goes through the
449
    /// button's own callback.
450
    pub window_frame: WindowFrame,
451
    /// RECT 1 - THE CONTAINER: the `VirtualView`'s on-screen box, computed by
452
    /// the framework from the outer DOM. You do not set this; you render into
453
    /// it.
454
    pub bounds: HidpiAdjustedBounds,
455
    /// RECT 2 - WHAT IS CURRENTLY MATERIALIZED, in VIRTUAL space: the window
456
    /// you returned last time (`origin` = where it starts in the document,
457
    /// `size` = its extent). Zero-sized on the first invoke.
458
    pub materialized: LogicalRect,
459
    /// RECT 3 - THE DOCUMENT, in VIRTUAL space: the extent you last declared,
460
    /// which is what the scrollbar currently represents.
461
    pub virtual_rect: LogicalRect,
462
    /// WHERE THE USER IS LOOKING: the live scroll offset in virtual space.
463
    ///
464
    /// This is the input your "which slice do I render?" math keys off. It was
465
    /// previously spelled `virtual_scroll_offset` and the engine hardcoded
466
    /// that to zero, so apps computing a page index from it always rendered
467
    /// the first page — one of the two reasons a `VirtualView` could not
468
    /// scroll.
469
    pub scroll_offset: LogicalPosition,
470
    /// Pointer to the callable (`OptionRefAny`) for FFI language bindings (Python, etc.)
471
    /// Set by the caller before invoking the callback. Native Rust callbacks have this as null.
472
    callable_ptr: *const OptionRefAny,
473
    /// Headless DOM measurement hook (see [`Self::measure_dom`]): a
474
    /// layout-crate trampoline (a [`MeasureDomFn`] stored as an opaque
475
    /// pointer, null = no hook) + its `LayoutWindow` context, injected at
476
    /// invoke time. Null on paths that cannot measure (then `measure_dom`
477
    /// returns zero).
478
    measure_dom_fn: *const c_void,
479
    measure_dom_ctx: *mut c_void,
480
    /// Extension for future ABI stability (mutable data)
481
    _abi_mut: *mut c_void,
482
}
483

            
484
/// Trampoline signature for [`VirtualViewCallbackInfo::measure_dom`] and
485
/// [`VirtualViewCallbackInfo::measure_dom_shrink_to_fit`]:
486
/// `(layout_window_ctx, dom, available, mode) -> content extent`.
487
///
488
/// The `Dom` is passed by pointer and CONSUMED (moved out) by the trampoline.
489
pub type MeasureDomFn =
490
    extern "C" fn(*mut c_void, *mut Dom, LogicalSize, MeasureDomMode) -> LogicalSize;
491

            
492
/// Which question a [`MeasureDomFn`] answers about a DOM.
493
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
494
#[repr(C)]
495
pub enum MeasureDomMode {
496
    /// Lay the DOM out against the given box and report the union of every
497
    /// node's bounds. A block root stretches to the box's width, so this
498
    /// reports the box's width for any block content - the right answer for
499
    /// "how tall is this item at this width".
500
    Extent,
501
    /// Lay the DOM out at its own max-content width (no wider than the given
502
    /// box) and report that - "how big does this content want to be", the
503
    /// answer a label or a popup needs.
504
    ShrinkToFit,
505
}
506

            
507
impl VirtualViewCallbackInfo {
508
    #[must_use]
509
1570
    pub const fn new<'a>(
510
1570
        reason: VirtualViewCallbackReason,
511
1570
        system_fonts: &'a FcFontCache,
512
1570
        image_cache: &'a ImageCache,
513
1570
        window_theme: WindowTheme,
514
1570
        window_frame: WindowFrame,
515
1570
        bounds: HidpiAdjustedBounds,
516
1570
        materialized: LogicalRect,
517
1570
        virtual_rect: LogicalRect,
518
1570
        scroll_offset: LogicalPosition,
519
1570
    ) -> Self {
520
1570
        Self {
521
1570
            reason,
522
1570
            system_fonts: core::ptr::from_ref::<FcFontCache>(system_fonts),
523
1570
            image_cache: core::ptr::from_ref::<ImageCache>(image_cache),
524
1570
            window_theme,
525
1570
            window_frame,
526
1570
            bounds,
527
1570
            materialized,
528
1570
            virtual_rect,
529
1570
            scroll_offset,
530
1570
            callable_ptr: core::ptr::null(),
531
1570
            measure_dom_fn: core::ptr::null(),
532
1570
            measure_dom_ctx: core::ptr::null_mut(),
533
1570
            _abi_mut: core::ptr::null_mut(),
534
1570
        }
535
1570
    }
536

            
537
    /// Set the callable pointer for FFI language bindings
538
1
    pub const fn set_callable_ptr(&mut self, callable: &OptionRefAny) {
539
1
        self.callable_ptr = core::ptr::from_ref::<OptionRefAny>(callable);
540
1
    }
541

            
542
    /// Inject the headless-measure trampoline (called by the layout crate
543
    /// right before the user callback is invoked).
544
961
    pub fn set_measure_dom_fn(&mut self, f: MeasureDomFn, ctx: *mut c_void) {
545
961
        self.measure_dom_fn = f as *const c_void;
546
961
        self.measure_dom_ctx = ctx;
547
961
    }
548

            
549
    /// Measure a DOM headlessly: style + lay it out against `available`
550
    /// constraints using the host window's fonts and system style, without
551
    /// touching the live layout. Returns the union of all node bounds.
552
    ///
553
    /// Use a very tall `available.height` (e.g. `1_000_000.0`) to obtain a
554
    /// DOM's natural height at a fixed width - the building block for
555
    /// virtual-scroll sizing: measure one (or a few) item template(s), then
556
    /// `virtual_scroll_size.height = item_height * item_count` and render
557
    /// only the visible window of items. Each call is a full cold layout
558
    /// pass, so cache measured sizes per item template.
559
    ///
560
    /// Returns `LogicalSize::zero()` when no measure hook was injected.
561
    #[must_use]
562
74
    pub fn measure_dom(&self, dom: Dom, available: LogicalSize) -> LogicalSize {
563
74
        if self.measure_dom_fn.is_null() {
564
7
            return LogicalSize::zero();
565
67
        }
566
        // SAFETY: measure_dom_fn is only ever set via set_measure_dom_fn,
567
        // which stores a valid MeasureDomFn.
568
67
        let f: MeasureDomFn = unsafe { core::mem::transmute(self.measure_dom_fn) };
569
67
        let mut dom = core::mem::ManuallyDrop::new(dom);
570
67
        f(
571
67
            self.measure_dom_ctx,
572
67
            core::ptr::from_mut::<Dom>(&mut dom),
573
67
            available,
574
67
            MeasureDomMode::Extent,
575
67
        )
576
74
    }
577

            
578
    /// Measure a DOM headlessly at the size its CONTENT asks for: as wide as
579
    /// its max-content width (no wider than `bound`), and as tall as that
580
    /// makes it. The natural-size counterpart of [`Self::measure_dom`],
581
    /// whose block root stretches to whatever width it is given - so a
582
    /// label measured that way reports the box, not the text.
583
    ///
584
    /// This is what a content-sized view returns as its `materialized`
585
    /// rect: a text label, a badge, a popup panel. Pass a generous `bound`
586
    /// (a few thousand pixels) for "unconstrained"; the view is then laid
587
    /// out at the size it reports (a `VirtualView` with `width: auto` is
588
    /// sized by what it returns).
589
    ///
590
    /// Returns `LogicalSize::zero()` when no measure hook was injected.
591
    #[must_use]
592
74
    pub fn measure_dom_shrink_to_fit(&self, dom: Dom, bound: LogicalSize) -> LogicalSize {
593
74
        if self.measure_dom_fn.is_null() {
594
1
            return LogicalSize::zero();
595
73
        }
596
        // SAFETY: see `measure_dom`.
597
73
        let f: MeasureDomFn = unsafe { core::mem::transmute(self.measure_dom_fn) };
598
73
        let mut dom = core::mem::ManuallyDrop::new(dom);
599
73
        f(
600
73
            self.measure_dom_ctx,
601
73
            core::ptr::from_mut::<Dom>(&mut dom),
602
73
            bound,
603
73
            MeasureDomMode::ShrinkToFit,
604
73
        )
605
74
    }
606

            
607
    /// Get the callable for FFI language bindings (Python, etc.)
608
    #[must_use]
609
69
    pub fn get_ctx(&self) -> OptionRefAny {
610
69
        if self.callable_ptr.is_null() {
611
4
            OptionRefAny::None
612
        } else {
613
65
            unsafe { (*self.callable_ptr).clone() }
614
        }
615
69
    }
616

            
617
    #[must_use]
618
575
    pub const fn get_bounds(&self) -> HidpiAdjustedBounds {
619
575
        self.bounds
620
575
    }
621

            
622
2
    const fn internal_get_system_fonts(&self) -> &FcFontCache {
623
2
        unsafe { &*self.system_fonts }
624
2
    }
625
1
    const fn internal_get_image_cache(&self) -> &ImageCache {
626
1
        unsafe { &*self.image_cache }
627
1
    }
628
}
629

            
630
/// Return value for a `VirtualView` rendering callback.
631
///
632
/// Contains two size/offset pairs for lazy loading and virtualization:
633
///
634
/// - `scroll_size` / `scroll_offset`: Size and position of actually rendered content
635
/// - `virtual_scroll_size` / `virtual_scroll_offset`: Size for scrollbar representation
636
///
637
/// The callback is re-invoked on: initial render, parent DOM recreation, window expansion
638
/// beyond `scroll_size`, or scrolling near content edges (`EDGE_THRESHOLD`, currently 200px).
639
///
640
/// Return `OptionDom::None` to keep the current DOM and only update scroll bounds.
641
#[derive(Debug, Clone, PartialEq, Eq)]
642
#[repr(C)]
643
pub struct VirtualViewReturn {
644
    /// The DOM with actual rendered content, or None to keep current DOM.
645
    ///
646
    /// - `OptionDom::Some(dom)` - Replace current content with this new DOM
647
    /// - `OptionDom::None` - Keep using the previous DOM, only update scroll bounds
648
    ///
649
    /// Returning `None` is an optimization when the callback determines that the
650
    /// current content is sufficient (e.g., already rendered ahead of scroll position).
651
    pub dom: OptionDom,
652

            
653
    /// WHAT THIS CALLBACK MATERIALIZED, in VIRTUAL space.
654
    ///
655
    /// `origin` = where this window of content begins in the document;
656
    /// `size` = how much of the document it covers.
657
    ///
658
    /// One rect, not a loose offset + size: they are a single fact about a
659
    /// single window, and storing them apart is exactly how the origin came
660
    /// to be dropped on the floor (content could not be placed, so a
661
    /// `VirtualView` could never actually scroll).
662
    ///
663
    /// The engine places the content at
664
    /// `container.origin + (materialized.origin - current_scroll_offset)`.
665
    ///
666
    /// **Example**: a table showing rows 10-30 at 30px each reports
667
    /// `origin.y = 300`, `size.height = 600`.
668
    pub materialized: LogicalRect,
669

            
670
    /// THE WHOLE DOCUMENT, in VIRTUAL space — what the scrollbar represents.
671
    ///
672
    /// `origin` is normally zero; `size` is your current best estimate and MAY
673
    /// change as work completes (e.g. a background pagination pass refining a
674
    /// page count). Refining it is cheap and safe: **only the scrollbar reads
675
    /// this**, so the thumb resizes and no content moves.
676
    ///
677
    /// **Example**: a 1000-row table reports `size.height = 30_000` even
678
    /// though `materialized` covers 600px of it.
679
    pub virtual_rect: LogicalRect,
680
}
681

            
682
impl Default for VirtualViewReturn {
683
13
    fn default() -> Self {
684
13
        Self {
685
13
            dom: OptionDom::None,
686
13
            materialized: LogicalRect::zero(),
687
13
            virtual_rect: LogicalRect::zero(),
688
13
        }
689
13
    }
690
}
691

            
692
impl VirtualViewReturn {
693
    /// Creates a new `VirtualViewReturn` with updated DOM content.
694
    ///
695
    /// Use this when the callback has rendered new content to display.
696
    ///
697
    /// # Arguments
698
    /// - `dom` - The new DOM to render
699
    /// - `materialized` - what you rendered, and where it sits in the document
700
    /// - `virtual_rect` - how big the document is (scrollbar sizing)
701
    #[must_use]
702
481
    pub const fn with_dom(dom: Dom, materialized: LogicalRect, virtual_rect: LogicalRect) -> Self {
703
481
        Self {
704
481
            dom: OptionDom::Some(dom),
705
481
            materialized,
706
481
            virtual_rect,
707
481
        }
708
481
    }
709

            
710
    /// Creates a return value that keeps the current DOM unchanged.
711
    ///
712
    /// Use this when the callback determines that the existing content
713
    /// is sufficient (e.g., already rendered ahead of scroll position).
714
    /// This is an optimization to avoid rebuilding the DOM unnecessarily.
715
    ///
716
    /// # Arguments
717
    /// - `materialized` - the window currently rendered, and where it sits
718
    /// - `virtual_rect` - how big the document is (scrollbar sizing)
719
    #[must_use]
720
6
    pub const fn keep_current(materialized: LogicalRect, virtual_rect: LogicalRect) -> Self {
721
6
        Self {
722
6
            dom: OptionDom::None,
723
6
            materialized,
724
6
            virtual_rect,
725
6
        }
726
6
    }
727
}
728

            
729
// --  thread callback
730

            
731
// -- timer callback
732

            
733
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
734
#[repr(C)]
735
pub struct TimerCallbackReturn {
736
    pub should_update: Update,
737
    pub should_terminate: TerminateTimer,
738
}
739

            
740
impl TimerCallbackReturn {
741
    /// Creates a new `TimerCallbackReturn` with the given update and terminate flags.
742
    #[must_use]
743
9
    pub const fn create(should_update: Update, should_terminate: TerminateTimer) -> Self {
744
9
        Self {
745
9
            should_update,
746
9
            should_terminate,
747
9
        }
748
9
    }
749

            
750
    /// Timer continues running, no DOM update needed.
751
    #[must_use]
752
3
    pub const fn continue_unchanged() -> Self {
753
3
        Self {
754
3
            should_update: Update::DoNothing,
755
3
            should_terminate: TerminateTimer::Continue,
756
3
        }
757
3
    }
758

            
759
    /// Timer continues running and DOM should be refreshed.
760
    #[must_use]
761
1
    pub const fn continue_and_refresh_dom() -> Self {
762
1
        Self {
763
1
            should_update: Update::RefreshDom,
764
1
            should_terminate: TerminateTimer::Continue,
765
1
        }
766
1
    }
767

            
768
    /// Timer should stop, no DOM update needed.
769
    #[must_use]
770
17425
    pub const fn terminate_unchanged() -> Self {
771
17425
        Self {
772
17425
            should_update: Update::DoNothing,
773
17425
            should_terminate: TerminateTimer::Terminate,
774
17425
        }
775
17425
    }
776

            
777
    /// Timer should stop and DOM should be refreshed.
778
    #[must_use]
779
2
    pub const fn terminate_and_refresh_dom() -> Self {
780
2
        Self {
781
2
            should_update: Update::RefreshDom,
782
2
            should_terminate: TerminateTimer::Terminate,
783
2
        }
784
2
    }
785
}
786

            
787
impl Default for TimerCallbackReturn {
788
1
    fn default() -> Self {
789
1
        Self::continue_unchanged()
790
1
    }
791
}
792

            
793
/// Reference data container for `LayoutCallbackInfo` (all read-only fields).
794
///
795
/// Gives the `layout()` function access to the `RendererResources` and the
796
/// `Window` — querying images and fonts, and the width / height.
797
///
798
/// This struct consolidates all readonly references that layout callbacks need to query state.
799
/// By grouping these into a single struct, we reduce the number of parameters to
800
/// `LayoutCallbackInfo::new()` from 6 to 2, making the API more maintainable and easier to extend.
801
///
802
/// This is pure syntax sugar - the struct lives on the stack in the caller and is passed by
803
/// reference.
804
#[derive(Debug)]
805
#[repr(C)]
806
pub struct LayoutCallbackInfoRefData<'a> {
807
    /// Allows the `layout()` function to reference image IDs
808
    pub image_cache: &'a ImageCache,
809
    /// OpenGL context so that the `layout()` function can render textures
810
    pub gl_context: &'a OptionGlContextPtr,
811
    /// Reference to the system font cache
812
    pub system_fonts: &'a FcFontCache,
813
    /// Platform-specific system style (colors, spacing, etc.)
814
    /// Used for CSD rendering and menu windows.
815
    pub system_style: Arc<SystemStyle>,
816
    /// Active route match (if routing is configured).
817
    /// Contains the matched pattern and extracted parameters.
818
    pub active_route: Option<&'a crate::resources::RouteMatch>,
819
    /// #28 (d): SNAPSHOT of the system's monitors, taken (locked + cloned)
820
    /// by the caller right before invoking the layout callback. A snapshot —
821
    /// not the live `Arc<Mutex<…>>` handle — because `azul-core` is `no_std`
822
    /// (no Mutex) and the list is read-only during a layout pass anyway.
823
    /// Lets `layout()` bound how much content it builds on first layout
824
    /// (e.g. at most monitor-height lines / monitor-area characters), so
825
    /// opening a huge file can never build an unbounded DOM.
826
    pub monitors: crate::window::MonitorVec,
827
    /// Safe-area insets: system bars, notch/cutout, and the on-screen
828
    /// keyboard's height. Live values, not the platform defaults.
829
    ///
830
    /// `layout()` needs these and could not reach them: they live on
831
    /// `LayoutWindow` and were exposed only through `CallbackInfo`, which is
832
    /// the EVENT callback. So an app could read the notch from a click handler
833
    /// and not from the function that decides where to draw — which is the one
834
    /// place it matters. A mobile app that must not draw under the status bar
835
    /// had no way to ask how tall it is.
836
    pub safe_area: azul_css::system::SafeAreaInsets,
837
}
838

            
839
/// What triggered the current `layout()` invocation.
840
///
841
/// The framework re-invokes the layout callback for any change that may
842
/// produce a structurally different DOM (resize across a CSS breakpoint,
843
/// theme toggle, route switch, callback returning `Update::RefreshDom`).
844
/// `LayoutCallbackInfo::relayout_reason()` exposes which trigger this
845
/// particular call corresponds to so the callback can branch - for
846
/// example, skip expensive analytics on `Resize` calls.
847
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
848
#[repr(C)]
849
#[derive(Default)]
850
pub enum RelayoutReason {
851
    /// First layout call for this window.
852
    #[default]
853
    Initial,
854
    /// A user callback returned `Update::RefreshDom`.
855
    RefreshDom,
856
    /// Window size changed across a CSS breakpoint or DPI scale change.
857
    /// The callback can branch on `info.window_width_*` to emit a
858
    /// different tree (e.g. hamburger menu vs sidebar).
859
    Resize,
860
    /// System theme changed (light/dark).
861
    ThemeChange,
862
    /// `CallbackInfo::switch_route` or `set_route_param` produced a new
863
    /// route match. The callback should branch on
864
    /// `info.get_active_route()`.
865
    RouteChange,
866
    /// Catch-all for relayouts that don't fit one of the above categories.
867
    Other,
868
}
869

            
870
#[derive(Clone, Copy)]
871
#[repr(C)]
872
pub struct LayoutCallbackInfo {
873
    /// Single reference to all readonly reference data
874
    /// This consolidates 4 individual parameters into 1, improving API ergonomics
875
    ref_data: *const LayoutCallbackInfoRefData<'static>,
876
    /// Window size (so that apps can return a different UI depending on
877
    /// the window size - mobile / desktop view). Should be later removed
878
    /// in favor of "resize" handlers and @media queries.
879
    pub window_size: WindowSize,
880
    /// Registers whether the UI is dependent on the window theme
881
    pub theme: WindowTheme,
882
    /// What triggered this `layout()` call. Read via `relayout_reason()`.
883
    pub relayout_reason: RelayoutReason,
884
    /// Pointer to the callable (`OptionRefAny`) for FFI language bindings (Python, etc.)
885
    /// Set by the caller before invoking the callback. Native Rust callbacks have this as null.
886
    callable_ptr: *const OptionRefAny,
887
    /// Extension for future ABI stability (mutable data)
888
    _abi_mut: *mut c_void,
889
}
890

            
891
/// One recorded window-size query made by a `layout()` callback.
892
///
893
/// See [`LayoutCallbackInfo::window_width_less_than`] & co. The engine replays
894
/// these against a
895
/// prospective new size to decide whether a resize could change the DOM at
896
/// all: if no recorded answer flips (and no CSS breakpoint is crossed), the
897
/// callback is provably size-stable across that resize and is not re-invoked.
898
#[repr(C)]
899
#[derive(Debug, Clone, Copy, PartialEq)]
900
pub struct SizeQuery {
901
    pub axis: SizeQueryAxis,
902
    pub op: SizeQueryOp,
903
    pub threshold_px: f32,
904
    /// The answer given at recording time, evaluated against the size the
905
    /// callback actually saw.
906
    pub answer: bool,
907
}
908

            
909
/// Which window dimension a [`SizeQuery`] tested.
910
#[repr(C)]
911
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
912
pub enum SizeQueryAxis {
913
    Width,
914
    Height,
915
}
916

            
917
/// The comparison a [`SizeQuery`] performed.
918
///
919
/// Four variants rather than a greater/smaller bool because the recorded
920
/// operator must REPLAY EXACTLY:
921
/// `window_width_less_than` is a strict `<` while `window_width_between`'s
922
/// lower bound is `>=`, and collapsing either onto the other misjudges a
923
/// resize landing precisely on the queried boundary — the one pixel the app
924
/// explicitly said it cares about.
925
#[repr(C)]
926
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
927
pub enum SizeQueryOp {
928
    /// `dim < threshold` (`window_width_less_than` / `window_height_less_than`)
929
    LessThan,
930
    /// `dim > threshold` (`window_width_greater_than` / `window_height_greater_than`)
931
    GreaterThan,
932
    /// `dim >= threshold` (the lower bound of `window_*_between`)
933
    GreaterOrEqual,
934
    /// `dim <= threshold` (the upper bound of `window_*_between`)
935
    LessOrEqual,
936
}
937

            
938
impl SizeQuery {
939
    /// What this query would answer at `size` — compare with [`Self::answer`]
940
    /// to detect a flip. MUST mirror the operators of the recording methods
941
    /// exactly (see [`SizeQueryOp`]), or the engine would skip a `layout()`
942
    /// re-invocation right at the boundary the app asked about.
943
    #[must_use]
944
9
    pub fn answer_at(&self, size: LogicalSize) -> bool {
945
9
        let dim = match self.axis {
946
9
            SizeQueryAxis::Width => size.width,
947
            SizeQueryAxis::Height => size.height,
948
        };
949
9
        match self.op {
950
5
            SizeQueryOp::LessThan => dim < self.threshold_px,
951
            SizeQueryOp::GreaterThan => dim > self.threshold_px,
952
2
            SizeQueryOp::GreaterOrEqual => dim >= self.threshold_px,
953
2
            SizeQueryOp::LessOrEqual => dim <= self.threshold_px,
954
        }
955
9
    }
956

            
957
    /// Would this query's answer differ at `size` from the recorded one?
958
    #[must_use]
959
9
    pub fn flips_at(&self, size: LogicalSize) -> bool {
960
9
        self.answer_at(size) != self.answer
961
9
    }
962
}
963

            
964
/// Thread-local recorder backing the responsive helpers
965
/// (`LayoutCallbackInfo::window_width_less_than` & co.).
966
///
967
/// A thread-local (rather than a field on the FFI-frozen `LayoutCallbackInfo`)
968
/// works because the layout callback is invoked SYNCHRONOUSLY on the calling
969
/// thread: the engine drains the recording immediately after the callback
970
/// returns, on the same thread that made the queries.
971
///
972
/// Bounded, and the overflow direction matters: SILENTLY dropping queries
973
/// would drop exactly the flips the engine needs to see — the UNSAFE
974
/// direction, a resize skipping a `layout()` that would have branched. So the
975
/// cap does not drop; it latches an `overflowed` flag that the drain reports,
976
/// and the engine then treats the callback as size-dependent EVERYWHERE
977
/// (every resize re-invokes it — today's behaviour, merely un-optimized).
978
#[cfg(feature = "std")]
979
mod size_query_recorder {
980
    use super::SizeQuery;
981

            
982
    /// More distinct thresholds than any real breakpoint scheme uses; a
983
    /// callback exceeding this is generating them programmatically.
984
    pub(super) const SIZE_QUERY_CAP: usize = 256;
985

            
986
    std::thread_local! {
987
        static RECORDED: core::cell::RefCell<(Vec<SizeQuery>, bool)> =
988
            const { core::cell::RefCell::new((Vec::new(), false)) };
989
    }
990

            
991
8314
    pub(super) fn record(q: SizeQuery) {
992
8314
        RECORDED.with(|r| {
993
8314
            let mut r = r.borrow_mut();
994
8314
            if r.0.len() >= SIZE_QUERY_CAP {
995
7714
                r.1 = true; // overflowed: the drain must report "unbounded"
996
7714
            } else {
997
600
                r.0.push(q);
998
600
            }
999
8314
        });
8314
    }
    /// Drain the recording. Returns `(queries, overflowed)`; `overflowed`
    /// means the cap was hit and the list is INCOMPLETE — treat every resize
    /// as potentially DOM-changing.
12
    pub(super) fn take() -> (Vec<SizeQuery>, bool) {
12
        RECORDED.with(|r| {
12
            let mut r = r.borrow_mut();
12
            let overflowed = r.1;
12
            r.1 = false;
12
            (core::mem::take(&mut r.0), overflowed)
12
        })
12
    }
}
#[cfg(feature = "std")]
8314
fn record_size_query(q: SizeQuery) {
8314
    size_query_recorder::record(q);
8314
}
/// Without `std` there is no thread-local to record into; the queries still
/// ANSWER correctly, the engine just cannot prove size-stability and falls
/// back to re-invoking `layout()` on breakpoint-relevant resizes (web builds
/// are out of scope for the resize fast path).
#[cfg(not(feature = "std"))]
fn record_size_query(_q: SizeQuery) {}
/// Drain the size queries recorded since the last drain on THIS thread.
///
/// Call immediately after a `layout()` callback returns, on the same thread.
/// `(queries, overflowed)` — on `overflowed == true` the list is incomplete
/// and the caller must treat the callback as size-dependent everywhere.
#[cfg(feature = "std")]
#[must_use]
12
pub fn take_recorded_size_queries() -> (alloc::vec::Vec<SizeQuery>, bool) {
12
    size_query_recorder::take()
12
}
#[cfg(not(feature = "std"))]
#[must_use]
pub fn take_recorded_size_queries() -> (alloc::vec::Vec<SizeQuery>, bool) {
    (alloc::vec::Vec::new(), false)
}
/// Which facet of the OS style a `layout()` callback read.
///
/// An "appearance change" is never one event. The light/dark polarity flips,
/// or the accent colour moves, or the UI font grows, or the icon theme is
/// swapped — and each of those reaches a different app differently. Whether
/// the change can alter what `layout()` RETURNS depends entirely on what that
/// callback read, and only the callback knows.
/// [`LayoutCallbackInfo::depends_on_system_style`] is how it says so; this
/// enum is the vocabulary.
///
/// Deliberately coarse. The distinction that pays is between the app that
/// merely mirrors light/dark (its DOM is byte-identical across two different
/// LIGHT schemes, so an accent change must not cost it a rebuild) and the app
/// that baked `colors.button_face` into inline CSS inside `layout()` (its DOM
/// is wrong the instant the palette moves). Finer facets would be more
/// precise and nobody would declare them correctly.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SystemStyleDependency {
    /// The light/dark polarity alone — [`LayoutCallbackInfo::get_theme`].
    Theme,
    /// The colour palette: text, background, accent, button, selection.
    Colors,
    /// The UI fonts — family, size, weight.
    Fonts,
    /// Sizing and spacing metrics: control sizes, scrollbar geometry,
    /// titlebar layout, input timings, focus ring.
    Metrics,
    /// The icon theme and the icon styling options.
    Icons,
    /// Accessibility and motion preferences — reduced motion, high contrast,
    /// animation speed.
    Accessibility,
    /// Everything: the callback took the whole [`SystemStyle`] and the engine
    /// cannot see which parts of it were read. The conservative answer, and
    /// what [`LayoutCallbackInfo::get_system_style`] records.
    Everything,
}
impl SystemStyleDependency {
    /// This facet's bit in a [`SystemStyleDependencies`] mask.
    #[must_use]
168
    pub const fn bit(self) -> u32 {
168
        match self {
12
            Self::Theme => 1 << 0,
9
            Self::Colors => 1 << 1,
5
            Self::Fonts => 1 << 2,
3
            Self::Metrics => 1 << 3,
3
            Self::Icons => 1 << 4,
3
            Self::Accessibility => 1 << 5,
133
            Self::Everything => u32::MAX,
        }
168
    }
}
/// The set of [`SystemStyleDependency`] facets one `layout()` call declared.
///
/// A bitmask rather than a list: the facets are few, the union is the only
/// operation, and it has to be cheap enough to fold on every declaration
/// inside a deep widget tree.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct SystemStyleDependencies {
    /// Bitmask over [`SystemStyleDependency::bit`]. `0` = nothing declared,
    /// which is NOT "depends on nothing" — see
    /// [`Self::dom_depends_on_change`].
    pub facets: u32,
}
impl SystemStyleDependencies {
    /// Nothing declared.
    #[must_use]
29056
    pub const fn empty() -> Self {
29056
        Self { facets: 0 }
29056
    }
    /// Every facet — what an undeclared callback is treated as.
    #[must_use]
    pub const fn all() -> Self {
        Self { facets: u32::MAX }
    }
    /// Nothing has been declared yet.
    #[must_use]
10
    pub const fn is_empty(&self) -> bool {
10
        self.facets == 0
10
    }
    /// Fold one facet in.
138
    pub const fn insert(&mut self, dep: SystemStyleDependency) {
138
        self.facets |= dep.bit();
138
    }
    /// Fold another set in.
    pub const fn union(&mut self, other: Self) {
        self.facets |= other.facets;
    }
    /// Was `dep` declared? `Everything` implies every facet.
    #[must_use]
30
    pub const fn contains(&self, dep: SystemStyleDependency) -> bool {
30
        let bit = dep.bit();
30
        self.facets & bit == bit
30
    }
    /// Would a system-style change from `old` to `new` alter what the
    /// callback that declared these dependencies returns — i.e. does the
    /// change need a full `Update::RefreshDom`, or only a restyle?
    ///
    /// An EMPTY set answers `true`. "Declared nothing" is not "depends on
    /// nothing": it is the state of every callback written before this API
    /// existed, and of every callback that reads the OS style through a
    /// widget it does not control. Skipping their rebuild would leave the
    /// previous palette baked into the DOM — a silent wrong-colours bug that
    /// only a theme switch reveals. Declaring is opt-in; conservatism is the
    /// default.
    #[must_use]
6
    pub fn dom_depends_on_change(&self, old: &SystemStyle, new: &SystemStyle) -> bool {
6
        if self.is_empty() {
2
            return old != new;
4
        }
4
        if self.contains(SystemStyleDependency::Theme) && old.theme != new.theme {
1
            return true;
3
        }
3
        if self.contains(SystemStyleDependency::Colors) && old.colors != new.colors {
1
            return true;
2
        }
2
        if self.contains(SystemStyleDependency::Fonts) && old.fonts != new.fonts {
            return true;
2
        }
2
        if self.contains(SystemStyleDependency::Metrics)
            && (old.metrics != new.metrics
                || old.input != new.input
                || old.focus_visuals != new.focus_visuals
                || old.scrollbar != new.scrollbar
                || old.scrollbar_preferences != new.scrollbar_preferences)
        {
            return true;
2
        }
2
        if self.contains(SystemStyleDependency::Icons)
            && (old.icon_style != new.icon_style
                || old.visual_hints != new.visual_hints
                || old.linux.icon_theme != new.linux.icon_theme)
        {
            return true;
2
        }
2
        if self.contains(SystemStyleDependency::Accessibility)
            && (old.accessibility != new.accessibility
                || old.animation != new.animation
                || old.prefers_reduced_motion != new.prefers_reduced_motion
                || old.prefers_high_contrast != new.prefers_high_contrast)
        {
            return true;
2
        }
2
        false
6
    }
}
/// Thread-local recorder behind [`LayoutCallbackInfo::depends_on_system_style`].
///
/// Same shape, and for the same reason, as the size-query recorder above: the
/// layout callback runs SYNCHRONOUSLY on the calling thread, so the engine
/// drains what it declared right after it returns. A mask cannot overflow, so
/// unlike the size queries there is no incomplete-recording flag.
#[cfg(feature = "std")]
mod style_dep_recorder {
    use super::SystemStyleDependencies;
    std::thread_local! {
        static DECLARED: core::cell::Cell<SystemStyleDependencies> =
            const { core::cell::Cell::new(SystemStyleDependencies { facets: 0 }) };
    }
134
    pub(super) fn record(dep: super::SystemStyleDependency) {
134
        DECLARED.with(|d| {
134
            let mut set = d.get();
134
            set.insert(dep);
134
            d.set(set);
134
        });
134
    }
10
    pub(super) fn take() -> SystemStyleDependencies {
10
        DECLARED.with(core::cell::Cell::take)
10
    }
}
#[cfg(feature = "std")]
134
fn record_style_dependency(dep: SystemStyleDependency) {
134
    style_dep_recorder::record(dep);
134
}
/// Without `std` there is no thread-local to record into. The declarations
/// still cost nothing and the engine falls back to rebuilding on every
/// system-style change — today's behaviour, merely un-optimized.
#[cfg(not(feature = "std"))]
fn record_style_dependency(_dep: SystemStyleDependency) {}
/// Drain the system-style dependencies declared since the last drain on THIS
/// thread.
///
/// Call immediately after a `layout()` callback returns, on the same thread.
/// The empty set means the callback declared nothing — which
/// [`SystemStyleDependencies::dom_depends_on_change`] reads as "assume it
/// depends on all of it".
#[cfg(feature = "std")]
#[must_use]
10
pub fn take_recorded_style_dependencies() -> SystemStyleDependencies {
10
    style_dep_recorder::take()
10
}
#[cfg(not(feature = "std"))]
#[must_use]
pub fn take_recorded_style_dependencies() -> SystemStyleDependencies {
    SystemStyleDependencies::empty()
}
impl core::fmt::Debug for LayoutCallbackInfo {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("LayoutCallbackInfo")
            .field("window_size", &self.window_size)
            .field("theme", &self.theme)
            .field("relayout_reason", &self.relayout_reason)
            .finish_non_exhaustive()
    }
}
impl LayoutCallbackInfo {
    #[must_use]
41
    pub const fn new<'a>(
41
        ref_data: &'a LayoutCallbackInfoRefData<'a>,
41
        window_size: WindowSize,
41
        theme: WindowTheme,
41
    ) -> Self {
41
        Self::new_with_reason(ref_data, window_size, theme, RelayoutReason::Initial)
41
    }
    // the `as *const ...<'static>` is a deliberate 'a -> 'static lifetime launder
    // on the raw pointer (see SAFETY note below), not a redundant cast.
    #[allow(clippy::unnecessary_cast)]
    #[must_use]
47
    pub const fn new_with_reason<'a>(
47
        ref_data: &'a LayoutCallbackInfoRefData<'a>,
47
        window_size: WindowSize,
47
        theme: WindowTheme,
47
        relayout_reason: RelayoutReason,
47
    ) -> Self {
47
        Self {
47
            // SAFETY: We cast away the lifetime 'a to 'static because LayoutCallbackInfo
47
            // only lives for the duration of the callback, which is shorter than 'a
47
            ref_data: core::ptr::from_ref::<LayoutCallbackInfoRefData<'a>>(ref_data)
47
                as *const LayoutCallbackInfoRefData<'static>,
47
            window_size,
47
            theme,
47
            relayout_reason,
47
            callable_ptr: core::ptr::null(),
47
            _abi_mut: core::ptr::null_mut(),
47
        }
47
    }
    /// Returns what triggered the current `layout()` invocation.
    #[must_use]
13
    pub const fn relayout_reason(&self) -> RelayoutReason {
13
        self.relayout_reason
13
    }
    /// Is the window's LOGICAL viewport wider than `width_px`?
    ///
    /// The structural-breakpoint helper: branch on this in `layout()` to
    /// return an entirely different DOM per form factor
    /// (`ribbon.dom_desktop()` vs `ribbon.dom_mobile()`), instead of
    /// emitting both trees and toggling visibility with `@media` rules.
    ///
    /// CONTRACT: the framework re-invokes `layout()` on every window resize
    /// (`RelayoutReason::Resize` - the regenerate path never takes the
    /// layout-equivalence shortcut when the window size changed), so the
    /// answer cannot go stale: crossing the breakpoint in either direction
    /// re-runs `layout()` and the callback returns the other tree. If a
    /// future optimization ever skips DOM regeneration on resize, it must
    /// register the thresholds queried here and force a rebuild when one is
    /// crossed - grep for this comment.
    #[must_use]
    pub fn viewport_bigger_than(&self, width_px: f32) -> bool {
        self.window_size.dimensions.width > width_px
    }
    /// Safe-area insets in logical px: system bars, notch / cutout, and the
    /// on-screen keyboard.
    ///
    /// The same values `CallbackInfo::get_safe_area_insets` returns, made
    /// reachable from `layout()`. They were only available from EVENT
    /// callbacks, which is the wrong half: an app could read the notch from a
    /// click handler but not from the function that decides where to draw.
    ///
    /// `keyboard` is kept separate from `bottom` deliberately. The bar is
    /// fixed and the keyboard moves, so a layout that must stay above the IME
    /// adds them, and one that only wants to avoid the home indicator does
    /// not.
    #[must_use]
    pub const fn get_safe_area_insets(&self) -> azul_css::system::SafeAreaInsets {
        // SAFETY: same contract as `get_monitors` above — `ref_data` is set
        // for the duration of the layout call.
        unsafe { (*self.ref_data).safe_area }
    }
    /// Set the callable pointer for FFI language bindings
1
    pub const fn set_callable_ptr(&mut self, callable: &OptionRefAny) {
1
        self.callable_ptr = core::ptr::from_ref::<OptionRefAny>(callable);
1
    }
    /// Get the callable for FFI language bindings (Python, etc.)
    #[must_use]
68
    pub fn get_ctx(&self) -> OptionRefAny {
68
        if self.callable_ptr.is_null() {
2
            OptionRefAny::None
        } else {
66
            unsafe { (*self.callable_ptr).clone() }
        }
68
    }
    /// Declare that the DOM this callback returns depends on `dep`.
    ///
    /// THE seam between "the OS appearance changed" and "this app's DOM is
    /// now wrong". A theme switch, an accent-colour change, a UI-font resize
    /// all arrive as the same kind of event, and the engine has no way to see
    /// which of them can change what `layout()` builds — only the callback
    /// knows.
    ///
    /// Declare narrowly and a change outside what you declared costs a
    /// RESTYLE (the cascade re-resolves `system-*` colours and `@theme`
    /// conditions against the new style, warm layout caches intact) instead
    /// of a full `Update::RefreshDom` (re-invoke `layout()`, rebuild the
    /// `StyledDom`, re-cascade, re-shape every run of text).
    ///
    /// ```ignore
    /// // "I mirror light/dark and nothing else": switching between two
    /// // light colour schemes cannot change my DOM.
    /// info.depends_on_system_style(SystemStyleDependency::Theme);
    /// let dark = info.get_theme() == WindowTheme::DarkMode;
    ///
    /// // "I paint my own buttons from the OS palette": ANY palette move
    /// // invalidates my DOM, light-to-light included.
    /// info.depends_on_system_style(SystemStyleDependency::Colors);
    /// ```
    ///
    /// Declarations UNION over the whole callback, widgets included, and the
    /// union is conservative: one widget calling
    /// [`Self::get_system_style`] declares [`SystemStyleDependency::Everything`]
    /// for the entire tree, because a whole-struct read is opaque.
    ///
    /// Declaring NOTHING is not "depends on nothing" — an undeclared callback
    /// is rebuilt on every system-style change, exactly as before this API
    /// existed. Reading the `theme` field directly (`info.theme`) declares
    /// nothing either: the engine cannot see a field read, the same way it
    /// cannot see `info.window_size` being used to branch the DOM.
    #[allow(clippy::unused_self)] // C-ABI-shaped method: receiver kept for API symmetry
134
    pub fn depends_on_system_style(&self, dep: SystemStyleDependency) {
134
        record_style_dependency(dep);
134
    }
    /// The window's light/dark polarity, declaring
    /// [`SystemStyleDependency::Theme`].
    ///
    /// The tracked way to read what the `theme` field also holds. Use this
    /// and a change that leaves the polarity alone — a new accent colour, a
    /// different light scheme — will not rebuild the DOM.
    #[must_use]
1
    pub fn get_theme(&self) -> WindowTheme {
1
        self.depends_on_system_style(SystemStyleDependency::Theme);
1
        self.theme
1
    }
    /// Get a clone of the system style Arc.
    ///
    /// Declares [`SystemStyleDependency::Everything`]: handing out the whole
    /// struct makes the read opaque, so the honest answer is that any part of
    /// it may have reached the DOM. A callback that only wants the palette or
    /// the fonts should say so with [`Self::depends_on_system_style`] and
    /// reach for [`Self::get_system_style_untracked`].
    #[must_use]
131
    pub fn get_system_style(&self) -> Arc<SystemStyle> {
131
        self.depends_on_system_style(SystemStyleDependency::Everything);
131
        self.get_system_style_untracked()
131
    }
    /// The system style WITHOUT declaring a dependency on all of it.
    ///
    /// For a callback that has already declared what it actually reads, and
    /// for engine-internal readers (CSD, menus) whose output is rebuilt by
    /// the engine itself rather than by the app's `layout()`.
    #[must_use]
132
    pub fn get_system_style_untracked(&self) -> Arc<SystemStyle> {
132
        unsafe { (*self.ref_data).system_style.clone() }
132
    }
    /// #28 (d): snapshot of the system's monitors, taken by the caller right
    /// before this layout pass. Empty when the platform hasn't populated
    /// monitor info (headless, web, very early startup).
    #[must_use]
1
    pub fn get_monitors(&self) -> crate::window::MonitorVec {
1
        unsafe { (*self.ref_data).monitors.clone() }
1
    }
    /// #28 (d): the LARGEST monitor size in physical px — the safe upper
    /// bound for "how much content could possibly be visible at once" when
    /// the window's own monitor is not yet known at first layout. Apps use
    /// it to bound how much content the first `layout()` builds (e.g. at
    /// most monitor-height text lines, or monitor-width × monitor-height
    /// characters for a single unbroken line), so opening a huge file never
    /// builds an unbounded DOM. `None` when no monitor info is available.
    #[must_use]
2
    pub fn get_max_monitor_size(&self) -> azul_css::props::basic::OptionLayoutSize {
2
        let monitors = unsafe { &(*self.ref_data).monitors };
2
        let mut best: Option<LayoutSize> = None;
3
        for m in monitors.as_ref() {
3
            let s = m.size;
3
            let better = best.is_none_or(|b| (s.width * s.height) > (b.width * b.height));
3
            if better {
2
                best = Some(s);
2
            }
        }
2
        best.into()
2
    }
13
    const fn internal_get_image_cache(&self) -> &ImageCache {
13
        unsafe { (*self.ref_data).image_cache }
13
    }
3
    const fn internal_get_system_fonts(&self) -> &FcFontCache {
3
        unsafe { (*self.ref_data).system_fonts }
3
    }
2
    const fn internal_get_gl_context(&self) -> &OptionGlContextPtr {
2
        unsafe { (*self.ref_data).gl_context }
2
    }
    #[must_use]
1
    pub fn get_gl_context(&self) -> OptionGlContextPtr {
1
        self.internal_get_gl_context().clone()
1
    }
    #[must_use]
2
    pub fn get_system_fonts(&self) -> Vec<AzStringPair> {
2
        let fc_cache = self.internal_get_system_fonts();
2
        fc_cache
2
            .list()
2
            .into_iter()
2
            .filter_map(|(pattern, font_id)| {
                let source = fc_cache.get_font_by_id(&font_id)?;
                match source {
                    OwnedFontSource::Memory(_) => None,
                    OwnedFontSource::Disk(d) => Some((pattern.name.as_ref()?.clone(), d.path)),
                }
            })
2
            .map(|(k, v)| AzStringPair {
                key: k.into(),
                value: v.into(),
            })
2
            .collect()
2
    }
    /// The window's ALREADY-BUILT system font cache.
    ///
    /// `get_system_fonts` only hands back stringified name/path pairs, which
    /// is useless to a layout callback that wants to run engine layout of
    /// its own (paginating a document, measuring for an export). Such an app
    /// had to call `build_font_cache()` and re-scan every font on the
    /// machine — measured at ~5 SECONDS on the first frame, during which the
    /// client cannot answer the compositor's configure/ping handshake and
    /// loses its surface.
    ///
    /// The cache is internally `Arc<RwLock<_>>` (rust-fontconfig 4.1+), so
    /// this clone is a handle, not a copy: the caller sees the same fonts
    /// the window already resolved, including builder-thread additions.
    #[must_use]
    pub fn get_font_cache(&self) -> FcFontCache {
        self.internal_get_system_fonts().clone()
    }
    #[must_use]
12
    pub fn get_image(&self, image_id: &AzString) -> Option<ImageRef> {
12
        self.internal_get_image_cache()
12
            .get_css_image_id(image_id)
12
            .cloned()
12
    }
    /// Get the active route match (pattern + extracted parameters).
    ///
    /// Returns `None` if no routes are configured or no route is active.
    #[must_use]
41
    pub const fn get_active_route(&self) -> Option<&crate::resources::RouteMatch> {
41
        unsafe { (*self.ref_data).active_route }
41
    }
    /// Get a route parameter by key (e.g. `get_route_param("id")` for `/user/:id`).
    ///
    /// Returns `None` if no route is active or the parameter doesn't exist.
    #[must_use]
39
    pub fn get_route_param(&self, key: &str) -> Option<&AzString> {
39
        self.get_active_route()?.get_param(key)
39
    }
    /// The pattern of the route this layout callback is rendering, e.g.
    /// `"/user/:id"`.
    ///
    /// `"/"` when the app configured no routes: an app without routing is on
    /// the default route, so a callback that branches on the pattern always
    /// has one string to branch on rather than an empty one.
    ///
    /// # C API
    /// ```c
    /// AzString pattern = AzLayoutCallbackInfo_getRoutePattern(&info);
    /// ```
    #[must_use]
    pub fn get_route_pattern(&self) -> AzString {
        self.get_active_route().map_or_else(
            || AzString::from_const_str("/"),
            |route| route.pattern.clone(),
        )
    }
    /// A route parameter by key, empty when the parameter or the route is
    /// absent. The owned-key, owned-return form the FFI needs;
    /// [`Self::get_route_param`] is the borrowing Rust one.
    ///
    /// # C API
    /// ```c
    /// AzString id = AzLayoutCallbackInfo_getRouteParamOrEmpty(&info,
    ///     AzString_fromConstStr("id"));
    /// ```
    #[allow(clippy::needless_pass_by_value)]
    #[must_use]
    pub fn get_route_param_or_empty(&self, key: AzString) -> AzString {
        self.get_route_param(key.as_str())
            .cloned()
            .unwrap_or_else(|| AzString::from_const_str(""))
    }
    // Responsive layout helper methods.
    //
    // These are THE sanctioned way for `layout()` to branch on window size
    // (mobile vs desktop DOM shapes, instead of `display:none` stacks). Every
    // call is RECORDED, and the recording is what makes resize cheap: a resize
    // that flips none of the recorded answers (and crosses no CSS breakpoint)
    // provably cannot change what the callback returns through this channel,
    // so the engine re-flows the existing DOM instead of re-invoking it
    // (`LayoutWindow::resize_needs_full_regeneration`). Reading the size
    // imperatively (`get_window_width()`, `info.window_size`) to branch the
    // DOM is a bug in the app: the engine cannot see that read, so the DOM
    // goes stale across exactly the resizes the app cared about.
    #[allow(clippy::unused_self)] // C-ABI-shaped method: receiver kept for API symmetry
6078
    fn record_width_query(&self, op: SizeQueryOp, threshold_px: f32, answer: bool) -> bool {
6078
        record_size_query(SizeQuery {
6078
            axis: SizeQueryAxis::Width,
6078
            op,
6078
            threshold_px,
6078
            answer,
6078
        });
6078
        answer
6078
    }
    #[allow(clippy::unused_self)] // C-ABI-shaped method: receiver kept for API symmetry
2236
    fn record_height_query(&self, op: SizeQueryOp, threshold_px: f32, answer: bool) -> bool {
2236
        record_size_query(SizeQuery {
2236
            axis: SizeQueryAxis::Height,
2236
            op,
2236
            threshold_px,
2236
            answer,
2236
        });
2236
        answer
2236
    }
    /// Returns true if the window width is less than the given pixel value.
    /// Recorded — see the note above these helpers.
    #[must_use]
1110
    pub fn window_width_less_than(&self, px: f32) -> bool {
1110
        let answer = self.window_size.dimensions.width < px;
1110
        self.record_width_query(SizeQueryOp::LessThan, px, answer)
1110
    }
    /// Returns true if the window width is greater than the given pixel value.
    /// Recorded — see the note above these helpers.
    #[must_use]
936
    pub fn window_width_greater_than(&self, px: f32) -> bool {
936
        let answer = self.window_size.dimensions.width > px;
936
        self.record_width_query(SizeQueryOp::GreaterThan, px, answer)
936
    }
    /// Returns true if the window width is between min and max (inclusive).
    /// Recorded as its two bounds — see the note above these helpers.
    #[must_use]
2016
    pub fn window_width_between(&self, min_px: f32, max_px: f32) -> bool {
2016
        let width = self.window_size.dimensions.width;
2016
        self.record_width_query(SizeQueryOp::GreaterOrEqual, min_px, width >= min_px)
2016
            & self.record_width_query(SizeQueryOp::LessOrEqual, max_px, width <= max_px)
2016
    }
    /// Returns true if the window height is less than the given pixel value.
    /// Recorded — see the note above these helpers.
    #[must_use]
107
    pub fn window_height_less_than(&self, px: f32) -> bool {
107
        let answer = self.window_size.dimensions.height < px;
107
        self.record_height_query(SizeQueryOp::LessThan, px, answer)
107
    }
    /// Returns true if the window height is greater than the given pixel value.
    /// Recorded — see the note above these helpers.
    #[must_use]
107
    pub fn window_height_greater_than(&self, px: f32) -> bool {
107
        let answer = self.window_size.dimensions.height > px;
107
        self.record_height_query(SizeQueryOp::GreaterThan, px, answer)
107
    }
    /// Returns true if the window height is between min and max (inclusive).
    /// Recorded as its two bounds — see the note above these helpers.
    #[must_use]
1011
    pub fn window_height_between(&self, min_px: f32, max_px: f32) -> bool {
1011
        let height = self.window_size.dimensions.height;
1011
        self.record_height_query(SizeQueryOp::GreaterOrEqual, min_px, height >= min_px)
1011
            & self.record_height_query(SizeQueryOp::LessOrEqual, max_px, height <= max_px)
1011
    }
    /// Returns the current window width in pixels
    #[must_use]
102
    pub const fn get_window_width(&self) -> f32 {
102
        self.window_size.dimensions.width
102
    }
    /// Returns the current window height in pixels
    #[must_use]
2
    pub const fn get_window_height(&self) -> f32 {
2
        self.window_size.dimensions.height
2
    }
    /// Returns the current window DPI scale factor (1.0 = 96 DPI, 2.0 = 192 DPI)
    #[allow(clippy::cast_precision_loss)] // bounded DPI/dimension/number conversion
    #[must_use]
6
    pub fn get_dpi_factor(&self) -> f32 {
6
        self.window_size.dpi as f32 / 96.0
6
    }
}
/// Information about the bounds of a laid-out div rectangle.
///
/// Necessary when invoking `VirtualViewCallbacks` and `RenderImageCallbacks`, so
/// that they can change what their content is based on their size.
#[derive(Debug, Copy, Clone)]
#[repr(C)]
pub struct HidpiAdjustedBounds {
    pub logical_size: LogicalSize,
    pub hidpi_factor: DpiScaleFactor,
}
impl HidpiAdjustedBounds {
    #[inline]
    #[allow(clippy::cast_precision_loss)] // bounded DPI/dimension/number conversion
    #[must_use]
20
    pub const fn from_bounds(bounds: LayoutSize, hidpi_factor: DpiScaleFactor) -> Self {
20
        let logical_size = LogicalSize::new(bounds.width as f32, bounds.height as f32);
20
        Self {
20
            logical_size,
20
            hidpi_factor,
20
        }
20
    }
    #[must_use]
13
    pub fn get_physical_size(&self) -> PhysicalSize<u32> {
13
        self.get_logical_size()
13
            .to_physical(self.get_hidpi_factor().inner.get())
13
    }
    #[must_use]
1423
    pub const fn get_logical_size(&self) -> LogicalSize {
1423
        self.logical_size
1423
    }
    #[must_use]
18
    pub const fn get_hidpi_factor(&self) -> DpiScaleFactor {
18
        self.hidpi_factor
18
    }
}
/// Defines the `focus_targeted` node ID for the next frame
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C, u8)]
pub enum FocusTarget {
    Id(DomNodeId),
    Path(FocusTargetPath),
    Previous,
    Next,
    First,
    Last,
    NoFocus,
    /// Move focus in a SPATIAL direction rather than along the tab order.
    /// APPENDED at the end for ABI stability.
    ///
    /// Tab order is a single sequence; a grid of thumbnails, a TV menu or a
    /// media-player transport row is two-dimensional, and pressing Right in
    /// one should land on the thing to the right, not on whatever happens to
    /// be next in document order.
    ///
    /// This is not really a device feature — it is a focus-engine feature that
    /// a dozen devices drive: a TV remote's D-pad, a game controller, a car's
    /// jog dial, and switch access. Android models it as a first-class input
    /// source (`SOURCE_DPAD`) and the W3C specifies it in `css-nav-1`. It
    /// needs no shell code at all: the search is geometric, over the focusable
    /// set the engine already computes.
    Directional(FocusDirection),
}
/// Which way [`FocusTarget::Directional`] should move.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub enum FocusDirection {
    Up,
    Down,
    Left,
    Right,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct FocusTargetPath {
    pub dom: DomId,
    pub css_path: CssPath,
}
// -- normal callback
// core callback types (usize-based placeholders)
//
// These types use `usize` instead of function pointers to avoid creating
// a circular dependency between azul-core and azul-layout.
//
// The actual function pointers will be stored in azul-layout, which will
// use unsafe code to transmute between usize and the real function pointers.
//
// IMPORTANT: The memory layout must be identical to the real types!
//
// Naming convention: "Core" prefix indicates these are the low-level types
/// Core callback type - uses usize instead of function pointer to avoid circular dependencies.
///
/// **IMPORTANT**: This is NOT actually a usize at runtime - it's a function pointer that is
/// cast to usize for storage in the data model. When invoking the callback, this usize is
/// unsafely cast back to the actual function pointer type:
/// `extern "C" fn(RefAny, CallbackInfo) -> Update`
///
/// This design allows azul-core to store callbacks without depending on azul-layout's
/// `CallbackInfo` type. The actual function pointer type is defined in azul-layout as
/// `CallbackType`.
pub type CoreCallbackType = usize;
/// Stores a callback as usize (actually a function pointer cast to usize)
///
/// **IMPORTANT**: The `cb` field stores a function pointer disguised as usize to avoid
/// circular dependencies between azul-core and azul-layout. When creating a `CoreCallback`,
/// you can directly assign a function pointer - Rust will implicitly cast it to usize.
/// When invoking, the usize must be unsafely cast back to the function pointer type.
///
/// Must return an `Update` that denotes if the screen should be redrawn.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct CoreCallback {
    pub cb: CoreCallbackType,
    /// For FFI: stores the foreign callable (e.g., `PyFunction`)
    /// Native Rust code sets this to None
    pub ctx: OptionRefAny,
}
/// Allow creating `CoreCallback` from a raw function pointer (as usize)
/// Sets callable to None (for native Rust/C usage)
impl From<CoreCallbackType> for CoreCallback {
1605
    fn from(cb: CoreCallbackType) -> Self {
1605
        Self {
1605
            cb,
1605
            ctx: OptionRefAny::None,
1605
        }
1605
    }
}
impl_option!(
    CoreCallback,
    OptionCoreCallback,
    [Debug, Eq, Clone, PartialEq, PartialOrd, Ord, Hash]
);
/// Data associated with a callback (event filter, callback, and user data)
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct CoreCallbackData {
    pub event: EventFilter,
    pub callback: CoreCallback,
    pub refany: RefAny,
}
impl_option!(
    CoreCallbackData,
    OptionCoreCallbackData,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);
impl_vec!(
    CoreCallbackData,
    CoreCallbackDataVec,
    CoreCallbackDataVecDestructor,
    CoreCallbackDataVecDestructorType,
    CoreCallbackDataVecSlice,
    OptionCoreCallbackData
);
impl_vec_clone!(
    CoreCallbackData,
    CoreCallbackDataVec,
    CoreCallbackDataVecDestructor
);
impl_vec_mut!(CoreCallbackData, CoreCallbackDataVec);
impl_vec_debug!(CoreCallbackData, CoreCallbackDataVec);
impl_vec_partialord!(CoreCallbackData, CoreCallbackDataVec);
impl_vec_ord!(CoreCallbackData, CoreCallbackDataVec);
impl_vec_partialeq!(CoreCallbackData, CoreCallbackDataVec);
impl_vec_eq!(CoreCallbackData, CoreCallbackDataVec);
impl_vec_hash!(CoreCallbackData, CoreCallbackDataVec);
impl CoreCallbackDataVec {
    #[inline]
    #[must_use]
5
    pub fn as_container(&self) -> NodeDataContainerRef<'_, CoreCallbackData> {
5
        NodeDataContainerRef {
5
            internal: self.as_ref(),
5
        }
5
    }
    #[inline]
2
    pub fn as_container_mut(&mut self) -> NodeDataContainerRefMut<'_, CoreCallbackData> {
2
        NodeDataContainerRefMut {
2
            internal: self.as_mut(),
2
        }
2
    }
}
// -- image rendering callback
/// Image rendering callback type - uses usize instead of function pointer
pub type CoreRenderImageCallbackType = usize;
/// Callback that returns a rendered OpenGL texture (usize placeholder)
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct CoreRenderImageCallback {
    pub cb: CoreRenderImageCallbackType,
    /// For FFI: stores the foreign callable (e.g., `PyFunction`)
    /// Native Rust code sets this to None
    pub ctx: OptionRefAny,
}
/// Allow creating `CoreRenderImageCallback` from a raw function pointer (as usize)
/// Sets callable to None (for native Rust/C usage)
impl From<CoreRenderImageCallbackType> for CoreRenderImageCallback {
168
    fn from(cb: CoreRenderImageCallbackType) -> Self {
168
        Self {
168
            cb,
168
            ctx: OptionRefAny::None,
168
        }
168
    }
}
/// Image callback with associated data
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct CoreImageCallback {
    pub refany: RefAny,
    pub callback: CoreRenderImageCallback,
}
impl_option!(
    CoreImageCallback,
    OptionCoreImageCallback,
    copy = false,
    [Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);
#[cfg(test)]
#[path = "callbacks_test.rs"]
mod callbacks_test;