nornir 0.4.16

Companion to cargo: dependency tracking, release gating, deploy, benchmarks, and documentation assembly. Project-agnostic.
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
//! Connected **dep graph → call graph** tab.
//!
//! Drill `repo → crate → function calls`. The levels are one nested graph: repos
//! and crates come from `symbol_facts` (and line up with `dep_graph_edges.via`),
//! and the leaf call graph comes from `call_edges` (`caller_path → callee_ident`).
//! Data is read over `Warehouse.Scan` (columns + stringified rows), so this works
//! both **embedded** (local warehouse) and **remote** (against a `nornir-server`,
//! scoped by the `nornir-workspace` header), exactly like the warehouse browser.

use std::collections::HashMap;
use std::path::PathBuf;

use eframe::egui::{self, Color32, FontId, Pos2, Sense, Stroke, Vec2};

use crate::warehouse::iceberg::{IcebergWarehouse, TablePreview};

/// Rows scanned per table. Call graphs are bounded by this; we note truncation.
const SCAN_LIMIT: u32 = 8000;
/// Cap rendered nodes (highest-degree kept) so a huge crate stays legible.
const MAX_NODES: usize = 160;

/// Volumetric-fog haze colour: a cold pale-blue "atmosphere" the far depths
/// dissolve into. Far geometry is blended toward this (matching the icy
/// palette) rather than merely dimmed, so the cloud reads as genuinely
/// volumetric.
const FOG_COLOR: Color32 = Color32::from_rgb(18, 26, 40);

enum Src {
    Local(PathBuf),
    Remote { endpoint: String, token: String },
}

struct Node {
    id: String,
    label: String,
    pos: Pos2,
    /// Depth coordinate (the 3rd axis) assigned by the chosen [`Layout3D`].
    z: f32,
    deg: usize,
}

/// 3D layout method for the call graph's depth axis — selectable in the toolbar.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Layout3D {
    /// #1 — extend the Fruchterman–Reingold force sim to xyz.
    Force,
    /// #2 — connected components → z-shells, biggest cluster at z=0 (center),
    /// the rest fanned out in ±z; "Iceland dots hang together".
    ClusterZ,
    /// #3 — topological layering: z = call depth (callers front, leaves back).
    Topo,
    /// #4 — spectral embedding: low eigenvectors of the graph Laplacian (power
    /// iteration) → xyz.
    Spectral,
    /// #5 — classical MDS on BFS hop-distances → xyz.
    Mds,
    /// #6 — keep the 2D force x,y; z = degree centrality so hubs pop toward you.
    Centrality,
    /// #7 — order by degree onto a 3-turn helix (spins beautifully around Y).
    Helix,
}

impl Layout3D {
    const ALL: [(Layout3D, &'static str); 7] = [
        (Layout3D::ClusterZ, "cluster z-shells"),
        (Layout3D::Force, "3D force"),
        (Layout3D::Topo, "topological"),
        (Layout3D::Spectral, "spectral"),
        (Layout3D::Mds, "MDS"),
        (Layout3D::Centrality, "centrality (hubs front)"),
        (Layout3D::Helix, "helix"),
    ];
    fn label(self) -> &'static str {
        Self::ALL.iter().find(|(l, _)| *l == self).map(|(_, s)| *s).unwrap_or("?")
    }
}

pub struct CallGraphState {
    src: Src,
    /// Selected workspace (the `nornir-workspace` gRPC header); empty for local.
    workspace: String,
    loaded: bool,
    error: Option<String>,
    /// Distinct repos and their crates, from `symbol_facts`.
    repos: Vec<String>,
    crates_by_repo: HashMap<String, Vec<String>>,
    sel_repo: Option<String>,
    sel_crate: Option<String>,
    /// Cached `call_edges` scan (reused across crate switches).
    call_rows: Option<TablePreview>,
    /// Cached `symbol_facts` scan — the details panel looks up a clicked
    /// node's kind/file/line/signature here.
    sym_rows: Option<TablePreview>,
    /// Clicked node (index into `nodes`) — drives the details side panel.
    selected: Option<usize>,
    /// Current laid-out graph.
    nodes: Vec<Node>,
    edges: Vec<(usize, usize)>,
    built_for: Option<(String, String)>,
    truncated: bool,
    pan: Vec2,
    zoom: f32,
    /// 3D Y-axis auto-spin: rotation angle (radians) + the last time the user
    /// touched the canvas. After 5s idle the graph rotates around its vertical
    /// axis; any drag/click/scroll freezes it and eases back to face-on.
    spin: f32,
    last_input: std::time::Instant,
    /// Selected 3D depth-axis layout.
    layout3d: Layout3D,
    /// Volumetric-fog density: far nodes/edges fade toward [`FOG_COLOR`] by
    /// `1 - exp(-density * depth_norm)`. 0 = crystal clear, higher = thicker
    /// haze. Tunable via the toolbar slider; never read on CLI/headless paths.
    fog_density: f32,
    /// C8: active facett palette — the painted chrome (edges, highlights,
    /// selection ring, labels) derives from this so a palette switch re-skins it.
    theme: super::facett_theme::Theme,
}

impl CallGraphState {
    pub fn local(root: PathBuf) -> Self {
        Self::with(Src::Local(root), String::new())
    }
    pub fn remote(endpoint: String, token: String, workspace: String) -> Self {
        Self::with(Src::Remote { endpoint, token }, workspace)
    }
    fn with(src: Src, workspace: String) -> Self {
        Self {
            src,
            workspace,
            loaded: false,
            error: None,
            repos: Vec::new(),
            crates_by_repo: HashMap::new(),
            sel_repo: None,
            sel_crate: None,
            call_rows: None,
            sym_rows: None,
            selected: None,
            nodes: Vec::new(),
            edges: Vec::new(),
            built_for: None,
            truncated: false,
            pan: Vec2::ZERO,
            zoom: 1.0,
            spin: 0.0,
            last_input: std::time::Instant::now(),
            layout3d: Layout3D::ClusterZ,
            fog_density: 2.0,
            theme: super::facett_theme::Theme::default(),
        }
    }

    /// C8: swap the active palette; the next draw re-skins from `t`.
    pub fn set_palette(&mut self, t: super::facett_theme::Theme) {
        self.theme = t;
    }

    fn scan(&self, table: &str) -> Result<TablePreview, String> {
        match &self.src {
            Src::Local(root) => IcebergWarehouse::open(root)
                .and_then(|wh| wh.scan_preview(table, SCAN_LIMIT as usize))
                .map_err(|e| format!("{e:#}")),
            Src::Remote { endpoint, token } => {
                super::remote::scan_table(endpoint, token, table, SCAN_LIMIT, &self.workspace)
                    .map_err(|e| format!("{e:#}"))
            }
        }
    }

    /// Re-scope to a different workspace (the picker switched): drop all cached
    /// scans/graph so the next draw rebuilds from the new workspace's warehouse.
    pub(crate) fn set_workspace(&mut self, workspace: String) {
        self.workspace = workspace;
        self.loaded = false;
        self.error = None;
        self.repos.clear();
        self.crates_by_repo.clear();
        self.sel_repo = None;
        self.sel_crate = None;
        self.call_rows = None;
        self.sym_rows = None;
        self.selected = None;
        self.nodes.clear();
        self.edges.clear();
        self.built_for = None;
    }

    /// Force a rebuild on the next draw (e.g. after a ⟳ Sync changed the
    /// warehouse) — drop the cached scans so `ensure_loaded` re-runs.
    pub(crate) fn invalidate(&mut self) {
        self.loaded = false;
        self.built_for = None;
    }

    /// Scan `symbol_facts` (for the repo/crate pickers) + `call_edges` once.
    fn ensure_loaded(&mut self) {
        if self.loaded {
            return;
        }
        self.loaded = true;
        let syms = match self.scan("symbol_facts") {
            Ok(p) => p,
            Err(e) => {
                self.error = Some(format!("scan symbol_facts: {e}"));
                return;
            }
        };
        let (Some(ri), Some(ci)) = (col(&syms, "repo"), col(&syms, "crate_name")) else {
            self.error = Some("symbol_facts missing repo/crate_name columns".into());
            return;
        };
        let mut repos: Vec<String> = Vec::new();
        for row in &syms.rows {
            let (repo, krate) = (cell(row, ri), cell(row, ci));
            if repo.is_empty() {
                continue;
            }
            if !repos.contains(&repo) {
                repos.push(repo.clone());
            }
            let cs = self.crates_by_repo.entry(repo).or_default();
            if !krate.is_empty() && !cs.contains(&krate) {
                cs.push(krate);
            }
        }
        repos.sort();
        for cs in self.crates_by_repo.values_mut() {
            cs.sort();
        }
        self.repos = repos;
        if self.sel_repo.is_none() {
            self.sel_repo = self.repos.first().cloned();
        }
        if let Some(r) = &self.sel_repo {
            self.sel_crate = self.crates_by_repo.get(r).and_then(|c| c.first().cloned());
        }
        self.sym_rows = Some(syms); // kept for the click-to-inspect details panel

        match self.scan("call_edges") {
            Ok(p) => self.call_rows = Some(p),
            Err(e) => self.error = Some(format!("scan call_edges: {e}")),
        }
    }

    /// Build + lay out the call graph for the selected (repo, crate).
    fn build_graph(&mut self) {
        let (Some(repo), Some(krate)) = (self.sel_repo.clone(), self.sel_crate.clone()) else {
            self.nodes.clear();
            self.edges.clear();
            return;
        };
        if self.built_for.as_ref() == Some(&(repo.clone(), krate.clone())) {
            return;
        }
        self.built_for = Some((repo.clone(), krate.clone()));
        self.nodes.clear();
        self.edges.clear();
        self.selected = None;
        self.truncated = false;

        let Some(rows) = &self.call_rows else { return };
        let (Some(ri), Some(ci), Some(fi), Some(ti)) = (
            col(rows, "repo"),
            col(rows, "crate_name"),
            col(rows, "caller_path"),
            col(rows, "callee_ident"),
        ) else {
            self.error = Some("call_edges missing expected columns".into());
            return;
        };

        // Collect raw edges for this crate, counting node degree.
        let mut deg: HashMap<String, usize> = HashMap::new();
        let mut raw: Vec<(String, String)> = Vec::new();
        for row in &rows.rows {
            if cell(row, ri) != repo || cell(row, ci) != krate {
                continue;
            }
            let (from, to) = (short(&cell(row, fi)), short(&cell(row, ti)));
            if from.is_empty() || to.is_empty() {
                continue;
            }
            *deg.entry(from.clone()).or_default() += 1;
            *deg.entry(to.clone()).or_default() += 1;
            raw.push((from, to));
        }

        // Cap to the highest-degree nodes for legibility.
        let mut keep: Vec<String> = deg.keys().cloned().collect();
        keep.sort_by(|a, b| deg[b].cmp(&deg[a]).then(a.cmp(b)));
        if keep.len() > MAX_NODES {
            keep.truncate(MAX_NODES);
            self.truncated = true;
        }
        let mut idx: HashMap<String, usize> = HashMap::new();
        let n = keep.len().max(1) as f32;
        for (i, id) in keep.iter().enumerate() {
            // Seed deterministically on a circle (no RNG → resume-safe).
            let ang = std::f32::consts::TAU * (i as f32) / n;
            idx.insert(id.clone(), self.nodes.len());
            self.nodes.push(Node {
                id: id.clone(),
                label: id.clone(),
                pos: Pos2::new(220.0 * ang.cos(), 220.0 * ang.sin()),
                z: 0.0,
                deg: deg[id],
            });
        }
        for (from, to) in raw {
            if let (Some(&a), Some(&b)) = (idx.get(&from), idx.get(&to)) {
                if a != b {
                    self.edges.push((a, b));
                }
            }
        }
        self.layout();
        self.assign_z3d();
        self.pan = Vec2::ZERO;
        self.zoom = 1.0;
    }

    /// Tiny Fruchterman–Reingold force layout (deterministic).
    fn layout(&mut self) {
        let n = self.nodes.len();
        if n < 2 {
            return;
        }
        let area = 640.0 * 480.0;
        let k = (area / n as f32).sqrt();
        let mut disp = vec![Vec2::ZERO; n];
        for _ in 0..120 {
            for d in disp.iter_mut() {
                *d = Vec2::ZERO;
            }
            // Repulsion (all pairs).
            for i in 0..n {
                for j in (i + 1)..n {
                    let mut delta = self.nodes[i].pos - self.nodes[j].pos;
                    let mut dist = delta.length();
                    if dist < 0.01 {
                        delta = Vec2::new(0.1 * (i as f32 + 1.0), 0.1);
                        dist = delta.length();
                    }
                    let force = (k * k) / dist;
                    let push = delta / dist * force;
                    disp[i] += push;
                    disp[j] -= push;
                }
            }
            // Attraction (edges).
            for &(a, b) in &self.edges {
                let delta = self.nodes[a].pos - self.nodes[b].pos;
                let dist = delta.length().max(0.01);
                let force = (dist * dist) / k;
                let pull = delta / dist * force;
                disp[a] -= pull;
                disp[b] += pull;
            }
            for i in 0..n {
                let d = disp[i];
                let len = d.length().max(0.01);
                self.nodes[i].pos += d / len * len.min(16.0);
            }
        }
    }

    /// Assign the depth (z) axis — and, for spectral/MDS, all three coords —
    /// per the selected [`Layout3D`]. Runs after the 2D force `layout()`.
    fn assign_z3d(&mut self) {
        let n = self.nodes.len();
        if n == 0 {
            return;
        }
        let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];
        for &(a, b) in &self.edges {
            adj[a].push(b);
            adj[b].push(a);
        }
        match self.layout3d {
            Layout3D::Force => self.layout_force3d(),
            Layout3D::ClusterZ => self.layout_cluster_z(&adj),
            Layout3D::Topo => self.layout_topo(),
            Layout3D::Spectral => self.layout_spectral(&adj),
            Layout3D::Mds => self.layout_mds(&adj),
            Layout3D::Centrality => self.layout_centrality(),
            Layout3D::Helix => self.layout_helix(),
        }
        self.normalize_3d();
    }

    /// #1 — a z-only force pass (x,y from the 2D layout): edges pull nodes
    /// together in depth, all pairs push apart → organic 3D relief.
    fn layout_force3d(&mut self) {
        let n = self.nodes.len();
        for i in 0..n {
            self.nodes[i].z = (i as f32 * 7.13).sin() * 120.0;
        }
        let k = 90.0;
        for _ in 0..90 {
            let mut dz = vec![0.0f32; n];
            for i in 0..n {
                for j in (i + 1)..n {
                    let mut d = self.nodes[i].z - self.nodes[j].z;
                    if d.abs() < 0.01 {
                        d = 0.1;
                    }
                    let f = (k * k) / d.abs() * d.signum() * 0.0016;
                    dz[i] += f;
                    dz[j] -= f;
                }
            }
            for &(a, b) in &self.edges {
                let d = self.nodes[a].z - self.nodes[b].z;
                dz[a] -= d * 0.05;
                dz[b] += d * 0.05;
            }
            for i in 0..n {
                self.nodes[i].z += dz[i].clamp(-20.0, 20.0);
            }
        }
    }

    /// #2 — **Louvain communities** → z-shells: biggest community at z=0 (center),
    /// the rest fanned out in ±z by size; community-mates share a depth (+jitter).
    /// Louvain (modularity) finds tight sub-clusters within a connected blob, so
    /// "iceland dots hang together" far better than connected-components did.
    fn layout_cluster_z(&mut self, adj: &[Vec<usize>]) {
        let n = self.nodes.len();
        let comp = louvain(adj);
        let nc = comp.iter().copied().max().map(|m| m + 1).unwrap_or(1);
        let mut sizes = vec![0usize; nc];
        for &c in &comp {
            sizes[c] += 1;
        }
        let mut order: Vec<usize> = (0..sizes.len()).collect();
        order.sort_by_key(|&c| std::cmp::Reverse(sizes[c]));
        let mut zof = vec![0.0f32; sizes.len()];
        for (rank, &c) in order.iter().enumerate() {
            let shell = ((rank + 1) / 2) as f32;
            let sign = if rank % 2 == 1 { 1.0 } else { -1.0 };
            zof[c] = sign * shell * 190.0;
        }
        for i in 0..n {
            self.nodes[i].z = zof[comp[i]] + (i as f32 * 12.9898).sin() * 22.0;
        }
    }

    /// #3 — topological layering: z = longest-path call depth (sources front,
    /// sinks back), centered.
    fn layout_topo(&mut self) {
        let n = self.nodes.len();
        let mut indeg = vec![0usize; n];
        let mut out: Vec<Vec<usize>> = vec![Vec::new(); n];
        for &(a, b) in &self.edges {
            out[a].push(b);
            indeg[b] += 1;
        }
        let mut layer = vec![0i32; n];
        let mut seen = vec![false; n];
        let mut work: Vec<usize> = (0..n).filter(|&i| indeg[i] == 0).collect();
        for &i in &work {
            seen[i] = true;
        }
        while let Some(u) = work.pop() {
            for &v in &out[u] {
                if layer[v] < layer[u] + 1 {
                    layer[v] = layer[u] + 1;
                }
                indeg[v] = indeg[v].saturating_sub(1);
                if indeg[v] == 0 && !seen[v] {
                    seen[v] = true;
                    work.push(v);
                }
            }
        }
        let maxl = layer.iter().cloned().max().unwrap_or(0).max(1) as f32;
        for i in 0..n {
            self.nodes[i].z = (layer[i] as f32 - maxl / 2.0) * 170.0;
        }
    }

    /// #4 — spectral embedding: 3 lowest non-trivial Laplacian eigenvectors via
    /// shifted power iteration (M = cI − L, deflating the constant) → x, y, z.
    fn layout_spectral(&mut self, adj: &[Vec<usize>]) {
        let n = self.nodes.len();
        if n < 4 {
            return;
        }
        let deg: Vec<f32> = adj.iter().map(|a| a.len() as f32).collect();
        let c = deg.iter().cloned().fold(0.0, f32::max) * 2.0 + 1.0;
        let mul = |v: &[f32]| -> Vec<f32> {
            let mut r = vec![0.0f32; n];
            for i in 0..n {
                r[i] = (c - deg[i]) * v[i];
                for &j in &adj[i] {
                    r[i] += v[j];
                }
            }
            r
        };
        let ortho = |v: &mut Vec<f32>, basis: &[Vec<f32>]| {
            for b in basis {
                let dot: f32 = v.iter().zip(b).map(|(x, y)| x * y).sum();
                for i in 0..n {
                    v[i] -= dot * b[i];
                }
            }
            let norm = v.iter().map(|x| x * x).sum::<f32>().sqrt().max(1e-6);
            for x in v.iter_mut() {
                *x /= norm;
            }
        };
        let mut basis = vec![vec![1.0 / (n as f32).sqrt(); n]];
        let mut coords: Vec<Vec<f32>> = Vec::new();
        for k in 0..3 {
            let mut v: Vec<f32> = (0..n).map(|i| ((i * 7 + k * 131 + 1) as f32).sin()).collect();
            ortho(&mut v, &basis);
            for _ in 0..70 {
                let mut nv = mul(&v);
                ortho(&mut nv, &basis);
                v = nv;
            }
            basis.push(v.clone());
            coords.push(v);
        }
        for i in 0..n {
            self.nodes[i].pos = Pos2::new(coords[0][i] * 320.0, coords[1][i] * 320.0);
            self.nodes[i].z = coords[2][i] * 320.0;
        }
    }

    /// #5 — classical MDS on BFS hop-distances → x, y, z (top-3 eigenvectors of
    /// the double-centered squared-distance matrix).
    fn layout_mds(&mut self, adj: &[Vec<usize>]) {
        let n = self.nodes.len();
        if n < 4 {
            return;
        }
        let far = (n as f32).sqrt() + 2.0;
        let mut dist = vec![vec![0.0f32; n]; n];
        for s in 0..n {
            let mut d = vec![-1i32; n];
            let mut q = std::collections::VecDeque::new();
            d[s] = 0;
            q.push_back(s);
            while let Some(u) = q.pop_front() {
                for &v in &adj[u] {
                    if d[v] < 0 {
                        d[v] = d[u] + 1;
                        q.push_back(v);
                    }
                }
            }
            for j in 0..n {
                dist[s][j] = if d[j] < 0 { far } else { d[j] as f32 };
            }
        }
        let mut b = vec![vec![0.0f32; n]; n];
        let mut rowm = vec![0.0f32; n];
        let mut all = 0.0f32;
        for i in 0..n {
            for j in 0..n {
                let d2 = dist[i][j] * dist[i][j];
                b[i][j] = d2;
                rowm[i] += d2;
                all += d2;
            }
        }
        let allm = all / (n * n) as f32;
        for r in rowm.iter_mut() {
            *r /= n as f32;
        }
        for i in 0..n {
            for j in 0..n {
                b[i][j] = -0.5 * (b[i][j] - rowm[i] - rowm[j] + allm);
            }
        }
        let mul = |v: &[f32]| -> Vec<f32> {
            (0..n).map(|i| (0..n).map(|j| b[i][j] * v[j]).sum()).collect()
        };
        let ortho = |v: &mut Vec<f32>, basis: &[Vec<f32>]| {
            for bb in basis {
                let dot: f32 = v.iter().zip(bb).map(|(x, y)| x * y).sum();
                for i in 0..n {
                    v[i] -= dot * bb[i];
                }
            }
            let norm = v.iter().map(|x| x * x).sum::<f32>().sqrt().max(1e-6);
            for x in v.iter_mut() {
                *x /= norm;
            }
        };
        let mut basis: Vec<Vec<f32>> = Vec::new();
        let mut coords: Vec<Vec<f32>> = Vec::new();
        for k in 0..3 {
            let mut v: Vec<f32> = (0..n).map(|i| ((i * 13 + k * 71 + 1) as f32).sin()).collect();
            ortho(&mut v, &basis);
            for _ in 0..70 {
                let mut nv = mul(&v);
                ortho(&mut nv, &basis);
                v = nv;
            }
            basis.push(v.clone());
            coords.push(v);
        }
        for i in 0..n {
            self.nodes[i].pos = Pos2::new(coords[0][i] * 26.0, coords[1][i] * 26.0);
            self.nodes[i].z = coords[2][i] * 26.0;
        }
    }

    /// #6 — z by degree centrality: x,y from the 2D force, hubs pushed toward
    /// the camera (negative z = near).
    fn layout_centrality(&mut self) {
        let n = self.nodes.len();
        let maxd = self.nodes.iter().map(|nd| nd.deg).max().unwrap_or(1).max(1) as f32;
        for i in 0..n {
            self.nodes[i].z = -((self.nodes[i].deg as f32 / maxd) - 0.5) * 520.0;
        }
    }

    /// #7 — order nodes by degree onto a 3-turn helix; spinning around Y reads as
    /// a rotating DNA strand.
    fn layout_helix(&mut self) {
        let n = self.nodes.len();
        let mut order: Vec<usize> = (0..n).collect();
        order.sort_by_key(|&i| std::cmp::Reverse(self.nodes[i].deg));
        let r = 240.0;
        let turns = 3.0;
        let denom = (n.max(2) - 1) as f32;
        for (rank, &i) in order.iter().enumerate() {
            let t = rank as f32 / denom;
            let ang = t * std::f32::consts::TAU * turns;
            self.nodes[i].pos = Pos2::new(r * ang.cos(), (t - 0.5) * 540.0);
            self.nodes[i].z = r * ang.sin();
        }
    }

    /// Rescale all three axes to a consistent on-screen extent so every layout
    /// fills the canvas comparably.
    fn normalize_3d(&mut self) {
        if self.nodes.is_empty() {
            return;
        }
        let (mut mnx, mut mxx, mut mny, mut mxy, mut mnz, mut mxz) =
            (f32::MAX, f32::MIN, f32::MAX, f32::MIN, f32::MAX, f32::MIN);
        for nd in &self.nodes {
            mnx = mnx.min(nd.pos.x);
            mxx = mxx.max(nd.pos.x);
            mny = mny.min(nd.pos.y);
            mxy = mxy.max(nd.pos.y);
            mnz = mnz.min(nd.z);
            mxz = mxz.max(nd.z);
        }
        let span = (mxx - mnx).max(mxy - mny).max(mxz - mnz).max(1.0);
        let scale = 520.0 / span;
        let (cx, cy, cz) = ((mnx + mxx) / 2.0, (mny + mxy) / 2.0, (mnz + mxz) / 2.0);
        for nd in &mut self.nodes {
            nd.pos = Pos2::new((nd.pos.x - cx) * scale, (nd.pos.y - cy) * scale);
            nd.z = (nd.z - cz) * scale;
        }
    }

    pub fn draw(&mut self, ui: &mut egui::Ui) {
        let theme = self.theme;
        self.ensure_loaded();

        egui::TopBottomPanel::top("cg_controls").show_inside(ui, |ui| {
            ui.horizontal_wrapped(|ui| {
                ui.label("repo:");
                let cur_repo = self.sel_repo.clone().unwrap_or_default();
                egui::ComboBox::from_id_salt("cg_repo")
                    .selected_text(if cur_repo.is_empty() { "".into() } else { cur_repo.clone() })
                    .show_ui(ui, |ui| {
                        for r in self.repos.clone() {
                            if ui.selectable_label(self.sel_repo.as_deref() == Some(&r), &r).clicked() {
                                self.sel_repo = Some(r.clone());
                                self.sel_crate =
                                    self.crates_by_repo.get(&r).and_then(|c| c.first().cloned());
                                self.built_for = None;
                            }
                        }
                    });
                ui.separator();
                ui.label("crate:");
                let crates = self
                    .sel_repo
                    .as_ref()
                    .and_then(|r| self.crates_by_repo.get(r))
                    .cloned()
                    .unwrap_or_default();
                let cur_crate = self.sel_crate.clone().unwrap_or_default();
                egui::ComboBox::from_id_salt("cg_crate")
                    .selected_text(if cur_crate.is_empty() { "".into() } else { cur_crate.clone() })
                    .show_ui(ui, |ui| {
                        for c in crates {
                            if ui.selectable_label(self.sel_crate.as_deref() == Some(&c), &c).clicked() {
                                self.sel_crate = Some(c);
                                self.built_for = None;
                            }
                        }
                    });
                ui.separator();
                if ui.button("↻ reload").clicked() {
                    self.loaded = false;
                    self.call_rows = None;
                    self.crates_by_repo.clear();
                    self.repos.clear();
                    self.built_for = None;
                    self.error = None;
                }
                if ui.button("⊙ fit").clicked() {
                    self.pan = Vec2::ZERO;
                    self.zoom = 1.0;
                }
                ui.separator();
                ui.label("3D:");
                egui::ComboBox::from_id_salt("cg_layout3d")
                    .selected_text(self.layout3d.label())
                    .show_ui(ui, |ui| {
                        for (l, name) in Layout3D::ALL {
                            if ui.selectable_label(self.layout3d == l, name).clicked() {
                                self.layout3d = l;
                                self.built_for = None; // rebuild with the new 3D layout
                            }
                        }
                    });
                ui.separator();
                // Volumetric-fog density: pure render param, no graph rebuild.
                ui.label("fog:")
                    .on_hover_text("volumetric haze density — far nodes/edges fade into the depth");
                ui.add(
                    egui::Slider::new(&mut self.fog_density, 0.0..=6.0)
                        .fixed_decimals(1)
                        .show_value(true),
                );
            });
        });

        self.build_graph();

        // Details panel for the clicked node: symbol facts + clickable
        // caller/callee navigation (click a name to jump the selection).
        if let Some(sel) = self.selected {
            if sel >= self.nodes.len() {
                self.selected = None;
            } else {
                let mut jump: Option<usize> = None;
                let mut close = false;
                egui::SidePanel::right("cg_details").default_width(300.0).show_inside(ui, |ui| {
                    let node = &self.nodes[sel];
                    ui.horizontal(|ui| {
                        ui.heading(&node.label);
                        if ui.button("").on_hover_text("close").clicked() {
                            close = true;
                        }
                    });
                    ui.label(format!("call degree: {}", node.deg));
                    ui.separator();

                    // symbol_facts lookup by item_name within the selected repo/crate.
                    if let (Some(syms), Some((repo, krate))) = (&self.sym_rows, &self.built_for) {
                        if let (Some(ri), Some(ci), Some(ni)) =
                            (col(syms, "repo"), col(syms, "crate_name"), col(syms, "item_name"))
                        {
                            let (fi, li, ki, si, vi) = (
                                col(syms, "file"),
                                col(syms, "line"),
                                col(syms, "item_kind"),
                                col(syms, "signature"),
                                col(syms, "visibility"),
                            );
                            for row in syms
                                .rows
                                .iter()
                                .filter(|r| {
                                    cell(r, ri) == *repo
                                        && cell(r, ci) == *krate
                                        && cell(r, ni) == node.label
                                })
                                .take(3)
                            {
                                if let (Some(k), Some(v)) = (ki, vi) {
                                    ui.label(format!("{} {}", cell(row, v), cell(row, k)));
                                }
                                if let (Some(f), Some(l)) = (fi, li) {
                                    ui.monospace(format!("{}:{}", cell(row, f), cell(row, l)));
                                }
                                if let Some(s) = si {
                                    let sig = cell(row, s);
                                    if !sig.is_empty() {
                                        ui.add(egui::Label::new(
                                            egui::RichText::new(sig).monospace().size(11.0),
                                        ).wrap());
                                    }
                                }
                                ui.add_space(4.0);
                            }
                        }
                    }

                    // Callers / callees from the laid-out edges — clickable.
                    let callers: Vec<usize> =
                        self.edges.iter().filter(|(_, b)| *b == sel).map(|(a, _)| *a).collect();
                    let callees: Vec<usize> =
                        self.edges.iter().filter(|(a, _)| *a == sel).map(|(_, b)| *b).collect();
                    egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
                        ui.separator();
                        ui.strong(format!("called by ({})", callers.len()));
                        for a in callers {
                            if ui.link(&self.nodes[a].label).clicked() {
                                jump = Some(a);
                            }
                        }
                        ui.separator();
                        ui.strong(format!("calls ({})", callees.len()));
                        for b in callees {
                            if ui.link(&self.nodes[b].label).clicked() {
                                jump = Some(b);
                            }
                        }
                    });
                });
                if close {
                    self.selected = None;
                } else if let Some(j) = jump {
                    self.selected = Some(j);
                    // Center the jumped-to node so navigation reads as movement.
                    self.pan = -(self.nodes[j].pos.to_vec2()) * self.zoom;
                }
            }
        }

        egui::CentralPanel::default().show_inside(ui, |ui| {
            if let Some(err) = &self.error {
                ui.colored_label(super::facett_theme::RED, err);
                return;
            }
            if self.nodes.is_empty() {
                ui.label(
                    "no call edges for this crate (pick another repo/crate; \
                     monitoring fills call_edges as it republishes)",
                );
                return;
            }
            let (resp, painter) =
                ui.allocate_painter(ui.available_size(), Sense::click_and_drag());
            let mut scroll = 0.0;
            if resp.dragged() {
                self.pan += resp.drag_delta();
            }
            if resp.hovered() {
                scroll = ui.input(|i| i.raw_scroll_delta.y);
                if scroll != 0.0 {
                    self.zoom = (self.zoom * (1.0 + scroll * 0.001)).clamp(0.2, 4.0);
                }
            }
            // 3D Y-axis auto-spin: after 5s idle the graph rotates around its
            // vertical axis; any drag/click/scroll freezes it and eases it back
            // to face-on so clicking stays easy.
            if resp.dragged() || resp.clicked() || scroll != 0.0 {
                self.last_input = std::time::Instant::now();
            }
            if self.last_input.elapsed().as_secs_f32() > 5.0 {
                self.spin += 0.006;
                if self.spin > std::f32::consts::PI {
                    self.spin -= 2.0 * std::f32::consts::PI;
                }
                ui.ctx().request_repaint();
            } else if self.spin.abs() > 0.0008 {
                self.spin *= 0.90;
                ui.ctx().request_repaint();
            } else {
                self.spin = 0.0;
            }
            let origin = resp.rect.center() + self.pan;
            let zoom = self.zoom;
            let focal = 1100.0_f32;
            let (sin, cos) = self.spin.sin_cos();
            // Rotate a layout point around the vertical (Y) axis + perspective:
            // returns the screen position and the perspective scale (near side
            // grows, far side shrinks — the 3D depth cue as it spins).
            let project = move |p: Pos2, z: f32| -> (Pos2, f32) {
                // Rotate (x, z) around the vertical Y axis, then perspective.
                let rx = p.x * cos + z * sin;
                let rz = -p.x * sin + z * cos;
                let persp = focal / (focal + rz);
                (origin + Vec2::new(rx, p.y) * (zoom * persp), persp)
            };
            let radius = move |deg: usize, persp: f32| {
                (3.0 + (deg as f32).sqrt() * 1.6) * zoom.clamp(0.6, 2.0) * persp
            };

            // Click-to-inspect: nearest node within its radius (+slop) selects it;
            // clicking empty canvas clears the selection.
            if resp.clicked() {
                if let Some(click) = resp.interact_pointer_pos() {
                    self.selected = self
                        .nodes
                        .iter()
                        .enumerate()
                        .map(|(i, n)| {
                            let (sp, persp) = project(n.pos, n.z);
                            (i, (sp - click).length(), radius(n.deg, persp))
                        })
                        .filter(|(_, d, r)| *d <= r.max(6.0) + 4.0)
                        .min_by(|a, b| a.1.total_cmp(&b.1))
                        .map(|(i, _, _)| i);
                }
            }

            // Edges with a small arrowhead toward the callee; edges touching the
            // selected node are highlighted (orange = outgoing, cyan = incoming).
            for &(a, b) in &self.edges {
                let (ja, jb) = (
                    project(self.nodes[a].pos, self.nodes[a].z),
                    project(self.nodes[b].pos, self.nodes[b].z),
                );
                let (pa, pb) = (ja.0, jb.0);
                let stroke = match self.selected {
                    Some(s) if a == s => Stroke::new(1.6, super::facett_theme::AMBER),
                    Some(s) if b == s => Stroke::new(1.6, theme.accent),
                    _ => {
                        // Volumetric fog: far edges dissolve into the haze colour,
                        // near edges read brighter + cooler. Depth is the mean of
                        // the two endpoints' projected depth.
                        let depth = 0.5 * (depth_norm(ja.1) + depth_norm(jb.1));
                        let base = theme.edge;
                        Stroke::new(1.0, fog_blend(base, depth, self.fog_density))
                    }
                };
                painter.line_segment([pa, pb], stroke);
                let dir = (pb - pa).normalized();
                let head = pb - dir * (6.0 + 4.0 * self.zoom);
                let perp = Vec2::new(-dir.y, dir.x) * 3.0;
                painter.line_segment([pb, head + perp], Stroke::new(1.0, theme.edge));
                painter.line_segment([pb, head - perp], Stroke::new(1.0, theme.edge));
            }
            // Nodes: radius + color scale with call degree; selection ring on top.
            // Draw far → near (by perspective depth) so near nodes overlay —
            // the key 3D cue alongside size + icy fog fade.
            let mut order: Vec<usize> = (0..self.nodes.len()).collect();
            order.sort_by(|&a, &b| {
                project(self.nodes[a].pos, self.nodes[a].z)
                    .1
                    .partial_cmp(&project(self.nodes[b].pos, self.nodes[b].z).1)
                    .unwrap_or(std::cmp::Ordering::Equal)
            });
            for &i in &order {
                let node = &self.nodes[i];
                let (p, persp) = project(node.pos, node.z);
                let r = radius(node.deg, persp);
                let col = fog_blend(heat(node.deg), depth_norm(persp), self.fog_density);
                painter.circle_filled(p, r, col);
                if self.selected == Some(i) {
                    painter.circle_stroke(p, r + 3.0, Stroke::new(2.0, theme.selection()));
                }
                if self.zoom > 0.85 || node.deg >= 4 || self.selected == Some(i) {
                    let lf = (120.0 + 110.0 * (persp.clamp(0.6, 1.3) - 0.6) / 0.7) as u8;
                    let base = Color32::from_rgb(lf, lf, (lf as f32 * 1.08).min(255.0) as u8);
                    painter.text(
                        p + Vec2::new(r + 2.0, -r),
                        egui::Align2::LEFT_BOTTOM,
                        &node.label,
                        FontId::proportional(11.0),
                        fog_blend(base, depth_norm(persp), self.fog_density),
                    );
                }
            }
            let (repo, krate) = self.built_for.clone().unwrap_or_default();
            let note = format!(
                "{repo} · {krate}{} fns, {} calls{}  ·  drag to pan, scroll to zoom",
                self.nodes.len(),
                self.edges.len(),
                if self.truncated { format!(" (top {MAX_NODES})") } else { String::new() }
            );
            let note = format!("{note} · click a node to inspect");
            painter.text(
                resp.rect.left_top() + Vec2::new(8.0, 8.0),
                egui::Align2::LEFT_TOP,
                note,
                FontId::proportional(12.0),
                theme.text_dim,
            );
        });
    }
}

/// Column index by name in a [`TablePreview`].
fn col(p: &TablePreview, name: &str) -> Option<usize> {
    p.columns.iter().position(|c| c == name)
}

fn cell(row: &[String], i: usize) -> String {
    row.get(i).cloned().unwrap_or_default()
}

/// Last `::`-segment of a path, for compact node labels.
fn short(path: &str) -> String {
    path.rsplit("::").next().unwrap_or(path).to_string()
}

/// Degree → warm color (cool=few calls, hot=hub).
/// Louvain community detection (single level, local modularity moves). Returns a
/// community id per node, relabelled to `0..k`. `adj` is the undirected
/// adjacency (each edge present both ways). Pure, deterministic (fixed order).
fn louvain(adj: &[Vec<usize>]) -> Vec<usize> {
    use std::collections::HashMap;
    let n = adj.len();
    let m2: f64 = adj.iter().map(|a| a.len()).sum::<usize>() as f64; // 2m
    if m2 == 0.0 {
        return (0..n).collect();
    }
    let deg: Vec<f64> = adj.iter().map(|a| a.len() as f64).collect();
    let mut comm: Vec<usize> = (0..n).collect();
    let mut sigma_tot = deg.clone(); // Σ degrees per community
    let mut improved = true;
    let mut passes = 0;
    while improved && passes < 30 {
        improved = false;
        passes += 1;
        for i in 0..n {
            let ci = comm[i];
            sigma_tot[ci] -= deg[i];
            // edges from i into each neighbouring community
            let mut k_in: HashMap<usize, f64> = HashMap::new();
            for &j in &adj[i] {
                if j != i {
                    *k_in.entry(comm[j]).or_insert(0.0) += 1.0;
                }
            }
            k_in.entry(ci).or_insert(0.0); // staying is always an option
            let (mut best_c, mut best_gain) = (ci, f64::MIN);
            for (&c, &kic) in &k_in {
                let gain = kic - sigma_tot[c] * deg[i] / m2;
                if gain > best_gain + 1e-9 {
                    best_gain = gain;
                    best_c = c;
                }
            }
            comm[i] = best_c;
            sigma_tot[best_c] += deg[i];
            if best_c != ci {
                improved = true;
            }
        }
    }
    let mut relabel: HashMap<usize, usize> = HashMap::new();
    comm.iter()
        .map(|&c| {
            let next = relabel.len();
            *relabel.entry(c).or_insert(next)
        })
        .collect()
}

/// Icy node colour: deep glacier-blue (low degree) → bright cyan/white (hubs).
/// Depth attenuation is applied separately by [`fog_blend`] so nodes and edges
/// share one volumetric model.
fn heat(deg: usize) -> Color32 {
    let t = (deg as f32 / 12.0).clamp(0.0, 1.0);
    let r = 40.0 + 150.0 * t;
    let g = 120.0 + 115.0 * t;
    let b = 190.0 + 60.0 * t;
    Color32::from_rgb(r as u8, g as u8, b as u8)
}

/// Map a perspective scale (`persp = focal / (focal + rz)`, >1 near .. <1 far)
/// to a normalized depth in `[0, 1]` where 0 = nearest (crisp) and 1 = farthest
/// (deepest haze). Pure: the fog model's only coupling to the projection.
fn depth_norm(persp: f32) -> f32 {
    // persp spans roughly [0.55 (far) .. 1.35 (near)] for this scene.
    (1.0 - (persp.clamp(0.55, 1.35) - 0.55) / 0.8).clamp(0.0, 1.0)
}

/// Volumetric fog: blend `color` toward [`FOG_COLOR`] by an exponential
/// extinction `1 - exp(-density * depth_norm)`. Near geometry (`depth ≈ 0`)
/// stays crisp; far geometry dissolves into the haze. Pure math — unit-tested.
fn fog_blend(color: Color32, depth: f32, density: f32) -> Color32 {
    let f = (1.0 - (-density * depth.clamp(0.0, 1.0)).exp()).clamp(0.0, 1.0);
    let lerp = |a: u8, b: u8| (a as f32 + (b as f32 - a as f32) * f).round() as u8;
    Color32::from_rgb(
        lerp(color.r(), FOG_COLOR.r()),
        lerp(color.g(), FOG_COLOR.g()),
        lerp(color.b(), FOG_COLOR.b()),
    )
}

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

    #[test]
    fn fog_near_is_crisp_far_is_haze() {
        let col = Color32::from_rgb(200, 220, 250);
        // Nearest depth → unchanged colour (no extinction).
        assert_eq!(fog_blend(col, 0.0, 2.0), col);
        // Far depth at a healthy density → very close to the haze colour.
        let far = fog_blend(col, 1.0, 6.0);
        let d = |a: u8, b: u8| (a as i32 - b as i32).abs();
        assert!(d(far.r(), FOG_COLOR.r()) <= 2);
        assert!(d(far.g(), FOG_COLOR.g()) <= 2);
        assert!(d(far.b(), FOG_COLOR.b()) <= 2);
    }

    #[test]
    fn fog_is_monotonic_in_depth() {
        let col = Color32::from_rgb(40, 120, 190);
        // Toward a darker/cooler haze the blue channel must decrease monotonically
        // as depth grows (more extinction → closer to FOG_COLOR.b()=40).
        let mut prev = col.b();
        for k in 1..=10 {
            let b = fog_blend(col, k as f32 / 10.0, 2.0).b();
            assert!(b <= prev, "channel not monotonic at step {k}");
            prev = b;
        }
    }

    #[test]
    fn zero_density_disables_fog() {
        let col = Color32::from_rgb(123, 45, 67);
        assert_eq!(fog_blend(col, 1.0, 0.0), col);
    }

    #[test]
    fn depth_norm_endpoints() {
        // Near (large persp) → 0, far (small persp) → 1.
        assert!(depth_norm(1.35) < 1e-3);
        assert!(depth_norm(0.55) > 1.0 - 1e-3);
        // Monotonic decrease with persp.
        assert!(depth_norm(0.7) > depth_norm(1.1));
    }
}