mermaid-text 0.45.0

Render Mermaid diagrams as Unicode box-drawing text — no browser, no image protocols, pure Rust
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
//! Post-routing nudging pass.
//!
//! Reads the routes produced by `router::route_all` and makes two targeted
//! post-processing adjustments:
//!
//! 1. Merge adjacent horizontal back-edge corridors (Bug 5).
//! 2. Evict routed path runs from the 1-cell halo around nodes when that node
//!    is not an endpoint of the edge (Bug 4).
//!
//! The pass operates on finished paths rather than A* costs. That keeps the
//! router's attach semantics intact and limits change to paths we can inspect
//! and re-stamp atomically.

use crate::layout::Grid;

/// Maximum row/col delta between two segments for them to be considered
/// "adjacent" and candidate for merging.
const MAX_NUDGE_DISTANCE: usize = 3;

/// Don't nudge very short segments. Stub segments are often endpoint-adjacent
/// and moving them detaches the edge from its source/target neighborhood.
const MIN_SEGMENT_LEN_FOR_NUDGE: usize = 4;

/// When evicting a halo run, try a few cells farther away before giving up.
const MAX_HALO_EVICTION_SHIFT: usize = 4;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Axis {
    Horizontal,
    Vertical,
}

/// A maximal collinear run of cells in one axis.
#[derive(Debug, Clone)]
struct Segment {
    edge_idx: usize,
    axis: Axis,
    /// row for Horizontal, col for Vertical.
    fixed_coord: usize,
    /// Inclusive start/end along the variable axis (col for H, row for V).
    range: (usize, usize),
    /// Index span in `paths[edge_idx]` that this segment covers
    /// (inclusive on both ends).
    path_idx_range: (usize, usize),
}

#[derive(Debug, Clone)]
struct Shift {
    edge_idx: usize,
    new_path: Vec<(usize, usize)>,
}

#[derive(Debug, Clone, Copy)]
struct NodeRect {
    col: usize,
    row: usize,
    width: usize,
    height: usize,
}

#[derive(Debug, Clone, Copy)]
struct HaloRun {
    axis: Axis,
    start_idx: usize,
    end_idx: usize,
    fixed_coord: usize,
    shift_dir: isize,
}

/// Run the nudging pass. Mutates `paths` in place and re-stamps the grid.
///
/// Two scans run in sequence:
/// 1. **Parallel-corridor merge (Bug 5)** — pairs of horizontal back-edge
///    segments at adjacent rows with overlapping column ranges merge onto
///    the outer row. Back-edges only; forward edges have different attach-
///    point semantics that are out of scope.
/// 2. **Foreign-halo eviction (Bug 4)** — runs of cells in a non-endpoint
///    node's 1-cell halo shift outward, with bridges in the adjacent
///    segments. Skipped for edges with a label (the label needs adjacent
///    free space; shifting the route would push labels off the route).
///
/// Arguments mirror per-edge state already collected in `render_inner`:
/// - `edge_is_back[i]` — true for back-edges.
/// - `edge_has_label[i]` — true when the edge carries a text label.
/// - `node_boxes` — every node bounding box, as `(col, row, w, h)`.
/// - `tip_for(i)` — arrow-tip glyph for edge `i`, used when re-stamping
///   the new path after a shift.
pub(crate) fn run(
    grid: &mut Grid,
    paths: &mut [Option<Vec<(usize, usize)>>],
    edge_is_back: &[bool],
    edge_has_label: &[bool],
    node_boxes: &[(usize, usize, usize, usize)],
    tip_for: impl Fn(usize) -> char,
) {
    let segments = collect_segments(paths);
    let shifts = plan_parallel_merges(&segments, paths, grid, edge_is_back);
    apply_shifts(grid, paths, shifts, &tip_for);
    evict_foreign_halo_runs(grid, paths, edge_has_label, node_boxes, &tip_for);
}

/// Walk all routed paths and emit their maximal segments.
fn collect_segments(paths: &[Option<Vec<(usize, usize)>>]) -> Vec<Segment> {
    let mut out = Vec::new();
    for (edge_idx, path_opt) in paths.iter().enumerate() {
        let Some(path) = path_opt else { continue };
        if path.len() < 2 {
            continue;
        }
        let mut start_idx = 0usize;
        let mut current_axis = step_axis(path, 0);
        for i in 1..path.len() - 1 {
            let next_axis = step_axis(path, i);
            if next_axis != current_axis {
                emit_segment(path, edge_idx, current_axis, start_idx, i, &mut out);
                start_idx = i;
                current_axis = next_axis;
            }
        }
        emit_segment(
            path,
            edge_idx,
            current_axis,
            start_idx,
            path.len() - 1,
            &mut out,
        );
    }
    out
}

/// Determine the axis of the step `path[i] → path[i+1]`. Diagonal
/// steps (which shouldn't occur for orthogonal routes) fall through
/// to Horizontal as a safe default.
fn step_axis(path: &[(usize, usize)], i: usize) -> Axis {
    let (c, _r) = path[i];
    let (nc, _nr) = path[i + 1];
    if c == nc {
        Axis::Vertical
    } else {
        Axis::Horizontal
    }
}

fn emit_segment(
    path: &[(usize, usize)],
    edge_idx: usize,
    axis: Axis,
    start_idx: usize,
    end_idx: usize,
    out: &mut Vec<Segment>,
) {
    if end_idx <= start_idx {
        return;
    }
    let (start_c, start_r) = path[start_idx];
    let (end_c, end_r) = path[end_idx];
    let (fixed_coord, range) = match axis {
        Axis::Horizontal => (start_r, (start_c.min(end_c), start_c.max(end_c))),
        Axis::Vertical => (start_c, (start_r.min(end_r), start_r.max(end_r))),
    };
    out.push(Segment {
        edge_idx,
        axis,
        fixed_coord,
        range,
        path_idx_range: (start_idx, end_idx),
    });
}

/// Find pairs of back-edges with horizontal segments at adjacent rows and
/// overlapping col ranges; plan a shift that merges them.
fn plan_parallel_merges(
    segments: &[Segment],
    paths: &[Option<Vec<(usize, usize)>>],
    grid: &Grid,
    edge_is_back: &[bool],
) -> Vec<Shift> {
    let mut shifts = Vec::new();
    let horizontals: Vec<&Segment> = segments
        .iter()
        .filter(|s| edge_is_back.get(s.edge_idx).copied().unwrap_or(false))
        .filter(|s| s.axis == Axis::Horizontal)
        .filter(|s| s.range.1 - s.range.0 + 1 >= MIN_SEGMENT_LEN_FOR_NUDGE)
        .collect();

    let mut already_shifted: std::collections::HashSet<usize> = std::collections::HashSet::new();

    for i in 0..horizontals.len() {
        for j in (i + 1)..horizontals.len() {
            let (a, b) = (horizontals[i], horizontals[j]);
            if a.edge_idx == b.edge_idx {
                continue;
            }
            if already_shifted.contains(&a.edge_idx) || already_shifted.contains(&b.edge_idx) {
                continue;
            }
            let row_delta = a.fixed_coord.abs_diff(b.fixed_coord);
            if row_delta == 0 || row_delta > MAX_NUDGE_DISTANCE {
                continue;
            }
            let (a_lo, a_hi) = a.range;
            let (b_lo, b_hi) = b.range;
            if a_hi < b_lo || b_hi < a_lo {
                continue;
            }
            let target_row = a.fixed_coord.max(b.fixed_coord);
            let source_seg = if a.fixed_coord < b.fixed_coord { a } else { b };
            let Some(old_path) = paths[source_seg.edge_idx].as_ref() else {
                continue;
            };
            let new_path = build_shifted_segment_path(old_path, source_seg, target_row);
            if !path_is_feasible(grid, &new_path) {
                continue;
            }
            shifts.push(Shift {
                edge_idx: source_seg.edge_idx,
                new_path,
            });
            already_shifted.insert(source_seg.edge_idx);
        }
    }
    shifts
}

/// Evict at most ONE halo run per render call.
///
/// The pass intentionally applies a single shift even when multiple foreign
/// halo runs exist on different edges. Rationale:
/// - Each shift mutates the grid (re-stamps direction bits and obstacle
///   classification); subsequent shifts must be planned against the post-
///   shift state, which would require re-running `plan_next_halo_shift`
///   in a loop with a fixed-point check. The crossings comparison adds
///   non-trivial cost (each candidate clones the grid in
///   `crossings_after_shift`), so a multi-shift loop would be quadratic
///   in the worst case.
/// - Empirically (gallery + corpus) one shift per call clears the visible
///   diamond-join Bug 4 fixture and leaves all other diagrams unchanged.
///   Diagrams with multiple foreign halo runs are rare enough that the
///   conservative single-shift behaviour is acceptable; if a future
///   fixture needs more, lift this into a bounded loop with an iteration
///   cap and re-baseline the snapshot suite.
fn evict_foreign_halo_runs(
    grid: &mut Grid,
    paths: &mut [Option<Vec<(usize, usize)>>],
    edge_has_label: &[bool],
    node_boxes: &[(usize, usize, usize, usize)],
    tip_for: &impl Fn(usize) -> char,
) {
    let rects: Vec<NodeRect> = node_boxes
        .iter()
        .map(|&(col, row, width, height)| NodeRect {
            col,
            row,
            width,
            height,
        })
        .collect();

    if let Some(shift) = plan_next_halo_shift(paths, grid, edge_has_label, &rects) {
        apply_shifts(grid, paths, vec![shift], tip_for);
    }
}

fn plan_next_halo_shift(
    paths: &[Option<Vec<(usize, usize)>>],
    grid: &Grid,
    edge_has_label: &[bool],
    rects: &[NodeRect],
) -> Option<Shift> {
    let baseline_crossings = count_crossings_in_grid(grid);
    for (edge_idx, path_opt) in paths.iter().enumerate() {
        if edge_has_label.get(edge_idx).copied().unwrap_or(false) {
            continue;
        }
        let Some(path) = path_opt.as_ref() else {
            continue;
        };
        if path.len() < 4 {
            continue;
        }
        let endpoint_nodes = endpoint_node_indices(path, rects);
        let baseline = count_foreign_halo_cells(path, rects, &endpoint_nodes);
        if baseline == 0 {
            continue;
        }

        for (node_idx, rect) in rects.iter().enumerate() {
            if endpoint_nodes.contains(&node_idx) {
                continue;
            }
            for run in collect_halo_runs(path, *rect) {
                if run.start_idx <= 1 || run.end_idx + 1 >= path.len() - 1 {
                    continue;
                }
                if !halo_run_has_corner_or_junction(grid, path, &run) {
                    continue;
                }
                for distance in 1..=MAX_HALO_EVICTION_SHIFT {
                    let Some(target_fixed) =
                        apply_signed_offset(run.fixed_coord, run.shift_dir * distance as isize)
                    else {
                        break;
                    };
                    let new_path = build_evicted_run_path(path, &run, target_fixed);
                    if !path_is_feasible(grid, &new_path) {
                        continue;
                    }
                    let candidate = count_foreign_halo_cells(&new_path, rects, &endpoint_nodes);
                    let candidate_crossings =
                        crossings_after_shift(grid, path, &new_path).unwrap_or(usize::MAX);
                    let crosses_ok = candidate_crossings <= baseline_crossings
                        || (baseline_crossings == 0 && candidate_crossings == 1);
                    if candidate < baseline && crosses_ok {
                        return Some(Shift { edge_idx, new_path });
                    }
                }
            }
        }
    }
    None
}

fn halo_run_has_corner_or_junction(grid: &Grid, path: &[(usize, usize)], run: &HaloRun) -> bool {
    path.iter()
        .take(run.end_idx + 1)
        .skip(run.start_idx)
        .any(|&(col, row)| matches!(grid.get(col, row), '' | '' | '' | '' | ''))
}

/// Speculatively apply `old_path → new_path` on a clone of the grid and
/// return the resulting crossing count.
///
/// Cost note: this clones the entire grid (O(width × height)) per call, and
/// `plan_next_halo_shift` may invoke it once per (edge × node × distance)
/// candidate. For typical gallery diagrams (≤ 50 cells × 30 cells × 12 edges
/// × 8 nodes × 4 distances) the wall-clock cost is well under the launch
/// budget's < 8 ms frame draw target, but for pathologically dense diagrams
/// this is the first thing to optimise (e.g. by tracking crossings
/// incrementally during `erase_path` / `draw_path`).
fn crossings_after_shift(
    grid: &Grid,
    old_path: &[(usize, usize)],
    new_path: &[(usize, usize)],
) -> Option<usize> {
    let mut scratch = grid.clone();
    scratch.erase_path(old_path);
    let &(tip_col, tip_row) = old_path.last()?;
    let tip = grid.get(tip_col, tip_row);
    scratch.draw_path(new_path.to_vec(), tip)?;
    Some(count_crossings_in_grid(&scratch))
}

fn count_crossings_in_grid(grid: &Grid) -> usize {
    let mut count = 0;
    for row in 0..grid.rows() {
        for col in 0..grid.cols() {
            let ch = grid.get(col, row);
            if ch == '' || ch == '' {
                count += 1;
            }
        }
    }
    count
}

fn endpoint_node_indices(path: &[(usize, usize)], rects: &[NodeRect]) -> Vec<usize> {
    let mut out = Vec::new();
    let endpoints = [path[0], *path.last().unwrap_or(&path[0])];
    for (idx, rect) in rects.iter().enumerate() {
        if endpoints
            .iter()
            .any(|&(c, r)| point_in_expanded_rect(*rect, c, r))
        {
            out.push(idx);
        }
    }
    out
}

fn count_foreign_halo_cells(
    path: &[(usize, usize)],
    rects: &[NodeRect],
    endpoint_nodes: &[usize],
) -> usize {
    path.iter()
        .enumerate()
        .filter(|(idx, _)| *idx > 0 && *idx + 1 < path.len())
        .filter(|&(_, &(c, r))| {
            rects.iter().enumerate().any(|(node_idx, rect)| {
                !endpoint_nodes.contains(&node_idx) && point_in_halo(*rect, c, r)
            })
        })
        .count()
}

fn collect_halo_runs(path: &[(usize, usize)], rect: NodeRect) -> Vec<HaloRun> {
    let mut runs = Vec::new();
    let mut i = 1usize;
    while i + 1 < path.len() {
        let (c, r) = path[i];
        if !point_in_halo(rect, c, r) {
            i += 1;
            continue;
        }
        let start = i;
        while i + 1 < path.len() {
            let (cc, rr) = path[i + 1];
            if !point_in_halo(rect, cc, rr) {
                break;
            }
            i += 1;
        }
        let end = i;
        if let Some(axis) = axis_for_run(path, start, end)
            && let Some(shift_dir) = shift_direction_for_run(rect, axis, path, start, end)
        {
            let fixed_coord = match axis {
                Axis::Horizontal => path[start].1,
                Axis::Vertical => path[start].0,
            };
            runs.push(HaloRun {
                axis,
                start_idx: start,
                end_idx: end,
                fixed_coord,
                shift_dir,
            });
        }
        i += 1;
    }
    runs
}

/// Return the axis of a halo run spanning `path[start_idx..=end_idx]`.
///
/// Multi-cell runs are classified by comparing the start and end cells
/// directly. Single-cell runs (`start_idx == end_idx`) have no run-internal
/// step to read, so we infer from the `path[start_idx-1] → path[start_idx]`
/// step. Callers always pass `start_idx ≥ 1`, so that lookup is in bounds.
fn axis_for_run(path: &[(usize, usize)], start_idx: usize, end_idx: usize) -> Option<Axis> {
    if start_idx < end_idx {
        if path[start_idx].0 == path[end_idx].0 {
            return Some(Axis::Vertical);
        }
        if path[start_idx].1 == path[end_idx].1 {
            return Some(Axis::Horizontal);
        }
        return None;
    }

    // Single-cell run: take the inbound step's axis. Optionally cross-check
    // against the outbound step's axis if the run isn't at the path tail —
    // a mismatch means the run cell IS a corner, which the run-shift logic
    // can't model, so we bail with `None`.
    let before = step_axis(path, start_idx - 1);
    if start_idx + 1 < path.len() {
        let after = step_axis(path, start_idx);
        if after != before {
            return None;
        }
    }
    Some(before)
}

fn shift_direction_for_run(
    rect: NodeRect,
    axis: Axis,
    path: &[(usize, usize)],
    start_idx: usize,
    end_idx: usize,
) -> Option<isize> {
    match axis {
        Axis::Vertical => {
            let col = path[start_idx].0;
            if col < rect.col {
                Some(-1)
            } else if col >= rect.col + rect.width {
                Some(1)
            } else if end_idx > start_idx {
                None
            } else {
                // One-cell corner overlap inside the top/bottom halo band.
                let prev = path[start_idx - 1];
                if prev.0 < col {
                    Some(1)
                } else if prev.0 > col {
                    Some(-1)
                } else {
                    None
                }
            }
        }
        Axis::Horizontal => {
            let row = path[start_idx].1;
            if row < rect.row {
                Some(-1)
            } else if row >= rect.row + rect.height {
                Some(1)
            } else if end_idx > start_idx {
                None
            } else {
                let prev = path[start_idx - 1];
                if prev.1 < row {
                    Some(1)
                } else if prev.1 > row {
                    Some(-1)
                } else {
                    None
                }
            }
        }
    }
}

/// Build a new path where the horizontal segment at `seg.path_idx_range` is
/// moved from its current row to `target_row`.
fn build_shifted_segment_path(
    old_path: &[(usize, usize)],
    seg: &Segment,
    target_row: usize,
) -> Vec<(usize, usize)> {
    let (start_idx, end_idx) = seg.path_idx_range;
    let mut new_path = Vec::with_capacity(old_path.len() + 4);

    new_path.extend_from_slice(&old_path[..start_idx]);
    let start_c = old_path[start_idx].0;
    if let Some(&(prev_c, prev_r)) = new_path.last() {
        if prev_c == start_c {
            extend_vertical(&mut new_path, prev_c, prev_r, target_row);
        } else {
            extend_vertical(&mut new_path, start_c, prev_r, target_row);
        }
    } else {
        push_cell(&mut new_path, (start_c, target_row));
    }

    for &(c, _) in old_path.iter().take(end_idx + 1).skip(start_idx) {
        push_cell(&mut new_path, (c, target_row));
    }

    if end_idx + 1 < old_path.len() {
        let end_c = old_path[end_idx].0;
        let (next_c, next_r) = old_path[end_idx + 1];
        extend_vertical(&mut new_path, end_c, target_row, next_r);
        extend_horizontal(&mut new_path, next_r, end_c, next_c);
        for &cell in old_path.iter().skip(end_idx + 2) {
            push_cell(&mut new_path, cell);
        }
    }

    new_path
}

fn build_evicted_run_path(
    old_path: &[(usize, usize)],
    run: &HaloRun,
    target_fixed: usize,
) -> Vec<(usize, usize)> {
    let prev_idx = run.start_idx - 1;
    let next_idx = run.end_idx + 1;
    let prev = old_path[prev_idx];
    let next = old_path[next_idx];
    let mut new_path = Vec::with_capacity(old_path.len() + 8);

    new_path.extend_from_slice(&old_path[..=prev_idx]);

    match run.axis {
        Axis::Vertical => {
            extend_horizontal(&mut new_path, prev.1, prev.0, target_fixed);
            let start_row = old_path[run.start_idx].1;
            extend_vertical(&mut new_path, target_fixed, prev.1, start_row);
            for &(_, row) in old_path.iter().take(run.end_idx + 1).skip(run.start_idx) {
                push_cell(&mut new_path, (target_fixed, row));
            }
            let end_row = old_path[run.end_idx].1;
            extend_vertical(&mut new_path, target_fixed, end_row, next.1);
            extend_horizontal(&mut new_path, next.1, target_fixed, next.0);
        }
        Axis::Horizontal => {
            extend_vertical(&mut new_path, prev.0, prev.1, target_fixed);
            let start_col = old_path[run.start_idx].0;
            extend_horizontal(&mut new_path, target_fixed, prev.0, start_col);
            for &(col, _) in old_path.iter().take(run.end_idx + 1).skip(run.start_idx) {
                push_cell(&mut new_path, (col, target_fixed));
            }
            let end_col = old_path[run.end_idx].0;
            extend_horizontal(&mut new_path, target_fixed, end_col, next.0);
            extend_vertical(&mut new_path, next.0, target_fixed, next.1);
        }
    }

    for &cell in old_path.iter().skip(next_idx + 1) {
        push_cell(&mut new_path, cell);
    }

    new_path
}

fn extend_horizontal(path: &mut Vec<(usize, usize)>, row: usize, from_col: usize, to_col: usize) {
    if from_col == to_col {
        push_cell(path, (to_col, row));
        return;
    }
    if from_col < to_col {
        for col in (from_col + 1)..=to_col {
            push_cell(path, (col, row));
        }
    } else {
        for col in (to_col..from_col).rev() {
            push_cell(path, (col, row));
        }
    }
}

fn extend_vertical(path: &mut Vec<(usize, usize)>, col: usize, from_row: usize, to_row: usize) {
    if from_row == to_row {
        push_cell(path, (col, to_row));
        return;
    }
    if from_row < to_row {
        for row in (from_row + 1)..=to_row {
            push_cell(path, (col, row));
        }
    } else {
        for row in (to_row..from_row).rev() {
            push_cell(path, (col, row));
        }
    }
}

fn push_cell(path: &mut Vec<(usize, usize)>, cell: (usize, usize)) {
    if path.last().copied() != Some(cell) {
        path.push(cell);
    }
}

/// Check that `path` doesn't pass through any invisible protected cells or
/// hard node boxes, other than the final tip cell.
fn path_is_feasible(grid: &Grid, path: &[(usize, usize)]) -> bool {
    if path.is_empty() {
        return false;
    }
    let last = path.len() - 1;
    for (i, &(c, r)) in path.iter().enumerate() {
        if i == last {
            continue;
        }
        if !grid.can_draw_path_cell(c, r) {
            return false;
        }
    }
    true
}

fn point_in_box(rect: NodeRect, col: usize, row: usize) -> bool {
    col >= rect.col
        && col < rect.col + rect.width
        && row >= rect.row
        && row < rect.row + rect.height
}

fn point_in_expanded_rect(rect: NodeRect, col: usize, row: usize) -> bool {
    let min_col = rect.col.saturating_sub(1);
    let min_row = rect.row.saturating_sub(1);
    let max_col = rect.col + rect.width;
    let max_row = rect.row + rect.height;
    col >= min_col && col <= max_col && row >= min_row && row <= max_row
}

fn point_in_halo(rect: NodeRect, col: usize, row: usize) -> bool {
    point_in_expanded_rect(rect, col, row) && !point_in_box(rect, col, row)
}

fn apply_signed_offset(value: usize, delta: isize) -> Option<usize> {
    if delta >= 0 {
        value.checked_add(delta as usize)
    } else {
        value.checked_sub(delta.unsigned_abs())
    }
}

/// Apply each shift atomically: erase old, draw new, update paths.
fn apply_shifts(
    grid: &mut Grid,
    paths: &mut [Option<Vec<(usize, usize)>>],
    shifts: Vec<Shift>,
    tip_for: &impl Fn(usize) -> char,
) {
    for shift in shifts {
        let Some(old_path) = paths[shift.edge_idx].clone() else {
            continue;
        };
        grid.erase_path(&old_path);
        let tip = tip_for(shift.edge_idx);
        if let Some(drawn) = grid.draw_path(shift.new_path.clone(), tip) {
            paths[shift.edge_idx] = Some(drawn);
        }
    }
}

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

    fn make_path(cells: &[(usize, usize)]) -> Vec<(usize, usize)> {
        cells.to_vec()
    }

    #[test]
    fn collect_segments_splits_at_corners() {
        let path = make_path(&[(0, 0), (0, 1), (0, 2), (1, 2), (2, 2), (2, 3)]);
        let paths = vec![Some(path)];
        let segs = collect_segments(&paths);
        assert_eq!(segs.len(), 3);
        assert_eq!(segs[0].axis, Axis::Vertical);
        assert_eq!(segs[1].axis, Axis::Horizontal);
        assert_eq!(segs[2].axis, Axis::Vertical);
    }

    #[test]
    fn collect_segments_keeps_forward_edges() {
        let path = make_path(&[(0, 0), (0, 1), (0, 2), (1, 2)]);
        let paths = vec![Some(path)];
        let segs = collect_segments(&paths);
        assert_eq!(segs.len(), 2);
    }

    #[test]
    fn extend_vertical_descends() {
        let mut p = vec![(5, 2)];
        extend_vertical(&mut p, 5, 2, 5);
        assert_eq!(p, vec![(5, 2), (5, 3), (5, 4), (5, 5)]);
    }

    #[test]
    fn extend_horizontal_ascends() {
        let mut p = vec![(5, 2)];
        extend_horizontal(&mut p, 2, 5, 2);
        assert_eq!(p, vec![(5, 2), (4, 2), (3, 2), (2, 2)]);
    }

    #[test]
    fn build_shifted_segment_path_moves_corridor_down_one_row() {
        let old_path = vec![
            (0, 0),
            (0, 1),
            (0, 2),
            (0, 3),
            (1, 3),
            (2, 3),
            (3, 3),
            (4, 3),
            (4, 2),
            (4, 1),
            (4, 0),
        ];
        let seg = Segment {
            edge_idx: 0,
            axis: Axis::Horizontal,
            fixed_coord: 3,
            range: (0, 4),
            path_idx_range: (3, 7),
        };
        let new_path = build_shifted_segment_path(&old_path, &seg, 4);
        assert!(new_path.contains(&(0, 4)));
        assert!(new_path.contains(&(4, 4)));
    }

    #[test]
    fn build_evicted_run_path_shifts_vertical_subrange_outward() {
        let old_path = vec![
            (0, 0),
            (1, 0),
            (2, 0),
            (2, 1),
            (2, 2),
            (2, 3),
            (2, 4),
            (1, 4),
            (0, 4),
        ];
        let run = HaloRun {
            axis: Axis::Vertical,
            start_idx: 3,
            end_idx: 5,
            fixed_coord: 2,
            shift_dir: 1,
        };
        let new_path = build_evicted_run_path(&old_path, &run, 3);
        assert!(new_path.contains(&(3, 1)));
        assert!(new_path.contains(&(3, 2)));
        assert!(new_path.contains(&(3, 3)));
        for w in new_path.windows(2) {
            let dc = w[0].0.abs_diff(w[1].0);
            let dr = w[0].1.abs_diff(w[1].1);
            assert_eq!(dc + dr, 1, "non-orthogonal step in {new_path:?}");
        }
    }

    #[test]
    fn count_foreign_halo_cells_exempts_endpoint_nodes() {
        let path = vec![(5, 0), (5, 1), (5, 2), (5, 3), (5, 4)];
        let rects = vec![
            NodeRect {
                col: 3,
                row: 0,
                width: 2,
                height: 1,
            },
            NodeRect {
                col: 3,
                row: 4,
                width: 2,
                height: 1,
            },
            NodeRect {
                col: 6,
                row: 2,
                width: 1,
                height: 1,
            },
        ];
        let endpoints = endpoint_node_indices(&path, &rects);
        assert_eq!(count_foreign_halo_cells(&path, &rects, &endpoints), 3);
    }
}