facett-core 0.1.0

facett — visual kernel: render a node/edge Scene into egui (wgpu fast path to come)
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
//! **facett-core** — the visual kernel. Render a node/edge **`Scene`** into egui.
//! Source-agnostic: build a `Scene` from anything (Arrow rows, a graph, a DAG),
//! hand it here, get pixels. The CPU painter is the reference; a **wgpu** fast
//! path (GPU viewport-cull + indirect draw, seeded from katana-osm's
//! `osm-viewer`) lands behind this same `draw()` call — consumers don't change.

use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Stroke, Ui, vec2};

pub mod caps;
pub mod clipboard;
pub mod deckfx;
pub mod effects;
pub mod harness;
pub mod theme;
pub mod trace; // structured IN/OUT/END event stream ($FACETT_TRACE) — the
               // machine-readable data a facet actually rendered.
pub use caps::FacetCaps;
pub use clipboard::ClipAction;
pub use deckfx::{DeckFx, DeckRaven};
pub use theme::{Theme, set_theme, theme};

/// A node: a label + a colour (the *consumer* picks the colour policy — hash by
/// label, by status, …).
#[derive(Clone)]
pub struct Node {
    pub label: String,
    pub color: Color32,
}

/// A directed edge between node indices.
#[derive(Clone, Copy)]
pub struct Edge {
    pub src: usize,
    pub dst: usize,
}

/// A drawable graph: nodes + edges (edges index into `nodes`).
#[derive(Default, Clone)]
pub struct Scene {
    pub nodes: Vec<Node>,
    pub edges: Vec<Edge>,
}

impl Scene {
    pub fn new() -> Self {
        Self::default()
    }
    /// Push a node, returning its index.
    pub fn node(&mut self, label: impl Into<String>, color: Color32) -> usize {
        self.nodes.push(Node { label: label.into(), color });
        self.nodes.len() - 1
    }
    pub fn edge(&mut self, src: usize, dst: usize) {
        self.edges.push(Edge { src, dst });
    }
    pub fn is_empty(&self) -> bool {
        self.nodes.is_empty()
    }
}

/// Node placement strategy.
#[derive(Clone, Copy, PartialEq, Eq, Default)]
pub enum Layout {
    #[default]
    Circular,
    /// Deterministic Fruchterman–Reingold (edges pull, all nodes repel). O(n²)
    /// per iteration — best for small/medium graphs.
    Force,
}

/// Draw a `Scene` into `ui` — the reusable render primitive. Empty scenes show
/// `empty_hint`. Labels render when the node count is small enough to read.
pub fn draw(ui: &mut Ui, scene: &Scene, layout: Layout, empty_hint: &str) {
    let (rect, _) = ui.allocate_exact_size(ui.available_size(), Sense::hover());
    let th = theme(ui);
    let painter = ui.painter_at(rect);
    let n = scene.nodes.len();
    if n == 0 {
        painter.text(rect.center(), Align2::CENTER_CENTER, empty_hint, FontId::proportional(13.0), th.text_dim);
        return;
    }
    let pos = positions(layout, scene, rect);
    for e in &scene.edges {
        if e.src < n && e.dst < n {
            painter.line_segment([pos[e.src], pos[e.dst]], Stroke::new(0.6, th.edge));
        }
    }
    for (i, node) in scene.nodes.iter().enumerate() {
        painter.circle_filled(pos[i], 5.0, node.color);
    }
    if n <= 60 {
        for (i, node) in scene.nodes.iter().enumerate() {
            painter.text(pos[i] + vec2(7.0, 0.0), Align2::LEFT_CENTER, &node.label, FontId::proportional(10.0), th.text);
        }
    }
}

fn positions(layout: Layout, scene: &Scene, rect: Rect) -> Vec<Pos2> {
    let n = scene.nodes.len();
    let center = rect.center();
    let radius = rect.size().min_elem() * 0.42;
    let circular = |i: usize| {
        let a = std::f32::consts::TAU * (i as f32) / (n as f32);
        vec2(a.cos(), a.sin())
    };
    match layout {
        Layout::Circular => (0..n).map(|i| center + radius * circular(i)).collect(),
        Layout::Force => {
            // Deterministic Fruchterman–Reingold from a circular seed (unit space).
            let mut p: Vec<egui::Vec2> = (0..n).map(circular).collect();
            let k = (1.0 / (n.max(1) as f32).sqrt()).clamp(0.05, 1.0);
            for _ in 0..120 {
                let mut disp = vec![egui::Vec2::ZERO; n];
                for i in 0..n {
                    for j in (i + 1)..n {
                        let d = p[i] - p[j];
                        let dist = d.length().max(1e-3);
                        let f = k * k / dist;
                        let dir = d / dist;
                        disp[i] += dir * f;
                        disp[j] -= dir * f;
                    }
                }
                for e in &scene.edges {
                    if e.src < n && e.dst < n {
                        let d = p[e.src] - p[e.dst];
                        let dist = d.length().max(1e-3);
                        let f = dist * dist / k;
                        let dir = d / dist;
                        disp[e.src] -= dir * f;
                        disp[e.dst] += dir * f;
                    }
                }
                for i in 0..n {
                    let dl = disp[i].length().max(1e-3);
                    p[i] += disp[i] / dl * dl.min(0.04); // capped step (cooling-free, deterministic)
                }
            }
            // Normalise to fit the rect.
            let (mut mn, mut mx) = (egui::vec2(f32::MAX, f32::MAX), egui::vec2(f32::MIN, f32::MIN));
            for v in &p {
                mn.x = mn.x.min(v.x);
                mn.y = mn.y.min(v.y);
                mx.x = mx.x.max(v.x);
                mx.y = mx.y.max(v.y);
            }
            let span = (mx - mn).max(egui::vec2(1e-3, 1e-3));
            p.iter()
                .map(|v| center + egui::vec2(((v.x - mn.x) / span.x - 0.5) * 2.0 * radius, ((v.y - mn.y) / span.y - 0.5) * 2.0 * radius))
                .collect()
        }
    }
}

/// The facett **component contract**. Every facet — graph, map, pipeline, table,
/// the ported nornir viewers — implements this, so consumers (korp, nornir, …)
/// compose them uniformly *and* get headless robot-testing for free.
///
/// The three things a component owes its host:
/// 1. a **title** (tab label / panel heading),
/// 2. how to **draw** itself into egui,
/// 3. its **observable state** as JSON — dumped to `$APP_STATE` for headless
///    assertions. **Rule:** every visible list/status/count goes in `state_json`.
pub trait Facet {
    fn title(&self) -> &str;
    fn ui(&mut self, ui: &mut Ui);
    fn state_json(&self) -> serde_json::Value;

    // --- uniform capability surface (all defaulted; see caps.rs / clipboard.rs) ---

    /// What this facet can do. Override to opt into capabilities.
    fn caps(&self) -> FacetCaps {
        FacetCaps::NONE
    }

    /// Current uniform scale (1.0 = native). Override if `caps().scalable`.
    fn scale(&self) -> f32 {
        1.0
    }
    /// Set the uniform scale; clamp internally. Default no-op (not scalable).
    fn set_scale(&mut self, _scale: f32) {}

    /// The current selection as JSON (also folded into `state_json` by
    /// convention). `Null` when nothing/none selectable.
    fn selection_json(&self) -> serde_json::Value {
        serde_json::Value::Null
    }

    /// Clipboard hooks — see clipboard.rs. Defaults: nothing to give/take.
    /// Returns the text to place on the clipboard (None = nothing copyable now).
    fn copy(&mut self) -> Option<String> {
        None
    }
    /// Like `copy`, but also removes the selection. Default delegates to `copy`.
    fn cut(&mut self) -> Option<String> {
        self.copy()
    }
    /// Accept pasted text. Returns true if consumed.
    fn paste(&mut self, _text: &str) -> bool {
        false
    }

    /// Optional downcast handle for hosts that need typed access to a specific
    /// facet living inside a [`FacetDeck`] (e.g. a robot-UI driver clicking an
    /// app-level control that must forward to a concrete component's own API).
    /// Defaulted to `None` so no existing facet has to change; a component opts in
    /// by returning `Some(self)`.
    fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
        None
    }
}

/// A tabbed set of [`Facet`]s — the reusable multi-component shell. Draws a tab
/// bar + the active facet, and composes **every** facet's `state_json` under its
/// title, so the whole-app introspection contract is free. korp/nornir can build
/// their window from a `FacetDeck` instead of hand-rolling tabs + the state dump.
pub struct FacetDeck {
    facets: Vec<Box<dyn Facet>>,
    active: usize,
    /// Opt-in deck effects (palette override + glow). `Default` = all off, so a
    /// deck that never opts in is unchanged and pays nothing.
    fx: DeckFx,
    /// A raven summoned through the deck, in flight or perched (or `None`).
    raven: Option<DeckRaven>,
}

impl FacetDeck {
    pub fn new(facets: Vec<Box<dyn Facet>>) -> Self {
        Self { facets, active: 0, fx: DeckFx::OFF, raven: None }
    }
    pub fn active(&self) -> usize {
        self.active
    }

    /// Typed mutable access to the facet with `title`, downcast to `T` — `None` if
    /// no such facet, or it doesn't opt into [`Facet::as_any_mut`], or the type
    /// mismatches. Lets a host drive a concrete component's own API (e.g. a
    /// robot-UI control forwarding a node selection to a `SystemChart`).
    pub fn facet_mut<T: std::any::Any>(&mut self, title: &str) -> Option<&mut T> {
        self.facets
            .iter_mut()
            .find(|f| f.title() == title)
            .and_then(|f| f.as_any_mut())
            .and_then(|a| a.downcast_mut::<T>())
    }

    // ── opt-in effects + theming (see deckfx.rs) ─────────────────────────────

    /// Enable deck effects up front (builder form of [`fx_mut`](Self::fx_mut)).
    pub fn with_fx(mut self, fx: DeckFx) -> Self {
        self.fx = fx;
        self
    }
    /// The current deck-effects config (read-only).
    pub fn fx(&self) -> &DeckFx {
        &self.fx
    }
    /// Mutate the deck-effects config (toggle glow, pin a palette, …).
    pub fn fx_mut(&mut self) -> &mut DeckFx {
        &mut self.fx
    }
    /// Override the deck theme with palette index `i` (wraps); enables the
    /// override. Convenience over `fx_mut().set_palette(i)`.
    pub fn set_palette(&mut self, i: usize) {
        self.fx.set_palette(i);
    }
    /// Advance to the next palette in [`Theme::ALL`] (wrapping); returns the new
    /// index. Convenience over `fx_mut().cycle_palette()`.
    pub fn cycle_palette(&mut self) -> usize {
        self.fx.cycle_palette()
    }

    /// **Summon the raven** to perch on `target` — any rect a facet/host hands us
    /// (a table row, a node, a header). Replaces any raven already in flight. The
    /// body is tinted from the deck's current palette (or the host theme). Logs an
    /// activity trail entry. Drive/paint happens automatically inside
    /// [`ui`](Self::ui).
    pub fn send_raven(&mut self, target: Rect) {
        let theme = self.effective_theme();
        self.raven = Some(DeckRaven::new(target, &theme));
        harness::trail(
            harness::Kind::Render,
            format!("raven launched → perch ({:.0},{:.0})", target.center().x, target.top()),
        );
    }
    /// True while a raven is present (flying or perched).
    pub fn has_raven(&self) -> bool {
        self.raven.is_some()
    }
    /// True once the summoned raven has landed (false if none).
    pub fn raven_perched(&self) -> bool {
        self.raven.as_ref().map(|r| r.is_perched()).unwrap_or(false)
    }
    /// Dismiss any raven.
    pub fn clear_raven(&mut self) {
        self.raven = None;
    }

    /// The theme the deck paints with: the fx palette override if set, else
    /// [`Theme::default`] (the host's own `set_theme` still applies its visuals;
    /// this is just the colour source for deck-owned effects/picker).
    fn effective_theme(&self) -> Theme {
        self.fx.theme().unwrap_or_default()
    }

    /// Draw a one-line **palette picker** — a switcher over [`Theme::ALL`] the
    /// host can place anywhere (toolbar, menu). Selecting a palette pins the fx
    /// override; `ui()` then applies it each frame. Returns the chosen index if it
    /// changed this frame.
    pub fn palette_picker(&mut self, ui: &mut Ui) -> Option<usize> {
        let mut sel = self.fx.palette().unwrap_or(0);
        let before = sel;
        ui.horizontal_wrapped(|ui| {
            ui.label("Palette:");
            for (i, ctor) in Theme::ALL.iter().enumerate() {
                ui.selectable_value(&mut sel, i, ctor().name);
            }
        });
        if sel != before || self.fx.palette().is_none() {
            self.fx.set_palette(sel);
        }
        (sel != before).then_some(sel)
    }

    /// The capabilities of the currently-active facet (or `NONE` if empty).
    pub fn active_caps(&self) -> FacetCaps {
        self.facets.get(self.active).map(|f| f.caps()).unwrap_or(FacetCaps::NONE)
    }

    /// The active facet's current scale (1.0 if none / not scalable).
    fn active_scale(&self) -> f32 {
        self.facets.get(self.active).map(|f| f.scale()).unwrap_or(1.0)
    }

    /// Multiply the active facet's scale by `k`, clamped to a sane range.
    fn scale_active(&mut self, k: f32) {
        if let Some(f) = self.facets.get_mut(self.active) {
            let s = (f.scale() * k).clamp(0.25, 4.0);
            f.set_scale(s);
        }
    }

    /// Reset the active facet's scale to native.
    fn reset_scale(&mut self) {
        if let Some(f) = self.facets.get_mut(self.active) {
            f.set_scale(1.0);
        }
    }

    /// Draw the tab bar + capability toolbar + the active facet, and route
    /// capability-gated shortcuts (Ctrl-+/-/0 for scale; Ctrl-C/X/V for clipboard).
    pub fn ui(&mut self, ui: &mut Ui) {
        // Opt-in palette override: apply the chosen Theme::ALL palette + its
        // egui Visuals each frame so the whole deck (and every facet that reads
        // `theme(ui)`) follows. No override → the host's own theme stays.
        if let Some(theme) = self.fx.theme() {
            set_theme(ui.ctx(), theme);
        }

        let titles: Vec<String> = self.facets.iter().map(|f| f.title().to_string()).collect();
        ui.horizontal(|ui| {
            for (i, t) in titles.iter().enumerate() {
                ui.selectable_value(&mut self.active, i, t);
            }
        });

        let caps = self.active_caps();

        // Capability-driven toolbar: only show controls the active facet honors.
        if caps.scalable {
            ui.horizontal(|ui| {
                if ui.button("").on_hover_text("Zoom out (Ctrl-−)").clicked() {
                    self.scale_active(1.0 / 1.1);
                }
                ui.label(format!("{:.0}%", self.active_scale() * 100.0));
                if ui.button("+").on_hover_text("Zoom in (Ctrl-+)").clicked() {
                    self.scale_active(1.1);
                }
                if ui.button("Reset").on_hover_text("Reset zoom (Ctrl-0)").clicked() {
                    self.reset_scale();
                }
            });
        }

        // Capability-gated scale shortcuts. egui has no semantic event for these,
        // so we hand-detect the key combos (clipboard uses semantic events below).
        if caps.scalable {
            let (cmd, plus, minus, zero) = ui.input(|i| {
                (
                    i.modifiers.command,
                    i.key_pressed(egui::Key::Plus) || i.key_pressed(egui::Key::Equals),
                    i.key_pressed(egui::Key::Minus),
                    i.key_pressed(egui::Key::Num0),
                )
            });
            if cmd {
                if plus {
                    self.scale_active(1.1);
                }
                if minus {
                    self.scale_active(1.0 / 1.1);
                }
                if zero {
                    self.reset_scale();
                }
            }
        }

        // Clipboard routing: drain semantic events and dispatch to the active
        // facet, gated by its caps. A focused TextEdit already consumed its own.
        self.route_clipboard(ui.ctx());

        ui.separator();
        // Render the active facet, capturing the rect it occupied so the deck can
        // bloom it (opt-in glow) without the facet knowing.
        let content = ui.scope(|ui| {
            if let Some(f) = self.facets.get_mut(self.active) {
                f.ui(ui);
            }
        });
        let content_rect = content.response.rect;

        // Opt-in glow on the active facet's content rect, pulsing.
        if self.fx.glow && content_rect.is_positive() {
            let theme = self.effective_theme();
            let time = ui.input(|i| i.time);
            let painter = ui.painter_at(content_rect);
            deckfx::paint_active_glow(&painter, content_rect.shrink(2.0), &theme, &self.fx, time);
            ui.ctx().request_repaint(); // keep the pulse animating
        }

        // Drive + paint a summoned raven on a foreground layer above everything.
        self.drive_raven(ui.ctx());
    }

    /// Advance + paint the summoned raven (if any) on a foreground layer. Pins its
    /// launch time on the first frame and keeps repainting while it flies.
    fn drive_raven(&mut self, ctx: &egui::Context) {
        let Some(raven) = self.raven.as_mut() else { return };
        raven.sprite.update(ctx);
        let painter =
            ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("facett_deck_raven")));
        raven.sprite.paint(&painter);
    }

    /// Route this frame's clipboard events to the active facet, gated by caps.
    /// The single OS-touching write (`clipboard::put`) lives here.
    fn route_clipboard(&mut self, ctx: &egui::Context) {
        let caps = self.active_caps();
        if !(caps.copyable || caps.cuttable || caps.pasteable) {
            return;
        }
        for action in clipboard::poll(ctx) {
            let Some(f) = self.facets.get_mut(self.active) else { continue };
            match action {
                ClipAction::Copy if caps.copyable => {
                    if let Some(t) = f.copy() {
                        clipboard::put(ctx, t);
                    }
                }
                ClipAction::Cut if caps.cuttable => {
                    if let Some(t) = f.cut() {
                        clipboard::put(ctx, t);
                    }
                }
                ClipAction::Paste(s) if caps.pasteable => {
                    f.paste(&s);
                }
                // Capability not declared → ignore (event may belong to a focused
                // sub-widget egui already handled).
                _ => {}
            }
        }
    }

    /// The whole-app observable state: the active facet + each facet's
    /// `state_json`, plus an **additive** sibling `caps` map (title → caps JSON)
    /// so the existing flat `facets[title]` shape is unchanged for consumers.
    pub fn state_json(&self) -> serde_json::Value {
        let mut facets = serde_json::Map::new();
        let mut caps = serde_json::Map::new();
        for f in &self.facets {
            facets.insert(f.title().to_string(), f.state_json());
            caps.insert(f.title().to_string(), f.caps().to_json());
        }
        serde_json::json!({
            "active": self.facets.get(self.active).map(|f| f.title()),
            "facets": facets,
            "caps": caps,
        })
    }
}

/// A stable, bright-ish colour from a string (FNV-1a). Handy default node colour.
pub fn hash_color(s: &str) -> Color32 {
    let mut h: u32 = 2166136261;
    for b in s.bytes() {
        h = (h ^ b as u32).wrapping_mul(16777619);
    }
    Color32::from_rgb((h & 0xFF) as u8 | 0x60, ((h >> 8) & 0xFF) as u8 | 0x60, ((h >> 16) & 0xFF) as u8 | 0x60)
}

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

    #[test]
    fn scene_builds() {
        let mut s = Scene::new();
        let a = s.node("Person", hash_color("Person"));
        let b = s.node("Company", hash_color("Company"));
        s.edge(a, b);
        assert_eq!(s.nodes.len(), 2);
        assert_eq!(s.edges.len(), 1);
        assert!(!s.is_empty());
    }

    #[test]
    fn force_layout_produces_finite_bounded_positions() {
        let mut scene = Scene::new();
        for i in 0..12 { scene.node(format!("n{i}"), hash_color("n")); }
        for i in 0..12 { scene.edge(i, (i + 1) % 12); }
        let rect = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(400.0, 400.0));
        let pos = positions(Layout::Force, &scene, rect);
        assert_eq!(pos.len(), 12);
        for p in &pos {
            assert!(p.x.is_finite() && p.y.is_finite(), "finite");
            assert!(rect.expand(50.0).contains(*p), "roughly within the rect");
        }
    }

    #[test]
    fn hash_color_is_stable() {
        assert_eq!(hash_color("Person"), hash_color("Person"));
        assert_ne!(hash_color("Person"), hash_color("Company"));
    }

    /// A minimal facet for deck tests.
    struct Stub(&'static str);
    impl Facet for Stub {
        fn title(&self) -> &str {
            self.0
        }
        fn ui(&mut self, ui: &mut Ui) {
            ui.label(self.0);
        }
        fn state_json(&self) -> serde_json::Value {
            serde_json::json!({ "t": self.0 })
        }
    }

    #[test]
    fn deck_fx_is_off_by_default() {
        let deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
        assert_eq!(*deck.fx(), DeckFx::OFF, "no effects until the host opts in");
        assert!(!deck.has_raven());
        assert!(!deck.fx().glow);
        assert!(deck.fx().palette().is_none());
    }

    #[test]
    fn deck_cycle_palette_walks_theme_all() {
        let mut deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
        let first = deck.cycle_palette();
        assert_eq!(first, 0);
        assert_eq!(deck.fx().theme().map(|t| t.name), Some(Theme::ALL[0]().name));
        // walks forward and wraps
        for _ in 1..Theme::ALL.len() {
            deck.cycle_palette();
        }
        assert_eq!(deck.cycle_palette(), 0, "wraps back to the first palette");
    }

    #[test]
    fn deck_send_raven_launches_and_perches_after_a_full_flight() {
        use crate::effects::RAVEN_FLIGHT_SECS;
        let mut deck = FacetDeck::new(vec![Box::new(Stub("rows"))]);
        assert!(!deck.has_raven());
        let target = egui::Rect::from_min_size(egui::pos2(120.0, 80.0), egui::vec2(200.0, 28.0));
        deck.send_raven(target);
        assert!(deck.has_raven(), "raven summoned");
        assert!(!deck.raven_perched(), "not perched at launch");

        // Drive the sprite headlessly past the flight duration → it perches.
        if let Some(r) = deck.raven.as_mut() {
            r.sprite.advance(RAVEN_FLIGHT_SECS + 0.1);
        }
        assert!(deck.raven_perched(), "perched after the flight duration");

        deck.clear_raven();
        assert!(!deck.has_raven());
    }

    #[test]
    fn deck_palette_override_applies_theme_in_a_ui_pass() {
        let mut deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
        deck.set_palette(1); // sci-fi
        let ctx = egui::Context::default();
        let mut seen = "";
        let _ = ctx.run(egui::RawInput::default(), |ctx| {
            egui::CentralPanel::default().show(ctx, |ui| {
                deck.ui(ui);
                seen = theme(ui).name;
            });
        });
        assert_eq!(seen, Theme::ALL[1]().name, "deck applied its palette override");
    }
}