astrelis-ui 0.2.4

UI Framework designed for Astrelis Game Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
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
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
//! Astrelis UI - Taffy-based UI system with WGPU rendering
//!
//! This crate provides a flexible UI system built on Taffy layout engine:
//! - Declarative widget API
//! - Flexbox and Grid layouts via Taffy
//! - GPU-accelerated rendering
//! - Event handling system
//! - Composable widget tree
//!
//! ## Quick Start
//!
//! ```rust,no_run
//! # use astrelis_ui::UiSystem;
//! # use astrelis_render::{Color, GraphicsContext};
//! # let graphics_context = GraphicsContext::new_owned_sync().expect("Failed to create graphics context");
//! let mut ui = UiSystem::new(graphics_context);
//!
//! ui.build(|root| {
//!     root.container()
//!         .width(800.0)
//!         .height(600.0)
//!         .padding(20.0)
//!         .child(|container| {
//!             container.text("Hello, World!")
//!                 .size(24.0)
//!                 .color(Color::WHITE)
//!                 .build();
//!             container.button("Click Me").build();
//!             container.container().build()
//!         })
//!         .build();
//! });
//!
//! // In render loop:
//! // ui.update(delta_time);
//! // ui.handle_events(&mut event_batch);
//! // ui.render(&mut render_pass, viewport_size);
//! ```
//!
//! ## API Conventions
//!
//! This crate follows consistent method naming conventions:
//!
//! ### Mutation Methods
//! - **`set_*()`** - Full replacement that may trigger complete rebuild/re-layout
//!   - Example: `set_text()` replaces text and triggers text shaping
//! - **`update_*()`** - Incremental update optimized with dirty flags
//!   - Example: `update_text()` only marks TEXT_SHAPING dirty, skipping layout
//! - **`add_*()`** - Append to a collection
//!   - Example: `add_widget()` appends to widget tree
//!
//! ### Accessor Methods
//! - **`get_*()`** - Returns `Option<&T>` for possibly-missing values
//!   - Example: `get_widget(id)` returns `Option<&Widget>`
//! - **`*()` (no prefix)** - Returns `&T`, panics if unavailable (use when required)
//!   - Example: `widget(id)` returns `&Widget` or panics
//! - **`try_*()`** - Fallible operation returning `Result`
//!   - Example: `try_layout()` returns `Result<(), LayoutError>`
//! - **`has_*()`** - Boolean check for existence
//!   - Example: `has_widget(id)` returns `bool`
//!
//! ### Computation Methods
//! - **`compute_*()`** - Expensive computation (results often cached)
//!   - Example: `compute_layout()` runs Taffy layout solver
//! - **`calculate_*()`** - Mathematical calculation
//!   - Example: `calculate_bounds()` computes widget bounds
//!
//! ### Builder Methods
//! - **`with_*(value)`** - Builder method returning `Self` for chaining
//!   - Example: `with_padding(20.0)` sets padding and returns builder
//! - **`build()`** - Finalizes builder and consumes it
//!   - Example: `widget.build()` adds widget to tree

pub mod animation;
pub mod builder;
pub mod clip;
pub mod constraint;
pub mod constraint_builder;
pub mod constraint_resolver;
pub mod culling;
pub mod debug;
pub mod dirty;
pub mod draw_list;
pub mod event;
pub mod focus;
pub mod glyph_atlas;
pub mod gpu_types;
pub mod inspector;
pub mod instance_buffer;
pub mod layout;
pub mod layout_engine;
pub mod length;
pub mod menu;
pub mod metrics;
pub mod metrics_collector;
pub mod middleware;
pub mod overlay;
pub mod plugin;
pub mod renderer;
pub mod scroll_plugin;
pub mod style;
pub use style::{Overflow, PointerEvents};
pub mod theme;
pub mod tooltip;
pub mod tree;
pub mod viewport_context;
pub mod virtual_scroll;
pub mod widget_id;
pub mod widgets;

pub use animation::{
    AnimatableProperty, Animation, AnimationState, AnimationSystem, EasingFunction,
    WidgetAnimations, bounce, fade_in, fade_out, scale, slide_in_left, slide_in_top, translate_x,
    translate_y,
};
use astrelis_core::geometry::Size;
pub use clip::{ClipRect, PhysicalClipRect};
pub use debug::DebugOverlay;
pub use dirty::{DirtyFlags, DirtyRanges, Versioned};
pub use draw_list::{DrawCommand, DrawList, ImageCommand, QuadCommand, RenderLayer, TextCommand};
pub use glyph_atlas::{
    GlyphBatch, atlas_entry_uv_coords, create_glyph_batches, glyph_to_instance, glyphs_to_instances,
};
pub use gpu_types::{ImageInstance, QuadInstance, QuadVertex, TextInstance};
pub use instance_buffer::InstanceBuffer;
pub use length::{Length, LengthAuto, LengthPercentage, auto, length, percent, vh, vmax, vmin, vw};
use std::sync::Arc;
// Re-export constraint system for advanced responsive layouts
pub use astrelis_render::ImageSampling;
pub use astrelis_text::{SyncTextShaper, TextPipeline, TextShapeRequest, TextShaper};
pub use constraint::{CalcExpr, Constraint};
pub use constraint_builder::{calc, clamp, max_of, max2, min_of, min2, px};
pub use constraint_resolver::{ConstraintResolver, ResolveContext};
pub use metrics::UiMetrics;
pub use viewport_context::ViewportContext;
pub use widget_id::{WidgetId, WidgetIdRegistry};
pub use widgets::{HScrollbar, ScrollbarOrientation, ScrollbarTheme, VScrollbar};
pub use widgets::{Image, ImageFit, ImageTexture, ImageUV};
pub use widgets::{ScrollAxis, ScrollContainer, ScrollbarVisibility};

// Re-export main types
pub use builder::{
    ContainerNodeBuilder,
    // Legacy aliases
    ImageBuilder,
    IntoNodeBuilder,
    LeafNodeBuilder,
    UiBuilder,
    WidgetBuilder,
};
#[cfg(feature = "docking")]
pub use builder::{DockSplitterNodeBuilder, DockTabsNodeBuilder};
pub use event::{UiEvent, UiEventSystem};
pub use focus::{FocusDirection, FocusEvent, FocusManager, FocusPolicy, FocusScopeId};
pub use layout::LayoutCache;
pub use renderer::UiRenderer;
pub use style::Style;
pub use theme::{ColorPalette, ColorRole, Shapes, Spacing, Theme, ThemeBuilder, Typography};
pub use tree::{NodeId, UiTree};
pub use widgets::Widget;

// Re-export new architecture modules
pub use culling::{AABB, CullingStats, CullingTree};
pub use inspector::{
    EditableProperty, InspectorConfig, InspectorGraphs, PropertyEditor, SearchState, TreeViewState,
    UiInspector, WidgetIdRegistryExt, WidgetKind,
};
pub use layout_engine::{LayoutEngine, LayoutMode, LayoutRequest};
pub use menu::{ContextMenu, MenuBar, MenuItem, MenuStyle};
pub use metrics_collector::{
    FrameTimingMetrics, MemoryMetrics, MetricsCollector, MetricsConfig, PerformanceWarning,
    WidgetMetrics,
};
pub use middleware::{
    InspectorMiddleware, Keybind, KeybindRegistry, MiddlewareContext, MiddlewareManager, Modifiers,
    OverlayContext, OverlayDrawList, OverlayRenderer, UiMiddleware,
};
pub use overlay::{
    AnchorAlignment, Overlay, OverlayConfig, OverlayId, OverlayManager, OverlayPosition, ZLayer,
};
pub use tooltip::{TooltipConfig, TooltipContent, TooltipManager, TooltipPosition};
pub use virtual_scroll::{
    ItemHeight, MountedItem, VirtualScrollConfig, VirtualScrollState, VirtualScrollStats,
    VirtualScrollUpdate, VirtualScrollView,
};

// Docking system re-exports
#[cfg(feature = "docking")]
pub use widgets::docking::{
    DRAG_THRESHOLD, DockSplitter, DockTabs, DockZone, DockingStyle, DragManager, DragState,
    DragType, PanelConstraints, SplitDirection, TabScrollIndicator, TabScrollbarPosition,
};

// Plugin system re-exports
pub use plugin::{
    CorePlugin, PluginHandle, PluginManager, TraversalBehavior, UiPlugin, WidgetOverflow,
    WidgetRenderContext, WidgetTypeDescriptor, WidgetTypeRegistry,
};

// Re-export common types from dependencies
pub use astrelis_core::math::{Vec2, Vec4};
pub use astrelis_render::Color;
pub use taffy::{
    AlignContent, AlignItems, Display, FlexDirection, FlexWrap, JustifyContent, Position,
};

use astrelis_core::profiling::profile_function;
use astrelis_render::{GraphicsContext, RenderWindow, Viewport};
use astrelis_winit::event::EventBatch;

// Re-export renderer descriptor for advanced configuration
pub use renderer::{UiRendererBuilder, UiRendererDescriptor};

/// Render-agnostic UI core managing tree, layout, and logic.
///
/// This is the inner layer that doesn't depend on graphics context.
/// Use this for benchmarks, tests, and headless UI processing.
pub struct UiCore {
    tree: UiTree,
    event_system: UiEventSystem,
    plugin_manager: PluginManager,
    viewport_size: Size<f32>,
    widget_registry: WidgetIdRegistry,
    viewport: Viewport,
    theme: Theme,
}

impl UiCore {
    /// Create a new render-agnostic UI core.
    ///
    /// Automatically adds [`CorePlugin`] and [`ScrollPlugin`](scroll_plugin::ScrollPlugin)
    /// to register all built-in widget types.
    /// When the `docking` feature is enabled, also adds [`DockingPlugin`](widgets::docking::plugin::DockingPlugin).
    pub fn new() -> Self {
        let mut plugin_manager = PluginManager::new();
        plugin_manager.add_plugin(CorePlugin);
        plugin_manager.add_plugin(scroll_plugin::ScrollPlugin::new());
        #[cfg(feature = "docking")]
        plugin_manager.add_plugin(widgets::docking::plugin::DockingPlugin::new());

        Self {
            tree: UiTree::new(),
            event_system: UiEventSystem::new(),
            plugin_manager,
            viewport_size: Size::new(800.0, 600.0),
            widget_registry: WidgetIdRegistry::new(),
            viewport: Viewport::default(),
            theme: Theme::dark(),
        }
    }

    /// Build the UI tree using a declarative builder API.
    pub fn build<F>(&mut self, build_fn: F)
    where
        F: FnOnce(&mut UiBuilder),
    {
        self.widget_registry.clear();
        let mut builder = UiBuilder::new(&mut self.tree, &mut self.widget_registry);
        build_fn(&mut builder);
        builder.finish();
    }

    /// Set the viewport size for layout calculations.
    ///
    /// When the viewport size changes, any constraints using viewport units
    /// (vw, vh, vmin, vmax) or complex expressions will be automatically
    /// re-resolved during the next layout computation.
    pub fn set_viewport(&mut self, viewport: Viewport) {
        let new_size = viewport.to_logical().into();
        let size_changed = self.viewport_size != new_size;

        self.viewport_size = new_size;
        self.viewport = viewport;

        // If size changed, mark viewport-constrained nodes as dirty
        if size_changed {
            self.tree.mark_viewport_dirty();
        }
    }

    /// Get the current viewport size.
    pub fn viewport_size(&self) -> Size<f32> {
        self.viewport_size
    }

    /// Compute layout without font rendering (uses approximate text sizing).
    pub fn compute_layout(&mut self) {
        #[cfg(feature = "docking")]
        {
            let padding = self
                .plugin_manager
                .get::<widgets::docking::plugin::DockingPlugin>()
                .map(|p| p.docking_context.style().content_padding)
                .unwrap_or(0.0);
            self.tree.set_docking_content_padding(padding);
        }
        let widget_registry = self.plugin_manager.widget_registry();
        self.tree
            .compute_layout(self.viewport_size, None, widget_registry);
        // Invalidate docking cache so stale layout coordinates are refreshed
        #[cfg(feature = "docking")]
        if let Some(dp) = self
            .plugin_manager
            .get_mut::<widgets::docking::plugin::DockingPlugin>()
        {
            dp.invalidate_cache();
        }
    }

    /// Run plugin post-layout hooks.
    ///
    /// This dispatches `post_layout` to all registered plugins, allowing them to
    /// perform custom post-processing (e.g., ScrollPlugin updating content/viewport sizes).
    pub fn run_post_layout_plugins(&mut self) {
        self.plugin_manager.post_layout(&mut self.tree);
    }

    /// Compute layout with instrumentation for performance metrics.
    pub fn compute_layout_instrumented(&mut self) -> UiMetrics {
        let widget_registry = self.plugin_manager.widget_registry();
        let metrics =
            self.tree
                .compute_layout_instrumented(self.viewport_size, None, widget_registry);
        #[cfg(feature = "docking")]
        if let Some(dp) = self
            .plugin_manager
            .get_mut::<widgets::docking::plugin::DockingPlugin>()
        {
            dp.invalidate_cache();
        }
        metrics
    }

    /// Get the node ID for a widget ID.
    pub fn get_node_id(&self, widget_id: WidgetId) -> Option<NodeId> {
        self.widget_registry.get_node(widget_id)
    }

    /// Register a widget ID to node ID mapping.
    pub fn register_widget(&mut self, widget_id: WidgetId, node_id: NodeId) {
        self.widget_registry.register(widget_id, node_id);
    }

    /// Update text content of a Text widget by ID with automatic dirty marking.
    ///
    /// Returns true if the content changed.
    pub fn update_text(&mut self, widget_id: WidgetId, new_content: impl Into<String>) -> bool {
        if let Some(node_id) = self.widget_registry.get_node(widget_id) {
            self.tree.update_text_content(node_id, new_content)
        } else {
            false
        }
    }

    /// Update button label by ID with automatic dirty marking.
    ///
    /// Returns true if the label changed.
    pub fn update_button_label(
        &mut self,
        widget_id: WidgetId,
        new_label: impl Into<String>,
    ) -> bool {
        if let Some(node_id) = self.widget_registry.get_node(widget_id)
            && let Some(node) = self.tree.get_node_mut(node_id)
            && let Some(button) = node.widget.as_any_mut().downcast_mut::<widgets::Button>()
        {
            let changed = button.set_label(new_label);
            if changed {
                self.tree
                    .mark_dirty_flags(node_id, DirtyFlags::TEXT_SHAPING);
            }
            return changed;
        }
        false
    }

    /// Update text input value by ID with automatic dirty marking.
    ///
    /// Returns true if the value changed.
    pub fn update_text_input(&mut self, widget_id: WidgetId, new_value: impl Into<String>) -> bool {
        if let Some(node_id) = self.widget_registry.get_node(widget_id)
            && let Some(node) = self.tree.get_node_mut(node_id)
            && let Some(input) = node
                .widget
                .as_any_mut()
                .downcast_mut::<widgets::TextInput>()
        {
            let changed = input.set_value(new_value);
            if changed {
                self.tree
                    .mark_dirty_flags(node_id, DirtyFlags::TEXT_SHAPING);
            }
            return changed;
        }
        false
    }

    /// Update widget color by ID with automatic dirty marking.
    ///
    /// Returns true if the color changed.
    pub fn update_color(&mut self, widget_id: WidgetId, color: astrelis_render::Color) -> bool {
        if let Some(node_id) = self.widget_registry.get_node(widget_id) {
            self.tree.update_color(node_id, color)
        } else {
            false
        }
    }

    /// Update widget opacity by ID with automatic dirty marking.
    ///
    /// Opacity is inherited: `computed_opacity = parent_opacity * node_opacity`.
    /// Returns true if the value changed.
    pub fn update_opacity(&mut self, widget_id: WidgetId, opacity: f32) -> bool {
        if let Some(node_id) = self.widget_registry.get_node(widget_id) {
            self.tree.update_opacity(node_id, opacity)
        } else {
            false
        }
    }

    /// Update widget visual translation by ID with automatic dirty marking.
    ///
    /// Translation is visual-only (does not affect layout).
    /// Returns true if the value changed.
    pub fn update_translate(&mut self, widget_id: WidgetId, translate: Vec2) -> bool {
        if let Some(node_id) = self.widget_registry.get_node(widget_id) {
            self.tree.update_translate(node_id, translate)
        } else {
            false
        }
    }

    /// Update widget visual X translation by ID.
    pub fn update_translate_x(&mut self, widget_id: WidgetId, x: f32) -> bool {
        if let Some(node_id) = self.widget_registry.get_node(widget_id) {
            self.tree.update_translate_x(node_id, x)
        } else {
            false
        }
    }

    /// Update widget visual Y translation by ID.
    pub fn update_translate_y(&mut self, widget_id: WidgetId, y: f32) -> bool {
        if let Some(node_id) = self.widget_registry.get_node(widget_id) {
            self.tree.update_translate_y(node_id, y)
        } else {
            false
        }
    }

    /// Update widget visual scale by ID.
    pub fn update_scale(&mut self, widget_id: WidgetId, scale: Vec2) -> bool {
        if let Some(node_id) = self.widget_registry.get_node(widget_id) {
            self.tree.update_scale(node_id, scale)
        } else {
            false
        }
    }

    /// Update widget visual X scale by ID.
    pub fn update_scale_x(&mut self, widget_id: WidgetId, x: f32) -> bool {
        if let Some(node_id) = self.widget_registry.get_node(widget_id) {
            self.tree.update_scale_x(node_id, x)
        } else {
            false
        }
    }

    /// Update widget visual Y scale by ID.
    pub fn update_scale_y(&mut self, widget_id: WidgetId, y: f32) -> bool {
        if let Some(node_id) = self.widget_registry.get_node(widget_id) {
            self.tree.update_scale_y(node_id, y)
        } else {
            false
        }
    }

    /// Set widget visibility by ID.
    ///
    /// When `false`, collapses from layout (like CSS `display: none`).
    /// Returns true if the value changed.
    pub fn set_visible(&mut self, widget_id: WidgetId, visible: bool) -> bool {
        if let Some(node_id) = self.widget_registry.get_node(widget_id) {
            self.tree.set_visible(node_id, visible)
        } else {
            false
        }
    }

    /// Toggle widget visibility by ID.
    ///
    /// Returns true if the value changed.
    pub fn toggle_visible(&mut self, widget_id: WidgetId) -> bool {
        if let Some(node_id) = self.widget_registry.get_node(widget_id) {
            self.tree.toggle_visible(node_id)
        } else {
            false
        }
    }

    /// Get mutable access to the tree.
    pub fn tree_mut(&mut self) -> &mut UiTree {
        &mut self.tree
    }

    /// Get reference to the tree.
    pub fn tree(&self) -> &UiTree {
        &self.tree
    }

    /// Get reference to the event system.
    pub fn events(&self) -> &UiEventSystem {
        &self.event_system
    }

    /// Get mutable access to the event system.
    pub fn event_system_mut(&mut self) -> &mut UiEventSystem {
        &mut self.event_system
    }

    /// Get reference to the widget registry.
    pub fn widget_registry(&self) -> &WidgetIdRegistry {
        &self.widget_registry
    }

    /// Set the theme, marking all widget colors dirty.
    pub fn set_theme(&mut self, theme: Theme) {
        self.theme = theme;
        self.tree.mark_all_dirty(DirtyFlags::COLOR);
    }

    /// Get a reference to the current theme.
    pub fn theme(&self) -> &Theme {
        &self.theme
    }

    /// Get a reference to the docking style.
    #[cfg(feature = "docking")]
    pub fn docking_style(&self) -> &widgets::docking::DockingStyle {
        self.plugin_manager
            .get::<widgets::docking::plugin::DockingPlugin>()
            .expect("DockingPlugin is auto-added when docking feature is enabled")
            .docking_context
            .style()
    }

    /// Replace the docking style.
    #[cfg(feature = "docking")]
    pub fn set_docking_style(&mut self, style: widgets::docking::DockingStyle) {
        self.plugin_manager
            .get_mut::<widgets::docking::plugin::DockingPlugin>()
            .expect("DockingPlugin is auto-added when docking feature is enabled")
            .docking_context
            .set_style(style);
    }

    /// Add a plugin to the UI core and return a handle for typed access.
    ///
    /// The plugin's widget types are registered immediately.
    ///
    /// # Panics
    ///
    /// Panics if a plugin of the same concrete type is already registered.
    pub fn add_plugin<P: UiPlugin>(&mut self, plugin: P) -> PluginHandle<P> {
        self.plugin_manager.add_plugin(plugin)
    }

    /// Get a handle for an already-registered plugin.
    ///
    /// Returns `Some(PluginHandle)` if the plugin is registered, `None` otherwise.
    /// Useful for obtaining handles to auto-registered plugins.
    pub fn plugin_handle<P: UiPlugin>(&self) -> Option<PluginHandle<P>> {
        self.plugin_manager.handle::<P>()
    }

    /// Get a reference to a registered plugin by type, using a handle as proof.
    pub fn plugin<P: UiPlugin>(&self, _handle: &PluginHandle<P>) -> &P {
        self.plugin_manager
            .get::<P>()
            .expect("plugin handle guarantees registration")
    }

    /// Get a mutable reference to a registered plugin by type, using a handle as proof.
    pub fn plugin_mut<P: UiPlugin>(&mut self, _handle: &PluginHandle<P>) -> &mut P {
        self.plugin_manager
            .get_mut::<P>()
            .expect("plugin handle guarantees registration")
    }

    /// Get a reference to the plugin manager.
    pub fn plugin_manager(&self) -> &PluginManager {
        &self.plugin_manager
    }

    /// Get a mutable reference to the plugin manager.
    pub fn plugin_manager_mut(&mut self) -> &mut PluginManager {
        &mut self.plugin_manager
    }

    /// Handle events from the event batch.
    pub fn handle_events(&mut self, events: &mut EventBatch) {
        self.event_system.handle_events_with_plugins(
            events,
            &mut self.tree,
            &mut self.plugin_manager,
        );
    }
}

impl Default for UiCore {
    fn default() -> Self {
        Self::new()
    }
}

/// Main UI system managing tree, layout, rendering, and events.
///
/// This wraps UiCore and adds rendering capabilities.
pub struct UiSystem {
    core: UiCore,
    renderer: UiRenderer,
}

impl UiSystem {
    /// Create a new UI system with default configuration (no depth testing).
    ///
    /// **Warning:** This creates a renderer without depth testing. If your render pass
    /// has a depth attachment, use [`from_window`](Self::from_window) instead to ensure
    /// pipeline-renderpass compatibility.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use astrelis_ui::UiSystem;
    /// # use astrelis_render::GraphicsContext;
    /// // For simple use without depth testing
    /// let graphics = GraphicsContext::new_owned_sync().expect("Failed to create graphics context");
    /// let ui = UiSystem::new(graphics);
    /// ```
    pub fn new(context: Arc<GraphicsContext>) -> Self {
        profile_function!();
        Self {
            core: UiCore::new(),
            renderer: UiRenderer::new(context),
        }
    }

    /// Create a new UI system configured for a specific window.
    ///
    /// This is the **recommended** constructor as it ensures the renderer's pipelines
    /// are compatible with the window's render pass configuration (surface format
    /// and depth format).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use astrelis_ui::UiSystem;
    /// # use astrelis_render::{GraphicsContext, RenderWindow, RenderWindowBuilder};
    /// # use astrelis_winit::window::Window;
    /// # fn example(winit_window: Window) {
    /// let graphics = GraphicsContext::new_owned_sync().expect("Failed to create graphics context");
    ///
    /// // Create window with depth buffer
    /// let window = RenderWindowBuilder::new()
    ///     .with_depth_default()
    ///     .build(winit_window, graphics.clone())
    ///     .expect("Failed to create window");
    ///
    /// // UI automatically uses matching formats
    /// let ui = UiSystem::from_window(graphics, &window);
    /// # }
    /// ```
    pub fn from_window(context: Arc<GraphicsContext>, window: &RenderWindow) -> Self {
        profile_function!();
        Self {
            core: UiCore::new(),
            renderer: UiRenderer::from_window(context, window),
        }
    }

    /// Create a new UI system with explicit configuration.
    ///
    /// Use this when you need full control over the renderer configuration,
    /// or when the target is not a `RenderWindow`.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use astrelis_ui::{UiSystem, UiRendererDescriptor};
    /// # use astrelis_render::{GraphicsContext, wgpu};
    /// let graphics = GraphicsContext::new_owned_sync().expect("Failed to create graphics context");
    ///
    /// let desc = UiRendererDescriptor {
    ///     name: "Game HUD".to_string(),
    ///     surface_format: wgpu::TextureFormat::Bgra8UnormSrgb,
    ///     depth_format: Some(wgpu::TextureFormat::Depth32Float),
    /// };
    ///
    /// let ui = UiSystem::with_descriptor(graphics, desc);
    /// ```
    pub fn with_descriptor(
        context: Arc<GraphicsContext>,
        descriptor: UiRendererDescriptor,
    ) -> Self {
        profile_function!();
        Self {
            core: UiCore::new(),
            renderer: UiRenderer::with_descriptor(context, descriptor),
        }
    }

    /// Build the UI tree using a declarative builder API.
    ///
    /// Note: This does a full rebuild. For incremental updates, use update methods.
    pub fn build<F>(&mut self, build_fn: F)
    where
        F: FnOnce(&mut UiBuilder),
    {
        // Clear the draw list since we're rebuilding the tree
        // This prevents stale draw commands from accumulating
        self.renderer.clear_draw_list();
        self.core.build(build_fn);
    }

    /// Update UI state (animations, hover, etc.).
    ///
    /// Note: This no longer marks the entire tree dirty - only changed widgets are marked.
    pub fn update(&mut self, delta_time: f32) {
        // Update plugin animations (docking ghost tabs, panel transitions, etc.)
        #[cfg(feature = "docking")]
        if let Some(dp) = self
            .core
            .plugin_manager
            .get_mut::<widgets::docking::plugin::DockingPlugin>()
        {
            dp.update_animations(delta_time);
        }

        let _ = delta_time;
    }

    /// Set the viewport size for layout calculations.
    pub fn set_viewport(&mut self, viewport: Viewport) {
        self.renderer.set_viewport(viewport);
        self.core.set_viewport(viewport);
    }

    /// Handle events from the event batch.
    pub fn handle_events(&mut self, events: &mut EventBatch) {
        self.core.handle_events(events);
    }

    /// Compute layout for all widgets.
    pub fn compute_layout(&mut self) {
        let viewport_size = self.core.viewport_size();
        let font_renderer = self.renderer.font_renderer();
        #[cfg(feature = "docking")]
        {
            let padding = self
                .core
                .plugin_manager
                .get::<widgets::docking::plugin::DockingPlugin>()
                .map(|p| p.docking_context.style().content_padding)
                .unwrap_or(0.0);
            self.core.tree.set_docking_content_padding(padding);
        }
        let widget_registry = self.core.plugin_manager.widget_registry();
        self.core
            .tree
            .compute_layout(viewport_size, Some(font_renderer), widget_registry);
        // Invalidate docking cache so stale layout coordinates are refreshed
        #[cfg(feature = "docking")]
        if let Some(dp) = self
            .core
            .plugin_manager
            .get_mut::<widgets::docking::plugin::DockingPlugin>()
        {
            dp.invalidate_cache();
        }
    }

    /// Get the node ID for a widget ID.
    pub fn get_node_id(&self, widget_id: WidgetId) -> Option<tree::NodeId> {
        self.core.get_node_id(widget_id)
    }

    /// Register a widget ID to node ID mapping.
    pub fn register_widget(&mut self, widget_id: WidgetId, node_id: tree::NodeId) {
        self.core.register_widget(widget_id, node_id);
    }

    /// Update text content of a Text widget by ID with automatic dirty marking.
    ///
    /// This is much faster than rebuilding the entire UI tree.
    /// Returns true if the content changed.
    ///
    /// # Example
    /// ```no_run
    /// # use astrelis_ui::{UiSystem, WidgetId};
    /// # use astrelis_render::GraphicsContext;
    /// # let context = GraphicsContext::new_owned_sync().expect("Failed to create graphics context");
    /// # let mut ui = UiSystem::new(context);
    /// let counter_id = WidgetId::new("counter");
    /// ui.update_text(counter_id, "Count: 42");
    /// ```
    pub fn update_text(&mut self, widget_id: WidgetId, new_content: impl Into<String>) -> bool {
        self.core.update_text(widget_id, new_content)
    }

    /// Get text cache statistics from the renderer.
    pub fn text_cache_stats(&self) -> String {
        self.renderer.text_cache_stats()
    }

    /// Get text cache hit rate.
    pub fn text_cache_hit_rate(&self) -> f32 {
        self.renderer.text_cache_hit_rate()
    }

    /// Log text cache statistics.
    pub fn log_text_cache_stats(&self) {
        self.renderer.log_text_cache_stats();
    }

    /// Update button label by ID with automatic dirty marking.
    ///
    /// Returns true if the label changed.
    pub fn update_button_label(
        &mut self,
        widget_id: WidgetId,
        new_label: impl Into<String>,
    ) -> bool {
        self.core.update_button_label(widget_id, new_label)
    }

    /// Update text input value by ID with automatic dirty marking.
    ///
    /// Returns true if the value changed.
    pub fn update_text_input(&mut self, widget_id: WidgetId, new_value: impl Into<String>) -> bool {
        self.core.update_text_input(widget_id, new_value)
    }

    /// Update widget color by ID with automatic dirty marking.
    ///
    /// Returns true if the color changed.
    pub fn update_color(&mut self, widget_id: WidgetId, color: astrelis_render::Color) -> bool {
        self.core.update_color(widget_id, color)
    }

    /// Update widget opacity by ID with automatic dirty marking.
    pub fn update_opacity(&mut self, widget_id: WidgetId, opacity: f32) -> bool {
        self.core.update_opacity(widget_id, opacity)
    }

    /// Update widget visual translation by ID.
    pub fn update_translate(&mut self, widget_id: WidgetId, translate: Vec2) -> bool {
        self.core.update_translate(widget_id, translate)
    }

    /// Update widget visual X translation by ID.
    pub fn update_translate_x(&mut self, widget_id: WidgetId, x: f32) -> bool {
        self.core.update_translate_x(widget_id, x)
    }

    /// Update widget visual Y translation by ID.
    pub fn update_translate_y(&mut self, widget_id: WidgetId, y: f32) -> bool {
        self.core.update_translate_y(widget_id, y)
    }

    /// Update widget visual scale by ID.
    pub fn update_scale(&mut self, widget_id: WidgetId, scale: Vec2) -> bool {
        self.core.update_scale(widget_id, scale)
    }

    /// Update widget visual X scale by ID.
    pub fn update_scale_x(&mut self, widget_id: WidgetId, x: f32) -> bool {
        self.core.update_scale_x(widget_id, x)
    }

    /// Update widget visual Y scale by ID.
    pub fn update_scale_y(&mut self, widget_id: WidgetId, y: f32) -> bool {
        self.core.update_scale_y(widget_id, y)
    }

    /// Set widget visibility by ID.
    pub fn set_visible(&mut self, widget_id: WidgetId, visible: bool) -> bool {
        self.core.set_visible(widget_id, visible)
    }

    /// Toggle widget visibility by ID.
    pub fn toggle_visible(&mut self, widget_id: WidgetId) -> bool {
        self.core.toggle_visible(widget_id)
    }

    /// Render the UI using retained mode instanced rendering.
    ///
    /// This is the high-performance path that only updates dirty nodes
    /// and uses GPU instancing for efficient rendering.
    ///
    /// Note: This automatically computes layout. If you need to control
    /// layout computation separately (e.g., for middleware freeze functionality),
    /// use `compute_layout()` + `render_without_layout()` instead.
    pub fn render(&mut self, render_pass: &mut astrelis_render::wgpu::RenderPass) {
        profile_function!();
        let logical_size = self.core.viewport_size();
        // Sync docking content padding before layout
        #[cfg(feature = "docking")]
        {
            let padding = self
                .core
                .plugin_manager
                .get::<widgets::docking::plugin::DockingPlugin>()
                .map(|p| p.docking_context.style().content_padding)
                .unwrap_or(0.0);
            self.core.tree.set_docking_content_padding(padding);
        }
        // Compute layout if dirty (clears layout-related dirty flags)
        let font_renderer = self.renderer.font_renderer();
        let widget_registry = self.core.plugin_manager.widget_registry();
        self.core
            .tree
            .compute_layout(logical_size, Some(font_renderer), widget_registry);

        // Invalidate docking cache so stale layout coordinates are refreshed
        #[cfg(feature = "docking")]
        if let Some(dp) = self
            .core
            .plugin_manager
            .get_mut::<widgets::docking::plugin::DockingPlugin>()
        {
            dp.invalidate_cache();
        }

        // Compute accurate tab widths using text shaping (docking only)
        #[cfg(feature = "docking")]
        {
            let font_renderer = self.renderer.font_renderer();
            crate::widgets::docking::compute_all_tab_widths(self.core.tree_mut(), font_renderer);
        }

        // Run plugin post-layout hooks (ScrollPlugin updates content/viewport sizes)
        self.core.run_post_layout_plugins();

        // Clean up draw commands for nodes removed since last frame
        let removed = self.core.tree_mut().drain_removed_nodes();
        if !removed.is_empty() {
            self.renderer.remove_stale_nodes(&removed);
        }

        // Render using retained mode (processes paint-only dirty flags)
        #[cfg(feature = "docking")]
        {
            // Get cross-container preview and animations from DockingPlugin
            let (preview, animations) = self
                .core
                .plugin_manager
                .get::<widgets::docking::plugin::DockingPlugin>()
                .map(|dp| (dp.cross_container_preview, &dp.dock_animations))
                .unzip();
            let widget_registry = self.core.plugin_manager.widget_registry();

            self.renderer.render_instanced_with_preview(
                self.core.tree(),
                render_pass,
                self.core.viewport,
                preview.flatten().as_ref(),
                animations,
                widget_registry,
            );
        }

        #[cfg(not(feature = "docking"))]
        {
            let widget_registry = self.core.plugin_manager.widget_registry();
            self.renderer.render_instanced(
                self.core.tree(),
                render_pass,
                self.core.viewport,
                widget_registry,
            );
        }

        // Clear all dirty flags after rendering
        // (layout computation no longer clears flags - renderer owns this)
        self.core.tree_mut().clear_dirty_flags();
    }

    /// Render the UI without computing layout.
    ///
    /// Use this when you want to manually control layout computation,
    /// for example when implementing layout freeze functionality with middleware.
    ///
    /// # Parameters
    /// - `render_pass`: The WGPU render pass to render into
    /// - `clear_dirty_flags`: Whether to clear dirty flags after rendering.
    ///   Set to `false` when layout is frozen to preserve dirty state for inspection.
    ///
    /// Typical usage:
    /// ```ignore
    /// // Check if middleware wants to freeze layout
    /// let skip_layout = middlewares.pre_layout(&ctx);
    /// if !skip_layout {
    ///     ui.compute_layout();
    /// }
    /// // Don't clear flags when frozen so inspector can keep showing them
    /// ui.render_without_layout(render_pass, !skip_layout);
    /// ```
    pub fn render_without_layout(
        &mut self,
        render_pass: &mut astrelis_render::wgpu::RenderPass,
        clear_dirty_flags: bool,
    ) {
        profile_function!();
        // Run plugin post-layout hooks (ScrollPlugin updates content/viewport sizes)
        self.core.run_post_layout_plugins();

        // Clean up draw commands for nodes removed since last frame
        let removed = self.core.tree_mut().drain_removed_nodes();
        if !removed.is_empty() {
            self.renderer.remove_stale_nodes(&removed);
        }

        // Render using retained mode (processes paint-only dirty flags)
        let widget_registry = self.core.plugin_manager.widget_registry();
        self.renderer.render_instanced(
            self.core.tree(),
            render_pass,
            self.core.viewport,
            widget_registry,
        );

        // Clear dirty flags unless we're in a frozen state
        if clear_dirty_flags {
            self.core.tree_mut().clear_dirty_flags();
        }
    }

    /// Get mutable access to the core for advanced usage.
    pub fn core_mut(&mut self) -> &mut UiCore {
        &mut self.core
    }

    /// Get reference to the core.
    pub fn core(&self) -> &UiCore {
        &self.core
    }

    /// Get mutable access to the tree for advanced usage.
    pub fn tree_mut(&mut self) -> &mut UiTree {
        self.core.tree_mut()
    }

    /// Get reference to the tree.
    pub fn tree(&self) -> &UiTree {
        self.core.tree()
    }

    /// Get mutable access to the event system.
    pub fn event_system_mut(&mut self) -> &mut UiEventSystem {
        self.core.event_system_mut()
    }

    /// Get reference to the font renderer.
    pub fn font_renderer(&self) -> &astrelis_text::FontRenderer {
        self.renderer.font_renderer()
    }

    /// Set the theme, marking all widget colors dirty.
    pub fn set_theme(&mut self, theme: Theme) {
        self.renderer.set_theme_colors(theme.colors.clone());
        self.core.set_theme(theme);
    }

    /// Get a reference to the current theme.
    pub fn theme(&self) -> &Theme {
        self.core.theme()
    }

    /// Get a reference to the docking style.
    #[cfg(feature = "docking")]
    pub fn docking_style(&self) -> &widgets::docking::DockingStyle {
        self.core.docking_style()
    }

    /// Replace the docking style.
    #[cfg(feature = "docking")]
    pub fn set_docking_style(&mut self, style: widgets::docking::DockingStyle) {
        self.core.set_docking_style(style);
    }

    /// Add a plugin to the UI system and return a handle for typed access.
    ///
    /// The plugin's widget types are registered immediately.
    ///
    /// # Panics
    ///
    /// Panics if a plugin of the same concrete type is already registered.
    pub fn add_plugin<P: UiPlugin>(&mut self, plugin: P) -> PluginHandle<P> {
        self.core.add_plugin(plugin)
    }

    /// Get a handle for an already-registered plugin.
    ///
    /// Returns `Some(PluginHandle)` if the plugin is registered, `None` otherwise.
    /// Useful for obtaining handles to auto-registered plugins.
    pub fn plugin_handle<P: UiPlugin>(&self) -> Option<PluginHandle<P>> {
        self.core.plugin_handle::<P>()
    }

    /// Get a reference to a registered plugin by type, using a handle as proof.
    pub fn plugin<P: UiPlugin>(&self, handle: &PluginHandle<P>) -> &P {
        self.core.plugin(handle)
    }

    /// Get a mutable reference to a registered plugin by type, using a handle as proof.
    pub fn plugin_mut<P: UiPlugin>(&mut self, handle: &PluginHandle<P>) -> &mut P {
        self.core.plugin_mut(handle)
    }

    /// Get a reference to the plugin manager.
    pub fn plugin_manager(&self) -> &PluginManager {
        self.core.plugin_manager()
    }

    /// Get the current renderer configuration.
    ///
    /// Returns the descriptor used to create the renderer, including surface format
    /// and depth format settings.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use astrelis_ui::UiSystem;
    /// # use astrelis_render::GraphicsContext;
    /// # fn example(ui: &UiSystem) {
    /// let desc = ui.renderer_descriptor();
    /// println!("Surface format: {:?}", desc.surface_format);
    /// # }
    /// ```
    pub fn renderer_descriptor(&self) -> &UiRendererDescriptor {
        self.renderer.descriptor()
    }

    /// Reconfigure the renderer with new format settings.
    ///
    /// Call this when the target surface format changes (e.g., window moved
    /// to a different monitor).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use astrelis_ui::{UiSystem, UiRendererDescriptor};
    /// # use astrelis_render::{GraphicsContext, RenderWindow};
    /// # fn example(ui: &mut UiSystem, window: &RenderWindow) {
    /// // Window moved to different monitor - surface format may have changed
    /// ui.reconfigure(UiRendererDescriptor::from_window(window));
    /// # }
    /// ```
    pub fn reconfigure(&mut self, descriptor: UiRendererDescriptor) {
        self.renderer.reconfigure(descriptor);
    }

    /// Reconfigure from a window, inheriting its format configuration.
    ///
    /// Convenience method for updating the renderer when a window's surface
    /// format changes (e.g., when moved to a different monitor).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use astrelis_ui::UiSystem;
    /// # use astrelis_render::{GraphicsContext, RenderWindow};
    /// # fn example(ui: &mut UiSystem, window: &RenderWindow) {
    /// // Handle surface format change after window moved
    /// ui.reconfigure_from_window(window);
    /// # }
    /// ```
    pub fn reconfigure_from_window(&mut self, window: &RenderWindow) {
        self.renderer.reconfigure_from_window(window);
    }
}