azul-core 0.0.8

Common datatypes used for the Azul document object model, shared across all azul-* crates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
//! Callback types for the Azul UI framework.
//!
//! This module defines the callback infrastructure used by the event system,
//! layout engine, and virtual view rendering. Key design patterns:
//!
//! - **Core vs Layout callback split**: `CoreCallbackType` and
//!   `CoreRenderImageCallbackType` store function pointers as `usize` to avoid
//!   circular dependencies between `azul-core` and `azul-layout`. The actual
//!   function pointer types are defined in `azul-layout` and transmuted at
//!   invocation time.
//!
//! - **FFI callable pattern**: Callback structs carry an optional
//!   `ctx: OptionRefAny` field that holds a foreign callable (e.g. a Python
//!   function object). The `extern "C"` trampoline stored in `cb` extracts
//!   both the user data and the foreign callable from `RefAny` and dispatches
//!   the call. Native Rust code sets `ctx` to `None`.
//!
//! - **Info structs**: `LayoutCallbackInfo`, `VirtualViewCallbackInfo`, and
//!   the layout-side `CallbackInfo` provide read-only access to framework
//!   resources (fonts, images, GL context, window size) during callback
//!   invocation.

#[cfg(not(feature = "std"))]
use alloc::string::ToString;
use alloc::{alloc::Layout, boxed::Box, collections::BTreeMap, sync::Arc, vec::Vec};
use core::{
    ffi::c_void,
    fmt,
    sync::atomic::{AtomicUsize, Ordering as AtomicOrdering},
};
#[cfg(feature = "std")]
use std::hash::Hash;

use azul_css::{
    css::{CssPath, CssPropertyValue},
    props::{
        basic::{
            AnimationInterpolationFunction, FontRef, InterpolateResolver, LayoutRect, LayoutSize,
        },
        property::{CssProperty, CssPropertyType},
    },
    system::SystemStyle,
    AzString,
};
use rust_fontconfig::{FcFontCache, OwnedFontSource};

use crate::{
    dom::{Dom, DomId, DomNodeId, EventFilter, OptionDom},
    geom::{LogicalPosition, LogicalRect, LogicalSize, OptionLogicalPosition, PhysicalSize},
    gl::OptionGlContextPtr,
    hit_test::OverflowingScrollNode,
    id::{NodeDataContainer, NodeDataContainerRef, NodeDataContainerRefMut, NodeId},
    prop_cache::CssPropertyCache,
    refany::{OptionRefAny, RefAny},
    resources::{
        DpiScaleFactor, FontInstanceKey, IdNamespace, ImageCache, ImageMask, ImageRef,
        RendererResources,
    },
    styled_dom::{
        NodeHierarchyItemId, NodeHierarchyItemVec, StyledNode,
        StyledNodeVec,
    },
    task::{
        Duration as AzDuration, GetSystemTimeCallback, Instant as AzInstant, Instant,
        TerminateTimer, ThreadId, ThreadReceiver, ThreadSendMsg, TimerId,
    },
    window::{
        AzStringPair, KeyboardState, MouseState, OptionChar, RawWindowHandle, UpdateFocusWarning,
        WindowFlags, WindowSize, WindowTheme,
    },
    FastBTreeSet, OrderedMap,
};

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

impl Update {
    pub fn max_self(&mut self, other: Self) {
        if *self == Update::DoNothing && other != Update::DoNothing {
            *self = other;
        } else if *self == Update::RefreshDom && other == Update::RefreshDomAllWindows {
            *self = other;
        }
    }
}

// -- layout callback

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

extern "C" fn default_layout_callback(_: RefAny, _: LayoutCallbackInfo) -> crate::dom::Dom {
    crate::dom::Dom::create_body()
}

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

impl_callback!(LayoutCallback, LayoutCallbackType);

impl LayoutCallback {
    pub fn create<I: Into<Self>>(cb: I) -> Self {
        cb.into()
    }
}

// Host-invoker plumbing for managed-FFI bindings (Lua, Ruby, Perl, …):
// expands to a static `az_layout_callback_thunk` (the `cb` we hand to the
// framework when the host calls `LayoutCallback::create_from_host_handle`),
// an `AzLayoutCallback_createFromHostHandle` C-ABI export, plus the
// `AzApp_setLayoutCallbackInvoker` setter the host calls once at module
// load. See `crate::host_invoker` for the design.
crate::impl_managed_callback! {
    wrapper:        LayoutCallback,
    info_ty:        LayoutCallbackInfo,
    return_ty:      crate::dom::Dom,
    default_ret:    crate::dom::Dom::create_body(),
    invoker_static: LAYOUT_CALLBACK_INVOKER,
    invoker_ty:     AzLayoutCallbackInvoker,
    thunk_fn:       az_layout_callback_thunk,
    setter_fn:      AzApp_setLayoutCallbackInvoker,
    from_handle_fn: AzLayoutCallback_createFromHostHandle,
}

impl Default for LayoutCallback {
    fn default() -> Self {
        Self {
            cb: default_layout_callback,
            ctx: OptionRefAny::None,
        }
    }
}

// -- virtualized view callback

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

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

// Host-invoker plumbing for VirtualViewCallback. See `crate::host_invoker`.
crate::impl_managed_callback! {
    wrapper:        VirtualViewCallback,
    info_ty:        VirtualViewCallbackInfo,
    return_ty:      VirtualViewReturn,
    default_ret:    VirtualViewReturn::default(),
    invoker_static: VIRTUAL_VIEW_CALLBACK_INVOKER,
    invoker_ty:     AzVirtualViewCallbackInvoker,
    thunk_fn:       az_virtual_view_callback_thunk,
    setter_fn:      AzApp_setVirtualViewCallbackInvoker,
    from_handle_fn: AzVirtualViewCallback_createFromHostHandle,
}

impl VirtualViewCallback {
    pub fn create(cb: VirtualViewCallbackType) -> Self {
        Self {
            cb,
            ctx: OptionRefAny::None,
        }
    }
}

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

/// Which edge triggered a scroll-based re-invocation
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub enum EdgeType {
    Top,
    Bottom,
    Left,
    Right,
}

#[derive(Debug)]
#[repr(C)]
pub struct VirtualViewCallbackInfo {
    pub reason: VirtualViewCallbackReason,
    pub system_fonts: *const FcFontCache,
    pub image_cache: *const ImageCache,
    pub window_theme: WindowTheme,
    pub bounds: HidpiAdjustedBounds,
    pub scroll_size: LogicalSize,
    pub scroll_offset: LogicalPosition,
    pub virtual_scroll_size: LogicalSize,
    pub virtual_scroll_offset: LogicalPosition,
    /// Pointer to the callable (OptionRefAny) for FFI language bindings (Python, etc.)
    /// Set by the caller before invoking the callback. Native Rust callbacks have this as null.
    callable_ptr: *const OptionRefAny,
    /// Extension for future ABI stability (mutable data)
    _abi_mut: *mut c_void,
}

impl Clone for VirtualViewCallbackInfo {
    fn clone(&self) -> Self {
        Self {
            reason: self.reason,
            system_fonts: self.system_fonts,
            image_cache: self.image_cache,
            window_theme: self.window_theme,
            bounds: self.bounds,
            scroll_size: self.scroll_size,
            scroll_offset: self.scroll_offset,
            virtual_scroll_size: self.virtual_scroll_size,
            virtual_scroll_offset: self.virtual_scroll_offset,
            callable_ptr: self.callable_ptr,
            _abi_mut: self._abi_mut,
        }
    }
}

impl VirtualViewCallbackInfo {
    pub fn new<'a>(
        reason: VirtualViewCallbackReason,
        system_fonts: &'a FcFontCache,
        image_cache: &'a ImageCache,
        window_theme: WindowTheme,
        bounds: HidpiAdjustedBounds,
        scroll_size: LogicalSize,
        scroll_offset: LogicalPosition,
        virtual_scroll_size: LogicalSize,
        virtual_scroll_offset: LogicalPosition,
    ) -> Self {
        Self {
            reason,
            system_fonts: system_fonts as *const FcFontCache,
            image_cache: image_cache as *const ImageCache,
            window_theme,
            bounds,
            scroll_size,
            scroll_offset,
            virtual_scroll_size,
            virtual_scroll_offset,
            callable_ptr: core::ptr::null(),
            _abi_mut: core::ptr::null_mut(),
        }
    }

    /// Set the callable pointer for FFI language bindings
    pub fn set_callable_ptr(&mut self, callable: &OptionRefAny) {
        self.callable_ptr = callable as *const OptionRefAny;
    }

    /// Get the callable for FFI language bindings (Python, etc.)
    pub fn get_ctx(&self) -> OptionRefAny {
        if self.callable_ptr.is_null() {
            OptionRefAny::None
        } else {
            unsafe { (*self.callable_ptr).clone() }
        }
    }

    pub fn get_bounds(&self) -> HidpiAdjustedBounds {
        self.bounds
    }

    fn internal_get_system_fonts<'a>(&'a self) -> &'a FcFontCache {
        unsafe { &*self.system_fonts }
    }
    fn internal_get_image_cache<'a>(&'a self) -> &'a ImageCache {
        unsafe { &*self.image_cache }
    }
}

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

    /// Size of the actual rendered content rectangle.
    ///
    /// This is the size of the content in the `dom` field (if Some). It may be smaller than
    /// `virtual_scroll_size` if only a subset of content is rendered (virtualization).
    ///
    /// **Example**: For a table showing rows 10-30, this might be 600px tall
    /// (20 rows x 30px each).
    pub scroll_size: LogicalSize,

    /// Offset of the actual rendered content within the virtual coordinate space.
    ///
    /// This positions the rendered content within the larger virtual space. For
    /// virtualized content, this will be non-zero to indicate where the rendered
    /// "window" starts.
    ///
    /// **Example**: For a table showing rows 10-30, this might be y=300
    /// (row 10 starts 300px from the top).
    pub scroll_offset: LogicalPosition,

    /// Size of the virtual content rectangle (for scrollbar sizing).
    ///
    /// This is the size the scrollbar will represent. It can be much larger than
    /// `scroll_size` to enable lazy loading and virtualization.
    ///
    /// **Example**: For a 1000-row table, this might be 30,000px tall
    /// (1000 rows x 30px each), even though only 20 rows are actually rendered.
    pub virtual_scroll_size: LogicalSize,

    /// Offset of the virtual content (usually zero).
    ///
    /// This is typically `(0, 0)` since the virtual space usually starts at the origin.
    /// Advanced use cases might use this for complex virtualization scenarios.
    pub virtual_scroll_offset: LogicalPosition,
}

impl Default for VirtualViewReturn {
    fn default() -> VirtualViewReturn {
        VirtualViewReturn {
            dom: OptionDom::None,
            scroll_size: LogicalSize::zero(),
            scroll_offset: LogicalPosition::zero(),
            virtual_scroll_size: LogicalSize::zero(),
            virtual_scroll_offset: LogicalPosition::zero(),
        }
    }
}

impl VirtualViewReturn {
    /// Creates a new VirtualViewReturn with updated DOM content.
    ///
    /// Use this when the callback has rendered new content to display.
    ///
    /// # Arguments
    /// - `dom` - The new DOM to render
    /// - `scroll_size` - Size of the actual rendered content
    /// - `scroll_offset` - Position of rendered content in virtual space
    /// - `virtual_scroll_size` - Size for scrollbar representation
    /// - `virtual_scroll_offset` - Usually `LogicalPosition::zero()`
    pub fn with_dom(
        dom: Dom,
        scroll_size: LogicalSize,
        scroll_offset: LogicalPosition,
        virtual_scroll_size: LogicalSize,
        virtual_scroll_offset: LogicalPosition,
    ) -> Self {
        Self {
            dom: OptionDom::Some(dom),
            scroll_size,
            scroll_offset,
            virtual_scroll_size,
            virtual_scroll_offset,
        }
    }

    /// Creates a return value that keeps the current DOM unchanged.
    ///
    /// Use this when the callback determines that the existing content
    /// is sufficient (e.g., already rendered ahead of scroll position).
    /// This is an optimization to avoid rebuilding the DOM unnecessarily.
    ///
    /// # Arguments
    /// - `scroll_size` - Size of the current rendered content
    /// - `scroll_offset` - Position of current content in virtual space
    /// - `virtual_scroll_size` - Size for scrollbar representation
    /// - `virtual_scroll_offset` - Usually `LogicalPosition::zero()`
    pub fn keep_current(
        scroll_size: LogicalSize,
        scroll_offset: LogicalPosition,
        virtual_scroll_size: LogicalSize,
        virtual_scroll_offset: LogicalPosition,
    ) -> Self {
        Self {
            dom: OptionDom::None,
            scroll_size,
            scroll_offset,
            virtual_scroll_size,
            virtual_scroll_offset,
        }
    }

}

// --  thread callback

// -- timer callback

#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct TimerCallbackReturn {
    pub should_update: Update,
    pub should_terminate: TerminateTimer,
}

impl TimerCallbackReturn {
    /// Creates a new TimerCallbackReturn with the given update and terminate flags.
    pub fn create(should_update: Update, should_terminate: TerminateTimer) -> Self {
        Self {
            should_update,
            should_terminate,
        }
    }

    /// Timer continues running, no DOM update needed.
    pub fn continue_unchanged() -> Self {
        Self {
            should_update: Update::DoNothing,
            should_terminate: TerminateTimer::Continue,
        }
    }

    /// Timer continues running and DOM should be refreshed.
    pub fn continue_and_refresh_dom() -> Self {
        Self {
            should_update: Update::RefreshDom,
            should_terminate: TerminateTimer::Continue,
        }
    }

    /// Timer should stop, no DOM update needed.
    pub fn terminate_unchanged() -> Self {
        Self {
            should_update: Update::DoNothing,
            should_terminate: TerminateTimer::Terminate,
        }
    }

    /// Timer should stop and DOM should be refreshed.
    pub fn terminate_and_refresh_dom() -> Self {
        Self {
            should_update: Update::RefreshDom,
            should_terminate: TerminateTimer::Terminate,
        }
    }
}

impl Default for TimerCallbackReturn {
    fn default() -> Self {
        Self::continue_unchanged()
    }
}

/// Gives the `layout()` function access to the `RendererResources` and the `Window`
/// (for querying images and fonts, as well as width / height)
#[derive(Debug)]
#[repr(C)]
/// Reference data container for LayoutCallbackInfo (all read-only fields)
///
/// This struct consolidates all readonly references that layout callbacks need to query state.
/// By grouping these into a single struct, we reduce the number of parameters to
/// LayoutCallbackInfo::new() from 6 to 2, making the API more maintainable and easier to extend.
///
/// This is pure syntax sugar - the struct lives on the stack in the caller and is passed by
/// reference.
pub struct LayoutCallbackInfoRefData<'a> {
    /// Allows the layout() function to reference image IDs
    pub image_cache: &'a ImageCache,
    /// OpenGL context so that the layout() function can render textures
    pub gl_context: &'a OptionGlContextPtr,
    /// Reference to the system font cache
    pub system_fonts: &'a FcFontCache,
    /// Platform-specific system style (colors, spacing, etc.)
    /// Used for CSD rendering and menu windows.
    pub system_style: Arc<SystemStyle>,
    /// Active route match (if routing is configured).
    /// Contains the matched pattern and extracted parameters.
    pub active_route: Option<&'a crate::resources::RouteMatch>,
}

/// What triggered the current `layout()` invocation.
///
/// The framework re-invokes the layout callback for any change that may
/// produce a structurally different DOM (resize across a CSS breakpoint,
/// theme toggle, route switch, callback returning `Update::RefreshDom`).
/// `LayoutCallbackInfo::relayout_reason()` exposes which trigger this
/// particular call corresponds to so the callback can branch — for
/// example, skip expensive analytics on `Resize` calls.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub enum RelayoutReason {
    /// First layout call for this window.
    Initial,
    /// A user callback returned `Update::RefreshDom`.
    RefreshDom,
    /// Window size changed across a CSS breakpoint or DPI scale change.
    /// The callback can branch on `info.window_width_*` to emit a
    /// different tree (e.g. hamburger menu vs sidebar).
    Resize,
    /// System theme changed (light/dark).
    ThemeChange,
    /// `CallbackInfo::switch_route` or `set_route_param` produced a new
    /// route match. The callback should branch on
    /// `info.get_active_route()`.
    RouteChange,
    /// Catch-all for relayouts that don't fit one of the above categories.
    Other,
}

impl Default for RelayoutReason {
    fn default() -> Self { RelayoutReason::Initial }
}

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

impl Clone for LayoutCallbackInfo {
    fn clone(&self) -> Self {
        Self {
            ref_data: self.ref_data,
            window_size: self.window_size,
            theme: self.theme,
            relayout_reason: self.relayout_reason,
            callable_ptr: self.callable_ptr,
            _abi_mut: self._abi_mut,
        }
    }
}

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 {
    pub fn new<'a>(
        ref_data: &'a LayoutCallbackInfoRefData<'a>,
        window_size: WindowSize,
        theme: WindowTheme,
    ) -> Self {
        Self::new_with_reason(ref_data, window_size, theme, RelayoutReason::Initial)
    }

    pub fn new_with_reason<'a>(
        ref_data: &'a LayoutCallbackInfoRefData<'a>,
        window_size: WindowSize,
        theme: WindowTheme,
        relayout_reason: RelayoutReason,
    ) -> Self {
        Self {
            // SAFETY: We cast away the lifetime 'a to 'static because LayoutCallbackInfo
            // only lives for the duration of the callback, which is shorter than 'a
            ref_data: ref_data as *const LayoutCallbackInfoRefData<'a>
                as *const LayoutCallbackInfoRefData<'static>,
            window_size,
            theme,
            relayout_reason,
            callable_ptr: core::ptr::null(),
            _abi_mut: core::ptr::null_mut(),
        }
    }

    /// Returns what triggered the current `layout()` invocation.
    pub fn relayout_reason(&self) -> RelayoutReason {
        self.relayout_reason
    }

    /// Set the callable pointer for FFI language bindings
    pub fn set_callable_ptr(&mut self, callable: &OptionRefAny) {
        self.callable_ptr = callable as *const OptionRefAny;
    }

    /// Get the callable for FFI language bindings (Python, etc.)
    pub fn get_ctx(&self) -> OptionRefAny {
        if self.callable_ptr.is_null() {
            OptionRefAny::None
        } else {
            unsafe { (*self.callable_ptr).clone() }
        }
    }

    /// Get a clone of the system style Arc
    pub fn get_system_style(&self) -> Arc<SystemStyle> {
        unsafe { (*self.ref_data).system_style.clone() }
    }

    fn internal_get_image_cache<'a>(&'a self) -> &'a ImageCache {
        unsafe { (*self.ref_data).image_cache }
    }
    fn internal_get_system_fonts<'a>(&'a self) -> &'a FcFontCache {
        unsafe { (*self.ref_data).system_fonts }
    }
    fn internal_get_gl_context<'a>(&'a self) -> &'a OptionGlContextPtr {
        unsafe { (*self.ref_data).gl_context }
    }

    pub fn get_gl_context(&self) -> OptionGlContextPtr {
        self.internal_get_gl_context().clone()
    }

    pub fn get_system_fonts(&self) -> Vec<AzStringPair> {
        let fc_cache = self.internal_get_system_fonts();

        fc_cache
            .list()
            .into_iter()
            .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.clone())),
                }
            })
            .map(|(k, v)| AzStringPair {
                key: k.into(),
                value: v.into(),
            })
            .collect()
    }

    pub fn get_image(&self, image_id: &AzString) -> Option<ImageRef> {
        self.internal_get_image_cache()
            .get_css_image_id(image_id)
            .cloned()
    }

    /// Get the active route match (pattern + extracted parameters).
    ///
    /// Returns `None` if no routes are configured or no route is active.
    pub fn get_active_route(&self) -> Option<&crate::resources::RouteMatch> {
        unsafe { (*self.ref_data).active_route }
    }

    /// 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.
    pub fn get_route_param(&self, key: &str) -> Option<&AzString> {
        self.get_active_route()?.get_param(key)
    }

    // Responsive layout helper methods
    /// Returns true if the window width is less than the given pixel value
    pub fn window_width_less_than(&self, px: f32) -> bool {
        self.window_size.dimensions.width < px
    }

    /// Returns true if the window width is greater than the given pixel value
    pub fn window_width_greater_than(&self, px: f32) -> bool {
        self.window_size.dimensions.width > px
    }

    /// Returns true if the window width is between min and max (inclusive)
    pub fn window_width_between(&self, min_px: f32, max_px: f32) -> bool {
        let width = self.window_size.dimensions.width;
        width >= min_px && width <= max_px
    }

    /// Returns true if the window height is less than the given pixel value
    pub fn window_height_less_than(&self, px: f32) -> bool {
        self.window_size.dimensions.height < px
    }

    /// Returns true if the window height is greater than the given pixel value
    pub fn window_height_greater_than(&self, px: f32) -> bool {
        self.window_size.dimensions.height > px
    }

    /// Returns true if the window height is between min and max (inclusive)
    pub fn window_height_between(&self, min_px: f32, max_px: f32) -> bool {
        let height = self.window_size.dimensions.height;
        height >= min_px && height <= max_px
    }

    /// Returns the current window width in pixels
    pub fn get_window_width(&self) -> f32 {
        self.window_size.dimensions.width
    }

    /// Returns the current window height in pixels
    pub fn get_window_height(&self) -> f32 {
        self.window_size.dimensions.height
    }

    /// Returns the current window DPI scale factor (1.0 = 96 DPI, 2.0 = 192 DPI)
    pub fn get_dpi_factor(&self) -> f32 {
        self.window_size.dpi as f32 / 96.0
    }
}

/// 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(always)]
    pub fn from_bounds(bounds: LayoutSize, hidpi_factor: DpiScaleFactor) -> Self {
        let logical_size = LogicalSize::new(bounds.width as f32, bounds.height as f32);
        Self {
            logical_size,
            hidpi_factor,
        }
    }

    pub fn get_physical_size(&self) -> PhysicalSize<u32> {
        self.get_logical_size()
            .to_physical(self.get_hidpi_factor().inner.get())
    }

    pub fn get_logical_size(&self) -> LogicalSize {
        self.logical_size
    }

    pub fn get_hidpi_factor(&self) -> DpiScaleFactor {
        self.hidpi_factor
    }
}

/// 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,
}

#[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 {
    fn from(cb: CoreCallbackType) -> Self {
        CoreCallback {
            cb,
            ctx: OptionRefAny::None,
        }
    }
}

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]
    pub fn as_container<'a>(&'a self) -> NodeDataContainerRef<'a, CoreCallbackData> {
        NodeDataContainerRef {
            internal: self.as_ref(),
        }
    }
    #[inline]
    pub fn as_container_mut<'a>(&'a mut self) -> NodeDataContainerRefMut<'a, CoreCallbackData> {
        NodeDataContainerRefMut {
            internal: self.as_mut(),
        }
    }
}

// -- 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 {
    fn from(cb: CoreRenderImageCallbackType) -> Self {
        CoreRenderImageCallback {
            cb,
            ctx: OptionRefAny::None,
        }
    }
}

/// 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]
);