nightshade 0.14.0

A cross-platform data-oriented 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
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
use std::collections::HashMap;

use nalgebra_glm::{Vec2, Vec4};

use crate::ecs::ui::components::{DragPayload, TileId};

use crate::ecs::text::components::{TextMesh, TextProperties};

use crate::prelude::*;
#[derive(Clone, Debug)]
pub struct ActiveDrag {
    pub source: freecs::Entity,
    pub payload: DragPayload,
    pub start_pos: Vec2,
    pub current_pos: Vec2,
}
use crate::ecs::ui::theme::ThemeState;
use crate::ecs::ui::types::{Rect, UiTextInstance};
use crate::render::wgpu::passes::geometry::{UiImage, UiLayer, UiRect};

#[derive(Clone)]
pub struct CachedTextMesh {
    pub mesh: TextMesh,
    pub slot_generation: u64,
    pub font_size: f32,
    pub wrap_width: Option<f32>,
    pub monospace_width: Option<f32>,
}

#[derive(Clone, Debug)]
pub enum UiEvent {
    ButtonClicked(freecs::Entity),
    SliderChanged {
        entity: freecs::Entity,
        value: f32,
    },
    ToggleChanged {
        entity: freecs::Entity,
        value: bool,
    },
    CheckboxChanged {
        entity: freecs::Entity,
        value: bool,
    },
    RadioChanged {
        entity: freecs::Entity,
        group_id: u32,
        option_index: usize,
    },
    TabChanged {
        entity: freecs::Entity,
        tab_index: usize,
    },
    TextInputChanged {
        entity: freecs::Entity,
        text: String,
    },
    TextInputSubmitted {
        entity: freecs::Entity,
        text: String,
    },
    DropdownChanged {
        entity: freecs::Entity,
        selected_index: usize,
    },
    MenuItemClicked {
        entity: freecs::Entity,
        item_index: usize,
    },
    ColorPickerChanged {
        entity: freecs::Entity,
        color: Vec4,
    },
    SelectableLabelClicked {
        entity: freecs::Entity,
        selected: bool,
    },
    DragValueChanged {
        entity: freecs::Entity,
        value: f32,
    },
    ContextMenuItemClicked {
        entity: freecs::Entity,
        item_index: usize,
        /// Caller-supplied tag from `ContextMenuBuilder::item_tagged`
        /// (or `checkable_tagged`), echoed back so apps can dispatch
        /// on a stable id instead of the item's positional index.
        /// Defaults to `0` for items added via the untagged
        /// `item`/`checkable` methods.
        tag: u32,
    },
    TreeNodeSelected {
        tree: freecs::Entity,
        node: freecs::Entity,
        selected: bool,
    },
    TreeNodeToggled {
        tree: freecs::Entity,
        node: freecs::Entity,
        expanded: bool,
    },
    TreeNodeContextMenu {
        tree: freecs::Entity,
        node: freecs::Entity,
        position: Vec2,
    },
    TreeNodeExpandRequested {
        tree: freecs::Entity,
        node: freecs::Entity,
        user_data: u64,
    },
    ModalClosed {
        entity: freecs::Entity,
        confirmed: bool,
    },
    CommandPaletteExecuted {
        entity: freecs::Entity,
        command_index: usize,
    },
    TileTabActivated {
        container: freecs::Entity,
        pane_id: TileId,
    },
    TileTabClosed {
        container: freecs::Entity,
        pane_id: TileId,
        title: String,
    },
    TileSplitterMoved {
        container: freecs::Entity,
        split_id: TileId,
        ratio: f32,
    },
    DragStarted {
        source: freecs::Entity,
        payload: DragPayload,
    },
    DragDropped {
        source: freecs::Entity,
        target: freecs::Entity,
        payload: DragPayload,
    },
    DragCancelled {
        source: freecs::Entity,
    },
    DragEnter {
        target: freecs::Entity,
        source: freecs::Entity,
        payload: DragPayload,
    },
    DragOver {
        target: freecs::Entity,
        source: freecs::Entity,
        position: Vec2,
    },
    DragLeave {
        target: freecs::Entity,
        source: freecs::Entity,
    },
    ShortcutTriggered {
        command_index: usize,
    },
    CanvasClicked {
        entity: freecs::Entity,
        command_id: u32,
        position: Vec2,
    },
    VirtualListItemClicked {
        entity: freecs::Entity,
        item_index: usize,
    },
    VirtualListItemRightClicked {
        entity: freecs::Entity,
        item_index: usize,
        screen_position: Vec2,
    },
    TextAreaChanged {
        entity: freecs::Entity,
        text: String,
    },
    RichTextEditorChanged {
        entity: freecs::Entity,
        text: String,
    },
    DataGridFilterChanged {
        entity: freecs::Entity,
        filters: Vec<String>,
    },
    RangeSliderChanged {
        entity: freecs::Entity,
        low: f32,
        high: f32,
    },
    DataGridCellEdited {
        entity: freecs::Entity,
        row: usize,
        column: usize,
        text: String,
    },
    BreadcrumbClicked {
        entity: freecs::Entity,
        segment_index: usize,
    },
    SplitterChanged {
        entity: freecs::Entity,
        ratio: f32,
    },
    MultiSelectChanged {
        entity: freecs::Entity,
        selected_indices: Vec<usize>,
    },
    DatePickerChanged {
        entity: freecs::Entity,
        year: i32,
        month: u32,
        day: u32,
    },
}

impl UiEvent {
    /// Returns the primary entity that this event targets.
    pub fn target_entity(&self) -> freecs::Entity {
        match self {
            UiEvent::ButtonClicked(entity) => *entity,
            UiEvent::SliderChanged { entity, .. } => *entity,
            UiEvent::ToggleChanged { entity, .. } => *entity,
            UiEvent::CheckboxChanged { entity, .. } => *entity,
            UiEvent::RadioChanged { entity, .. } => *entity,
            UiEvent::TabChanged { entity, .. } => *entity,
            UiEvent::TextInputChanged { entity, .. } => *entity,
            UiEvent::TextInputSubmitted { entity, .. } => *entity,
            UiEvent::DropdownChanged { entity, .. } => *entity,
            UiEvent::MenuItemClicked { entity, .. } => *entity,
            UiEvent::ColorPickerChanged { entity, .. } => *entity,
            UiEvent::SelectableLabelClicked { entity, .. } => *entity,
            UiEvent::DragValueChanged { entity, .. } => *entity,
            UiEvent::ContextMenuItemClicked { entity, .. } => *entity,
            UiEvent::TreeNodeSelected { node, .. } => *node,
            UiEvent::TreeNodeToggled { node, .. } => *node,
            UiEvent::TreeNodeContextMenu { node, .. } => *node,
            UiEvent::TreeNodeExpandRequested { node, .. } => *node,
            UiEvent::ModalClosed { entity, .. } => *entity,
            UiEvent::CommandPaletteExecuted { entity, .. } => *entity,
            UiEvent::TileTabActivated { container, .. } => *container,
            UiEvent::TileTabClosed { container, .. } => *container,
            UiEvent::TileSplitterMoved { container, .. } => *container,
            UiEvent::DragStarted { source, .. } => *source,
            UiEvent::DragDropped { target, .. } => *target,
            UiEvent::DragCancelled { source, .. } => *source,
            UiEvent::DragEnter { target, .. } => *target,
            UiEvent::DragOver { target, .. } => *target,
            UiEvent::DragLeave { target, .. } => *target,
            UiEvent::ShortcutTriggered { .. } => freecs::Entity::default(),
            UiEvent::CanvasClicked { entity, .. } => *entity,
            UiEvent::VirtualListItemClicked { entity, .. } => *entity,
            UiEvent::VirtualListItemRightClicked { entity, .. } => *entity,
            UiEvent::TextAreaChanged { entity, .. } => *entity,
            UiEvent::RichTextEditorChanged { entity, .. } => *entity,
            UiEvent::DataGridFilterChanged { entity, .. } => *entity,
            UiEvent::RangeSliderChanged { entity, .. } => *entity,
            UiEvent::DataGridCellEdited { entity, .. } => *entity,
            UiEvent::BreadcrumbClicked { entity, .. } => *entity,
            UiEvent::SplitterChanged { entity, .. } => *entity,
            UiEvent::MultiSelectChanged { entity, .. } => *entity,
            UiEvent::DatePickerChanged { entity, .. } => *entity,
        }
    }

    /// Returns `true` if this event type should bubble up the parent chain.
    /// Most interaction events bubble. Layout and animation lifecycle events
    /// do not.
    pub fn bubbles(&self) -> bool {
        match self {
            UiEvent::ButtonClicked(_)
            | UiEvent::SliderChanged { .. }
            | UiEvent::ToggleChanged { .. }
            | UiEvent::CheckboxChanged { .. }
            | UiEvent::RadioChanged { .. }
            | UiEvent::TabChanged { .. }
            | UiEvent::TextInputChanged { .. }
            | UiEvent::TextInputSubmitted { .. }
            | UiEvent::DropdownChanged { .. }
            | UiEvent::MenuItemClicked { .. }
            | UiEvent::ColorPickerChanged { .. }
            | UiEvent::SelectableLabelClicked { .. }
            | UiEvent::DragValueChanged { .. }
            | UiEvent::ContextMenuItemClicked { .. }
            | UiEvent::TreeNodeSelected { .. }
            | UiEvent::TreeNodeToggled { .. } => true,
            UiEvent::TreeNodeContextMenu { .. }
            | UiEvent::TreeNodeExpandRequested { .. }
            | UiEvent::ModalClosed { .. }
            | UiEvent::CommandPaletteExecuted { .. }
            | UiEvent::TileTabActivated { .. }
            | UiEvent::TileTabClosed { .. }
            | UiEvent::TileSplitterMoved { .. }
            | UiEvent::DragStarted { .. }
            | UiEvent::DragDropped { .. }
            | UiEvent::DragCancelled { .. }
            | UiEvent::DragEnter { .. }
            | UiEvent::DragOver { .. }
            | UiEvent::DragLeave { .. }
            | UiEvent::ShortcutTriggered { .. }
            | UiEvent::CanvasClicked { .. }
            | UiEvent::VirtualListItemClicked { .. }
            | UiEvent::VirtualListItemRightClicked { .. }
            | UiEvent::DataGridFilterChanged { .. }
            | UiEvent::DataGridCellEdited { .. } => false,
            UiEvent::TextAreaChanged { .. }
            | UiEvent::RichTextEditorChanged { .. }
            | UiEvent::RangeSliderChanged { .. }
            | UiEvent::BreadcrumbClicked { .. }
            | UiEvent::SplitterChanged { .. }
            | UiEvent::MultiSelectChanged { .. }
            | UiEvent::DatePickerChanged { .. } => true,
        }
    }
}

#[derive(Default, Debug)]
pub struct UiImageLayerAllocator {
    pub next_layer: u32,
    pub free_layers: Vec<u32>,
}

impl UiImageLayerAllocator {
    pub const MAX_LAYERS: u32 = crate::render::wgpu::ui_texture_array::UI_TEXTURE_MAX_LAYERS;

    pub fn allocate(&mut self) -> Option<u32> {
        if let Some(layer) = self.free_layers.pop() {
            return Some(layer);
        }
        if self.next_layer >= Self::MAX_LAYERS {
            return None;
        }
        let layer = self.next_layer;
        self.next_layer += 1;
        Some(layer)
    }

    pub fn release(&mut self, layer: u32) {
        if layer >= Self::MAX_LAYERS {
            return;
        }
        if self.free_layers.contains(&layer) {
            return;
        }
        self.free_layers.push(layer);
    }
}

#[derive(Default, Debug)]
pub struct RenderSlotAllocator {
    pub rect_slots: std::collections::HashMap<freecs::Entity, u32>,
    pub image_slots: std::collections::HashMap<freecs::Entity, u32>,
    pub text_slots: std::collections::HashMap<freecs::Entity, u32>,
    pub free_rect_slots: Vec<u32>,
    pub free_image_slots: Vec<u32>,
    pub free_text_slots: Vec<u32>,
    pub next_rect_slot: u32,
    pub next_image_slot: u32,
    pub next_text_slot: u32,
    pub dirty_rect_slots: std::collections::HashSet<u32>,
    pub dirty_image_slots: std::collections::HashSet<u32>,
    pub dirty_text_slots: std::collections::HashSet<u32>,
}

pub fn allocate_rect_slot(allocator: &mut RenderSlotAllocator, entity: freecs::Entity) -> u32 {
    if let Some(&slot) = allocator.rect_slots.get(&entity) {
        return slot;
    }
    let slot = allocator.free_rect_slots.pop().unwrap_or_else(|| {
        let s = allocator.next_rect_slot;
        allocator.next_rect_slot += 1;
        s
    });
    allocator.rect_slots.insert(entity, slot);
    allocator.dirty_rect_slots.insert(slot);
    slot
}

pub fn release_rect_slot(allocator: &mut RenderSlotAllocator, entity: freecs::Entity) {
    if let Some(slot) = allocator.rect_slots.remove(&entity) {
        allocator.free_rect_slots.push(slot);
        allocator.dirty_rect_slots.remove(&slot);
    }
}

pub fn mark_rect_dirty(allocator: &mut RenderSlotAllocator, entity: freecs::Entity) {
    if let Some(&slot) = allocator.rect_slots.get(&entity) {
        allocator.dirty_rect_slots.insert(slot);
    }
}

pub fn allocate_image_slot(allocator: &mut RenderSlotAllocator, entity: freecs::Entity) -> u32 {
    if let Some(&slot) = allocator.image_slots.get(&entity) {
        return slot;
    }
    let slot = allocator.free_image_slots.pop().unwrap_or_else(|| {
        let s = allocator.next_image_slot;
        allocator.next_image_slot += 1;
        s
    });
    allocator.image_slots.insert(entity, slot);
    allocator.dirty_image_slots.insert(slot);
    slot
}

pub fn release_image_slot(allocator: &mut RenderSlotAllocator, entity: freecs::Entity) {
    if let Some(slot) = allocator.image_slots.remove(&entity) {
        allocator.free_image_slots.push(slot);
        allocator.dirty_image_slots.remove(&slot);
    }
}

pub fn allocate_text_slot(allocator: &mut RenderSlotAllocator, entity: freecs::Entity) -> u32 {
    if let Some(&slot) = allocator.text_slots.get(&entity) {
        return slot;
    }
    let slot = allocator.free_text_slots.pop().unwrap_or_else(|| {
        let s = allocator.next_text_slot;
        allocator.next_text_slot += 1;
        s
    });
    allocator.text_slots.insert(entity, slot);
    allocator.dirty_text_slots.insert(slot);
    slot
}

pub fn release_text_slot(allocator: &mut RenderSlotAllocator, entity: freecs::Entity) {
    if let Some(slot) = allocator.text_slots.remove(&entity) {
        allocator.free_text_slots.push(slot);
        allocator.dirty_text_slots.remove(&slot);
    }
}

pub fn clear_render_slot_dirty(allocator: &mut RenderSlotAllocator) {
    allocator.dirty_rect_slots.clear();
    allocator.dirty_image_slots.clear();
    allocator.dirty_text_slots.clear();
}

/// Per-frame mirror of input state that the retained UI cares about. Populated
/// each frame by `ui_retained_input_sync_system` from the global input resource
/// (or from the focused secondary window if applicable). Read by widget
/// handlers and the layout system.
#[derive(Default)]
pub struct RetainedUiInputMirror {
    pub frame_chars: Vec<char>,
    pub frame_keys: Vec<(winit::keyboard::KeyCode, bool)>,
    pub ctrl_held: bool,
    pub shift_held: bool,
    pub scroll_delta: Vec2,
}

/// Wall-clock and per-frame delta in seconds. Driven by the timing system
/// each frame and read by transition, animation, and drag tick handlers.
#[derive(Default, Debug, Clone, Copy)]
pub struct RetainedUiTiming {
    pub current_time: f64,
    pub delta_time: f32,
}

/// Frame-level dirty flags and the cached tail-counts used to truncate
/// [`RetainedUiFrame`] buffers on a non-dirty frame. Also holds per-entity
/// `node_versions` and the global frame counter.
#[derive(Default)]
pub struct RetainedUiDirty {
    pub layout_dirty: bool,
    pub render_dirty: bool,
    pub global_version: u64,
    pub last_compute_viewport: Option<(u32, u32)>,
    pub last_compute_dpi: f32,
    pub last_compute_text_generation: u64,
    pub cached_node_rect_count: usize,
    pub cached_node_image_count: usize,
    pub cached_node_text_count: usize,
    pub node_versions: std::collections::HashMap<freecs::Entity, u64>,
}

/// Cached text-mesh data and per-character color overrides, keyed by text
/// slot. Reset when DPI changes; otherwise stable across frames.
#[derive(Default)]
pub struct RetainedUiTextCache {
    pub mesh: Vec<Option<CachedTextMesh>>,
    pub mesh_dpi: f32,
    pub character_colors: HashMap<usize, Vec<Option<Vec4>>>,
    pub character_background_colors: HashMap<usize, Vec<Option<Vec4>>>,
}

/// Active drag-and-drop session and the entity currently under the
/// pointer if drop tracking is on.
#[derive(Default, Debug)]
pub struct RetainedUiDragDrop {
    pub active: Option<ActiveDrag>,
    pub over_entity: Option<freecs::Entity>,
}

/// Reduced-motion preference, screen-reader announce queue, and the test-id
/// lookup driven by `with_test_id`.
#[derive(Default)]
pub struct RetainedUiAccessibility {
    pub reduced_motion: bool,
    pub announce_queue: Vec<String>,
    pub test_id_map: HashMap<String, freecs::Entity>,
    pub named_entities: HashMap<String, freecs::Entity>,
}

/// Cross-entity groupings: radio mutually-exclusive groups, selectable-label
/// groups, and registered keyboard shortcuts.
#[derive(Default)]
pub struct RetainedUiGroups {
    pub radio: HashMap<u32, Vec<freecs::Entity>>,
    pub selectable_labels: HashMap<u32, Vec<freecs::Entity>>,
    pub shortcuts: Vec<(crate::ecs::ui::components::ShortcutBinding, usize)>,
}

/// Pointer interaction state. Tracks which entity is hovered, focused,
/// active, the last click for double-click detection, and the cursor icon
/// the UI wants the OS to display.
#[derive(Default, Debug)]
pub struct RetainedUiInteraction {
    pub focused_entity: Option<freecs::Entity>,
    pub hovered_entity: Option<freecs::Entity>,
    pub active_entity: Option<freecs::Entity>,
    pub requested_cursor: Option<winit::window::CursorIcon>,
    pub applied_cursor: Option<winit::window::CursorIcon>,
    pub last_click: Option<(freecs::Entity, f64, Vec2)>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NavDirection {
    Up,
    Down,
    Left,
    Right,
}

#[derive(Debug)]
pub struct RetainedUiGamepadNav {
    pub held_direction: Option<NavDirection>,
    pub next_repeat_at: f64,
    pub deadzone: f32,
    pub initial_repeat_delay: f64,
    pub repeat_interval: f64,
    pub enabled: bool,
}

impl Default for RetainedUiGamepadNav {
    fn default() -> Self {
        Self {
            held_direction: None,
            next_repeat_at: 0.0,
            deadzone: 0.5,
            initial_repeat_delay: 0.4,
            repeat_interval: 0.12,
            enabled: true,
        }
    }
}

/// Floating overlay entities and their visibility flags. Tooltips,
/// popups, toasts, modals, and the dock-target indicator live here.
#[derive(Default, Debug)]
pub struct RetainedUiOverlays {
    pub tooltip_state: Option<TooltipActiveState>,
    pub popup_entities: Vec<freecs::Entity>,
    pub toast_container: Option<freecs::Entity>,
    pub toast_entries: Vec<ToastEntry>,
    pub toast_corner: ToastCorner,
    pub dock_indicator_active: bool,
    pub dock_indicator_panel: Option<freecs::Entity>,
    pub active_context_menu: Option<freecs::Entity>,
    pub active_modal: Option<freecs::Entity>,
    pub focus_ring_visible: bool,
}

/// Per-frame draw record buffers built by `ui_layout_render_sync_system` and
/// consumed by the GPU prepare passes. These reset each frame the layout is
/// dirty, otherwise they're truncated back to the last cached counts.
#[derive(Default)]
pub struct RetainedUiFrame {
    pub rects: Vec<UiRect>,
    pub rect_entities: Vec<Option<freecs::Entity>>,
    pub ui_images: Vec<UiImage>,
    pub text_meshes: Vec<UiTextInstance>,
    pub overlay_rects: Vec<UiRect>,
    pub overlay_text: Vec<OverlayText>,
    pub events: Vec<UiEvent>,
    pub bubbled_events: Vec<BubbledUiEvent>,
}

#[derive(Clone, Debug)]
pub struct TopProgressBar {
    pub value: Option<f32>,
    pub indeterminate: bool,
    pub phase: f32,
    pub height: f32,
    pub color: Option<Vec4>,
}

impl Default for TopProgressBar {
    fn default() -> Self {
        Self {
            value: None,
            indeterminate: false,
            phase: 0.0,
            height: 2.0,
            color: None,
        }
    }
}

impl TopProgressBar {
    pub fn set(&mut self, value: f32) {
        self.value = Some(value.clamp(0.0, 1.0));
        self.indeterminate = false;
    }

    pub fn set_indeterminate(&mut self) {
        self.value = None;
        self.indeterminate = true;
    }

    pub fn clear(&mut self) {
        self.value = None;
        self.indeterminate = false;
    }

    pub fn is_active(&self) -> bool {
        self.value.is_some() || self.indeterminate
    }
}

#[derive(Default, PartialEq, Eq, Clone, Copy, Debug)]
pub enum UiBreakpoint {
    Compact,
    Medium,
    #[default]
    Wide,
}

impl UiBreakpoint {
    pub fn from_width(width: f32) -> Self {
        if width < 720.0 {
            UiBreakpoint::Compact
        } else if width < 1024.0 {
            UiBreakpoint::Medium
        } else {
            UiBreakpoint::Wide
        }
    }

    pub fn is_compact(self) -> bool {
        matches!(self, UiBreakpoint::Compact)
    }

    pub fn is_medium_or_narrower(self) -> bool {
        matches!(self, UiBreakpoint::Compact | UiBreakpoint::Medium)
    }
}

#[derive(Default, Clone, Copy, Debug)]
pub struct UiViewport {
    pub size: Vec2,
    pub breakpoint: UiBreakpoint,
}

#[derive(Default)]
pub struct RetainedUiState {
    pub enabled: bool,
    pub theme_state: ThemeState,
    pub interaction: RetainedUiInteraction,
    pub overlays: RetainedUiOverlays,
    pub timing: RetainedUiTiming,
    pub dirty: RetainedUiDirty,
    pub text_cache: RetainedUiTextCache,
    pub drag: RetainedUiDragDrop,
    pub accessibility: RetainedUiAccessibility,
    pub groups: RetainedUiGroups,
    pub z_sorted_nodes: Vec<(freecs::Entity, f32)>,
    pub frame: RetainedUiFrame,
    pub layout_graph: crate::ecs::ui::layout_graph::LayoutGraph,
    pub taffy: crate::ecs::ui::taffy_layout::UiTaffy,
    pub render_slots: RenderSlotAllocator,
    pub input: RetainedUiInputMirror,
    pub background_color: Option<Vec4>,
    pub top_progress_bar: TopProgressBar,
    pub icon_set: crate::ecs::ui::icons::IconSet,
    pub dock_state: DockState,
    pub gamepad_nav: RetainedUiGamepadNav,
    pub next_focus_order: i32,
    pub viewport: UiViewport,
    pub picking_grid: Option<crate::ecs::ui::picking::PickingGrid>,
    pub custom_state_count: usize,
    pub clipboard_text: String,
    /// Registry of chrome widgets (menu bar, toolbar, status bar, shortcuts)
    /// installed on the window.
    pub window_chrome: WindowChrome,
}

/// First-class registry of the chrome widgets that belong to a window.
/// Each field stores the entity of the corresponding widget when one is
/// installed, or `None` when that window has no such chrome.
#[derive(Default, Clone, Debug)]
pub struct WindowChrome {
    pub menu_bar: Option<freecs::Entity>,
    pub toolbar: Option<freecs::Entity>,
    pub status_bar: Option<freecs::Entity>,
    /// Keyboard shortcuts that are scoped to this window. Activations
    /// outside the owning window are ignored.
    pub shortcuts: Vec<WindowShortcut>,
}

#[derive(Clone, Debug)]
pub struct WindowShortcut {
    pub binding: crate::ecs::ui::components::ShortcutBinding,
    pub command_index: usize,
}

/// An event that has been propagated up the parent chain from its original
/// target entity. Call [`stop_propagation`](BubbledUiEvent::stop_propagation)
/// to prevent ancestor entities from seeing this event.
///
/// ```ignore
/// for event in ui_bubbled_events_for(world, container) {
///     if let UiEvent::ButtonClicked(_) = &event.event {
///         // A button somewhere inside `container` was clicked
///     }
/// }
/// ```
#[derive(Clone, Debug)]
pub struct BubbledUiEvent {
    pub event: UiEvent,
    pub target: freecs::Entity,
    pub ancestor: freecs::Entity,
    pub stopped: bool,
}

impl BubbledUiEvent {
    /// Marks this event as stopped so that further ancestor entities will
    /// not receive it from [`World::ui_bubbled_events_for`].
    pub fn stop_propagation(&mut self) {
        self.stopped = true;
    }

    /// Returns `true` if [`stop_propagation`](Self::stop_propagation) has
    /// been called on this event.
    pub fn stopped(&self) -> bool {
        self.stopped
    }
}

#[derive(Clone, Debug)]
pub struct TooltipActiveState {
    pub entity: freecs::Entity,
    pub hover_start: f64,
    pub text: String,
    pub tooltip_entity: Option<freecs::Entity>,
}

#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct ReservedAreas {
    pub left: f32,
    pub right: f32,
    pub top: f32,
    pub bottom: f32,
}

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct PanelDockConfig {
    pub id: String,
    pub title: String,
    pub kind: crate::ecs::ui::components::UiPanelKind,
    pub focus_order: i32,
    pub size: f32,
    pub visible: bool,
    pub collapsed: bool,
    pub floating_position: Option<[f32; 2]>,
    pub floating_size: Option<[f32; 2]>,
}

#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct WindowDockLayout {
    pub reserved_areas: ReservedAreas,
    pub panels: Vec<PanelDockConfig>,
}

#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct DockState {
    pub primary: WindowDockLayout,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ToastSeverity {
    Info,
    Success,
    Warning,
    Error,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum ToastCorner {
    TopLeft,
    TopRight,
    BottomLeft,
    #[default]
    BottomRight,
}

#[derive(Clone, Debug)]
pub struct ToastEntry {
    pub entity: freecs::Entity,
    pub spawn_time: f64,
    pub duration: f32,
    pub dismissing: bool,
}

pub struct DrawRectParams {
    pub position: Vec2,
    pub size: Vec2,
    pub color: Vec4,
    pub corner_radius: f32,
    pub border_width: f32,
    pub border_color: Vec4,
    pub layer: UiLayer,
    pub z_index: i32,
}

pub struct OverlayText {
    pub text: String,
    pub position: Vec2,
    pub properties: TextProperties,
    pub clip_rect: Option<Rect>,
    pub layer: UiLayer,
    pub z_index: i32,
}

impl RetainedUiState {
    pub fn draw_overlay_rect(&mut self, rect: UiRect) {
        self.frame.overlay_rects.push(rect);
    }

    pub fn draw_overlay_text(
        &mut self,
        text: &str,
        position: Vec2,
        properties: TextProperties,
        clip_rect: Option<Rect>,
        layer: UiLayer,
        z_index: i32,
    ) {
        self.frame.overlay_text.push(OverlayText {
            text: text.to_string(),
            position,
            properties,
            clip_rect,
            layer,
            z_index,
        });
    }

    pub fn register_custom_state(&mut self) -> usize {
        let index = crate::ecs::ui::state::STATE_COUNT + self.custom_state_count;
        self.custom_state_count += 1;
        index
    }

    pub fn total_state_count(&self) -> usize {
        crate::ecs::ui::state::STATE_COUNT + self.custom_state_count
    }

    pub fn interaction_for_active(&self) -> &RetainedUiInteraction {
        &self.interaction
    }

    pub fn interaction_for_active_mut(&mut self) -> &mut RetainedUiInteraction {
        &mut self.interaction
    }

    pub fn events_for_active(&self) -> &[UiEvent] {
        &self.frame.events
    }

    pub fn events_for_active_mut(&mut self) -> &mut Vec<UiEvent> {
        &mut self.frame.events
    }

    pub fn draw_rect(&mut self, position: Vec2, size: Vec2, color: Vec4) {
        self.frame.rects.push(UiRect {
            position,
            size,
            color,
            corner_radius: 0.0,
            border_width: 0.0,
            border_color: Vec4::new(0.0, 0.0, 0.0, 0.0),
            rotation: 0.0,
            clip_rect: None,
            layer: UiLayer::FloatingPanels,
            z_index: 0,
            shadow: None,
            effect_kind: 0,
            effect_params: [0.0; 4],
            quad_corners: None,
        });
    }

    pub fn draw_rect_styled(&mut self, params: DrawRectParams) {
        self.frame.rects.push(UiRect {
            position: params.position,
            size: params.size,
            color: params.color,
            corner_radius: params.corner_radius,
            border_width: params.border_width,
            border_color: params.border_color,
            rotation: 0.0,
            clip_rect: None,
            layer: params.layer,
            z_index: params.z_index,
            shadow: None,
            effect_kind: 0,
            effect_params: [0.0; 4],
            quad_corners: None,
        });
    }
}

pub fn blend_color(from: Vec4, to: Vec4, t: f32) -> Vec4 {
    if t <= 0.0 {
        return from;
    }
    if t >= 1.0 {
        return to;
    }

    let from_hsla = rgba_to_hsla(from);
    let to_hsla = rgba_to_hsla(to);

    let mut h_diff = to_hsla.x - from_hsla.x;
    if h_diff > 0.5 {
        h_diff -= 1.0;
    } else if h_diff < -0.5 {
        h_diff += 1.0;
    }

    let h = (from_hsla.x + h_diff * t).rem_euclid(1.0);
    let s = from_hsla.y + (to_hsla.y - from_hsla.y) * t;
    let l = from_hsla.z + (to_hsla.z - from_hsla.z) * t;
    let a = from_hsla.w + (to_hsla.w - from_hsla.w) * t;

    hsla_to_rgba(Vec4::new(h, s, l, a))
}

fn rgba_to_hsla(color: Vec4) -> Vec4 {
    let r = color.x;
    let g = color.y;
    let b = color.z;
    let a = color.w;

    let max = r.max(g).max(b);
    let min = r.min(g).min(b);
    let l = (max + min) * 0.5;

    if (max - min).abs() < f32::EPSILON {
        return Vec4::new(0.0, 0.0, l, a);
    }

    let d = max - min;
    let s = if l > 0.5 {
        d / (2.0 - max - min)
    } else {
        d / (max + min)
    };

    let h = if (max - r).abs() < f32::EPSILON {
        let mut h = (g - b) / d;
        if g < b {
            h += 6.0;
        }
        h / 6.0
    } else if (max - g).abs() < f32::EPSILON {
        ((b - r) / d + 2.0) / 6.0
    } else {
        ((r - g) / d + 4.0) / 6.0
    };

    Vec4::new(h, s, l, a)
}

fn hsla_to_rgba(hsla: Vec4) -> Vec4 {
    let h = hsla.x;
    let s = hsla.y;
    let l = hsla.z;
    let a = hsla.w;

    if s.abs() < f32::EPSILON {
        return Vec4::new(l, l, l, a);
    }

    let q = if l < 0.5 {
        l * (1.0 + s)
    } else {
        l + s - l * s
    };
    let p = 2.0 * l - q;

    let r = hue_to_rgb(p, q, h + 1.0 / 3.0);
    let g = hue_to_rgb(p, q, h);
    let b = hue_to_rgb(p, q, h - 1.0 / 3.0);

    Vec4::new(r, g, b, a)
}

fn hue_to_rgb(p: f32, q: f32, mut t: f32) -> f32 {
    if t < 0.0 {
        t += 1.0;
    }
    if t > 1.0 {
        t -= 1.0;
    }
    if t < 1.0 / 6.0 {
        return p + (q - p) * 6.0 * t;
    }
    if t < 0.5 {
        return q;
    }
    if t < 2.0 / 3.0 {
        return p + (q - p) * (2.0 / 3.0 - t) * 6.0;
    }
    p
}

#[cfg(test)]
mod tests {
    use super::*;

    fn dummy_entity(id: u32) -> freecs::Entity {
        freecs::Entity { id, generation: 0 }
    }

    #[test]
    fn button_clicked_bubbles() {
        assert!(UiEvent::ButtonClicked(dummy_entity(0)).bubbles());
    }

    #[test]
    fn slider_changed_bubbles() {
        assert!(
            UiEvent::SliderChanged {
                entity: dummy_entity(0),
                value: 0.0
            }
            .bubbles()
        );
    }

    #[test]
    fn tree_node_context_menu_does_not_bubble() {
        assert!(
            !UiEvent::TreeNodeContextMenu {
                tree: dummy_entity(0),
                node: dummy_entity(1),
                position: Vec2::zeros(),
            }
            .bubbles()
        );
    }

    #[test]
    fn modal_closed_does_not_bubble() {
        assert!(
            !UiEvent::ModalClosed {
                entity: dummy_entity(0),
                confirmed: true,
            }
            .bubbles()
        );
    }

    #[test]
    fn target_entity_button() {
        let entity = dummy_entity(42);
        assert_eq!(UiEvent::ButtonClicked(entity).target_entity(), entity);
    }

    #[test]
    fn target_entity_tree_node_selected() {
        let tree = dummy_entity(1);
        let node = dummy_entity(2);
        assert_eq!(
            UiEvent::TreeNodeSelected {
                tree,
                node,
                selected: true
            }
            .target_entity(),
            node
        );
    }

    #[test]
    fn target_entity_modal_closed() {
        let entity = dummy_entity(5);
        assert_eq!(
            UiEvent::ModalClosed {
                entity,
                confirmed: false
            }
            .target_entity(),
            entity
        );
    }

    #[test]
    fn all_bubbling_events_bubble() {
        let entity = dummy_entity(0);
        let bubbling_events = [
            UiEvent::ButtonClicked(entity),
            UiEvent::SliderChanged { entity, value: 0.0 },
            UiEvent::ToggleChanged {
                entity,
                value: false,
            },
            UiEvent::CheckboxChanged {
                entity,
                value: false,
            },
            UiEvent::RadioChanged {
                entity,
                group_id: 0,
                option_index: 0,
            },
            UiEvent::TabChanged {
                entity,
                tab_index: 0,
            },
            UiEvent::TextInputChanged {
                entity,
                text: String::new(),
            },
            UiEvent::TextInputSubmitted {
                entity,
                text: String::new(),
            },
            UiEvent::DropdownChanged {
                entity,
                selected_index: 0,
            },
            UiEvent::MenuItemClicked {
                entity,
                item_index: 0,
            },
            UiEvent::ColorPickerChanged {
                entity,
                color: Vec4::zeros(),
            },
            UiEvent::SelectableLabelClicked {
                entity,
                selected: false,
            },
            UiEvent::DragValueChanged { entity, value: 0.0 },
            UiEvent::ContextMenuItemClicked {
                entity,
                item_index: 0,
                tag: 0,
            },
            UiEvent::TreeNodeSelected {
                tree: entity,
                node: entity,
                selected: false,
            },
            UiEvent::TreeNodeToggled {
                tree: entity,
                node: entity,
                expanded: false,
            },
        ];
        for event in &bubbling_events {
            assert!(event.bubbles(), "Expected {:?} to bubble", event);
        }
    }

    #[test]
    fn all_non_bubbling_events_do_not_bubble() {
        let entity = dummy_entity(0);
        let non_bubbling_events = [
            UiEvent::TreeNodeContextMenu {
                tree: entity,
                node: entity,
                position: Vec2::zeros(),
            },
            UiEvent::ModalClosed {
                entity,
                confirmed: false,
            },
            UiEvent::CommandPaletteExecuted {
                entity,
                command_index: 0,
            },
            UiEvent::TileTabActivated {
                container: entity,
                pane_id: TileId(0),
            },
            UiEvent::TileTabClosed {
                container: entity,
                pane_id: TileId(0),
                title: String::new(),
            },
            UiEvent::TileSplitterMoved {
                container: entity,
                split_id: TileId(0),
                ratio: 0.5,
            },
        ];
        for event in &non_bubbling_events {
            assert!(!event.bubbles(), "Expected {:?} not to bubble", event);
        }
    }
}