darkly 0.5.0

A GPU-native paint engine on wgpu: brushes, layers, blend modes, masks, selections, and undo.
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
pub mod filter;
pub mod filters;
pub mod layer_kind;
pub mod layer_kinds;

pub use filter::{Filter, FilterEntityRegistration, FilterKind, FilterRegistry};
pub use filters::mask::MaskFilter;
pub use filters::selection::{SelectionCpuCache, SelectionFilter};
pub use layer_kind::{LayerKindRegistration, LayerKindRegistry};

use std::collections::HashMap;

use slotmap::{SecondaryMap, SlotMap};

use crate::coord::{CanvasPoint, CanvasRect};
use crate::layer::*;

pub enum SelectionMode {
    Replace,
    Add,
    Subtract,
    Intersect,
}

#[derive(Clone, Copy)]
pub enum MoveTarget {
    Before(LayerId),
    After(LayerId),
    IntoGroupTop(LayerId),
    IntoGroupBottom(LayerId),
}

/// One slot in [`Document::entities`]. Tree nodes (layers + groups) and
/// filters share a single id space and a single storage map so callers can
/// pass any [`LayerId`] through the same lookup surface.
pub enum Entity {
    Node(LayerNode),
    Filter(Filter),
}

impl Entity {
    pub fn as_node(&self) -> Option<&LayerNode> {
        match self {
            Entity::Node(n) => Some(n),
            Entity::Filter(_) => None,
        }
    }

    pub fn as_node_mut(&mut self) -> Option<&mut LayerNode> {
        match self {
            Entity::Node(n) => Some(n),
            Entity::Filter(_) => None,
        }
    }

    pub fn as_modifier(&self) -> Option<&Filter> {
        match self {
            Entity::Filter(m) => Some(m),
            Entity::Node(_) => None,
        }
    }

    pub fn as_modifier_mut(&mut self) -> Option<&mut Filter> {
        match self {
            Entity::Filter(m) => Some(m),
            Entity::Node(_) => None,
        }
    }
}

pub struct Document {
    /// User-visible document name. Sourced by the tab strip, used as the
    /// default filename in the Save As picker, and serialized at the top
    /// of `manifest.json`. Defaults to `"Untitled"` for fresh documents.
    ///
    /// Single source of truth — there is no JS-side parallel name map
    /// (the engine's `document_name()` query backs the tab title).
    pub name: String,
    pub width: u32,
    pub height: u32,

    /// Offset of the **canvas window** within the fixed canvas/plane space.
    ///
    /// There is one coordinate frame — canvas/plane space — in which layer
    /// extents, undo rects, and selection regions all live (and may be
    /// negative, e.g. paste). The canvas *window* is the visible/exported
    /// rectangle `(canvas_origin, width, height)` within that plane.
    /// Default `(0, 0)`; canvas resize / crop move the window by changing
    /// this and `width`/`height` while content stays put in the plane.
    /// Serialized beside `width`/`height`; undoable via `CanvasResizeAction`.
    pub canvas_origin: CanvasPoint,

    /// Sticky "has unsaved changes" bit. Set at the [`UndoStack::push`]
    /// chokepoint — any new undoable mutation flips it true. Cleared
    /// only by a successful save (`poll_save_result`) or a load
    /// (`open_document` installs a fresh staging doc with `dirty = false`).
    /// Not undoable on purpose: an undo back to the original state
    /// shouldn't pretend the work was never done. Not serialized — the
    /// flag describes editor session state, not file content.
    pub dirty: bool,

    /// Single shared slot store for every layer, group, and filter in this
    /// document. Lookups are O(1); generational keys mean stale ids return
    /// `None` instead of aliasing onto a recycled slot.
    pub entities: SlotMap<LayerId, Entity>,

    /// Parent pointer for every linked entity:
    /// - For a tree node: its tree parent (a group). Root has no entry.
    /// - For a filter: its host node. Selection has no entry.
    ///
    /// Entities present in `entities` but absent from `parent` are *orphans* —
    /// either the root itself, the selection filter, or a subtree that has
    /// been detached for undo and is waiting to be reattached.
    pub parent: SecondaryMap<LayerId, LayerId>,

    /// The implicit root group's id. Allocated in [`Document::new`]; replaces
    /// the old well-known `ROOT_ID = 0` constant. The root group itself is
    /// never exposed to the UI — only its children are.
    pub root: LayerId,

    /// Global selection filter id, if allocated. The filter itself lives
    /// in [`Self::entities`]; this just remembers which entry it is. Once
    /// allocated it stays for the document's lifetime, with `common.visible`
    /// toggling whether ops respect the selection.
    pub selection: Option<LayerId>,

    /// Monotonic per-base-name counters for default display names. A fresh
    /// add yields `"{base} 1"`, `"{base} 2"`, … keyed by whatever base label
    /// the caller passes ([`Self::next_name`]). Counters survive deletes
    /// within a session (the next add doesn't reuse a freed number, just
    /// like Photoshop and Krita), giving stable, readable labels even
    /// after heavy churn.
    ///
    /// One uniform mechanism across every kind that lays down a layer or
    /// filter — raster, group, mask, void (per void-type), and any future
    /// kind. The base label is the caller's responsibility: hardcoded for
    /// fixed kinds (`"Layer"`, `"Group"`, `"Mask"`), registry-resolved for
    /// dynamic ones (the void's display name, e.g. `"Noise"`).
    name_counters: HashMap<String, u32>,
}

impl Document {
    pub fn new(width: u32, height: u32) -> Self {
        let mut entities: SlotMap<LayerId, Entity> = SlotMap::with_key();
        // Allocate the root with a placeholder id, then patch the id after
        // insertion. SlotMap::insert_with_key does this in one step. The
        // root is never shown in the UI, so its name is internal only.
        let root = entities.insert_with_key(|key| {
            Entity::Node(LayerNode::Group(LayerGroup::new(key, "Root".to_string())))
        });
        Document {
            name: "Untitled".to_string(),
            width,
            height,
            canvas_origin: CanvasPoint::new(0, 0),
            dirty: false,
            entities,
            parent: SecondaryMap::new(),
            root,
            selection: None,
            name_counters: HashMap::new(),
        }
    }

    /// Produce the next default display name for a given base label,
    /// bumping the per-base counter. `next_name("Layer")` yields
    /// `"Layer 1"`, then `"Layer 2"`, …; `next_name("Noise")` runs an
    /// independent sequence. The single chokepoint for default naming
    /// across every add-* path.
    fn next_name(&mut self, base: &str) -> String {
        let counter = self.name_counters.entry(base.to_string()).or_insert(1);
        let name = format!("{base} {counter}");
        *counter += 1;
        name
    }

    /// Id of the implicit root group. Replaces the old `ROOT_ID` constant.
    pub fn root_id(&self) -> LayerId {
        self.root
    }

    /// The canvas window as a plane-space rect: `(canvas_origin, width,
    /// height)`. Single source of truth for "the canvas region" used as
    /// layer / selection / undo bounds. Equals `(0, 0, width, height)` for
    /// a fresh document and moves with crop / resize.
    pub fn canvas_rect(&self) -> CanvasRect {
        CanvasRect::new(self.canvas_origin, self.width, self.height)
    }

    // ---------------------------------------------------------------
    // Lookup — every method is O(1) (tree walks happen only in the
    // explicitly-named whole-tree queries: `flat_layers`, `all_*`,
    // `node_count`).
    // ---------------------------------------------------------------

    pub fn find_node(&self, id: LayerId) -> Option<&LayerNode> {
        self.entities.get(id).and_then(Entity::as_node)
    }

    pub fn find_node_mut(&mut self, id: LayerId) -> Option<&mut LayerNode> {
        self.entities.get_mut(id).and_then(Entity::as_node_mut)
    }

    pub fn find_filter(&self, id: LayerId) -> Option<&Filter> {
        self.entities.get(id).and_then(Entity::as_modifier)
    }

    pub fn find_filter_mut(&mut self, id: LayerId) -> Option<&mut Filter> {
        self.entities.get_mut(id).and_then(Entity::as_modifier_mut)
    }

    /// Canvas-space pixel bounds of any pixel-bearing node — a raster layer or
    /// a mask/selection filter. `None` for nodes that have no pixels (groups,
    /// void layers) or unknown ids. Lets callers treat "things with pixels"
    /// uniformly without branching on layer vs filter or on layer kind.
    pub fn node_pixel_bounds(&self, id: LayerId) -> Option<CanvasRect> {
        if let Some(b) = self.find_node(id).and_then(|n| n.pixels()) {
            return Some(b.bounds);
        }
        self.find_filter(id)
            .and_then(|m| m.pixels())
            .map(|b| b.bounds)
    }

    /// Set the canvas-space pixel bounds of a raster layer or filter. No-op
    /// for nodes without pixels or unknown ids. Pairs with
    /// [`node_pixel_bounds`](Self::node_pixel_bounds); used by image rescale to
    /// keep the document's extents in step with the resampled GPU textures.
    pub fn set_node_pixel_bounds(&mut self, id: LayerId, bounds: CanvasRect) {
        if let Some(b) = self.find_node_mut(id).and_then(|n| n.pixels_mut()) {
            b.bounds = bounds;
        } else if let Some(b) = self.find_filter_mut(id).and_then(|m| m.pixels_mut()) {
            b.bounds = bounds;
        }
    }

    /// Find the host node a filter is attached to (the layer or group that
    /// owns it on its `filters` list).
    pub fn find_filter_host(&self, filter_id: LayerId) -> Option<&LayerNode> {
        let host_id = *self.parent.get(filter_id)?;
        self.find_node(host_id)
    }

    pub fn find_filter_host_mut(&mut self, filter_id: LayerId) -> Option<&mut LayerNode> {
        let host_id = *self.parent.get(filter_id)?;
        self.find_node_mut(host_id)
    }

    pub fn layer(&self, id: LayerId) -> Option<&Layer> {
        match self.find_node(id)? {
            LayerNode::Layer(l) => Some(l),
            LayerNode::Group(_) => None,
        }
    }

    pub fn layer_mut(&mut self, id: LayerId) -> Option<&mut Layer> {
        match self.find_node_mut(id)? {
            LayerNode::Layer(l) => Some(l),
            LayerNode::Group(_) => None,
        }
    }

    /// True if `id` refers to a filter (rather than a layer/group). Cheap
    /// disambiguator for callers that hold a node id and need to dispatch.
    pub fn is_filter(&self, id: LayerId) -> bool {
        matches!(self.entities.get(id), Some(Entity::Filter(_)))
    }

    /// True when `id` may be mutated by the user.
    ///
    /// `false` when the node itself or any ancestor (host for a filter;
    /// parent group for a layer/group, walked to the root) carries
    /// `locked = true`. Mirrors Krita's `KisBaseNode::isEditable` — locks
    /// cascade down the tree so locking a group also protects its contents.
    ///
    /// Unknown ids return `true`; the caller's existing "node not found"
    /// path handles them. The lock check is *policy*; this predicate is the
    /// single source of truth for "may this be modified?" and is called
    /// from every mutating engine entry point.
    pub fn is_node_editable(&self, id: LayerId) -> bool {
        let mut cur = id;
        loop {
            match self.entities.get(cur) {
                Some(Entity::Node(n)) if n.common().locked => return false,
                Some(Entity::Filter(m)) if m.common.locked => return false,
                Some(_) => {}
                None => return true,
            }
            match self.parent.get(cur) {
                Some(&p) if p != cur => cur = p,
                _ => return true,
            }
        }
    }

    /// Pixel-buffer accessor that works for any pixel-bearing entity — raster
    /// layers and pixel-storing filters (today: masks, selection). Returns
    /// `None` for groups, pure-effect filters, or unknown ids.
    pub fn pixel_buffer(&self, id: LayerId) -> Option<&PixelBuffer> {
        match self.entities.get(id)? {
            Entity::Node(n) => n.pixels(),
            Entity::Filter(m) => m.pixels(),
        }
    }

    pub fn pixel_buffer_mut(&mut self, id: LayerId) -> Option<&mut PixelBuffer> {
        match self.entities.get_mut(id)? {
            Entity::Node(n) => n.pixels_mut(),
            Entity::Filter(m) => m.pixels_mut(),
        }
    }

    pub fn parent_of(&self, id: LayerId) -> Option<LayerId> {
        self.parent.get(id).copied()
    }

    /// True iff `ancestor` appears on the parent chain above `descendant`.
    /// A node is not its own ancestor. Detached or orphaned nodes have no
    /// ancestors. Used by batch ops to dedupe a selection that contains
    /// both a group and one of its descendants.
    pub fn is_ancestor_of(&self, ancestor: LayerId, descendant: LayerId) -> bool {
        let mut cur = self.parent_of(descendant);
        while let Some(p) = cur {
            if p == ancestor {
                return true;
            }
            cur = self.parent_of(p);
        }
        false
    }

    /// True iff this node and every ancestor up to the root are individually
    /// `visible`. The compositor's `compose_children` walk already short-
    /// circuits invisible subtrees ([`crate::gpu::compositor::Compositor`]
    /// line ~2665), so this is the corresponding read-side helper for
    /// callers (engine, frontend) that need the same answer without walking
    /// the tree themselves — e.g. deciding whether to keep a camera void's
    /// MediaStream uploading frames when a parent group hid it.
    pub fn effective_visible(&self, id: LayerId) -> bool {
        let mut current = id;
        loop {
            match self.find_node(current) {
                Some(n) if !n.visible() => return false,
                Some(_) => {}
                None => return false,
            }
            match self.parent_of(current) {
                Some(p) => current = p,
                None => return true,
            }
        }
    }

    /// Index of an entity within its parent container.
    /// - For a tree node: position in its parent group's `children` Vec.
    /// - For a filter: position in its host node's `filters` Vec.
    pub fn position_in_parent(&self, id: LayerId) -> Option<usize> {
        let parent_id = *self.parent.get(id)?;
        let parent_node = self.find_node(parent_id)?;
        if self.is_filter(id) {
            parent_node.filters().iter().position(|c| *c == id)
        } else {
            match parent_node {
                LayerNode::Group(g) => g.children.iter().position(|c| *c == id),
                LayerNode::Layer(_) => None,
            }
        }
    }

    /// First mask filter on a host, if any. Replaces the old
    /// `host.filters().mask()` pattern — that helper used to live on
    /// `ModifierList`, but with id-references it needs the document to
    /// resolve.
    pub fn mask_filter_id(&self, host_id: LayerId) -> Option<LayerId> {
        let host = self.find_node(host_id)?;
        host.filters().iter().copied().find(|mid| {
            self.find_filter(*mid)
                .map(|m| matches!(m.kind, FilterKind::Mask(_)))
                .unwrap_or(false)
        })
    }

    pub fn mask_filter(&self, host_id: LayerId) -> Option<&Filter> {
        self.find_filter(self.mask_filter_id(host_id)?)
    }

    pub fn has_mask(&self, host_id: LayerId) -> bool {
        self.mask_filter_id(host_id).is_some()
    }

    /// Filter-id list for a host node, in bottom-up order.
    pub fn filters_of(&self, host_id: LayerId) -> &[LayerId] {
        match self.find_node(host_id) {
            Some(n) => n.filters(),
            None => &[],
        }
    }

    /// Children of a group, in display order.
    pub fn children_of(&self, group_id: LayerId) -> &[LayerId] {
        match self.find_node(group_id) {
            Some(LayerNode::Group(g)) => &g.children,
            _ => &[],
        }
    }

    // ---------------------------------------------------------------
    // Whole-tree queries — these enumerate the world by definition,
    // so they're O(N). They walk from `root` and so naturally exclude
    // any orphans parked in the slotmap awaiting undo reattach.
    // ---------------------------------------------------------------

    pub fn flat_layers(&self) -> Vec<&Layer> {
        let mut out = Vec::new();
        self.flatten_into(self.root, &mut out);
        out
    }

    fn flatten_into<'a>(&'a self, group_id: LayerId, out: &mut Vec<&'a Layer>) {
        let Some(LayerNode::Group(g)) = self.find_node(group_id) else {
            return;
        };
        for &child_id in &g.children {
            match self.find_node(child_id) {
                Some(LayerNode::Layer(l)) => out.push(l),
                Some(LayerNode::Group(child)) if !child.common.visible => {}
                Some(LayerNode::Group(_)) => {
                    // Passthrough groups: children composited directly into
                    // parent. Normal groups: TODO — needs isolated compositing
                    // buffer. For now, flatten children in both modes.
                    self.flatten_into(child_id, out);
                }
                None => {}
            }
        }
    }

    /// All raster layers in the tree, regardless of visibility. Used for GPU
    /// sync — we keep GPU textures in sync even for hidden layers.
    pub fn all_raster_layers(&self) -> Vec<&RasterLayer> {
        let mut out = Vec::new();
        self.collect_raster_layers(self.root, &mut out);
        out
    }

    fn collect_raster_layers<'a>(&'a self, group_id: LayerId, out: &mut Vec<&'a RasterLayer>) {
        let Some(LayerNode::Group(g)) = self.find_node(group_id) else {
            return;
        };
        for &child_id in &g.children {
            match self.find_node(child_id) {
                Some(LayerNode::Layer(Layer::Raster(r))) => out.push(r),
                Some(LayerNode::Group(_)) => self.collect_raster_layers(child_id, out),
                _ => {}
            }
        }
    }

    /// Every content layer (raster + void) in the tree, regardless of
    /// visibility. Both kinds share the standard blend pipeline and live
    /// in the unified compositor `layer_cache`, so the GPU sync path only
    /// needs to know "this is a layer the compositor manages" — kind
    /// dispatch happens once, inside the compositor's `ensure_layer`.
    pub fn all_content_layers(&self) -> Vec<&Layer> {
        let mut out = Vec::new();
        self.collect_content_layers(self.root, &mut out);
        out
    }

    fn collect_content_layers<'a>(&'a self, group_id: LayerId, out: &mut Vec<&'a Layer>) {
        let Some(LayerNode::Group(g)) = self.find_node(group_id) else {
            return;
        };
        for &child_id in &g.children {
            match self.find_node(child_id) {
                // Filter layers transform the group accumulator rather than
                // contributing a texture — they are realized by the
                // compositor's filter arm, not the standard blend walk.
                Some(LayerNode::Layer(l)) if l.is_blend_content() => out.push(l),
                Some(LayerNode::Group(_)) => self.collect_content_layers(child_id, out),
                _ => {}
            }
        }
    }

    pub fn all_groups(&self) -> Vec<&LayerGroup> {
        let mut out = Vec::new();
        self.collect_groups(self.root, &mut out);
        out
    }

    fn collect_groups<'a>(&'a self, group_id: LayerId, out: &mut Vec<&'a LayerGroup>) {
        let Some(LayerNode::Group(g)) = self.find_node(group_id) else {
            return;
        };
        for &child_id in &g.children {
            if let Some(LayerNode::Group(child)) = self.find_node(child_id) {
                out.push(child);
                self.collect_groups(child_id, out);
            }
        }
    }

    /// Host ids of every node that composites in place (a passthrough group or
    /// a filter layer) *and* carries a visible mask — the set the compositor
    /// must keep a snapshot+lerp buffer for. Kind-agnostic: it asks each node
    /// [`LayerNode::composites_in_place`] rather than enumerating which kinds
    /// qualify, so a new in-place kind is picked up with no edit here.
    pub fn masked_in_place_hosts(&self) -> Vec<LayerId> {
        let mut out = Vec::new();
        self.collect_masked_in_place(self.root, &mut out);
        out
    }

    fn collect_masked_in_place(&self, group_id: LayerId, out: &mut Vec<LayerId>) {
        let Some(LayerNode::Group(g)) = self.find_node(group_id) else {
            return;
        };
        for &child_id in &g.children {
            let Some(node) = self.find_node(child_id) else {
                continue;
            };
            if node.composites_in_place()
                && self
                    .mask_filter(child_id)
                    .map(|m| m.common.visible)
                    .unwrap_or(false)
            {
                out.push(child_id);
            }
            if matches!(node, LayerNode::Group(_)) {
                self.collect_masked_in_place(child_id, out);
            }
        }
    }

    /// Every filter attached to any host in the tree. The global selection
    /// filter is *not* included (it has no host); use
    /// [`Document::selection_id`] for that.
    pub fn all_filters(&self) -> Vec<&Filter> {
        let mut out = Vec::new();
        self.collect_filters(self.root, &mut out);
        out
    }

    fn collect_filters<'a>(&'a self, group_id: LayerId, out: &mut Vec<&'a Filter>) {
        let Some(LayerNode::Group(g)) = self.find_node(group_id) else {
            return;
        };
        // Filters on the group itself.
        for &mid in &g.filters {
            if let Some(m) = self.find_filter(mid) {
                out.push(m);
            }
        }
        // Then descend.
        for &child_id in &g.children {
            match self.find_node(child_id) {
                Some(LayerNode::Layer(l)) => {
                    for &mid in l.filters() {
                        if let Some(m) = self.find_filter(mid) {
                            out.push(m);
                        }
                    }
                }
                Some(LayerNode::Group(_)) => self.collect_filters(child_id, out),
                None => {}
            }
        }
    }

    /// Count of all tree nodes (layers + groups, excluding the root and
    /// filters). Walks the tree; intended for tests and rare diagnostics.
    pub fn node_count(&self) -> usize {
        fn walk(doc: &Document, group_id: LayerId, counter: &mut usize) {
            let Some(LayerNode::Group(g)) = doc.find_node(group_id) else {
                return;
            };
            for &child_id in &g.children {
                *counter += 1;
                if matches!(doc.find_node(child_id), Some(LayerNode::Group(_))) {
                    walk(doc, child_id, counter);
                }
            }
        }
        let mut n = 0;
        walk(self, self.root, &mut n);
        n
    }

    pub fn flat_layer_index(&self, id: LayerId) -> Option<usize> {
        self.flat_layers().iter().position(|l| l.id() == id)
    }

    /// All tree-node ids (layers + groups) in display order (DFS over the
    /// full tree, descending into every group regardless of visibility or
    /// collapsed-state). Excludes the implicit root and filters. Used by
    /// batch ops that need a stable total order across a selection that
    /// mixes layers and groups, including cross-parent selections.
    ///
    /// Iteration is bottom-of-stack first within each parent's
    /// `children` Vec — so for a panel that displays "top of stack first,"
    /// the last entry in this Vec for a given selection is the
    /// **panel-topmost** member. `merge_layers` uses this to locate the
    /// topmost selected layer across arbitrary parents.
    pub fn all_node_ids_in_order(&self) -> Vec<LayerId> {
        let mut out = Vec::new();
        self.collect_node_ids(self.root, &mut out);
        out
    }

    fn collect_node_ids(&self, group_id: LayerId, out: &mut Vec<LayerId>) {
        let Some(LayerNode::Group(g)) = self.find_node(group_id) else {
            return;
        };
        for &child_id in &g.children {
            out.push(child_id);
            if matches!(self.find_node(child_id), Some(LayerNode::Group(_))) {
                self.collect_node_ids(child_id, out);
            }
        }
    }

    // ---------------------------------------------------------------
    // Mutation — every entry point that adds, removes, or reparents an
    // entity goes through here so the slotmap, the parent map, and the
    // children/filter Vecs stay consistent.
    // ---------------------------------------------------------------

    /// Add a new raster layer, positioning it relative to `anchor` per
    /// [`Document::resolve_anchor_target`].
    pub fn add_raster_layer(&mut self, anchor: Option<LayerId>) -> LayerId {
        let bounds = self.canvas_rect();
        let name = self.next_name("Layer");
        let id = self.entities.insert_with_key(|key| {
            Entity::Node(LayerNode::Layer(Layer::Raster(RasterLayer::new(
                key, bounds, name,
            ))))
        });
        let target = self.resolve_anchor_target(anchor);
        self.attach_at_target(id, target);
        id
    }

    /// Add a new void (procedural) layer. Carries no pixel buffer — the
    /// compositor regenerates content each frame from `void_type` + `params`.
    /// Caller is responsible for ensuring `void_type` is a registered void
    /// kind and `params` matches its schema; the engine wrapper does that.
    ///
    /// `display_label` is the registry's `display_name` for the void type
    /// (e.g. `"Noise"`) — used as the default layer name so the panel shows
    /// `"Noise 1"`, `"Noise 2"`, … rather than a generic `"Void N"`. The
    /// label is the doc's only knowledge of the registry; the registry
    /// itself lives on the compositor (GPU-coupled) so it can't be
    /// dereferenced here.
    ///
    /// `initial_transform` is the void kind's seeded gizmo affine (the camera's
    /// selfie flip; identity for everything else), set atomically with creation
    /// so it's part of the single add-undo step and round-trips through
    /// save/load like any later gizmo edit.
    pub fn add_void_layer(
        &mut self,
        void_type: String,
        display_label: &str,
        params: Vec<crate::gpu::params::ParamValue>,
        initial_transform: crate::transform::Transform,
        anchor: Option<LayerId>,
    ) -> LayerId {
        let name = self.next_name(display_label);
        let id = self.entities.insert_with_key(|key| {
            let mut layer = VoidLayer::new(key, name, void_type, params);
            layer.transform = initial_transform;
            Entity::Node(LayerNode::Layer(Layer::Void(layer)))
        });
        let target = self.resolve_anchor_target(anchor);
        self.attach_at_target(id, target);
        id
    }

    /// Add a new filter layer — a non-destructive procedural transform that
    /// filters the composite of everything below it. Carries no pixel buffer;
    /// the compositor runs the shared filter pipeline named by `pipeline` over
    /// the running group accumulator each frame.
    ///
    /// `display_label` is the registry's display name for the filter type
    /// (e.g. `"Invert Colors"`) — used as the default layer name. The caller
    /// (engine wrapper) is responsible for validating `pipeline` against the
    /// [`FilterPipelineRegistry`](crate::gpu::filter::FilterPipelineRegistry);
    /// that registry is GPU-coupled and lives on the compositor, so it can't be
    /// dereferenced here.
    pub fn add_filter_layer(
        &mut self,
        pipeline: String,
        display_label: &str,
        params: Vec<crate::gpu::params::ParamValue>,
        anchor: Option<LayerId>,
    ) -> LayerId {
        let name = self.next_name(display_label);
        let id = self.entities.insert_with_key(|key| {
            Entity::Node(LayerNode::Layer(Layer::Filter(
                crate::layer::FilterLayer::new(key, name, pipeline, params),
            )))
        });
        let target = self.resolve_anchor_target(anchor);
        self.attach_at_target(id, target);
        id
    }

    /// Iterate every void layer in the tree, regardless of visibility. Used
    /// for GPU sync — same shape as [`Self::all_raster_layers`].
    pub fn all_void_layers(&self) -> Vec<&VoidLayer> {
        let mut out = Vec::new();
        self.collect_void_layers(self.root, &mut out);
        out
    }

    fn collect_void_layers<'a>(&'a self, group_id: LayerId, out: &mut Vec<&'a VoidLayer>) {
        let Some(LayerNode::Group(g)) = self.find_node(group_id) else {
            return;
        };
        for &child_id in &g.children {
            match self.find_node(child_id) {
                Some(LayerNode::Layer(Layer::Void(v))) => out.push(v),
                Some(LayerNode::Group(_)) => self.collect_void_layers(child_id, out),
                _ => {}
            }
        }
    }

    /// Add a new empty group; positioning follows the same rules as
    /// [`Document::add_raster_layer`].
    pub fn add_group(&mut self, anchor: Option<LayerId>) -> LayerId {
        let name = self.next_name("Group");
        let id = self
            .entities
            .insert_with_key(|key| Entity::Node(LayerNode::Group(LayerGroup::new(key, name))));
        let target = self.resolve_anchor_target(anchor);
        self.attach_at_target(id, target);
        id
    }

    /// Add a [`MaskFilter`] to a host node, returning the new filter's id.
    /// Bounds default to the full canvas for every host kind; the mask then
    /// owns and grows its bounds independently (see [`Self::host_default_bounds`]).
    /// Returns `None` if the host id is unknown.
    ///
    /// Note: only one mask per host is enforced at the UI layer, not here —
    /// the model supports N. Callers that want the singleton invariant should
    /// check [`Document::has_mask`] before adding.
    pub fn add_mask_filter(&mut self, host_id: LayerId) -> Option<LayerId> {
        let bounds = self.host_default_bounds(host_id)?;
        let name = self.next_name("Mask");
        let id = self.entities.insert_with_key(|key| {
            Entity::Filter(Filter {
                id: key,
                common: NodeCommon::new(name),
                kind: FilterKind::mask_with_bounds(bounds),
            })
        });
        // Patch the filter's id field to match its slot key.
        if let Some(Entity::Filter(m)) = self.entities.get_mut(id) {
            m.id = id;
        }
        // Link to the host.
        if let Some(host) = self.find_node_mut(host_id) {
            host.modifiers_mut().push(id);
            self.parent.insert(id, host_id);
            Some(id)
        } else {
            self.entities.remove(id);
            None
        }
    }

    /// Allocate the global selection filter if not already present, sized
    /// to the canvas. Idempotent — returns the filter id either way.
    pub fn ensure_selection_filter(&mut self) -> LayerId {
        if let Some(id) = self.selection {
            return id;
        }
        let bounds = self.canvas_rect();
        let id = self.entities.insert_with_key(|key| {
            let mut m = Filter {
                id: key,
                common: NodeCommon::new("Selection".to_string()),
                kind: FilterKind::selection_with_bounds(bounds),
            };
            // Default `visible = false` mirrors today's "always allocated,
            // .active toggles whether ops respect it" semantics.
            m.common.visible = false;
            Entity::Filter(m)
        });
        // Patch id field to slot key.
        if let Some(Entity::Filter(m)) = self.entities.get_mut(id) {
            m.id = id;
        }
        self.selection = Some(id);
        // Per the plan, the selection lives "at the document root rather than
        // on a host's `filters` list" — so no entry in `parent`.
        id
    }

    /// Selection filter id, if allocated.
    pub fn selection_id(&self) -> Option<LayerId> {
        self.selection
    }

    /// True when the selection filter is allocated AND its `common.visible`
    /// flag is set — equivalent to today's `gpu_selection.active`.
    pub fn selection_active(&self) -> bool {
        self.selection
            .and_then(|id| self.find_filter(id))
            .is_some_and(|m| m.common.visible)
    }

    /// Move a node to a new position in the tree.
    pub fn move_layer(&mut self, layer_id: LayerId, target: MoveTarget) {
        if self.unlink_node(layer_id).is_none() {
            return;
        }
        self.attach_at_target(layer_id, target);
    }

    /// Detach a node from the tree for undo purposes, leaving it parked in
    /// `entities` so its id stays stable across undo/redo. Returns the id on
    /// success. Reattach with [`Document::reinsert_node`]; if the undo entry
    /// is later discarded, call [`Document::remove_node`] to actually free it.
    pub fn detach_for_undo(&mut self, id: LayerId) -> Option<LayerId> {
        self.unlink_node(id)
    }

    /// Reinsert a previously detached node at a specific position.
    pub fn reinsert_node(&mut self, id: LayerId, parent: Option<LayerId>, position: usize) {
        if !self.entities.contains_key(id) {
            return;
        }
        let parent_id = self.resolve_parent_group(parent);
        self.link_child(id, parent_id, Some(position));
    }

    /// Detach a filter from its host for undo purposes. The filter stays
    /// in `entities`, so reattach via [`Document::reinsert_filter`] preserves
    /// the id.
    pub fn detach_filter_for_undo(&mut self, id: LayerId) -> Option<LayerId> {
        self.unlink_filter(id)
    }

    /// Reattach a previously detached filter to a host. Append-only — the
    /// model doesn't expose a position parameter today because masks use
    /// "first mask" lookup rather than positional access.
    pub fn reinsert_filter(&mut self, filter_id: LayerId, host_id: LayerId) {
        if !self.is_filter(filter_id) {
            return;
        }
        if let Some(host) = self.find_node_mut(host_id) {
            host.modifiers_mut().push(filter_id);
            self.parent.insert(filter_id, host_id);
        }
    }

    /// Remove a node (layer or group) and everything beneath it (descendant
    /// nodes, all filters on every node in the subtree) from `entities`.
    /// Permanent — call [`Document::detach_for_undo`] instead if the caller
    /// wants id-stable detach for undo.
    pub fn remove_node(&mut self, id: LayerId) {
        if id == self.root {
            return;
        }
        // Unlink first so the parent's children Vec is consistent if anyone
        // observes mid-purge.
        self.unlink_node(id);
        self.purge_subtree(id);
    }

    /// Permanently remove a filter from `entities` (and its host's filter
    /// list, if still attached).
    pub fn remove_filter(&mut self, id: LayerId) {
        self.unlink_filter(id);
        // Selection sentinel: if this was the selection, clear the field too.
        if self.selection == Some(id) {
            self.selection = None;
        }
        self.entities.remove(id);
    }

    // ---------------------------------------------------------------
    // Internal helpers — every mutation path funnels through these so
    // the slotmap / parent map / children Vec stay in sync.
    // ---------------------------------------------------------------

    /// Resolve an `Option<LayerId>` parent into a concrete group id, defaulting
    /// to `self.root` on `None` or on an id that isn't a group.
    fn resolve_parent_group(&self, parent: Option<LayerId>) -> LayerId {
        match parent {
            Some(id) if matches!(self.find_node(id), Some(LayerNode::Group(_))) => id,
            _ => self.root,
        }
    }

    /// Insert `child` into `group`'s children Vec at `position` (or at the end
    /// if `None`), and update the parent map. Caller guarantees `child` is in
    /// `entities` and `group` is a group.
    fn link_child(&mut self, child: LayerId, group: LayerId, position: Option<usize>) {
        let Some(LayerNode::Group(g)) = self.find_node_mut(group) else {
            return;
        };
        let pos = position
            .map(|p| p.min(g.children.len()))
            .unwrap_or(g.children.len());
        g.children.insert(pos, child);
        self.parent.insert(child, group);
    }

    /// Unlink a node from its parent's children Vec and from the parent map.
    /// Returns the node's id if it was linked, `None` if it was the root or
    /// already orphaned.
    fn unlink_node(&mut self, id: LayerId) -> Option<LayerId> {
        if id == self.root {
            return None;
        }
        let parent_id = self.parent.remove(id)?;
        if let Some(LayerNode::Group(g)) = self.find_node_mut(parent_id) {
            g.children.retain(|c| *c != id);
        }
        Some(id)
    }

    /// Unlink a filter from its host's filters Vec and from the parent
    /// map. Returns the filter's id if it was linked.
    fn unlink_filter(&mut self, id: LayerId) -> Option<LayerId> {
        let host_id = self.parent.remove(id)?;
        if let Some(host) = self.find_node_mut(host_id) {
            host.modifiers_mut().retain(|m| *m != id);
        }
        Some(id)
    }

    /// Resolve a UI "anchor" (typically the currently selected node in the
    /// layers panel) into a [`MoveTarget`] that places a newly-created node
    /// where the user expects.
    ///
    /// - `None` / unknown / stale id → top of root.
    /// - Filter id → recurse against the filter's host.
    /// - Group id → top of that group's children.
    /// - Layer id → sibling immediately above the anchor.
    pub fn resolve_anchor_target(&self, anchor: Option<LayerId>) -> MoveTarget {
        let Some(id) = anchor else {
            return MoveTarget::IntoGroupTop(self.root);
        };
        if self.is_filter(id) {
            return match self.parent.get(id).copied() {
                Some(host) => self.resolve_anchor_target(Some(host)),
                None => MoveTarget::IntoGroupTop(self.root),
            };
        }
        match self.find_node(id) {
            Some(LayerNode::Group(_)) => MoveTarget::IntoGroupTop(id),
            Some(LayerNode::Layer(_)) => MoveTarget::After(id),
            None => MoveTarget::IntoGroupTop(self.root),
        }
    }

    /// Apply a [`MoveTarget`] to a node already unlinked from the tree.
    fn attach_at_target(&mut self, node: LayerId, target: MoveTarget) {
        match target {
            MoveTarget::Before(ref_id) => {
                if let Some(parent_id) = self.parent_of(ref_id) {
                    let pos = self
                        .children_of(parent_id)
                        .iter()
                        .position(|c| *c == ref_id)
                        .unwrap_or(0);
                    self.link_child(node, parent_id, Some(pos));
                } else {
                    self.link_child(node, self.root, None);
                }
            }
            MoveTarget::After(ref_id) => {
                if let Some(parent_id) = self.parent_of(ref_id) {
                    let pos = self
                        .children_of(parent_id)
                        .iter()
                        .position(|c| *c == ref_id)
                        .map(|p| p + 1)
                        .unwrap_or_else(|| self.children_of(parent_id).len());
                    self.link_child(node, parent_id, Some(pos));
                } else {
                    self.link_child(node, self.root, None);
                }
            }
            MoveTarget::IntoGroupTop(group_id) => {
                let group = self.resolve_parent_group(Some(group_id));
                self.link_child(node, group, None);
            }
            MoveTarget::IntoGroupBottom(group_id) => {
                let group = self.resolve_parent_group(Some(group_id));
                self.link_child(node, group, Some(0));
            }
        }
    }

    /// Recursively remove a subtree (the node, its descendants, and every
    /// filter on every node in the subtree) from `entities` and the parent
    /// map. Caller is responsible for unlinking the subtree's root from its
    /// parent first.
    fn purge_subtree(&mut self, id: LayerId) {
        // Collect ids depth-first so we can remove them all without holding
        // borrows across `entities.remove` calls.
        let mut nodes_to_purge = Vec::new();
        self.collect_subtree_ids(id, &mut nodes_to_purge);
        for nid in nodes_to_purge {
            // Drop filters attached to this node first.
            let mod_ids: Vec<LayerId> = match self.find_node(nid) {
                Some(n) => n.filters().to_vec(),
                None => Vec::new(),
            };
            for mid in mod_ids {
                self.parent.remove(mid);
                self.entities.remove(mid);
            }
            self.parent.remove(nid);
            self.entities.remove(nid);
        }
    }

    fn collect_subtree_ids(&self, id: LayerId, out: &mut Vec<LayerId>) {
        out.push(id);
        if let Some(LayerNode::Group(g)) = self.find_node(id) {
            // Clone to avoid holding the borrow while recursing.
            let children: Vec<LayerId> = g.children.clone();
            for child in children {
                self.collect_subtree_ids(child, out);
            }
        }
    }

    /// Creation-default bounds for a fresh mask on `host_id`: the full canvas,
    /// for every host kind. A mask owns its bounds independently of its host
    /// (it grows itself via `grow_filter`); the host's extent is only a
    /// historical seed, not a runtime dependency — mirroring Krita's
    /// parent-extent *fallback* (a default bbox, not a coupling). The
    /// mask-apply pass samples the mask in its own space, so the default size
    /// is just "cover the visible canvas".
    fn host_default_bounds(&self, host_id: LayerId) -> Option<CanvasRect> {
        // `?` keeps the "unknown host → no mask" guard the callers rely on.
        self.find_node(host_id)?;
        Some(self.canvas_rect())
    }
}

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

    #[test]
    fn add_layers() {
        let mut doc = Document::new(256, 256);
        let id = doc.add_raster_layer(None);
        assert_eq!(doc.flat_layers().len(), 1);
        assert_eq!(doc.flat_layers()[0].id(), id);
    }

    #[test]
    fn effective_visible_walks_ancestors() {
        // Camera void's GPU-saving gates rely on this helper being honest
        // about parent visibility: a layer whose own eye is on but whose
        // parent group is hidden must report effective_visible = false,
        // otherwise the camera keeps uploading frames behind a hidden group.
        let mut doc = Document::new(256, 256);
        let outer = doc.add_group(None);
        let inner = doc.add_group(Some(outer));
        let leaf = doc.add_raster_layer(Some(inner));

        assert!(doc.effective_visible(leaf), "all visible → true");

        if let Some(LayerNode::Group(g)) = doc.find_node_mut(outer) {
            g.common.visible = false;
        }
        assert!(
            !doc.effective_visible(leaf),
            "outer group hidden → leaf not effective-visible even though its own eye is on",
        );

        if let Some(LayerNode::Group(g)) = doc.find_node_mut(outer) {
            g.common.visible = true;
        }
        if let Some(node) = doc.find_node_mut(leaf) {
            // SAFETY of pattern: this is just toggling the bool on the
            // raster's LayerCommon; using the trait getter would require
            // an extra borrow gymnastics.
            match node {
                LayerNode::Layer(crate::layer::Layer::Raster(r)) => r.common.visible = false,
                _ => unreachable!(),
            }
        }
        assert!(!doc.effective_visible(leaf), "leaf's own eye off → false");
    }

    #[test]
    fn mask_on_filter_layer_resolves_without_colliding_with_the_effect() {
        // A mask added to a filter layer must land in the filter's polymorphic
        // `filters` list, resolve via `mask_filter`, and leave the procedural
        // effect (`pipeline`/`params`) untouched — the no-collision property
        // that makes filter layers carry masks like any other host. Pins it so
        // a future change to the `filters` Vec can't silently break it.
        let mut doc = Document::new(64, 64);
        let filter = doc.add_filter_layer("invert".to_string(), "Invert", Vec::new(), None);

        let mask_id = doc.add_mask_filter(filter).expect("filter is a valid host");

        // Resolves through the generic host-mask path.
        assert_eq!(
            doc.mask_filter(filter).map(|m| m.id),
            Some(mask_id),
            "mask must resolve via the generic mask_filter() path",
        );
        // Landed in the filter's own `filters` list.
        let node = doc.find_node(filter).expect("filter node present");
        assert!(
            node.filters().contains(&mask_id),
            "mask id must be in the filter layer's filters list",
        );
        // The procedural effect is untouched — `compose_filter_arm` builds it
        // from `pipeline`/`params`, never from `filters`.
        match node {
            LayerNode::Layer(Layer::Filter(f)) => {
                assert_eq!(f.pipeline, "invert", "filter pipeline must be untouched");
                assert!(f.params.is_empty(), "invert is parameter-free");
                assert_eq!(f.filters, vec![mask_id], "only the mask is attached");
            }
            _ => unreachable!("filter node is a Filter layer"),
        }

        // A visible mask on the filter makes it an in-place masked host, so the
        // compositor's ensure-trigger picks it up.
        assert!(
            node.composites_in_place(),
            "filter layer composites in place"
        );
        assert_eq!(
            doc.masked_in_place_hosts(),
            vec![filter],
            "the masked filter layer is collected as an in-place masked host",
        );
    }

    #[test]
    fn flat_layers_respects_group_visibility() {
        let mut doc = Document::new(256, 256);
        let l1 = doc.add_raster_layer(None);
        let g1 = doc.add_group(None);
        let l2 = doc.add_raster_layer(Some(g1));

        let flat = doc.flat_layers();
        assert_eq!(flat.len(), 2);
        assert_eq!(flat[0].id(), l1);
        assert_eq!(flat[1].id(), l2);

        if let Some(LayerNode::Group(g)) = doc.find_node_mut(g1) {
            g.common.visible = false;
        }
        let flat = doc.flat_layers();
        assert_eq!(flat.len(), 1);
        assert_eq!(flat[0].id(), l1);
    }

    #[test]
    fn move_layer_between_groups() {
        let mut doc = Document::new(256, 256);
        let l1 = doc.add_raster_layer(None);
        let g1 = doc.add_group(None);
        let l2 = doc.add_raster_layer(Some(g1));

        doc.move_layer(l2, MoveTarget::Before(l1));
        let flat = doc.flat_layers();
        assert_eq!(flat[0].id(), l2);
        assert_eq!(flat[1].id(), l1);
    }

    #[test]
    fn nested_groups_flatten_correctly() {
        let mut doc = Document::new(256, 256);
        let l1 = doc.add_raster_layer(None);
        let g1 = doc.add_group(None);
        let l2 = doc.add_raster_layer(Some(g1));

        let flat = doc.flat_layers();
        assert_eq!(flat.len(), 2);
        assert_eq!(flat[0].id(), l1);
        assert_eq!(flat[1].id(), l2);
    }

    #[test]
    fn remove_group_removes_children() {
        let mut doc = Document::new(256, 256);
        let g1 = doc.add_group(None);
        let _l1 = doc.add_raster_layer(Some(g1));

        doc.remove_node(g1);
        assert!(doc.flat_layers().is_empty());
    }

    #[test]
    fn detach_insert_roundtrip() {
        let mut doc = Document::new(256, 256);
        let l1 = doc.add_raster_layer(None);
        let l2 = doc.add_raster_layer(None);
        let l3 = doc.add_raster_layer(None);

        doc.move_layer(l1, MoveTarget::After(l3));
        let flat = doc.flat_layers();
        assert_eq!(flat[0].id(), l2);
        assert_eq!(flat[1].id(), l3);
        assert_eq!(flat[2].id(), l1);
    }

    #[test]
    fn add_modifier_attaches_to_host() {
        let mut doc = Document::new(256, 256);
        let l = doc.add_raster_layer(None);
        assert!(doc.filters_of(l).is_empty());

        let mod_id = doc.add_mask_filter(l).unwrap();
        assert_eq!(doc.filters_of(l).len(), 1);
        assert_eq!(doc.mask_filter_id(l), Some(mod_id));

        assert!(doc.is_filter(mod_id));
        assert!(!doc.is_filter(l));
    }

    #[test]
    fn remove_modifier_detaches() {
        let mut doc = Document::new(256, 256);
        let l = doc.add_raster_layer(None);
        let mod_id = doc.add_mask_filter(l).unwrap();

        doc.remove_filter(mod_id);
        assert!(doc.filters_of(l).is_empty());
        assert!(!doc.is_filter(mod_id));
        // Truly purged from entities (not just unlinked).
        assert!(doc.find_filter(mod_id).is_none());
    }

    #[test]
    fn pixel_buffer_dispatches_layer_or_modifier() {
        let mut doc = Document::new(256, 256);
        let l = doc.add_raster_layer(None);
        let mod_id = doc.add_mask_filter(l).unwrap();

        let layer_buf = doc.pixel_buffer(l).unwrap();
        assert_eq!(layer_buf.format, wgpu::TextureFormat::Rgba8Unorm);

        let mask_buf = doc.pixel_buffer(mod_id).unwrap();
        assert_eq!(mask_buf.format, wgpu::TextureFormat::R8Unorm);

        let g = doc.add_group(None);
        assert!(doc.pixel_buffer(g).is_none());
    }

    #[test]
    fn modifier_host_lookup() {
        let mut doc = Document::new(256, 256);
        let l = doc.add_raster_layer(None);
        let mod_id = doc.add_mask_filter(l).unwrap();

        let host = doc.find_filter_host(mod_id).unwrap();
        assert_eq!(host.id(), l);
        assert_eq!(doc.parent_of(mod_id), Some(l));
    }

    // -----------------------------------------------------------------
    // Slotmap-invariant regression tests.
    // -----------------------------------------------------------------

    #[test]
    fn stale_id_returns_none() {
        // After purging a layer, looking it up by its old id MUST return None
        // — slotmap's generational keys make this safe even after another
        // layer is allocated into the same slot.
        let mut doc = Document::new(256, 256);
        let stale = doc.add_raster_layer(None);
        doc.remove_node(stale);
        // Allocate something else; the slot may be recycled with a bumped
        // generation. The stale key must still not resolve.
        let _other = doc.add_raster_layer(None);
        assert!(doc.find_node(stale).is_none());
        assert!(doc.layer(stale).is_none());
        assert!(doc.parent_of(stale).is_none());
        assert!(!doc.is_filter(stale));
    }

    #[test]
    fn parent_index_consistent_after_move() {
        let mut doc = Document::new(256, 256);
        let g1 = doc.add_group(None);
        let g2 = doc.add_group(None);
        let l = doc.add_raster_layer(Some(g1));
        assert_eq!(doc.parent_of(l), Some(g1));
        doc.move_layer(l, MoveTarget::IntoGroupTop(g2));
        assert_eq!(doc.parent_of(l), Some(g2));
        // And g1 no longer references it.
        assert!(!doc.children_of(g1).contains(&l));
        assert!(doc.children_of(g2).contains(&l));
    }

    #[test]
    fn detach_for_undo_preserves_id() {
        // Detach is orphan-keep: id stays valid in `entities`, filters
        // attached to the detached node stay attached, and reattach restores
        // everything at the requested position.
        let mut doc = Document::new(256, 256);
        let l = doc.add_raster_layer(None);
        let m = doc.add_mask_filter(l).unwrap();

        let parent = doc.parent_of(l);
        let pos = doc.position_in_parent(l).unwrap();

        let detached = doc.detach_for_undo(l).unwrap();
        assert_eq!(detached, l);
        assert!(doc.parent_of(l).is_none());
        // Still resolvable in entities.
        assert!(doc.find_node(l).is_some());
        // Filter still attached to the detached node.
        assert_eq!(doc.parent_of(m), Some(l));
        assert_eq!(doc.filters_of(l), &[m]);
        // Not in the tree.
        assert!(doc.flat_layers().is_empty());

        doc.reinsert_node(l, parent, pos);
        assert_eq!(doc.parent_of(l), parent.or(Some(doc.root)));
        assert_eq!(doc.flat_layers().len(), 1);
        assert_eq!(doc.mask_filter_id(l), Some(m));
    }

    #[test]
    fn purge_subtree_frees_descendants() {
        // remove_node must actually purge from `entities` — not just unlink.
        let mut doc = Document::new(256, 256);
        let g = doc.add_group(None);
        let l = doc.add_raster_layer(Some(g));
        let m = doc.add_mask_filter(l).unwrap();
        let inner_g = doc.add_group(None);
        // Reparent inner_g under g.
        doc.move_layer(inner_g, MoveTarget::IntoGroupTop(g));
        let inner_l = doc.add_raster_layer(Some(inner_g));

        doc.remove_node(g);
        for id in [g, l, m, inner_g, inner_l] {
            assert!(
                doc.entities.get(id).is_none(),
                "{:?} should have been purged from entities",
                id.to_ffi()
            );
        }
    }

    // -----------------------------------------------------------------
    // Anchor-aware insertion (`add_raster_layer` / `add_group` with an
    // optional anchor that points at the currently-selected node).
    // -----------------------------------------------------------------

    #[test]
    fn add_raster_layer_no_anchor_lands_at_root_top() {
        let mut doc = Document::new(256, 256);
        let _l1 = doc.add_raster_layer(None);
        let _l2 = doc.add_raster_layer(None);
        let new_id = doc.add_raster_layer(None);
        assert_eq!(doc.children_of(doc.root).last().copied(), Some(new_id));
    }

    #[test]
    fn add_raster_layer_with_layer_anchor_lands_above() {
        let mut doc = Document::new(256, 256);
        let l1 = doc.add_raster_layer(None);
        let l2 = doc.add_raster_layer(None);
        let l3 = doc.add_raster_layer(None);
        let new_id = doc.add_raster_layer(Some(l1));
        assert_eq!(doc.children_of(doc.root), &[l1, new_id, l2, l3]);
    }

    #[test]
    fn add_raster_layer_with_layer_anchor_inside_group() {
        let mut doc = Document::new(256, 256);
        let g = doc.add_group(None);
        let inner_a = doc.add_raster_layer(Some(g));
        let inner_b = doc.add_raster_layer(Some(g));
        let new_id = doc.add_raster_layer(Some(inner_a));
        assert_eq!(doc.parent_of(new_id), Some(g));
        assert_eq!(doc.children_of(g), &[inner_a, new_id, inner_b]);
    }

    #[test]
    fn add_raster_layer_with_group_anchor_lands_inside_group_top() {
        let mut doc = Document::new(256, 256);
        let g = doc.add_group(None);
        let inner_a = doc.add_raster_layer(Some(g));
        let new_id = doc.add_raster_layer(Some(g));
        assert_eq!(doc.parent_of(new_id), Some(g));
        assert_eq!(doc.children_of(g), &[inner_a, new_id]);
    }

    #[test]
    fn add_raster_layer_with_mask_anchor_lands_above_host() {
        let mut doc = Document::new(256, 256);
        let l1 = doc.add_raster_layer(None);
        let l2 = doc.add_raster_layer(None);
        let mask = doc.add_mask_filter(l1).unwrap();
        let new_id = doc.add_raster_layer(Some(mask));
        // Filter resolves to its host layer → After(host) in root.
        assert_eq!(doc.children_of(doc.root), &[l1, new_id, l2]);
    }

    #[test]
    fn add_raster_layer_with_stale_anchor_falls_back_to_root_top() {
        let mut doc = Document::new(256, 256);
        let stale = doc.add_raster_layer(None);
        doc.remove_node(stale);
        let _other = doc.add_raster_layer(None);
        let new_id = doc.add_raster_layer(Some(stale));
        assert_eq!(doc.children_of(doc.root).last().copied(), Some(new_id));
    }

    #[test]
    fn add_group_with_layer_anchor_lands_above() {
        let mut doc = Document::new(256, 256);
        let l1 = doc.add_raster_layer(None);
        let l2 = doc.add_raster_layer(None);
        let new_g = doc.add_group(Some(l1));
        assert_eq!(doc.children_of(doc.root), &[l1, new_g, l2]);
    }

    #[test]
    fn add_group_with_group_anchor_lands_inside() {
        let mut doc = Document::new(256, 256);
        let outer = doc.add_group(None);
        let inner_l = doc.add_raster_layer(Some(outer));
        let new_g = doc.add_group(Some(outer));
        assert_eq!(doc.parent_of(new_g), Some(outer));
        assert_eq!(doc.children_of(outer), &[inner_l, new_g]);
    }
}