Skip to main content

schedr_ui/
graph.rs

1//! The run graph's layout: a layered (Sugiyama) layout of our own (decision 22A), top to
2//! bottom.
3//!
4//! 1. **Layers:** each task one layer below its lowest upstream task (the longest path from a
5//!    task without upstream ones).
6//! 2. **Long edges** get a point in every layer they cross (dummy nodes), so they are routed
7//!    between the tasks rather than through them.
8//! 3. **Crossings:** layers are reordered by the mean position of their neighbours
9//!    (barycenters), sweeping down and up; the order with the fewest crossings seen is kept,
10//!    the tasks' own order first, so the result is never worse than that.
11//! 4. **x:** each node as near its neighbours' mean as the order and the gaps allow (a
12//!    least-squares fit under those constraints, by pool-adjacent-violators), sweeping down
13//!    and up; then shifted so the leftmost node starts at the margin.
14//!
15//! **Groups** (decision 65): a group's tasks stay together. Every layer is ordered group by
16//! group (a group's place is its members' mean; nested groups inside their parent), a long
17//! edge's points belong to the innermost group both its ends are in, and after the x fit any
18//! other task is pushed clear of a group's box in every layer the box spans. A box is its
19//! members' extent and its nested boxes', with padding and a band for its label on top; the
20//! space between layers grows with the deepest nesting, so labels never meet.
21//!
22//! **Resources** beside the tasks: a resource's setup and cleanup are taken out of the
23//! layers' order and drawn in a box of their own on the left, each resource in a lane, its
24//! setup and cleanup in the layers they would have had (so every row stays where it was). Their
25//! edges run in a channel between the box and the tasks (a track per resource and direction),
26//! reaching it through the space below their upstream node's layer and leaving it through the
27//! space above their downstream node's: never through a box.
28//!
29//! Deterministic: the same graph always gets the same layout.
30
31#[cfg(test)]
32mod tests;
33
34/// A task's box: width.
35pub const NODE_WIDTH: f64 = 180.0;
36/// A task's box: height.
37pub const NODE_HEIGHT: f64 = 44.0;
38/// The space between two boxes side by side.
39const GAP: f64 = 32.0;
40/// The space next to a long edge passing a layer.
41const DUMMY_GAP: f64 = 16.0;
42/// The space between layers.
43const LAYER_GAP: f64 = 56.0;
44/// The space around the drawing.
45pub const MARGIN: f64 = 16.0;
46/// Reordering sweeps (each one down and one up).
47const SWEEPS: usize = 12;
48/// Placement sweeps.
49const PLACEMENTS: usize = 8;
50/// A group box's padding around its contents (sides and bottom).
51pub const GROUP_PAD: f64 = 10.0;
52/// A group box's band for its label, above its contents.
53pub const GROUP_LABEL: f64 = 22.0;
54/// Rounds of pushing other tasks clear of the group boxes, at most.
55const SEPARATIONS: usize = 24;
56
57/// A group of nodes, for [`layout_grouped`].
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub struct GroupSpec {
60    /// The group it is nested in (an index into the same list, before this one).
61    pub parent: Option<usize>,
62}
63
64/// A group's box, drawn around its nodes.
65#[derive(Debug, Clone, Copy, PartialEq)]
66pub struct GroupBox {
67    /// The group's index in the groups given.
68    pub group: usize,
69    /// The box's left edge.
70    pub left: f64,
71    /// The box's top edge.
72    pub top: f64,
73    /// The box's width.
74    pub width: f64,
75    /// The box's height.
76    pub height: f64,
77    /// How deeply it is nested (0 for a top-level group).
78    pub depth: usize,
79}
80
81/// A node placed: its box's centre.
82#[derive(Debug, Clone, Copy, PartialEq)]
83pub struct Placed {
84    /// The centre's x.
85    pub x: f64,
86    /// The centre's y.
87    pub y: f64,
88    /// Its layer (0 at the top).
89    pub layer: usize,
90}
91
92/// An edge's route: from the bottom of `from`'s box, straight down through each layer it
93/// crosses (beside that layer's boxes, from the top of their band to its bottom), to the top
94/// of `to`'s box. Between layers it bends; within a layer it never does, so it can't cut a
95/// box.
96#[derive(Debug, Clone, PartialEq)]
97pub struct Route {
98    /// The edge's index in the edges given.
99    pub edge: usize,
100    /// The upstream node's index.
101    pub from: usize,
102    /// The downstream node's index.
103    pub to: usize,
104    /// The points, first to last.
105    pub points: Vec<(f64, f64)>,
106}
107
108/// A graph laid out.
109#[derive(Debug, Clone, PartialEq)]
110pub struct Layout {
111    /// The nodes, in the order given.
112    pub nodes: Vec<Placed>,
113    /// The edges, in the order given (an edge that doesn't go down, which a DAG never has, is
114    /// left out).
115    pub routes: Vec<Route>,
116    /// The groups' boxes, outer before inner (a group without nodes has none).
117    pub boxes: Vec<GroupBox>,
118    /// The resources' box on the left, if any are put aside ([`layout_sided`]).
119    pub side: Option<SideBox>,
120    /// The drawing's width.
121    pub width: f64,
122    /// The drawing's height.
123    pub height: f64,
124}
125
126/// The box of the nodes put aside: the resources' section, left of the tasks.
127#[derive(Debug, Clone, Copy, PartialEq)]
128pub struct SideBox {
129    /// Its left edge.
130    pub left: f64,
131    /// Its top edge (its label's band above its contents).
132    pub top: f64,
133    /// Its width.
134    pub width: f64,
135    /// Its height.
136    pub height: f64,
137}
138
139/// The space between two tracks of the channel beside the side box.
140const TRACK: f64 = 6.0;
141
142/// A node of the layered graph: a task, or a point of a long edge.
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144enum Item {
145    Node(usize),
146    Dummy,
147}
148
149impl Item {
150    const fn width(self) -> f64 {
151        match self {
152            Self::Node(_) => NODE_WIDTH,
153            Self::Dummy => 0.0,
154        }
155    }
156}
157
158/// The layered graph: items per layer and edges between consecutive layers (by item index).
159struct Layered {
160    items: Vec<Item>,
161    /// Each item's groups, outermost first (empty outside any group).
162    paths: Vec<Vec<usize>>,
163    layer_of: Vec<usize>,
164    /// `layers[l]`: the items of layer `l`, in order.
165    layers: Vec<Vec<usize>>,
166    /// Each item's neighbours in the layer above and below.
167    up: Vec<Vec<usize>>,
168    down: Vec<Vec<usize>>,
169    /// Each kept edge: its index, and its chain of items, `from` first.
170    chains: Vec<(usize, Vec<usize>)>,
171}
172
173/// Lays out `count` nodes joined by `edges` (`(from, to)` indices; `to` runs after `from`).
174#[must_use]
175pub fn layout(count: usize, edges: &[(usize, usize)]) -> Layout {
176    layout_grouped(count, edges, &[], &vec![None; count])
177}
178
179/// [`layout`], with `groups` and each node's innermost group (`node_group`, by index into
180/// `groups`) kept together and boxed.
181#[must_use]
182pub fn layout_grouped(
183    count: usize,
184    edges: &[(usize, usize)],
185    groups: &[GroupSpec],
186    node_group: &[Option<usize>],
187) -> Layout {
188    layout_sided(count, edges, groups, node_group, &[])
189}
190
191/// [`layout_grouped`], with the nodes of `sides` (each a resource's setup and cleanup) put in
192/// a box of their own on the left, a lane per resource (see the module's docs).
193#[must_use]
194pub fn layout_sided(
195    count: usize,
196    edges: &[(usize, usize)],
197    groups: &[GroupSpec],
198    node_group: &[Option<usize>],
199    sides: &[(usize, usize)],
200) -> Layout {
201    let layer = layers(count, edges);
202    let lanes = side_lanes(count, sides, &layer);
203    let aside = |n: usize| lanes.get(n).copied().flatten();
204    let paths: Vec<Vec<usize>> = (0..count)
205        .map(|n| {
206            if aside(n).is_some() {
207                Vec::new()
208            } else {
209                group_path(groups, node_group.get(n).copied().flatten())
210            }
211        })
212        .collect();
213    let deepest = paths.iter().map(Vec::len).max().unwrap_or(0);
214    // Room between layers for the deepest boxes' padding and labels.
215    let layer_gap = LAYER_GAP + to_f64(deepest.saturating_sub(1)) * (GROUP_PAD + GROUP_LABEL);
216    // The side box's label needs a band on top too.
217    let bands = deepest.max(usize::from(lanes.iter().any(Option::is_some)));
218    let top = MARGIN + to_f64(bands) * GROUP_LABEL;
219    let mut graph = layered(count, &task_edges(count, edges, &lanes), &layer, paths);
220    for row in &mut graph.layers {
221        row.retain(|&i| i >= count || aside(i).is_none());
222    }
223    let in_tasks = |i: usize| i >= count || aside(i).is_none();
224    for l in 0..graph.layers.len() {
225        let keys: Vec<f64> = (0..graph.layers[l].len()).map(to_f64).collect();
226        arrange(&mut graph, l, &keys);
227    }
228    reduce_crossings(&mut graph);
229    let mut x = place(&graph);
230    separate(&graph, groups, &mut x);
231    let y = |l: usize| top + NODE_HEIGHT / 2.0 + to_f64(l) * (NODE_HEIGHT + layer_gap);
232    let mut boxes = group_boxes(&graph, groups, &x, &y);
233    squeeze(&graph, &mut x, &mut boxes);
234    // Everything shifted so the leftmost box or node starts at the margin.
235    let left = boxes
236        .iter()
237        .map(|b| b.left)
238        .chain(
239            graph
240                .items
241                .iter()
242                .enumerate()
243                .filter(|(i, _)| in_tasks(*i))
244                .map(|(i, item)| x[i] - item.width() / 2.0),
245        )
246        .fold(f64::INFINITY, f64::min);
247    let side = SideFrame::of(&lanes);
248    if left.is_finite() {
249        let shift = side.tasks_left() - left;
250        for value in &mut x {
251            *value += shift;
252        }
253        for group_box in &mut boxes {
254            group_box.left += shift;
255        }
256    }
257    let nodes = (0..count)
258        .map(|n| Placed {
259            x: aside(n).map_or(x[n], |(lane, _)| SideFrame::lane_x(lane)),
260            y: y(layer[n]),
261            layer: layer[n],
262        })
263        .collect::<Vec<_>>();
264    let mut routes = chain_routes(&graph, &x, &y);
265    routes.extend(side_routes(edges, &nodes, &lanes, &side, layer_gap));
266    routes.sort_by_key(|route| route.edge);
267    let side_box = side.frame(&nodes, &lanes);
268    let right = graph
269        .items
270        .iter()
271        .enumerate()
272        .filter(|(i, _)| in_tasks(*i))
273        .map(|(i, item)| x[i] + item.width() / 2.0)
274        .chain(boxes.iter().map(|b| b.left + b.width))
275        .chain(side_box.map(|b| b.left + b.width))
276        .fold(0.0_f64, f64::max);
277    let bottom = boxes
278        .iter()
279        .map(|b| b.top + b.height)
280        .chain(side_box.map(|b| b.top + b.height))
281        .fold(0.0_f64, f64::max);
282    let depth = layer.iter().copied().max().map_or(0, |l| l + 1);
283    Layout {
284        nodes,
285        routes,
286        boxes,
287        side: side_box,
288        width: right + MARGIN,
289        height: if depth == 0 {
290            2.0 * MARGIN
291        } else {
292            (y(depth - 1) + NODE_HEIGHT / 2.0).max(bottom) + MARGIN
293        },
294    }
295}
296
297/// The edges as the layers see them: a side node's out of range (skipped), routed apart
298/// ([`side_routes`]); the others' indices kept.
299fn task_edges(
300    count: usize,
301    edges: &[(usize, usize)],
302    lanes: &[Option<(usize, usize)>],
303) -> Vec<(usize, usize)> {
304    let aside = |n: usize| lanes.get(n).copied().flatten().is_some();
305    edges
306        .iter()
307        .map(|&(f, t)| {
308            if aside(f) || aside(t) {
309                (count, count)
310            } else {
311                (f, t)
312            }
313        })
314        .collect()
315}
316
317/// The routes of the edges between tasks: down through each layer a long edge crosses.
318fn chain_routes(graph: &Layered, x: &[f64], y: &impl Fn(usize) -> f64) -> Vec<Route> {
319    graph
320        .chains
321        .iter()
322        .map(|(edge, chain)| {
323            let (from, to) = (chain[0], chain[chain.len() - 1]);
324            let mut points = vec![(x[from], y(graph.layer_of[from]) + NODE_HEIGHT / 2.0)];
325            for &i in &chain[1..chain.len() - 1] {
326                let middle = y(graph.layer_of[i]);
327                points.push((x[i], middle - NODE_HEIGHT / 2.0));
328                points.push((x[i], middle + NODE_HEIGHT / 2.0));
329            }
330            points.push((x[to], y(graph.layer_of[to]) - NODE_HEIGHT / 2.0));
331            Route {
332                edge: *edge,
333                from,
334                to,
335                points,
336            }
337        })
338        .collect()
339}
340
341/// Each node's place aside, `(lane, resource)`, if it is a side node: each resource of
342/// `sides` (setup, cleanup) in the first lane free from its setup's layer to its cleanup's.
343fn side_lanes(
344    count: usize,
345    sides: &[(usize, usize)],
346    layer: &[usize],
347) -> Vec<Option<(usize, usize)>> {
348    let mut lanes = vec![None; count];
349    // The last layer each lane is taken to.
350    let mut ends: Vec<usize> = Vec::new();
351    let mut order: Vec<usize> = (0..sides.len())
352        .filter(|&r| sides[r].0 < count && sides[r].1 < count && sides[r].0 != sides[r].1)
353        .collect();
354    order.sort_by_key(|&r| (layer[sides[r].0], r));
355    for (resource, r) in order.into_iter().enumerate() {
356        let (setup, cleanup) = sides[r];
357        if lanes[setup].is_some() || lanes[cleanup].is_some() {
358            continue; // a node in two resources, which validation refuses
359        }
360        let (first, last) = (
361            layer[setup].min(layer[cleanup]),
362            layer[setup].max(layer[cleanup]),
363        );
364        let lane = ends
365            .iter()
366            .position(|&end| end < first)
367            .unwrap_or(ends.len());
368        if lane == ends.len() {
369            ends.push(last);
370        } else {
371            ends[lane] = last;
372        }
373        lanes[setup] = Some((lane, resource));
374        lanes[cleanup] = Some((lane, resource));
375    }
376    lanes
377}
378
379/// The routes of the edges to or from a side node (`lanes`, see [`side_lanes`]): out of the
380/// upstream node's bottom, through the space below its layer to the resource's track in the
381/// channel, along it, and through the space above the downstream node's layer into its top.
382fn side_routes(
383    edges: &[(usize, usize)],
384    nodes: &[Placed],
385    lanes: &[Option<(usize, usize)>],
386    side: &SideFrame,
387    layer_gap: f64,
388) -> Vec<Route> {
389    let aside = |n: usize| lanes.get(n).copied().flatten();
390    let edge_y = NODE_HEIGHT / 2.0 + layer_gap / 2.0;
391    let mut routes = Vec::new();
392    for (edge, &(from, to)) in edges.iter().enumerate() {
393        let (Some(a), Some(b)) = (nodes.get(from), nodes.get(to)) else {
394            continue;
395        };
396        if a.layer >= b.layer {
397            continue;
398        }
399        let (start, end) = (aside(from), aside(to));
400        let track = match (start, end) {
401            (Some((_, resource)), _) => 2 * resource,
402            (None, Some((_, resource))) => 2 * resource + 1,
403            (None, None) => continue,
404        };
405        let (top, bottom) = (b.y - NODE_HEIGHT / 2.0, a.y + NODE_HEIGHT / 2.0);
406        // A resource's own setup to its cleanup: straight down its lane.
407        let own = matches!((start, end), (Some((_, r)), Some((_, s))) if r == s);
408        let points = if own {
409            vec![(a.x, bottom), (b.x, top)]
410        } else {
411            // Out of the bottom, along the gap below, the track, the gap above, into the top:
412            // the gaps hold no box, so no box is cut.
413            let (below, above, cx) = (a.y + edge_y, b.y - edge_y, side.track_x(track));
414            vec![
415                (a.x, bottom),
416                (a.x, below),
417                (cx, below),
418                (cx, above),
419                (b.x, above),
420                (b.x, top),
421            ]
422        };
423        routes.push(Route {
424            edge,
425            from,
426            to,
427            points,
428        });
429    }
430    routes
431}
432
433/// The side box's geometry: its lanes, then the channel's tracks (two per resource), then the
434/// tasks.
435struct SideFrame {
436    lanes: usize,
437    resources: usize,
438}
439
440impl SideFrame {
441    fn of(lanes: &[Option<(usize, usize)>]) -> Self {
442        let most = |pick: fn(&(usize, usize)) -> usize| {
443            lanes.iter().flatten().map(pick).max().map_or(0, |m| m + 1)
444        };
445        Self {
446            lanes: most(|p| p.0),
447            resources: most(|p| p.1),
448        }
449    }
450
451    /// The box's right edge.
452    fn right(&self) -> f64 {
453        MARGIN
454            + 2.0 * GROUP_PAD
455            + to_f64(self.lanes) * NODE_WIDTH
456            + to_f64(self.lanes.saturating_sub(1)) * GAP
457    }
458
459    fn lane_x(lane: usize) -> f64 {
460        MARGIN + GROUP_PAD + NODE_WIDTH / 2.0 + to_f64(lane) * (NODE_WIDTH + GAP)
461    }
462
463    fn track_x(&self, track: usize) -> f64 {
464        self.right() + TRACK * to_f64(track + 1)
465    }
466
467    /// Where the tasks start: the margin, or past the box and its channel.
468    fn tasks_left(&self) -> f64 {
469        if self.lanes == 0 {
470            MARGIN
471        } else {
472            self.track_x(2 * self.resources) + GAP
473        }
474    }
475
476    /// The box around the side nodes placed.
477    fn frame(&self, nodes: &[Placed], lanes: &[Option<(usize, usize)>]) -> Option<SideBox> {
478        let ys = || {
479            nodes
480                .iter()
481                .zip(lanes)
482                .filter(|(_, lane)| lane.is_some())
483                .map(|(n, _)| n.y)
484        };
485        let first = ys().fold(f64::INFINITY, f64::min);
486        let last = ys().fold(f64::NEG_INFINITY, f64::max);
487        if self.lanes == 0 || !first.is_finite() {
488            return None;
489        }
490        let top = first - NODE_HEIGHT / 2.0 - GROUP_PAD - GROUP_LABEL;
491        Some(SideBox {
492            left: MARGIN,
493            top,
494            width: self.right() - MARGIN,
495            height: last + NODE_HEIGHT / 2.0 + GROUP_PAD - top,
496        })
497    }
498}
499
500/// A group and its ancestors, outermost first.
501fn group_path(groups: &[GroupSpec], innermost: Option<usize>) -> Vec<usize> {
502    let mut path = Vec::new();
503    let mut at = innermost.filter(|&g| g < groups.len());
504    while let Some(g) = at {
505        if path.contains(&g) || path.len() > groups.len() {
506            break; // a cycle, which validation refuses: stop rather than loop
507        }
508        path.push(g);
509        at = groups[g].parent.filter(|&p| p < groups.len());
510    }
511    path.reverse();
512    path
513}
514
515/// Each node's layer: one below its lowest upstream node. Nodes on a cycle (never in a valid
516/// DAG) go below everything else.
517pub(crate) fn layers(count: usize, edges: &[(usize, usize)]) -> Vec<usize> {
518    let mut upstream = vec![0_usize; count];
519    let mut downstream = vec![Vec::new(); count];
520    for &(from, to) in edges
521        .iter()
522        .filter(|(f, t)| f != t && *f < count && *t < count)
523    {
524        upstream[to] += 1;
525        downstream[from].push(to);
526    }
527    let mut layer = vec![0_usize; count];
528    let mut done = vec![false; count];
529    let mut ready: Vec<usize> = (0..count).filter(|&n| upstream[n] == 0).collect();
530    while let Some(n) = ready.pop() {
531        done[n] = true;
532        for &d in &downstream[n] {
533            layer[d] = layer[d].max(layer[n] + 1);
534            upstream[d] -= 1;
535            if upstream[d] == 0 {
536                ready.push(d);
537            }
538        }
539    }
540    let below = layer.iter().copied().max().unwrap_or(0) + 1;
541    for n in (0..count).filter(|&n| !done[n]) {
542        layer[n] = below;
543    }
544    layer
545}
546
547fn layered(
548    count: usize,
549    edges: &[(usize, usize)],
550    layer: &[usize],
551    mut paths: Vec<Vec<usize>>,
552) -> Layered {
553    let mut items: Vec<Item> = (0..count).map(Item::Node).collect();
554    let mut layer_of = layer.to_vec();
555    let mut chains = Vec::new();
556    for (edge, &(from, to)) in edges.iter().enumerate() {
557        if from >= count || to >= count || layer[from] >= layer[to] {
558            continue;
559        }
560        // A long edge's points are in the groups both its ends are in.
561        let shared: Vec<usize> = paths[from]
562            .iter()
563            .zip(&paths[to])
564            .take_while(|(a, b)| a == b)
565            .map(|(a, _)| *a)
566            .collect();
567        let mut chain = vec![from];
568        for l in layer[from] + 1..layer[to] {
569            items.push(Item::Dummy);
570            layer_of.push(l);
571            paths.push(shared.clone());
572            chain.push(items.len() - 1);
573        }
574        chain.push(to);
575        chains.push((edge, chain));
576    }
577    let depth = layer_of.iter().copied().max().map_or(0, |l| l + 1);
578    let mut layers = vec![Vec::new(); depth];
579    for (i, &l) in layer_of.iter().enumerate() {
580        layers[l].push(i);
581    }
582    let mut up = vec![Vec::new(); items.len()];
583    let mut down = vec![Vec::new(); items.len()];
584    for (_, chain) in &chains {
585        for pair in chain.windows(2) {
586            down[pair[0]].push(pair[1]);
587            up[pair[1]].push(pair[0]);
588        }
589    }
590    Layered {
591        items,
592        paths,
593        layer_of,
594        layers,
595        up,
596        down,
597        chains,
598    }
599}
600
601/// Reorders the layers by barycenters, keeping the order with the fewest crossings seen.
602fn reduce_crossings(graph: &mut Layered) {
603    let mut best = graph.layers.clone();
604    let mut fewest = crossings(graph);
605    for _ in 0..SWEEPS {
606        for l in 1..graph.layers.len() {
607            reorder(graph, l, true);
608        }
609        for l in (0..graph.layers.len().saturating_sub(1)).rev() {
610            reorder(graph, l, false);
611        }
612        let now = crossings(graph);
613        if now < fewest {
614            fewest = now;
615            best.clone_from(&graph.layers);
616        }
617        if fewest == 0 {
618            break;
619        }
620    }
621    graph.layers = best;
622}
623
624/// Sorts layer `l` by its items' mean position among their neighbours above (`by_up`) or
625/// below; an item without such neighbours keeps its place.
626fn reorder(graph: &mut Layered, l: usize, by_up: bool) {
627    let position = positions(graph);
628    let keys: Vec<(f64, usize)> = graph.layers[l]
629        .iter()
630        .enumerate()
631        .map(|(place, &i)| {
632            let near = if by_up { &graph.up[i] } else { &graph.down[i] };
633            let key = if near.is_empty() {
634                to_f64(place)
635            } else {
636                near.iter().map(|&n| to_f64(position[n])).sum::<f64>() / to_f64(near.len())
637            };
638            (key, i)
639        })
640        .collect();
641    let mut wanted = vec![0.0; graph.items.len()];
642    for (key, i) in &keys {
643        wanted[*i] = *key;
644    }
645    let keys: Vec<f64> = graph.layers[l].iter().map(|&i| wanted[i]).collect();
646    arrange(graph, l, &keys);
647}
648
649/// Orders layer `l` by `keys` (one per item, in the layer's current order), group by group:
650/// a group's members stay together, placed by their mean key; nested groups likewise inside.
651/// Stable: ties keep their order.
652fn arrange(graph: &mut Layered, l: usize, keys: &[f64]) {
653    let members: Vec<(usize, f64)> = graph.layers[l]
654        .iter()
655        .copied()
656        .zip(keys.iter().copied())
657        .collect();
658    graph.layers[l] = arrange_level(&graph.paths, &members, 0);
659}
660
661/// One thing [`arrange_level`] places: its key, its first place in the layer, the group it
662/// stands for (`None` for a single item) and its items with their keys.
663type Unit = (f64, usize, Option<usize>, Vec<(usize, f64)>);
664
665fn arrange_level(paths: &[Vec<usize>], members: &[(usize, f64)], depth: usize) -> Vec<usize> {
666    // Units: an item not deeper in a group, or a whole group at this depth.
667    let mut units: Vec<Unit> = Vec::new();
668    for (place, &(item, key)) in members.iter().enumerate() {
669        match paths[item].get(depth) {
670            None => units.push((key, place, None, vec![(item, key)])),
671            Some(&group) => match units.iter_mut().find(|u| u.2 == Some(group)) {
672                Some(unit) => unit.3.push((item, key)),
673                None => units.push((key, place, Some(group), vec![(item, key)])),
674            },
675        }
676    }
677    for unit in &mut units {
678        if unit.2.is_some() {
679            unit.0 = unit.3.iter().map(|(_, k)| k).sum::<f64>() / to_f64(unit.3.len());
680        }
681    }
682    // Sibling groups keep one order in every layer (by index), so their boxes never swap
683    // sides: each group's key is raised to at least the one before it; tasks outside groups
684    // then fall between them by their own keys.
685    let mut grouped: Vec<usize> = (0..units.len()).filter(|&u| units[u].2.is_some()).collect();
686    grouped.sort_by_key(|&u| units[u].2);
687    let mut floor = f64::NEG_INFINITY;
688    for &u in &grouped {
689        floor = floor.max(units[u].0);
690        units[u].0 = floor;
691    }
692    units.sort_by(|a, b| {
693        a.0.total_cmp(&b.0).then_with(|| match (a.2, b.2) {
694            (Some(x), Some(y)) => x.cmp(&y),
695            _ => a.1.cmp(&b.1),
696        })
697    });
698    units
699        .into_iter()
700        .flat_map(|(_, _, group, inside)| match group {
701            None => inside.into_iter().map(|(i, _)| i).collect::<Vec<_>>(),
702            Some(_) => arrange_level(paths, &inside, depth + 1),
703        })
704        .collect()
705}
706
707/// Each item's place in its layer.
708fn positions(graph: &Layered) -> Vec<usize> {
709    let mut position = vec![0; graph.items.len()];
710    for layer in &graph.layers {
711        for (place, &i) in layer.iter().enumerate() {
712            position[i] = place;
713        }
714    }
715    position
716}
717
718/// The crossings between every two consecutive layers.
719fn crossings(graph: &Layered) -> usize {
720    let position = positions(graph);
721    let mut total = 0;
722    for layer in &graph.layers {
723        let edges: Vec<(usize, usize)> = layer
724            .iter()
725            .flat_map(|&i| graph.down[i].iter().map(move |&d| (i, d)))
726            .map(|(a, b)| (position[a], position[b]))
727            .collect();
728        for (k, a) in edges.iter().enumerate() {
729            total += edges[k + 1..]
730                .iter()
731                .filter(|b| (a.0 < b.0 && a.1 > b.1) || (a.0 > b.0 && a.1 < b.1))
732                .count();
733        }
734    }
735    total
736}
737
738/// Each item's x (its centre).
739fn place(graph: &Layered) -> Vec<f64> {
740    let mut x = vec![0.0; graph.items.len()];
741    for layer in &graph.layers {
742        let mut at = 0.0;
743        for &i in layer {
744            x[i] = at + graph.items[i].width() / 2.0;
745            at += graph.items[i].width() + gap(graph.items[i]);
746        }
747    }
748    for _ in 0..PLACEMENTS {
749        for l in 1..graph.layers.len() {
750            fit(graph, l, &graph.up, &mut x);
751        }
752        for l in (0..graph.layers.len().saturating_sub(1)).rev() {
753            fit(graph, l, &graph.down, &mut x);
754        }
755    }
756    x
757}
758
759/// Pushes every item clear of the boxes of the groups it isn't in, keeping each layer's
760/// order. Everything only moves right, so the rounds settle.
761///
762/// A group is rigid: the left edges of the layers whose first member is in that group itself
763/// share the rightmost one, lined up outermost group first, and a layer only moves right. A
764/// layer that holds a nested group stays with that group, so a parent does not chase a child
765/// that has indented. An item pushed out of a box takes with it the outermost group it
766/// belongs to that does not contain that box, by the same delta on every layer that group
767/// occupies, each item at most once, including what follows it. A layer a box spans without
768/// one of its members is not shoved.
769fn separate(graph: &Layered, groups: &[GroupSpec], x: &mut [f64]) {
770    let paths: Vec<Vec<usize>> = (0..groups.len())
771        .map(|g| group_path(groups, Some(g)))
772        .collect();
773    for _ in 0..SEPARATIONS * groups.len() {
774        align_groups(graph, groups, x);
775        let mut moved = false;
776        for (g, path) in paths.iter().enumerate() {
777            moved |= clear(graph, g, path, x);
778        }
779        if !moved {
780            break;
781        }
782    }
783}
784
785/// Lines groups up, outermost first (a group's path, so a parent's nested groups are finished
786/// before the next sibling). A second pass moves nothing.
787fn align_groups(graph: &Layered, groups: &[GroupSpec], x: &mut [f64]) {
788    let mut order: Vec<(Vec<usize>, usize)> = (0..groups.len())
789        .map(|g| (group_path(groups, Some(g)), g))
790        .collect();
791    order.sort_by(|a, b| a.0.cmp(&b.0));
792    for (_, g) in order {
793        align_group(graph, g, x);
794    }
795}
796
797/// Moves `g`'s lagging layers right so each shares the rightmost left edge of its first
798/// member. A layer that holds a group nested in `g` is left where that group put it, because
799/// sliding the layer would drag the nested group with it.
800fn align_group(graph: &Layered, g: usize, x: &mut [f64]) {
801    // (layer index, index of the first member, its left edge)
802    let mut bands: Vec<(usize, usize, f64)> = Vec::new();
803    for (layer_index, layer) in graph.layers.iter().enumerate() {
804        let Some(at) = layer.iter().position(|&i| graph.paths[i].contains(&g)) else {
805            continue;
806        };
807        let holds_nested = layer[at..].iter().any(|&other| {
808            let path = &graph.paths[other];
809            path.contains(&g) && path.last() != Some(&g)
810        });
811        if holds_nested {
812            continue;
813        }
814        let item = layer[at];
815        let left = x[item] - graph.items[item].width() / 2.0;
816        bands.push((layer_index, at, left));
817    }
818    let Some(target) = bands.iter().map(|&(_, _, left)| left).reduce(f64::max) else {
819        return;
820    };
821    for (layer_index, at, left) in bands {
822        let by = target - left;
823        if by <= 1e-9 {
824            continue;
825        }
826        shift_from(&graph.layers[layer_index], at, by, x);
827    }
828}
829
830/// Whether an item with groups `item` belongs left of a group with path `group`: when it is in
831/// a sibling group ordered before the group's branch, as the layers are ordered.
832fn belongs_left(item: &[usize], group: &[usize]) -> bool {
833    item.iter()
834        .zip(group)
835        .find(|(a, b)| a != b)
836        .is_some_and(|(a, b)| a < b)
837}
838
839/// One pass of [`separate`] for group `g` (its groups `path`); whether anything moved.
840fn clear(graph: &Layered, g: usize, path: &[usize], x: &mut [f64]) -> bool {
841    let inside = |i: usize| graph.paths[i].contains(&g);
842    let mut moved = false;
843    for layer in &graph.layers {
844        // The span as it is now: each move below changes it.
845        let Some((left, right, first, last)) = group_spans_of(graph, g, x) else {
846            return moved;
847        };
848        let Some(&head) = layer.first() else {
849            continue;
850        };
851        if !(first..=last).contains(&graph.layer_of[head]) {
852            continue;
853        }
854        let block = layer.iter().position(|&i| inside(i));
855        if let Some(start) = block
856            && start > 0
857        {
858            let before = layer[start - 1];
859            let reach = x[before] + graph.items[before].width() / 2.0 + gap(graph.items[before]);
860            if reach > left + 1e-9 {
861                shift_group(graph, g, reach - left, x);
862                moved = true;
863                continue;
864            }
865        }
866        // The left side: before the group's members, or (in a layer without them) up to the
867        // last item of a group ordered before this one, as the layers are ordered.
868        let split = block.unwrap_or_else(|| {
869            layer
870                .iter()
871                .rposition(|&i| belongs_left(&graph.paths[i], path))
872                .map_or(0, |k| k + 1)
873        });
874        if block.is_none() && split > 0 {
875            let reach = layer[..split]
876                .iter()
877                .map(|&i| x[i] + graph.items[i].width() / 2.0 + gap(graph.items[i]))
878                .fold(f64::NEG_INFINITY, f64::max);
879            if reach > left + 1e-9 {
880                // The group goes right of the items that belong left of it.
881                shift_group(graph, g, reach - left, x);
882                moved = true;
883                continue;
884            }
885        }
886        let outside = layer.iter().enumerate().skip(split).find(|&(_, &i)| {
887            !inside(i)
888                && x[i] + graph.items[i].width() / 2.0 > left + 1e-9
889                && x[i] - graph.items[i].width() / 2.0 < right - 1e-9
890        });
891        if let Some((k, &i)) = outside {
892            let wanted = right + gap(graph.items[i]).min(GAP);
893            let edge = x[i] - graph.items[i].width() / 2.0;
894            let by = wanted - edge;
895            if by > 1e-9 {
896                shift_out(graph, layer, k, path, by, x);
897                moved = true;
898            }
899        }
900    }
901    moved
902}
903
904/// Cuts every vertical strip that holds no item (a node or an edge's bend) and no box edge
905/// down to [`GAP`] (B149): [`separate`] only moves things right, and a push that cascades
906/// through nested groups can leave a wide empty strip behind. Order is kept and nothing
907/// crosses a strip that is cut, so every box still holds exactly what it held.
908fn squeeze(graph: &Layered, x: &mut [f64], boxes: &mut [GroupBox]) {
909    // Occupied intervals: the items; a box's edges as points.
910    let mut taken: Vec<(f64, f64)> = graph
911        .items
912        .iter()
913        .enumerate()
914        .map(|(i, item)| (x[i] - item.width() / 2.0, x[i] + item.width() / 2.0))
915        .chain(boxes.iter().flat_map(|b| {
916            let right = b.left + b.width;
917            [(b.left, b.left), (right, right)]
918        }))
919        .collect();
920    taken.sort_by(|a, b| a.0.total_cmp(&b.0));
921    // (where a cut starts, how much it removes)
922    let mut cuts: Vec<(f64, f64)> = Vec::new();
923    let mut reach = f64::NEG_INFINITY;
924    for (start, end) in taken {
925        if reach.is_finite() && start - reach > GAP + 1e-9 {
926            cuts.push((reach, start - reach - GAP));
927        }
928        reach = reach.max(end);
929    }
930    if cuts.is_empty() {
931        return;
932    }
933    let moved = |at: f64| {
934        at - cuts
935            .iter()
936            .filter(|&&(from, _)| from < at - 1e-9)
937            .map(|&(_, by)| by)
938            .sum::<f64>()
939    };
940    for value in x.iter_mut() {
941        *value = moved(*value);
942    }
943    for group_box in boxes.iter_mut() {
944        let right = moved(group_box.left + group_box.width);
945        group_box.left = moved(group_box.left);
946        group_box.width = right - group_box.left;
947    }
948}
949
950/// Moves the items of `layer` from position `k` on right by `by`.
951fn shift_from(layer: &[usize], k: usize, by: f64, x: &mut [f64]) {
952    for &i in &layer[k..] {
953        x[i] += by;
954    }
955}
956
957/// Moves group `g` right by `by`: in each layer, its first member and everything after it.
958/// A group that follows, and does not contain `g`, moves on every layer it occupies too.
959fn shift_group(graph: &Layered, g: usize, by: f64, x: &mut [f64]) {
960    let ancestors = graph
961        .paths
962        .iter()
963        .find_map(|path| {
964            path.iter()
965                .position(|&at| at == g)
966                .map(|at| path[..at].to_vec())
967        })
968        .unwrap_or_default();
969    shift_closure(graph, &[g], &[], &ancestors, by, x);
970}
971
972/// Moves the items of `layer` from `k` on right by `by`, and with them the outermost group
973/// each belongs to that does not contain the group of `cleared` (that group's path).
974fn shift_out(
975    graph: &Layered,
976    layer: &[usize],
977    k: usize,
978    cleared: &[usize],
979    by: f64,
980    x: &mut [f64],
981) {
982    let mut start = Vec::new();
983    let mut bare = Vec::new();
984    for &item in &layer[k..] {
985        match graph.paths[item].iter().find(|&&h| !cleared.contains(&h)) {
986            Some(&group) => {
987                if !start.contains(&group) {
988                    start.push(group);
989                }
990            }
991            None => bare.push(item),
992        }
993    }
994    shift_closure(graph, &start, &bare, cleared, by, x);
995}
996
997/// Adds `by` once to every item in the closure of `start` and `bare`. A group in `blocked`
998/// is not pulled in by what follows: moving it would move the box being cleared.
999fn shift_closure(
1000    graph: &Layered,
1001    start: &[usize],
1002    bare: &[usize],
1003    blocked: &[usize],
1004    by: f64,
1005    x: &mut [f64],
1006) {
1007    if by <= 1e-9 {
1008        return;
1009    }
1010    let group_count = graph
1011        .paths
1012        .iter()
1013        .flat_map(|path| path.iter().copied())
1014        .max()
1015        .map_or(0, |group| group + 1);
1016    let mut taken = vec![false; group_count];
1017    let mut queued = vec![false; group_count];
1018    let mut moved = vec![false; graph.items.len()];
1019    let mut queue = Vec::new();
1020    for &group in start {
1021        if group < group_count && !queued[group] {
1022            queued[group] = true;
1023            queue.push(group);
1024        }
1025    }
1026    for &item in bare {
1027        moved[item] = true;
1028    }
1029    while let Some(group) = queue.pop() {
1030        if taken[group] {
1031            continue;
1032        }
1033        taken[group] = true;
1034        for layer in &graph.layers {
1035            let Some(at) = layer
1036                .iter()
1037                .position(|&item| graph.paths[item].contains(&group))
1038            else {
1039                continue;
1040            };
1041            for &item in &layer[at..] {
1042                if moved[item] {
1043                    continue;
1044                }
1045                moved[item] = true;
1046                take_group(
1047                    graph,
1048                    layer,
1049                    item,
1050                    blocked,
1051                    &taken,
1052                    &moved,
1053                    &mut queued,
1054                    &mut queue,
1055                );
1056            }
1057        }
1058    }
1059    for (item, moves) in moved.iter().enumerate() {
1060        if *moves {
1061            x[item] += by;
1062        }
1063    }
1064}
1065
1066/// Queues the innermost group of `item` whose first member on `layer` is already moving,
1067/// skipping groups in `blocked`.
1068#[expect(
1069    clippy::too_many_arguments,
1070    reason = "the closure's flags, each borrowed differently"
1071)]
1072fn take_group(
1073    graph: &Layered,
1074    layer: &[usize],
1075    item: usize,
1076    blocked: &[usize],
1077    taken: &[bool],
1078    moved: &[bool],
1079    queued: &mut [bool],
1080    queue: &mut Vec<usize>,
1081) {
1082    for &group in graph.paths[item].iter().rev() {
1083        if group >= taken.len() || taken[group] || blocked.contains(&group) {
1084            break;
1085        }
1086        let starts = layer
1087            .iter()
1088            .find(|&&other| graph.paths[other].contains(&group))
1089            .is_some_and(|&other| moved[other]);
1090        if !starts {
1091            continue;
1092        }
1093        if !queued[group] {
1094            queued[group] = true;
1095            queue.push(group);
1096        }
1097        break;
1098    }
1099}
1100
1101/// [`group_spans`] for one group.
1102fn group_spans_of(graph: &Layered, group: usize, x: &[f64]) -> Option<(f64, f64, usize, usize)> {
1103    let mut span: Option<(f64, f64, usize, usize)> = None;
1104    for (item, path) in graph.paths.iter().enumerate() {
1105        let Some(depth) = path.iter().position(|&h| h == group) else {
1106            continue;
1107        };
1108        let half = graph.items[item].width() / 2.0;
1109        let pad = to_f64(path.len() - depth) * GROUP_PAD;
1110        let left = x[item] - half - pad;
1111        let right = x[item] + half + pad;
1112        let layer = graph.layer_of[item];
1113        span = Some(match span {
1114            None => (left, right, layer, layer),
1115            Some((lo, hi, first, last)) => (
1116                lo.min(left),
1117                hi.max(right),
1118                first.min(layer),
1119                last.max(layer),
1120            ),
1121        });
1122    }
1123    span
1124}
1125
1126/// Each group's box across x (with its padding and its nested groups' padding) and the
1127/// layers it spans, or `None` for a group without items.
1128fn group_spans(
1129    graph: &Layered,
1130    group_count: usize,
1131    x: &[f64],
1132) -> Vec<Option<(f64, f64, usize, usize)>> {
1133    (0..group_count)
1134        .map(|g| group_spans_of(graph, g, x))
1135        .collect()
1136}
1137
1138/// The groups' boxes, outer before inner.
1139fn group_boxes(
1140    graph: &Layered,
1141    groups: &[GroupSpec],
1142    x: &[f64],
1143    y: &impl Fn(usize) -> f64,
1144) -> Vec<GroupBox> {
1145    let spans = group_spans(graph, groups.len(), x);
1146    let mut boxes: Vec<GroupBox> = Vec::new();
1147    for (g, span) in spans.iter().enumerate() {
1148        let Some((left, right, first, last)) = *span else {
1149            continue;
1150        };
1151        let depth = group_path(groups, Some(g)).len() - 1;
1152        // The deepest nesting under this group, per layer edge, sets its vertical padding.
1153        let below = graph
1154            .paths
1155            .iter()
1156            .filter_map(|p| p.iter().position(|&h| h == g).map(|at| p.len() - at))
1157            .max()
1158            .unwrap_or(1);
1159        let top = y(first) - NODE_HEIGHT / 2.0 - to_f64(below) * GROUP_LABEL;
1160        let bottom = y(last) + NODE_HEIGHT / 2.0 + to_f64(below) * GROUP_PAD;
1161        boxes.push(GroupBox {
1162            group: g,
1163            left,
1164            top,
1165            width: right - left,
1166            height: bottom - top,
1167            depth,
1168        });
1169    }
1170    boxes.sort_by_key(|b| (b.depth, b.group));
1171    boxes
1172}
1173
1174const fn gap(item: Item) -> f64 {
1175    match item {
1176        Item::Node(_) => GAP,
1177        Item::Dummy => DUMMY_GAP,
1178    }
1179}
1180
1181/// Moves layer `l`'s items as near their neighbours' (`near`) mean x as their order and the
1182/// gaps allow: the least-squares fit of `x[k] = offset[k] + y[k]` with `y` non-decreasing,
1183/// by pool-adjacent-violators. An item without neighbours wants to stay where it is.
1184fn fit(graph: &Layered, l: usize, near: &[Vec<usize>], x: &mut [f64]) {
1185    let layer = &graph.layers[l];
1186    let mut offset = Vec::with_capacity(layer.len());
1187    let mut at = 0.0;
1188    for (k, &i) in layer.iter().enumerate() {
1189        if k > 0 {
1190            let before = graph.items[layer[k - 1]];
1191            at += before.width() / 2.0 + gap(before) + graph.items[i].width() / 2.0;
1192        }
1193        offset.push(at);
1194    }
1195    // Blocks of (sum of wanted y, count), merged while out of order.
1196    let mut blocks: Vec<(f64, f64, usize)> = Vec::new();
1197    for (k, &i) in layer.iter().enumerate() {
1198        let wanted = if near[i].is_empty() {
1199            x[i]
1200        } else {
1201            near[i].iter().map(|&n| x[n]).sum::<f64>() / to_f64(near[i].len())
1202        };
1203        blocks.push((wanted - offset[k], 1.0, 1));
1204        while blocks.len() > 1 {
1205            let (sum, n, _) = blocks[blocks.len() - 1];
1206            let (before_sum, before_n, _) = blocks[blocks.len() - 2];
1207            if before_sum / before_n <= sum / n {
1208                break;
1209            }
1210            let last = blocks.pop().expect("two blocks");
1211            let previous = blocks.last_mut().expect("two blocks");
1212            previous.0 += last.0;
1213            previous.1 += last.1;
1214            previous.2 += last.2;
1215        }
1216    }
1217    let mut k = 0;
1218    for (sum, n, items) in blocks {
1219        for _ in 0..items {
1220            x[layer[k]] = offset[k] + sum / n;
1221            k += 1;
1222        }
1223    }
1224}
1225
1226fn to_f64(n: usize) -> f64 {
1227    f64::from(u32::try_from(n).unwrap_or(u32::MAX))
1228}