jackdaw 0.4.0

A 3D level editor built with Bevy
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
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
use std::collections::HashSet;

use bevy::{input_focus::InputFocus, prelude::*, ui::ui_transform::UiGlobalTransform};
use bevy_enhanced_input::prelude::{Press, *};
use bevy_monitors::prelude::{Mutation, NotifyChanged};
use jackdaw_api::prelude::*;
use jackdaw_feathers::{
    context_menu::spawn_context_menu,
    icons::IconFont,
    text_edit::{self, EditorTextEdit, TextEditCommitEvent, TextEditProps, TextEditValue},
    tokens,
    tree_view::{ROW_BG, TreeRowStyle, tree_row},
};
use jackdaw_widgets::context_menu::{ContextMenuAction, ContextMenuState};
use jackdaw_widgets::tree_view::{
    EntityCategory, TreeChildrenPopulated, TreeFocused, TreeIndex, TreeNode, TreeNodeExpanded,
    TreeRowChildren, TreeRowClicked, TreeRowContent, TreeRowDropped, TreeRowDroppedOnRoot,
    TreeRowInlineRename, TreeRowLabel, TreeRowRenamed, TreeRowSelected, TreeRowStartRename,
    TreeRowVisibilityToggled,
};

use crate::{
    EditorEntity, EditorHidden, OP_PREFIX,
    commands::{CommandHistory, EditorCommand, ReparentEntity, SetJsnField},
    entity_ops,
    layout::HierarchyFilter,
    selection::{Selected, Selection},
};
use jackdaw_feathers::dialog::{DialogActionEvent, DialogChildrenSlot};
use jackdaw_jsn::BrushGroup;

/// Stores the default name for the template save dialog.
#[derive(Resource, Default)]
struct PendingTemplateDefaultName(String);

/// Marker for the template name text input inside the dialog.
#[derive(Component)]
struct TemplateNameInput;

/// Marker for the hierarchy panel
#[derive(Component)]
#[require(EditorEntity)]
pub struct HierarchyPanel;

/// Marker for the container that holds tree rows. Carries the
/// widget-side [`jackdaw_widgets::tree_view::TreeRoot`] so the
/// per-container `TreeIndex` knows where to file the rows that
/// descend from it. Multi-instance Outliner tabs each spawn their
/// own container; the index keys rows by `(container, source)` so
/// they don't collide.
#[derive(Component)]
#[require(EditorEntity, jackdaw_widgets::tree_view::TreeRoot)]
pub struct HierarchyTreeContainer;

/// Controls whether the hierarchy shows all entities or only named ones.
/// `false` = named only (default), `true` = all entities (minus `EditorEntity`).
#[derive(Resource, Default)]
pub struct HierarchyShowAll(pub bool);

/// Marker for the show-all toggle button in the hierarchy panel.
#[derive(Component)]
pub struct HierarchyShowAllButton;

pub struct HierarchyPlugin;

impl Plugin for HierarchyPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<ContextMenuState>()
            .init_resource::<PendingTemplateDefaultName>()
            .init_resource::<HierarchyShowAll>()
            .add_systems(Startup, setup_tree_node_expanded_watcher)
            .add_systems(OnEnter(crate::AppState::Editor), setup_name_watcher)
            .add_systems(
                Update,
                (
                    apply_hierarchy_filter,
                    auto_focus_inline_rename,
                    populate_template_dialog,
                    toggle_show_all_button,
                    update_show_all_button_appearance,
                    on_show_all_changed,
                    jackdaw_feathers::tree_view::tree_keyboard_navigation,
                    style_game_spawned_rows,
                )
                    .run_if(in_state(crate::AppState::Editor)),
            )
            .add_systems(
                PostUpdate,
                rebuild_hierarchy_on_container_added
                    .after(jackdaw_widgets::tree_view::maintain_tree_index),
            )
            .add_observer(handle_inline_rename_commit)
            .add_observer(on_root_entity_added)
            .add_observer(on_entity_reparented)
            .add_observer(on_entity_deparented)
            .add_observer(on_tree_node_expanded)
            .add_observer(on_tree_row_clicked)
            .add_observer(on_entity_removed)
            .add_observer(on_name_changed)
            .add_observer(on_entity_selected)
            .add_observer(on_entity_deselected)
            .add_observer(on_tree_row_dropped)
            .add_observer(on_tree_row_dropped_on_root)
            .add_observer(on_tree_row_start_rename)
            .add_observer(on_tree_row_renamed)
            .add_observer(on_context_menu_action)
            .add_observer(on_visibility_toggled)
            .add_observer(on_template_dialog_action)
            .add_observer(on_entity_hidden);
    }
}

/// Classify a scene entity by its primary component for tree display.
fn classify_entity(world: &World, entity: Entity) -> EntityCategory {
    if world.get::<BrushGroup>(entity).is_some() {
        return EntityCategory::Mesh;
    }
    if world.get::<Camera>(entity).is_some() {
        return EntityCategory::Camera;
    }
    if world.get::<PointLight>(entity).is_some()
        || world.get::<DirectionalLight>(entity).is_some()
        || world.get::<SpotLight>(entity).is_some()
    {
        return EntityCategory::Light;
    }
    if world.get::<Mesh3d>(entity).is_some() {
        return EntityCategory::Mesh;
    }
    if world.get::<SceneRoot>(entity).is_some() {
        return EntityCategory::Scene;
    }
    EntityCategory::Entity
}

/// Check if an entity has any non-editor children.
fn has_visible_children(world: &World, entity: Entity) -> bool {
    let Some(children) = world.get::<Children>(entity) else {
        return false;
    };
    children.iter().any(|child| {
        world.get::<EditorEntity>(child).is_none() && world.get::<EditorHidden>(child).is_none()
    })
}

/// Snapshot of every `HierarchyTreeContainer` in the world. Cached
/// via `world.run_system_cached(...)` so the `QueryState` is reused
/// across the per-frame observer dispatches that fan out spawns to
/// every Outliner panel.
fn collect_hierarchy_containers(
    containers: Query<Entity, With<HierarchyTreeContainer>>,
) -> Vec<Entity> {
    containers.iter().collect()
}

/// Walk `entity`'s parent chain until a `HierarchyTreeContainer` is
/// found, returning its [`Entity`]. Used by per-row code paths that
/// need to address the owning Outliner panel for `TreeIndex` lookups
/// keyed by `(container, source)`.
fn ancestor_hierarchy_root(world: &World, entity: Entity) -> Option<Entity> {
    let mut current = entity;
    loop {
        if world.get::<HierarchyTreeContainer>(current).is_some() {
            return Some(current);
        }
        match world.get::<ChildOf>(current) {
            Some(ChildOf(parent)) => current = *parent,
            None => return None,
        }
    }
}

/// Spawn a single (non-recursive) tree row for a source entity in
/// `parent_container`. Multi-instance tree containers each call
/// this with their own container; the `TreeIndex` is keyed by
/// `(container, source)` so the rows don't collide.
///
/// We register the new row in `TreeIndex` inline rather than waiting
/// for `maintain_tree_index` (which doesn't run until later in
/// `PostUpdate`). Without the immediate insert, two observers firing
/// on the same scene-entity spawn (e.g. `on_root_entity_added` plus
/// `on_name_changed`) both see an empty index and queue duplicate
/// rows, which is what produced the doubled Outliner entries.
fn spawn_single_tree_row(world: &mut World, source: Entity, parent_container: Entity) -> Entity {
    let label = world
        .get::<Name>(source)
        .map(|n| n.as_str().to_string())
        .unwrap_or_else(|| format!("Entity {source}"));
    let has_children = has_visible_children(world, source);
    let category = classify_entity(world, source);
    let icon_font = world.resource::<IconFont>().0.clone();
    let style = TreeRowStyle { icon_font };

    let tree_row_entity = world
        .spawn((
            tree_row(&label, has_children, false, source, category, &style),
            ChildOf(parent_container),
        ))
        .id();

    // Register immediately under the owning Outliner panel so the
    // next caller in the same `commands.queue` flush sees the row
    // and skips it.
    if let Some(root) = ancestor_hierarchy_root(world, parent_container) {
        world
            .resource_mut::<TreeIndex>()
            .insert(root, source, tree_row_entity);
    }
    tree_row_entity
}

// This has to be a system instead of an observer because it must run after `tree_view::maintain_tree_index`
fn rebuild_hierarchy_on_container_added(
    added: Query<Entity, Added<HierarchyTreeContainer>>,
    mut commands: Commands,
) {
    if !added.is_empty() {
        commands.queue(rebuild_hierarchy);
    }
}

fn rebuild_hierarchy(world: &mut World) -> Result {
    fn rebuild_hierarchy_inner(
        world: &mut World,
        containers: &mut QueryState<Entity, With<HierarchyTreeContainer>>,
        roots: &mut QueryState<
            Entity,
            (
                With<Transform>,
                Without<EditorEntity>,
                Without<EditorHidden>,
                Without<ChildOf>,
            ),
        >,
    ) {
        // Every Outliner panel gets its own copy of the tree, so
        // iterate every container that's currently mounted. Zero
        // containers (headless tests, pre-Editor state) means there's
        // nothing to rebuild against.
        let containers: Vec<Entity> = containers.iter(world).collect();
        if containers.is_empty() {
            return;
        }

        // Collect all root scene entities (Transform, no ChildOf, no editor markers).
        let roots: Vec<Entity> = roots.iter(world).collect();
        let show_all = world.resource::<HierarchyShowAll>().0;

        let mut root_data: Vec<(Entity, EntityCategory, String)> = roots
            .into_iter()
            .filter(|&e| show_all || world.get::<Name>(e).is_some())
            .map(|e| {
                let category = classify_entity(world, e);
                let name = world
                    .get::<Name>(e)
                    .map(|n| n.as_str().to_string())
                    .unwrap_or_else(|| format!("Entity {e}"));
                (e, category, name)
            })
            .collect();

        root_data.sort_by(|(_, cat_a, name_a), (_, cat_b, name_b)| {
            cat_a.cmp(cat_b).then_with(|| name_a.cmp(name_b))
        });

        for container in containers {
            for (entity, _category, _name) in &root_data {
                if world.resource::<TreeIndex>().contains(container, *entity) {
                    continue;
                }
                spawn_single_tree_row(world, *entity, container);
            }
        }
    }
    world
        .run_system_cached(rebuild_hierarchy_inner)
        .map_err(BevyError::from)
}

/// When a new entity gets Transform and has no parent, create a row
/// for it in every Outliner panel. Multi-instance setups iterate
/// every container; the per-`(container, source)` `TreeIndex`
/// keys keep them independent.
fn on_root_entity_added(
    trigger: On<Add, Transform>,
    mut commands: Commands,
    tree_index: Res<TreeIndex>,
    editor_check: Query<(), Or<(With<EditorEntity>, With<EditorHidden>)>>,
    child_of_check: Query<(), With<ChildOf>>,
) {
    let entity = trigger.event_target();

    if editor_check.contains(entity) || child_of_check.contains(entity) {
        return;
    }
    if tree_index.contains_anywhere(entity) {
        return;
    }

    commands.queue(move |world: &mut World| {
        // Re-check: ChildOf may have been added between observer and command flush
        if world.get::<ChildOf>(entity).is_some() {
            return;
        }
        if world.get::<EditorEntity>(entity).is_some()
            || world.get::<EditorHidden>(entity).is_some()
        {
            return;
        }
        // In named-only mode, skip entities without a Name
        if !world.resource::<HierarchyShowAll>().0 && world.get::<Name>(entity).is_none() {
            return;
        }
        let containers: Vec<Entity> = world
            .run_system_cached(collect_hierarchy_containers)
            .unwrap_or_default();
        for container in containers {
            if world.resource::<TreeIndex>().contains(container, entity) {
                continue;
            }
            spawn_single_tree_row(world, entity, container);
        }
    });
}

/// When an entity's Name is added/changed, update its row label in
/// every Outliner panel. Also creates a row in each container if the
/// entity is a visible root without one yet.
fn on_name_changed(
    trigger: On<Add, Name>,
    mut commands: Commands,
    name_query: Query<&Name>,
    tree_index: Res<TreeIndex>,
    tree_nodes: Query<&Children, With<TreeNode>>,
    content_query: Query<&Children, With<TreeRowContent>>,
    mut label_query: Query<&mut Text, With<TreeRowLabel>>,
    editor_check: Query<(), Or<(With<EditorEntity>, With<EditorHidden>)>>,
    child_of_check: Query<(), With<ChildOf>>,
) {
    let entity = trigger.event_target();
    let Ok(name) = name_query.get(entity) else {
        return;
    };

    let any_row = tree_index.contains_anywhere(entity);
    if any_row {
        // Update label in every container that has a row for this source.
        for (_container, tree_entity) in tree_index.rows_for_source(entity) {
            let Ok(children) = tree_nodes.get(tree_entity) else {
                continue;
            };
            for child in children.iter() {
                if let Ok(content_children) = content_query.get(child) {
                    for grandchild in content_children.iter() {
                        if let Ok(mut text) = label_query.get_mut(grandchild) {
                            text.0 = name.as_str().to_string();
                            break;
                        }
                    }
                }
            }
        }
    } else {
        // No row exists anywhere yet. Spawn one per container if this
        // is a visible root.
        if editor_check.contains(entity) || child_of_check.contains(entity) {
            return;
        }

        commands.queue(move |world: &mut World| {
            // Re-check: ChildOf may have been added between observer and command flush
            if world.get::<ChildOf>(entity).is_some() {
                return;
            }
            if world.get::<EditorEntity>(entity).is_some()
                || world.get::<EditorHidden>(entity).is_some()
            {
                return;
            }
            let mut q = world.query_filtered::<Entity, With<HierarchyTreeContainer>>();
            let containers: Vec<Entity> = q.iter(world).collect();
            for container in containers {
                if world.resource::<TreeIndex>().contains(container, entity) {
                    continue;
                }
                spawn_single_tree_row(world, entity, container);
            }
        });
    }
}

/// Spawn a watcher entity that notifies us when Name is mutated in-place.
fn setup_name_watcher(mut commands: Commands) {
    commands
        .spawn((EditorEntity, NotifyChanged::<Name>::default()))
        .observe(on_name_mutated);
}

/// Pre-register the `NotifyChanged<TreeNodeExpanded>` hook during
/// Startup. `bevy_monitors`'s add-hook queues a command that calls
/// `world.schedule_scope(Update, ...)` the first time any entity with
/// `NotifyChanged<C>` spawns. If that first spawn happens while `Update`
/// is already executing (e.g. `reconcile_tree` spawning scene tree rows
/// on workspace switch), the queued command panics with "Schedule
/// Update not found". Registering a watcher entity here in Startup
/// flushes the hook before any `Update` tick runs, so subsequent spawns
/// take the `DetectingChanges<TreeNodeExpanded>` early-return branch.
fn setup_tree_node_expanded_watcher(mut commands: Commands) {
    commands.spawn(NotifyChanged::<TreeNodeExpanded>::default());
}

/// When an entity's Name is mutated in-place (e.g. via inspector),
/// update the row label in every Outliner panel that has a row for it.
fn on_name_mutated(
    trigger: On<Mutation<Name>>,
    name_query: Query<&Name>,
    tree_index: Res<TreeIndex>,
    tree_nodes: Query<&Children, With<TreeNode>>,
    content_query: Query<&Children, With<TreeRowContent>>,
    mut label_query: Query<&mut Text, With<TreeRowLabel>>,
) {
    let entity = trigger.mutated;
    let Ok(name) = name_query.get(entity) else {
        return;
    };
    for (_container, tree_entity) in tree_index.rows_for_source(entity) {
        let Ok(children) = tree_nodes.get(tree_entity) else {
            continue;
        };
        for child in children.iter() {
            let Ok(content_children) = content_query.get(child) else {
                continue;
            };
            for grandchild in content_children.iter() {
                if let Ok(mut text) = label_query.get_mut(grandchild) {
                    text.0 = name.as_str().to_string();
                    break;
                }
            }
        }
    }
}

/// When an entity gets a parent (`ChildOf` added or changed),
/// reparent or create its row in every Outliner panel.
fn on_entity_reparented(
    trigger: On<Add, ChildOf>,
    mut commands: Commands,
    tree_index: Res<TreeIndex>,
    editor_check: Query<(), Or<(With<EditorEntity>, With<EditorHidden>)>>,
    tree_node_check: Query<(), With<TreeNode>>,
    child_of_query: Query<&ChildOf>,
    children_query: Query<&Children>,
    tree_row_children: Query<Entity, With<TreeRowChildren>>,
    populated_query: Query<&TreeChildrenPopulated>,
) {
    let entity = trigger.event_target();

    // Skip editor/hidden entities and tree row UI entities
    if editor_check.contains(entity) || tree_node_check.contains(entity) {
        return;
    }

    let Ok(&ChildOf(new_parent)) = child_of_query.get(entity) else {
        return;
    };

    // For every Outliner panel that has a row for the new parent, find
    // its `TreeRowChildren` container and either reparent the existing
    // row (if this entity already has a row in that panel) or queue a
    // fresh spawn (if the parent's children are populated).
    let parent_rows: Vec<(Entity, Entity)> = tree_index.rows_for_source(new_parent).collect();
    if parent_rows.is_empty() {
        return;
    }

    for (container, parent_tree) in parent_rows {
        let parent_children_container = children_query
            .get(parent_tree)
            .ok()
            .and_then(|children| children.iter().find(|c| tree_row_children.contains(*c)));

        if let Some(tree_entity) = tree_index.get(container, entity) {
            if let Some(parent_children_container) = parent_children_container {
                commands
                    .entity(tree_entity)
                    .insert(ChildOf(parent_children_container));
            } else {
                let container_for_remove = container;
                let source = entity;
                commands.queue(move |world: &mut World| {
                    world
                        .resource_mut::<TreeIndex>()
                        .remove(container_for_remove, source);
                    if let Ok(ec) = world.get_entity_mut(tree_entity) {
                        ec.despawn();
                    }
                });
            }
            continue;
        }

        let Some(parent_children_container) = parent_children_container else {
            continue;
        };
        let populated = populated_query
            .get(parent_tree)
            .map(|p| p.0)
            .unwrap_or(false);
        if !populated {
            continue; // Lazy loading handles it when parent is expanded
        }

        let container_for_spawn = container;
        let parent_children_container_for_spawn = parent_children_container;
        commands.queue(move |world: &mut World| {
            if world
                .resource::<TreeIndex>()
                .contains(container_for_spawn, entity)
            {
                return;
            }
            // In named-only mode, skip entities without a Name
            if !world.resource::<HierarchyShowAll>().0 && world.get::<Name>(entity).is_none() {
                return;
            }
            spawn_single_tree_row(world, entity, parent_children_container_for_spawn);
        });
    }
}

/// When `ChildOf` is removed (entity deparented back to root, e.g.
/// via undo of a reparent), move its row back to the root container
/// in every Outliner panel. Without this, panels show stale parent
/// information after an undo.
fn on_entity_deparented(
    trigger: On<Remove, ChildOf>,
    mut commands: Commands,
    tree_index: Res<TreeIndex>,
    editor_check: Query<(), Or<(With<EditorEntity>, With<EditorHidden>)>>,
    tree_node_check: Query<(), With<TreeNode>>,
) {
    let entity = trigger.event_target();
    if editor_check.contains(entity) || tree_node_check.contains(entity) {
        return;
    }
    for (container, tree_entity) in tree_index.rows_for_source(entity) {
        commands.entity(tree_entity).insert(ChildOf(container));
    }
}

/// When an entity's Name is removed, despawn its row in every
/// Outliner panel that has one.
fn on_entity_removed(
    trigger: On<Despawn, Name>,
    mut commands: Commands,
    tree_index: Res<TreeIndex>,
) {
    let entity = trigger.event_target();

    for (_container, tree_entity) in tree_index.rows_for_source(entity) {
        if let Ok(mut ec) = commands.get_entity(tree_entity) {
            ec.despawn();
        }
    }
}

/// When `EditorHidden` is added, remove the row in every Outliner panel
/// that has one (handles race with observers).
fn on_entity_hidden(
    trigger: On<Add, EditorHidden>,
    mut commands: Commands,
    tree_index: Res<TreeIndex>,
) {
    let entity = trigger.event_target();
    for (_container, tree_entity) in tree_index.rows_for_source(entity) {
        if let Ok(mut ec) = commands.get_entity(tree_entity) {
            ec.despawn();
        }
    }
}

/// When a tree node is expanded for the first time, spawn tree rows for its children.
fn on_tree_node_expanded(
    trigger: On<Mutation<TreeNodeExpanded>>,
    mut commands: Commands,
    tree_query: Query<(
        &TreeNodeExpanded,
        &TreeChildrenPopulated,
        &TreeNode,
        &Children,
    )>,
    tree_row_children_marker: Query<Entity, With<TreeRowChildren>>,
    remote_check: Query<(), With<crate::remote::entity_browser::RemoteEntityProxy>>,
) {
    let entity = trigger.event_target();
    let Ok((expanded, populated, tree_node, children)) = tree_query.get(entity) else {
        return;
    };

    // Only populate on first expansion
    if !expanded.0 || populated.0 {
        return;
    }

    let source = tree_node.0;

    // Skip remote entity proxies, handled by entity_browser observer
    if remote_check.contains(source) {
        return;
    }

    let Some(container) = children
        .iter()
        .find(|c| tree_row_children_marker.contains(*c))
    else {
        return;
    };
    let tree_row_entity = entity;

    commands.queue(move |world: &mut World| {
        // Double-check populated flag (guard against duplicate events)
        if let Some(pop) = world.get::<TreeChildrenPopulated>(tree_row_entity)
            && pop.0
        {
            return;
        }

        // Mark as populated
        if let Some(mut pop) = world.get_mut::<TreeChildrenPopulated>(tree_row_entity) {
            pop.0 = true;
        }

        // Collect visible children with classification
        let source_children: Vec<Entity> = world
            .get::<Children>(source)
            .map(|c| c.iter().collect())
            .unwrap_or_default();

        // Resolve the `HierarchyTreeContainer` that owns this
        // expansion by walking up from the per-row children container.
        // `TreeIndex` keys rows by their owning `HierarchyTreeContainer`,
        // so the duplicate check below needs that ancestor, not the
        // intermediate `TreeRowChildren` entity.
        let owning_root = ancestor_hierarchy_root(world, container);

        let mut child_data: Vec<(Entity, String, EntityCategory)> = Vec::new();
        for child in source_children {
            if world.get::<EditorEntity>(child).is_some()
                || world.get::<EditorHidden>(child).is_some()
            {
                continue;
            }
            // Skip children that already have a row under this
            // expansion's owning Outliner. Other Outliner panels'
            // expansion paths will spawn rows for the same child.
            if let Some(root) = owning_root
                && world.resource::<TreeIndex>().contains(root, child)
            {
                continue;
            }
            let name = world
                .get::<Name>(child)
                .map(|n| n.as_str().to_string())
                .unwrap_or_else(|| format!("Entity {child}"));
            let category = classify_entity(world, child);
            child_data.push((child, name, category));
        }

        // Sort by (category, name)
        child_data.sort_by(|(_, name_a, cat_a), (_, name_b, cat_b)| {
            cat_a.cmp(cat_b).then_with(|| name_a.cmp(name_b))
        });

        // Spawn tree rows
        for (child_entity, _name, _category) in child_data {
            spawn_single_tree_row(world, child_entity, container);
        }
    });
}

/// Handle tree row click → select the source entity.
/// Plain click on selected entity → deselect. Ctrl+Click → toggle.
fn on_tree_row_clicked(
    event: On<TreeRowClicked>,
    mut commands: Commands,
    mut selection: ResMut<Selection>,
    mut focused: ResMut<TreeFocused>,
    keyboard: Res<ButtonInput<KeyCode>>,
    parent_query: Query<&ChildOf>,
    tree_nodes: Query<Entity, With<TreeNode>>,
    remote_check: Query<(), With<crate::remote::entity_browser::RemoteEntityProxy>>,
) {
    // Skip remote entity proxies, handled by entity_browser observer
    if remote_check.contains(event.source_entity) {
        return;
    }

    let ctrl = keyboard.any_pressed([KeyCode::ControlLeft, KeyCode::ControlRight]);

    if ctrl {
        selection.toggle(&mut commands, event.source_entity);
    } else if selection.is_selected(event.source_entity) {
        selection.clear(&mut commands);
    } else {
        selection.select_single(&mut commands, event.source_entity);
    }

    // Set keyboard focus to the tree row containing this content
    let content_entity = event.entity;
    if let Ok(&ChildOf(tree_row)) = parent_query.get(content_entity)
        && tree_nodes.contains(tree_row)
    {
        focused.0 = Some(tree_row);
    }
}

/// When Selected is added, highlight the corresponding row in every
/// Outliner panel.
fn on_entity_selected(
    trigger: On<Add, Selected>,
    mut commands: Commands,
    tree_index: Res<TreeIndex>,
    tree_nodes: Query<&Children, With<TreeNode>>,
    tree_row_contents: Query<Entity, With<TreeRowContent>>,
    mut bg_query: Query<&mut BackgroundColor>,
    mut border_query: Query<&mut BorderColor>,
) {
    let entity = trigger.event_target();

    for (_container, tree_entity) in tree_index.rows_for_source(entity) {
        let Ok(children) = tree_nodes.get(tree_entity) else {
            continue;
        };
        for child in children.iter() {
            if tree_row_contents.contains(child) {
                if let Ok(mut ec) = commands.get_entity(child) {
                    ec.insert(TreeRowSelected);
                }
                if let Ok(mut bg) = bg_query.get_mut(child) {
                    bg.0 = tokens::SELECTED_BG;
                }
                if let Ok(mut border) = border_query.get_mut(child) {
                    *border = BorderColor::all(tokens::SELECTED_BORDER);
                }
                break;
            }
        }
    }
}

/// When Selected is removed, unhighlight the corresponding row in
/// every Outliner panel.
fn on_entity_deselected(
    trigger: On<Remove, Selected>,
    mut commands: Commands,
    tree_index: Res<TreeIndex>,
    tree_nodes: Query<&Children, With<TreeNode>>,
    tree_row_contents: Query<Entity, With<TreeRowContent>>,
    mut bg_query: Query<&mut BackgroundColor>,
    mut border_query: Query<&mut BorderColor>,
) {
    let entity = trigger.event_target();

    for (_container, tree_entity) in tree_index.rows_for_source(entity) {
        let Ok(children) = tree_nodes.get(tree_entity) else {
            continue;
        };
        for child in children.iter() {
            if tree_row_contents.contains(child) {
                if let Ok(mut ec) = commands.get_entity(child) {
                    ec.remove::<TreeRowSelected>();
                }
                if let Ok(mut bg) = bg_query.get_mut(child) {
                    bg.0 = ROW_BG;
                }
                if let Ok(mut border) = border_query.get_mut(child) {
                    *border = BorderColor::all(Color::NONE);
                }
                break;
            }
        }
    }
}

/// Handle tree row dropped → reparent the scene entity with undo support.
fn on_tree_row_dropped(
    event: On<TreeRowDropped>,
    mut commands: Commands,
    parent_query: Query<&ChildOf>,
) {
    let dragged = event.dragged_source;
    let target = event.target_source;

    if dragged == target {
        return;
    }

    // Cycle check: walk up from target, ensure dragged is not an ancestor
    let mut current = target;
    while let Ok(&ChildOf(parent)) = parent_query.get(current) {
        if parent == dragged {
            return;
        }
        current = parent;
    }

    let old_parent = parent_query.get(dragged).ok().map(|c| c.0);

    let mut cmd = ReparentEntity {
        entity: dragged,
        old_parent,
        new_parent: Some(target),
    };

    commands.queue(move |world: &mut World| {
        cmd.execute(world);
        world
            .resource_mut::<CommandHistory>()
            .undo_stack
            .push(Box::new(cmd));
        world.resource_mut::<CommandHistory>().redo_stack.clear();
    });
}

/// Handle tree row dropped on root container → deparent the scene entity.
fn on_tree_row_dropped_on_root(
    event: On<TreeRowDroppedOnRoot>,
    mut commands: Commands,
    parent_query: Query<&ChildOf, Without<EditorEntity>>,
    tree_index: Res<TreeIndex>,
) {
    let dragged = event.dragged_source;

    let old_parent = match parent_query.get(dragged) {
        Ok(child_of) => Some(child_of.0),
        Err(_) => return,
    };

    let mut cmd = ReparentEntity {
        entity: dragged,
        old_parent,
        new_parent: None,
    };

    commands.queue(move |world: &mut World| {
        cmd.execute(world);
        world
            .resource_mut::<CommandHistory>()
            .undo_stack
            .push(Box::new(cmd));
        world.resource_mut::<CommandHistory>().redo_stack.clear();
    });

    // Move every Outliner panel's row for this source back under its
    // own root container.
    for (container, tree_entity) in tree_index.rows_for_source(dragged) {
        commands.entity(tree_entity).insert(ChildOf(container));
    }
}

/// Open the hierarchy row context menu under the cursor (RMB).
#[operator(
    id = "hierarchy.open_context_menu",
    label = "Open Context Menu",
    description = "Show the context menu for the entity under the cursor.",
    allows_undo = false
)]
pub(crate) fn hierarchy_open_context_menu(
    _: In<OperatorParameters>,
    mut commands: Commands,
    mut state: ResMut<ContextMenuState>,
    windows: Query<&Window>,
    selection: Res<Selection>,
    tree_row_contents: Query<(Entity, &ChildOf), With<TreeRowContent>>,
    tree_nodes: Query<&TreeNode>,
    computed_nodes: Query<(&ComputedNode, &UiGlobalTransform), With<TreeRowContent>>,
    extension_add_entries: Query<&jackdaw_api_internal::lifecycle::RegisteredMenuEntry>,
) -> OperatorResult {
    let Ok(window) = windows.single() else {
        return OperatorResult::Cancelled;
    };
    let Some(cursor_pos) = window.cursor_position() else {
        return OperatorResult::Cancelled;
    };

    // Close any existing context menu
    if let Some(menu) = state.menu_entity.take()
        && let Ok(mut ec) = commands.get_entity(menu)
    {
        ec.despawn();
    }

    // Find which tree row content the cursor is over by hit testing
    let mut target_source = None;
    for (content_entity, child_of) in &tree_row_contents {
        let Ok((computed, global_transform)) = computed_nodes.get(content_entity) else {
            continue;
        };
        let size = computed.size();
        let (_, _, translation) = global_transform.to_scale_angle_translation();
        let pos = translation;
        let half = size / 2.0;
        let rect = Rect::from_center_half_size(pos, half);
        if rect.contains(cursor_pos)
            && let Ok(tree_node) = tree_nodes.get(child_of.0)
        {
            target_source = Some(tree_node.0);
            break;
        }
    }

    let Some(target) = target_source else {
        return OperatorResult::Cancelled;
    };

    // If the right-clicked entity isn't selected, select it
    if !selection.is_selected(target) {
        commands.queue(move |world: &mut World| {
            let old_entities: Vec<Entity> = world.resource::<Selection>().entities.clone();
            let mut selection = world.resource_mut::<Selection>();
            selection.entities.clear();
            selection.entities.push(target);

            for &e in &old_entities {
                if e != target
                    && let Ok(mut ec) = world.get_entity_mut(e)
                {
                    ec.remove::<Selected>();
                }
            }
            if let Ok(mut ec) = world.get_entity_mut(target) {
                ec.insert(Selected);
            }
        });
    }

    // Built-in context menu items. The "Add Child ..." entries are the
    // parent-aware variant: they spawn the entity and reparent it under
    // the right-clicked target.
    let mut owned_items: Vec<(String, String)> = vec![
        (
            "hierarchy.focus".into(),
            "Focus                    F".into(),
        ),
        ("hierarchy.rename".into(), "Rename              F2".into()),
        (
            "hierarchy.duplicate".into(),
            "Duplicate        Ctrl+D".into(),
        ),
        ("hierarchy.delete".into(), "Delete             Del".into()),
        (
            "hierarchy.save_template".into(),
            "Save as Template...".into(),
        ),
        ("hierarchy.add_cube".into(), "Add Child Cube".into()),
        ("hierarchy.add_sphere".into(), "Add Child Sphere".into()),
        ("hierarchy.add_light".into(), "Add Child Light".into()),
        ("hierarchy.add_empty".into(), "Add Child Empty".into()),
    ];

    // Append extension-contributed Add entries from the same source the
    // toolbar Add menu and the Add Entity picker use. One
    // `register_menu_entry` call therefore surfaces in all three places.
    let mut ext_rows: Vec<(String, String)> = extension_add_entries
        .iter()
        .filter(|entry| entry.menu == TopLevelMenu::Add)
        .map(|entry| {
            (
                format!("{OP_PREFIX}{}", entry.operator_id),
                format!("Add {}", entry.label),
            )
        })
        .collect();
    ext_rows.sort_by(|a, b| a.1.cmp(&b.1));
    owned_items.extend(ext_rows);

    let items: Vec<(&str, &str)> = owned_items
        .iter()
        .map(|(a, l)| (a.as_str(), l.as_str()))
        .collect();

    let menu = spawn_context_menu(&mut commands, cursor_pos, Some(target), &items);
    state.menu_entity = Some(menu);
    state.target_entity = Some(target);
    OperatorResult::Finished
}

/// Handle context menu actions for hierarchy operations.
fn on_context_menu_action(
    event: On<ContextMenuAction>,
    mut commands: Commands,
    global_transforms: Query<&GlobalTransform>,
    mut camera_query: Query<&mut Transform, With<jackdaw_camera::JackdawCameraSettings>>,
) {
    let target_entity = event.target_entity;

    match event.action.as_str() {
        "hierarchy.focus" => {
            if let Some(target) = target_entity
                && let Ok(global_tf) = global_transforms.get(target)
            {
                let target_pos = global_tf.translation();
                let scale = global_tf.compute_transform().scale;
                let dist = (scale.length() * 3.0).max(5.0);

                for mut transform in &mut camera_query {
                    let forward = transform.forward().as_vec3();
                    transform.translation = target_pos - forward * dist;
                    *transform = transform.looking_at(target_pos, Vec3::Y);
                }
            }
        }
        "hierarchy.rename" => {
            if let Some(target) = target_entity {
                commands
                    .operator(RenameBeginOp::ID)
                    .param("entity", target)
                    .call();
            }
        }
        "hierarchy.duplicate" => {
            commands.queue(|world: &mut World| {
                entity_ops::duplicate_selected(world);
            });
        }
        "hierarchy.delete" => {
            commands.queue(|world: &mut World| {
                entity_ops::delete_selected(world);
            });
        }
        "hierarchy.add_cube" => {
            if let Some(parent) = target_entity {
                commands.queue(move |world: &mut World| {
                    entity_ops::create_entity_in_world(world, entity_ops::EntityTemplate::Cube);
                    // Reparent the newly created entity under the target
                    let selection = world.resource::<Selection>();
                    if let Some(new_entity) = selection.primary() {
                        world.entity_mut(new_entity).insert(ChildOf(parent));
                    }
                });
            }
        }
        "hierarchy.add_sphere" => {
            if let Some(parent) = target_entity {
                commands.queue(move |world: &mut World| {
                    entity_ops::create_entity_in_world(world, entity_ops::EntityTemplate::Sphere);
                    let selection = world.resource::<Selection>();
                    if let Some(new_entity) = selection.primary() {
                        world.entity_mut(new_entity).insert(ChildOf(parent));
                    }
                });
            }
        }
        "hierarchy.add_light" => {
            if let Some(parent) = target_entity {
                commands.queue(move |world: &mut World| {
                    entity_ops::create_entity_in_world(
                        world,
                        entity_ops::EntityTemplate::PointLight,
                    );
                    let selection = world.resource::<Selection>();
                    if let Some(new_entity) = selection.primary() {
                        world.entity_mut(new_entity).insert(ChildOf(parent));
                    }
                });
            }
        }
        "hierarchy.add_empty" => {
            if let Some(parent) = target_entity {
                commands.queue(move |world: &mut World| {
                    entity_ops::create_entity_in_world(world, entity_ops::EntityTemplate::Empty);
                    let selection = world.resource::<Selection>();
                    if let Some(new_entity) = selection.primary() {
                        world.entity_mut(new_entity).insert(ChildOf(parent));
                    }
                });
            }
        }
        "hierarchy.save_template" => {
            if let Some(target) = target_entity {
                // Store the target entity and open a dialog for template name
                commands.queue(move |world: &mut World| {
                    world
                        .resource_mut::<crate::entity_templates::PendingTemplateSave>()
                        .entity = Some(target);
                    // Get the entity name as default template name
                    let default_name = world
                        .get::<Name>(target)
                        .map(|n| n.as_str().to_string())
                        .unwrap_or_else(|| "template".to_string());
                    world.resource_mut::<PendingTemplateDefaultName>().0 = default_name;
                });
                commands.trigger(jackdaw_feathers::dialog::OpenDialogEvent::new(
                    "Save as Template",
                    "Save",
                ));
            }
        }
        action if action.starts_with(OP_PREFIX) => {
            // Extension-contributed Add entry. Dispatch through the same
            // path as the toolbar Add menu and the Add Entity picker so
            // operators behave identically regardless of which surface
            // invoked them.
            let operator_id = action.strip_prefix(OP_PREFIX).unwrap().to_string();
            commands.queue(move |world: &mut World| {
                world
                    .operator(operator_id)
                    .settings(CallOperatorSettings {
                        execution_context: ExecutionContext::Invoke,
                        creates_history_entry: true,
                    })
                    .call()
            });
        }
        _ => {}
    }
}

/// Toggle entity visibility when the eye icon is clicked.
fn on_visibility_toggled(
    event: On<TreeRowVisibilityToggled>,
    mut commands: Commands,
    visibility_query: Query<&Visibility>,
) {
    let source = event.source_entity;

    let current = visibility_query
        .get(source)
        .copied()
        .unwrap_or(Visibility::Inherited);

    let new_visibility = match current {
        Visibility::Hidden => Visibility::Inherited,
        _ => Visibility::Hidden,
    };

    let old_json = serde_json::Value::String(format!("{current:?}"));
    let new_json = serde_json::Value::String(format!("{new_visibility:?}"));

    let cmd = SetJsnField {
        entity: source,
        type_path: "bevy_camera::visibility::Visibility".to_string(),
        field_path: String::new(),
        old_value: old_json,
        new_value: new_json,
        was_derived: false,
    };

    commands.queue(move |world: &mut World| {
        let mut cmd = Box::new(cmd);
        cmd.execute(world);
        let mut history = world.resource_mut::<CommandHistory>();
        history.push_executed(cmd);
    });
}

pub(crate) fn add_to_extension(ctx: &mut ExtensionContext) {
    ctx.register_operator::<RenameBeginOp>()
        .register_operator::<HierarchyOpenContextMenuOp>();
    let ext = ctx.id();
    ctx.spawn((
        Action::<HierarchyOpenContextMenuOp>::new(),
        ActionOf::<crate::core_extension::CoreExtensionInputContext>::new(ext),
        bindings![(MouseButton::Right, Press::default())],
    ));
    ctx.spawn((
        Action::<RenameBeginOp>::new(),
        ActionOf::<crate::core_extension::CoreExtensionInputContext>::new(ext),
        bindings![(KeyCode::F2, Press::default())],
    ));
}

/// Marker for inline rename `text_edit` entity, linking back to the label entity and source entity.
#[derive(Component)]
struct InlineRenameInput {
    label_entity: Entity,
    source_entity: Entity,
}

fn on_tree_row_start_rename(event: On<TreeRowStartRename>, mut commands: Commands) {
    let target = event.source_entity;
    commands
        .operator(RenameBeginOp::ID)
        .param("entity", target)
        .call();
}

/// `is_available` for `hierarchy.rename_begin`: only fires when no
/// inline rename is already in progress.
fn no_rename_in_progress(rename_check: Query<(), With<InlineRenameInput>>) -> bool {
    rename_check.is_empty()
}

/// Pick the entity to rename: the explicit `entity` operator
/// parameter wins (used by the context-menu "Rename" action and the
/// `TreeRowStartRename` event), otherwise fall back to the primary
/// selection so a bare F2 press renames whatever the user has
/// highlighted in the outliner. Pulled out so the regression check
/// for the F2-without-selection path can run as a unit test.
pub(crate) fn resolve_rename_target(
    params: &OperatorParameters,
    selection: &Selection,
) -> Option<Entity> {
    params.as_entity("entity").or_else(|| selection.primary())
}

fn entity_name(names: &Query<&Name>, entity: Entity) -> String {
    names
        .get(entity)
        .map(|n| n.as_str().to_string())
        .unwrap_or_default()
}

/// Resolve the label entity and its containing row for a scene
/// entity's tree node. With multi-instance Outliner panels, returns
/// the first match across all containers; the inline-rename UX
/// targets one panel at a time and the others stay synchronised
/// once the rename commits via `on_name_changed` / `on_name_mutated`.
fn find_rename_targets(
    source: Entity,
    tree_index: &TreeIndex,
    tree_nodes: &Query<&Children, With<TreeNode>>,
    content_query: &Query<(Entity, &Children), With<TreeRowContent>>,
    label_query: &Query<Entity, With<TreeRowLabel>>,
) -> Option<(Entity, Entity)> {
    for (_container, tree_entity) in tree_index.rows_for_source(source) {
        let Ok(children) = tree_nodes.get(tree_entity) else {
            continue;
        };
        for child in children.iter() {
            if let Ok((content_e, content_children)) = content_query.get(child) {
                for grandchild in content_children.iter() {
                    if label_query.contains(grandchild) {
                        return Some((grandchild, content_e));
                    }
                }
            }
        }
    }
    None
}

/// Custom command: drop the inline-rename marker from a tree-row label
/// and restore its displayed text + visibility. Issued from rename
/// commit/cancel paths so the queue boundary is explicit.
struct RestoreLabel {
    label_entity: Entity,
    text: String,
}

impl Command for RestoreLabel {
    fn apply(self, world: &mut World) {
        let Ok(mut ec) = world.get_entity_mut(self.label_entity) else {
            return;
        };
        ec.remove::<TreeRowInlineRename>();
        ec.insert(Text::new(self.text));
        if let Some(mut node) = ec.get_mut::<Node>() {
            node.display = Display::Flex;
        }
    }
}

/// Begin inline rename of an entity in the hierarchy tree.
#[operator(
    id = "hierarchy.rename_begin",
    label = "Rename Entity",
    description = "Rename the selected entity in the hierarchy.",
    modal = true,
    cancel = cancel_rename_begin,
    is_available = no_rename_in_progress,
    params(entity(Entity, doc = "Scene entity to rename.")),
)]
pub fn rename_begin(
    params: In<OperatorParameters>,
    mut commands: Commands,
    tree_index: Res<TreeIndex>,
    tree_nodes: Query<&Children, With<TreeNode>>,
    content_query: Query<(Entity, &Children), With<TreeRowContent>>,
    label_query: Query<Entity, With<TreeRowLabel>>,
    names: Query<&Name>,
    rename_inputs: Query<(), With<InlineRenameInput>>,
    active: ActiveModalQuery,
    selection: Res<Selection>,
) -> OperatorResult {
    if active.is_modal_running() {
        return if rename_inputs.is_empty() {
            OperatorResult::Finished
        } else {
            OperatorResult::Running
        };
    }

    let Some(source) = resolve_rename_target(&params, &selection) else {
        return OperatorResult::Cancelled;
    };
    let Some((label_entity, content_entity)) = find_rename_targets(
        source,
        &tree_index,
        &tree_nodes,
        &content_query,
        &label_query,
    ) else {
        return OperatorResult::Cancelled;
    };

    commands.entity(label_entity).insert(TreeRowInlineRename);
    commands
        .entity(label_entity)
        .entry::<Node>()
        .and_modify(|mut node| {
            node.display = Display::None;
        });

    commands.spawn((
        InlineRenameInput {
            label_entity,
            source_entity: source,
        },
        text_edit::text_edit(
            TextEditProps::default()
                .with_default_value(entity_name(&names, source))
                .allow_empty(),
        ),
        ChildOf(content_entity),
    ));
    OperatorResult::Running
}

fn cancel_rename_begin(
    mut commands: Commands,
    rename_query: Query<(Entity, &InlineRenameInput)>,
    names: Query<&Name>,
    mut input_focus: ResMut<InputFocus>,
) {
    for (rename_entity, inline_rename) in &rename_query {
        input_focus.clear();
        let original = entity_name(&names, inline_rename.source_entity);
        commands.queue(RestoreLabel {
            label_entity: inline_rename.label_entity,
            text: original,
        });
        commands.entity(rename_entity).despawn();
    }
}

/// Auto-focus inline rename `text_edit` inputs one frame after spawn.
fn auto_focus_inline_rename(
    rename_inputs: Query<(Entity, &InlineRenameInput, &Children)>,
    wrappers: Query<&jackdaw_feathers::text_edit::TextEditConfig>,
    wrapper_children: Query<&Children>,
    editor_text_edits: Query<Entity, With<EditorTextEdit>>,
    mut input_focus: ResMut<InputFocus>,
) {
    for (_rename_entity, _inline, children) in &rename_inputs {
        // The text_edit outer entity has children: [wrapper] which has children: [..., EditorTextEdit]
        for child in children.iter() {
            if wrappers.contains(child) {
                // this is the label/wrapper -- skip, we need the actual wrapper node
                continue;
            }
            // child might be the wrapper entity (has TextEditWrapper inside)
            if let Ok(wrapper_kids) = wrapper_children.get(child) {
                for wk in wrapper_kids.iter() {
                    if editor_text_edits.contains(wk) {
                        if input_focus.0 != Some(wk) {
                            input_focus.0 = Some(wk);
                        }
                        return;
                    }
                }
            }
        }
    }
}

/// Handle `TextEditCommitEvent` for inline renames.
fn handle_inline_rename_commit(
    event: On<TextEditCommitEvent>,
    rename_inputs: Query<(Entity, &InlineRenameInput)>,
    child_of_query: Query<&ChildOf>,
    mut commands: Commands,
    mut input_focus: ResMut<InputFocus>,
) {
    // Walk up from the committed entity to find if it belongs to an InlineRenameInput
    // event.entity is the inner EditorTextEdit → parent is wrapper → parent is text_edit outer → parent is content
    // The InlineRenameInput is on the text_edit outer entity
    let mut current = event.entity;
    let mut found = None;
    for _ in 0..4 {
        let Ok(child_of) = child_of_query.get(current) else {
            break;
        };
        if let Ok((rename_entity, inline_rename)) = rename_inputs.get(child_of.parent()) {
            found = Some((
                rename_entity,
                inline_rename.label_entity,
                inline_rename.source_entity,
            ));
            break;
        }
        current = child_of.parent();
    }

    let Some((rename_entity, label_entity, source_entity)) = found else {
        return;
    };

    input_focus.clear();
    commands.queue(RestoreLabel {
        label_entity,
        text: event.text.clone(),
    });
    commands.entity(rename_entity).despawn();

    // Trigger the rename
    commands.trigger(TreeRowRenamed {
        entity: label_entity,
        source_entity,
        new_name: event.text.clone(),
    });
}

/// Commit inline rename: update Name with undo.
fn on_tree_row_renamed(event: On<TreeRowRenamed>, mut commands: Commands, names: Query<&Name>) {
    let source = event.source_entity;
    let new_name = event.new_name.clone();

    // Apply name change with undo
    let old_name = names
        .get(source)
        .map(|n| n.as_str().to_string())
        .unwrap_or_default();

    if old_name == new_name {
        return;
    }

    commands.queue(move |world: &mut World| {
        let cmd = SetJsnField {
            entity: source,
            type_path: "bevy_ecs::name::Name".to_string(),
            field_path: String::new(),
            old_value: serde_json::Value::String(old_name),
            new_value: serde_json::Value::String(new_name),
            was_derived: false,
        };
        let mut cmd = Box::new(cmd);
        cmd.execute(world);
        let mut history = world.resource_mut::<CommandHistory>();
        history.push_executed(cmd);
    });
}

/// When the template dialog opens, populate its children slot with a name input.
fn populate_template_dialog(
    mut commands: Commands,
    pending: Res<crate::entity_templates::PendingTemplateSave>,
    default_name: Res<PendingTemplateDefaultName>,
    slots: Query<(Entity, &Children), (With<DialogChildrenSlot>, Changed<Children>)>,
    existing_inputs: Query<(), With<TemplateNameInput>>,
) {
    // Only act when there's a pending template save
    if pending.entity.is_none() {
        return;
    }
    // Don't re-populate if we already have an input
    if !existing_inputs.is_empty() {
        return;
    }
    for (slot_entity, children) in &slots {
        if children.is_empty() {
            commands.spawn((
                TemplateNameInput,
                text_edit::text_edit(
                    TextEditProps::default()
                        .with_placeholder("Template name...")
                        .with_default_value(default_name.0.clone())
                        .allow_empty(),
                ),
                ChildOf(slot_entity),
            ));
        }
    }
}

/// When the dialog's action button is clicked, save the template.
fn on_template_dialog_action(
    _event: On<DialogActionEvent>,
    mut commands: Commands,
    pending: Res<crate::entity_templates::PendingTemplateSave>,
    name_inputs: Query<&TextEditValue, With<TemplateNameInput>>,
) {
    let Some(_entity) = pending.entity else {
        return;
    };

    let name = name_inputs
        .iter()
        .next()
        .map(|input| input.0.trim().to_string())
        .unwrap_or_default();

    if name.is_empty() {
        return;
    }

    commands.queue(move |world: &mut World| {
        crate::entity_templates::save_entity_template(world, &name);
        world
            .resource_mut::<crate::entity_templates::PendingTemplateSave>()
            .entity = None;
    });
}

/// Toggle the show-all state when the button is pressed.
fn toggle_show_all_button(
    mut show_all: ResMut<HierarchyShowAll>,
    interactions: Query<&Interaction, (Changed<Interaction>, With<HierarchyShowAllButton>)>,
) {
    for interaction in &interactions {
        if *interaction == Interaction::Pressed {
            show_all.0 = !show_all.0;
        }
    }
}

/// Style hierarchy rows whose source entity was spawned during
/// `PlayState::Playing` (i.e. has the `GameSpawned` marker) in
/// italic, so the user can tell at a glance which rows are
/// authored vs transient runtime state that'll disappear on Stop.
///
/// Uses the `EditorFontItalic` handle loaded by
/// `jackdaw_feathers::icons`. Text colour stays at the theme's
/// primary foreground; only the font handle changes. Runs every
/// frame while in `Editor` state; the body is a few pointer-chasing
/// lookups per game-spawned entity; cheap enough to skip change
/// detection. We only write when the font differs to keep bevy's
/// `Changed<TextFont>` quiet for downstream consumers.
fn style_game_spawned_rows(
    game_spawned: Query<Entity, With<crate::pie::GameSpawned>>,
    index: Res<jackdaw_widgets::tree_view::TreeIndex>,
    italic_font: Option<Res<jackdaw_feathers::icons::EditorFontItalic>>,
    children_q: Query<&Children>,
    row_content_q: Query<(), With<jackdaw_widgets::tree_view::TreeRowContent>>,
    label_q: Query<(), With<jackdaw_widgets::tree_view::TreeRowLabel>>,
    mut text_fonts: Query<&mut TextFont>,
) {
    let Some(italic_font) = italic_font else {
        return;
    };
    // Italicise the row in every Outliner panel that has one for the
    // game-spawned source.
    for source in &game_spawned {
        for (_container, row_entity) in index.rows_for_source(source) {
            let Ok(row_children) = children_q.get(row_entity) else {
                continue;
            };
            for content in row_children.iter() {
                if !row_content_q.contains(content) {
                    continue;
                }
                let Ok(content_children) = children_q.get(content) else {
                    continue;
                };
                for maybe_label in content_children.iter() {
                    if !label_q.contains(maybe_label) {
                        continue;
                    }
                    if let Ok(mut tf) = text_fonts.get_mut(maybe_label)
                        && tf.font != italic_font.0
                    {
                        tf.font = italic_font.0.clone();
                    }
                }
            }
        }
    }
}

/// Update the show-all button icon color based on active state.
fn update_show_all_button_appearance(
    show_all: Res<HierarchyShowAll>,
    buttons: Query<&Children, With<HierarchyShowAllButton>>,
    mut text_colors: Query<&mut TextColor>,
) {
    if !show_all.is_changed() {
        return;
    }
    let color = if show_all.0 {
        tokens::TEXT_PRIMARY
    } else {
        tokens::TEXT_SECONDARY
    };
    for children in &buttons {
        for child in children.iter() {
            if let Ok(mut tc) = text_colors.get_mut(child) {
                tc.0 = color;
            }
        }
    }
}

/// When the show-all toggle changes, clear and rebuild the hierarchy.
fn on_show_all_changed(show_all: Res<HierarchyShowAll>, mut commands: Commands) {
    if show_all.is_changed() && !show_all.is_added() {
        commands.queue(|world: &mut World| {
            if let Err(err) = world.run_system_cached(clear_all_tree_rows) {
                error!("Failed to clear tree rows: {err}");
            }
            rebuild_hierarchy(world)
        });
    }
}

/// Despawn every Outliner panel's tree rows and reset the
/// `TreeIndex`. Used by show-all toggle and similar full-rebuild
/// paths.
pub fn clear_all_tree_rows(
    world: &mut World,
    containers: &mut QueryState<Entity, With<HierarchyTreeContainer>>,
) {
    let containers: Vec<Entity> = containers.iter(world).collect();
    if containers.is_empty() {
        return;
    }

    for container in &containers {
        let tree_rows: Vec<Entity> = world
            .get::<Children>(*container)
            .map(|c| c.iter().collect())
            .unwrap_or_default();
        for row in tree_rows {
            if let Ok(ec) = world.get_entity_mut(row) {
                ec.despawn();
            }
        }
    }

    world.resource_mut::<TreeIndex>().clear();
}

/// Filter hierarchy tree rows based on the filter text input.
fn apply_hierarchy_filter(
    filter_input: Query<&TextEditValue, (With<HierarchyFilter>, Changed<TextEditValue>)>,
    tree_nodes: Query<(Entity, &TreeNode)>,
    names: Query<&Name>,
    parent_query: Query<&ChildOf>,
    tree_row_children_query: Query<(), With<TreeRowChildren>>,
    mut display_query: Query<&mut Node>,
) {
    let Ok(text_edit_value) = filter_input.single() else {
        return;
    };

    let filter = text_edit_value.0.trim().to_lowercase();

    if filter.is_empty() {
        for (tree_entity, _) in &tree_nodes {
            if let Ok(mut node) = display_query.get_mut(tree_entity) {
                node.display = Display::Flex;
            }
        }
        return;
    }

    // First pass: determine which source entities match the filter
    let mut visible_tree_entities: HashSet<Entity> = HashSet::new();

    for (tree_entity, tree_node) in &tree_nodes {
        let label = names
            .get(tree_node.0)
            .map(|n| n.as_str().to_lowercase())
            .unwrap_or_else(|_| format!("entity {}", tree_node.0).to_lowercase());
        let matches = label.contains(&filter);

        if matches {
            visible_tree_entities.insert(tree_entity);

            // Walk up ancestors: tree row → ChildOf → TreeRowChildren → ChildOf → parent tree row
            let mut current = tree_entity;
            while let Ok(&ChildOf(parent)) = parent_query.get(current) {
                if tree_row_children_query.contains(parent) {
                    if let Ok(&ChildOf(grandparent)) = parent_query.get(parent) {
                        visible_tree_entities.insert(grandparent);
                        current = grandparent;
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }
        }
    }

    // Second pass: set display on all tree rows
    for (tree_entity, _) in &tree_nodes {
        if let Ok(mut node) = display_query.get_mut(tree_entity) {
            node.display = if visible_tree_entities.contains(&tree_entity) {
                Display::Flex
            } else {
                Display::None
            };
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use jackdaw_api_internal::operator::OperatorParameters;
    use jackdaw_jsn::PropertyValue;
    use std::collections::BTreeMap;

    fn empty_params() -> OperatorParameters {
        OperatorParameters(BTreeMap::new())
    }

    fn params_with_entity(key: &str, entity: Entity) -> OperatorParameters {
        let mut map = BTreeMap::new();
        map.insert(key.to_string(), PropertyValue::Entity(entity));
        OperatorParameters(map)
    }

    /// `RenameBeginOp` dispatched with an explicit `entity` param
    /// (the path the context-menu "Rename" item and the
    /// `TreeRowStartRename` event use) returns that entity. The
    /// param wins over any selection state.
    #[test]
    fn resolve_rename_target_prefers_entity_param() {
        let target = Entity::from_raw_u32(7).unwrap();
        let other = Entity::from_raw_u32(42).unwrap();
        let params = params_with_entity("entity", target);
        let selection = Selection {
            entities: vec![other],
        };
        assert_eq!(resolve_rename_target(&params, &selection), Some(target));
    }

    /// F2 keybind regression cover: the bare keypress dispatches
    /// `RenameBeginOp` with no params, and the operator must read
    /// the primary selection. Before the fix, the op early-returned
    /// `Cancelled` whenever no `entity` param was supplied, so F2
    /// silently did nothing even with a selected outliner row.
    #[test]
    fn resolve_rename_target_falls_back_to_selection_primary() {
        let primary = Entity::from_raw_u32(11).unwrap();
        let params = empty_params();
        let selection = Selection {
            // The last entry is the primary selection.
            entities: vec![Entity::from_raw_u32(99).unwrap(), primary],
        };
        assert_eq!(resolve_rename_target(&params, &selection), Some(primary));
    }

    /// No param, no selection: the op cancels. Confirms the early
    /// bail still fires, so a stray F2 in an empty scene doesn't
    /// fall into find-rename-targets with a garbage entity.
    #[test]
    fn resolve_rename_target_returns_none_without_selection_or_param() {
        let params = empty_params();
        let selection = Selection::default();
        assert_eq!(resolve_rename_target(&params, &selection), None);
    }
}