1use std::cmp::Ordering;
11use std::sync::Arc;
12use std::sync::atomic::AtomicUsize;
13use std::sync::atomic::Ordering as AtomicOrdering;
14
15#[cfg(feature = "serialize")]
16use serde::Serialize;
17pub use small_set::SmallSet as LineIds;
19
20pub type PrefixLineColor = Option<usize>;
24
25use crate::column::Column;
26use crate::pipeline::types::Ancestor;
27use crate::pipeline::types::LinkLine;
28
29#[derive(Clone, Debug, Default, PartialEq, Eq)]
36#[cfg_attr(feature = "serialize", derive(Serialize))]
37pub struct GraphRowLineIds {
38 pub before_link: Vec<LineIds>,
43
44 pub link_line: Option<Vec<LinkLineIds>>,
46
47 pub after_link: Vec<LineIds>,
51}
52
53#[derive(Clone, Debug, Default, PartialEq, Eq)]
56#[cfg_attr(feature = "serialize", derive(Serialize))]
57pub struct LinkLineIds {
58 pub vertical: LineIds,
60
61 pub horizontal: LineIds,
63
64 pub left_fork: LineIds,
66
67 pub right_fork: LineIds,
69
70 pub left_merge: LineIds,
72
73 pub right_merge: LineIds,
75}
76
77pub struct LineIdContext<'a, N> {
79 pub node: &'a N,
81 pub parent: &'a Ancestor<N>,
83 pub parent_count: usize,
86 pub node_column: usize,
88 pub parent_column: usize,
90 pub before_link: &'a [LineIds],
93 pub column_line_ids: &'a [LineIds],
96 pub allocated_line_ids: &'a LineIds,
98}
99
100pub type LineIdAllocator<N> = dyn Fn(&LineIdContext<'_, N>) -> usize + Send + Sync;
105
106pub const COLOR_RULE_PRESETS: [&str; 3] = [
113 "parent,incoming,free",
114 "incoming,next-free",
115 "single:node-lane,lane",
116];
117
118#[derive(Clone, Copy)]
119enum Condition {
120 Always,
121 Single,
122 NotSingle,
123}
124
125#[derive(Clone, Copy)]
126enum Source {
127 Parent,
128 Incoming,
129 Free,
130 NextFree,
131 Lane,
132 NodeLane,
133}
134
135#[derive(Clone, Copy)]
136struct Rule {
137 condition: Condition,
138 source: Source,
139}
140
141pub fn build_line_id_allocator_from_rules<N>(
161 rules: &str,
162 line_id_count: usize,
163) -> Option<Arc<LineIdAllocator<N>>> {
164 if line_id_count == 0 {
165 return None;
166 }
167 let rules: Box<[Rule]> = rules
168 .split(',')
169 .map(|text| {
170 let text = text.trim();
171 let (condition, source) = if let Some((condition, source)) = text.split_once(':') {
172 let condition = match condition {
173 "single" => Condition::Single,
174 "!single" => Condition::NotSingle,
175 _ => return None,
176 };
177 (condition, source)
178 } else {
179 (Condition::Always, text)
180 };
181 let source = match source {
182 "parent" => Source::Parent,
183 "incoming" => Source::Incoming,
184 "free" => Source::Free,
185 "next-free" => Source::NextFree,
186 "lane" => Source::Lane,
187 "node-lane" => Source::NodeLane,
188 _ => return None,
189 };
190 Some(Rule { condition, source })
191 })
192 .collect::<Option<Vec<_>>>()?
193 .into_boxed_slice();
194 let cursor = AtomicUsize::new(line_id_count - 1);
195 Some(Arc::new(move |context: &LineIdContext<'_, N>| {
196 for rule in &rules {
197 let applies = match rule.condition {
198 Condition::Always => true,
199 Condition::Single => context.parent_count == 1,
200 Condition::NotSingle => context.parent_count != 1,
201 };
202 if !applies {
203 continue;
204 }
205 let id = match rule.source {
206 Source::Parent => context.column_line_ids[context.parent_column]
207 .iter()
208 .next()
209 .filter(|id| *id < line_id_count),
210 Source::Incoming => context.before_link[context.node_column]
211 .iter()
212 .take_while(|id| *id < line_id_count)
213 .find(|id| !context.allocated_line_ids.contains(*id)),
214 Source::Free => {
215 (0..line_id_count).find(|id| !context.allocated_line_ids.contains(*id))
216 }
217 Source::NextFree => {
218 let previous = cursor.load(AtomicOrdering::Relaxed);
220 let start = if previous + 1 == line_id_count {
221 0
222 } else {
223 previous + 1
224 };
225 let selected = (start..line_id_count)
226 .chain(0..start)
227 .find(|id| !context.allocated_line_ids.contains(*id));
228 if let Some(selected) = selected {
229 cursor.store(selected, AtomicOrdering::Relaxed);
230 }
231 selected
232 }
233 Source::Lane => Some(context.parent_column % line_id_count),
234 Source::NodeLane => Some(context.node_column % line_id_count),
235 };
236 if let Some(id) = id {
237 return id;
238 }
239 }
240 0
241 }))
242}
243
244#[derive(Default)]
245pub(crate) struct ColoringState {
246 column_ids: Vec<LineIds>,
247}
248
249pub(crate) struct RowColoring {
250 node_column: usize,
251 before_link: Vec<LineIds>,
252 connections: Vec<LineIds>,
253 head_line_id: Option<usize>,
254 moved_parent_column: Option<usize>,
255}
256
257impl ColoringState {
258 fn allocated_line_ids(&self) -> LineIds {
259 let mut allocated = LineIds::empty();
260 for ids in &self.column_ids {
261 allocated.union_with(ids);
262 }
263 allocated
264 }
265
266 pub(crate) fn begin_row(&mut self, width: usize, node_column: usize) -> RowColoring {
267 self.column_ids.resize_with(width, LineIds::empty);
268 let before_link = self.column_ids.clone();
269 self.column_ids[node_column] = LineIds::empty();
270 RowColoring {
271 node_column,
272 before_link,
273 connections: vec![LineIds::empty(); width],
274 head_line_id: None,
275 moved_parent_column: None,
276 }
277 }
278
279 pub(crate) fn add_parent(
280 &mut self,
281 row: &mut RowColoring,
282 index: usize,
283 allocate: impl FnOnce(&[LineIds], &[LineIds], &LineIds) -> usize,
284 ) {
285 let width = self.column_ids.len().max(index + 1);
286 self.column_ids.resize_with(width, LineIds::empty);
287 row.before_link.resize_with(width, LineIds::empty);
288 row.connections.resize_with(width, LineIds::empty);
289 let allocated = self.allocated_line_ids();
290 let id = allocate(&row.before_link, &self.column_ids, &allocated);
291 let ids = LineIds::from(id);
292 row.head_line_id.get_or_insert(id);
293 self.column_ids[index].union_with(&ids);
294 row.connections[index].union_with(&ids);
295 }
296
297 pub(crate) fn move_parent(&mut self, row: &mut RowColoring, parent_column: usize) {
298 self.column_ids.swap(row.node_column, parent_column);
299 row.connections.swap(row.node_column, parent_column);
300 row.moved_parent_column = Some(parent_column);
301 }
302
303 pub(crate) fn finish_row<N>(
304 &mut self,
305 mut row: RowColoring,
306 link_line: Option<&[LinkLine]>,
307 columns: &[Column<N>],
308 ) -> Box<GraphRowLineIds> {
309 let link_line = link_line.map(|line| row.link_line_ids(line));
310 if row.before_link[row.node_column].is_empty()
313 && let Some(id) = row.head_line_id
314 {
315 row.before_link[row.node_column] = LineIds::from(id);
316 }
317 let after_link = self.column_ids.clone();
319 self.column_ids.truncate(columns.len());
320 for (ids, column) in self.column_ids.iter_mut().zip(columns) {
321 if !matches!(column, Column::Parent(_) | Column::Ancestor(_)) {
322 *ids = LineIds::empty();
323 }
324 }
325 Box::new(GraphRowLineIds {
326 before_link: row.before_link,
327 link_line,
328 after_link,
329 })
330 }
331}
332
333impl RowColoring {
334 fn link_line_ids(&self, line: &[LinkLine]) -> Vec<LinkLineIds> {
335 let mut ids = vec![LinkLineIds::default(); line.len()];
336 for (index, cell) in line.iter().enumerate() {
337 if index != self.node_column && cell.intersects(LinkLine::VERTICAL) {
338 ids[index].vertical = self.before_link[index].clone();
339 }
340 }
341 for (index, connection) in self.connections.iter().enumerate() {
342 if connection.is_empty() {
343 continue;
344 }
345 match index.cmp(&self.node_column) {
346 Ordering::Less => {
347 ids[index].right_fork.union_with(connection);
348 ids[self.node_column].left_merge.union_with(connection);
349 for cell in &mut ids[index + 1..self.node_column] {
350 cell.horizontal.union_with(connection);
351 }
352 }
353 Ordering::Greater => {
354 ids[index].left_fork.union_with(connection);
355 ids[self.node_column].right_merge.union_with(connection);
356 for cell in &mut ids[self.node_column + 1..index] {
357 cell.horizontal.union_with(connection);
358 }
359 }
360 Ordering::Equal => {
361 ids[index].vertical.union_with(connection);
362 }
363 }
364 }
365 if let Some(parent_column) = self.moved_parent_column {
366 let mut connection = &self.before_link[parent_column];
367 if connection.is_empty() {
368 connection = &self.connections[self.node_column];
370 }
371 ids[self.node_column].right_fork.union_with(connection);
372 ids[parent_column].left_merge.union_with(connection);
373 for cell in &mut ids[self.node_column + 1..parent_column] {
374 cell.horizontal.union_with(connection);
375 }
376 }
377 ids
378 }
379}
380
381#[cfg(test)]
382mod tests {
383 use super::*;
384 use crate::pipeline::GraphRowShaper;
385 use crate::pipeline::row_shape_to_prefix_lines::box_drawing::BoxDrawingPrefixLineRenderer;
386 use crate::pipeline::row_shape_to_prefix_lines::box_drawing::Curved;
387 use crate::pipeline::types::Ancestor;
388 use crate::pipeline::types::GraphRowShape;
389 use crate::pipeline::types::NodeLine;
390 use crate::pipeline::types::PadLine;
391 use crate::pipeline::types::PrefixLine;
392 use crate::pipeline::types::PrefixLineKind;
393 use crate::pipeline::types::PrefixLinePart;
394 use crate::pipeline::types::PrefixLineRenderer;
395 use crate::pipeline::types::TextLine;
396 use crate::test_utils::indent;
397
398 fn ids(values: impl IntoIterator<Item = usize>) -> LineIds {
399 values.into_iter().collect()
400 }
401
402 fn render_graph(rows: &[GraphRowShape<&str>], selected_id: Option<usize>) -> String {
404 let width = rows
405 .iter()
406 .map(|row| row.node_line.len() * 2)
407 .max()
408 .unwrap();
409 let mut renderer = BoxDrawingPrefixLineRenderer::<Curved>::new();
410 let mut out = String::new();
411 for row in rows {
412 let mut filtered = row.clone();
413 if let Some(id) = selected_id {
414 let colors = row.line_ids.as_ref().unwrap();
415 for (cell, ids) in filtered.node_line.iter_mut().zip(&colors.before_link) {
417 if !ids.contains(id) {
418 *cell = NodeLine::Blank;
419 }
420 }
421 if let (Some(line), Some(colors)) = (&mut filtered.link_line, &colors.link_line) {
422 for (cell, colors) in line.iter_mut().zip(colors) {
423 let mut mask = LinkLine::empty();
424 for (flag, ids) in [
425 (LinkLine::VERTICAL, &colors.vertical),
426 (LinkLine::HORIZONTAL, &colors.horizontal),
427 (LinkLine::LEFT_FORK, &colors.left_fork),
428 (LinkLine::RIGHT_FORK, &colors.right_fork),
429 (LinkLine::LEFT_MERGE, &colors.left_merge),
430 (LinkLine::RIGHT_MERGE, &colors.right_merge),
431 ] {
432 if ids.contains(id) {
433 mask |= flag;
434 }
435 }
436 if mask.intersects(LinkLine::VERTICAL) {
437 mask |= LinkLine::CHILD;
438 }
439 *cell &= mask;
440 }
441 }
442 for (index, ids) in colors.after_link.iter().enumerate() {
443 if !ids.contains(id) {
444 filtered.ancestry_line[index] = PadLine::Blank;
445 if let Some(terms) = &mut filtered.term_line {
446 terms[index] = false;
447 }
448 }
449 }
450 }
451 let mut prefixes = renderer.next_prefix_lines(&filtered);
452 if row.has_indirect_ancestor() && !filtered.has_indirect_ancestor() {
453 let index = prefixes
455 .iter()
456 .position(|line| line.kind == PrefixLineKind::PostAncestry)
457 .unwrap();
458 let mut ancestry = prefixes[index].clone();
459 ancestry.kind = PrefixLineKind::Ancestry;
460 prefixes.insert(index, ancestry);
461 }
462 for line in prefixes {
463 if matches!(
465 line.kind,
466 PrefixLineKind::PreNode | PrefixLineKind::PostNode
467 ) {
468 continue;
469 }
470 let text: String = line
471 .parts
472 .into_iter()
473 .map(|(part, _)| match part {
474 PrefixLinePart::Text(text) => text,
475 PrefixLinePart::NodeGlyph => "o".to_owned(),
476 })
477 .collect();
478 out.push_str(&format!(
479 "{:width$} # {} {:?}\n",
480 text.trim_end(),
481 row.node,
482 line.kind
483 ));
484 }
485 }
486 indent(&out)
487 }
488
489 #[test]
490 fn test_default_allocator_preserves_line_id() {
491 let graph = || {
492 [
493 ("H", vec![Ancestor::Parent("A"), Ancestor::Parent("B")]),
494 ("A", vec![]),
495 ("B", vec![Ancestor::Parent("C")]),
496 ("C", vec![]),
497 ]
498 };
499 let shape = |allocator| {
500 let mut shaper = GraphRowShaper::new().with_line_id_allocator(allocator);
501 graph()
502 .into_iter()
503 .map(|(node, parents)| shaper.next_row_shape(node, parents))
504 .collect::<Vec<_>>()
505 };
506 let plain = shape(None);
507 assert_eq!(
508 render_graph(&plain, None),
509 r#"
510 o # H Node
511 ├─╮ # H Link
512 │ │ # H PostAncestry
513 o │ # A Node
514 │ # A PostAncestry
515 o # B Node
516 │ # B PostAncestry
517 o # C Node
518 # C PostAncestry"#
519 );
520 let colored = shape(build_line_id_allocator_from_rules(COLOR_RULE_PRESETS[0], 4));
522 assert_eq!(
523 render_graph(&colored, Some(0)),
524 r#"
525 o # H Node
526 │ # H Link
527 │ # H PostAncestry
528 o # A Node
529 # A PostAncestry
530 # B Node
531 # B PostAncestry
532 # C Node
533 # C PostAncestry"#
534 );
535 assert_eq!(
536 render_graph(&colored, Some(1)),
537 r#"
538 # H Node
539 ╰─╮ # H Link
540 │ # H PostAncestry
541 │ # A Node
542 │ # A PostAncestry
543 o # B Node
544 │ # B PostAncestry
545 o # C Node
546 # C PostAncestry"#
547 );
548 }
549
550 #[test]
551 fn test_graph_coloring() {
552 let graph = || {
554 [
555 (
556 "M",
557 vec![
558 Ancestor::Parent("A"),
559 Ancestor::Parent("B"),
560 Ancestor::Parent("C"),
561 ],
562 ),
563 ("C", vec![Ancestor::Parent("R")]),
564 ("B", vec![Ancestor::Parent("R"), Ancestor::Anonymous]),
565 ("Z", vec![Ancestor::Parent("D")]),
566 ("A", vec![Ancestor::Parent("R")]),
567 ("R", vec![Ancestor::Ancestor("P")]),
568 ("D", vec![]),
569 ("P", vec![]),
570 ]
571 };
572 let shape = |allocator| {
573 let mut shaper = GraphRowShaper::new().with_line_id_allocator(allocator);
574 shaper.reserve("P");
575 graph()
576 .into_iter()
577 .map(|(node, parents)| shaper.next_row_shape(node, parents))
578 .collect::<Vec<_>>()
579 };
580 let plain = shape(None);
581 assert_eq!(
582 render_graph(&plain, None),
583 r#"
584 o # M Node
585 ├─┬─╮ # M Link
586 │ │ │ # M PostAncestry
587 │ │ o # C Node
588 │ │ │ # C PostAncestry
589 │ o │ # B Node
590 │ ├─╮ # B Link
591 │ │ │ # B Term
592 │ ~ │ # B Term
593 │ │ # B PostAncestry
594 │ o │ # Z Node
595 │ │ │ # Z PostAncestry
596 o │ │ # A Node
597 ├───╯ # A Link
598 │ │ # A PostAncestry
599 o │ # R Node
600 ╭─╯ │ # R Link
601 ╷ │ # R Ancestry
602 ╷ │ # R PostAncestry
603 ╷ o # D Node
604 ╷ # D Ancestry
605 ╷ # D PostAncestry
606 o # P Node
607 # P PostAncestry"#
608 );
609
610 let colored = shape(build_line_id_allocator_from_rules(COLOR_RULE_PRESETS[0], 4));
611 assert_eq!(
612 render_graph(&colored, Some(0)),
613 r#"
614 o # M Node
615 │ # M Link
616 │ # M PostAncestry
617 │ # C Node
618 │ # C PostAncestry
619 │ # B Node
620 │ # B Link
621 │ # B Term
622 │ # B Term
623 │ # B PostAncestry
624 │ # Z Node
625 │ # Z PostAncestry
626 o # A Node
627 # A Link
628 # A PostAncestry
629 # R Node
630 # R Link
631 # R Ancestry
632 # R PostAncestry
633 # D Node
634 # D Ancestry
635 # D PostAncestry
636 # P Node
637 # P PostAncestry"#
638 );
639 assert_eq!(
640 render_graph(&colored, Some(1)),
641 r#"
642 # M Node
643 ╰─╮ # M Link
644 │ # M PostAncestry
645 │ # C Node
646 │ # C PostAncestry
647 o # B Node
648 │ # B Link
649 │ # B Term
650 ~ # B Term
651 # B PostAncestry
652 o # Z Node
653 │ # Z PostAncestry
654 │ # A Node
655 │ # A Link
656 │ # A PostAncestry
657 │ # R Node
658 │ # R Link
659 │ # R Ancestry
660 │ # R PostAncestry
661 o # D Node
662 # D Ancestry
663 # D PostAncestry
664 # P Node
665 # P PostAncestry"#
666 );
667 assert_eq!(
668 render_graph(&colored, Some(2)),
669 r#"
670 # M Node
671 ╰───╮ # M Link
672 │ # M PostAncestry
673 o # C Node
674 │ # C PostAncestry
675 │ # B Node
676 ╰─╮ # B Link
677 │ # B Term
678 │ # B Term
679 │ # B PostAncestry
680 │ # Z Node
681 │ # Z PostAncestry
682 │ # A Node
683 ├───╯ # A Link
684 │ # A PostAncestry
685 o # R Node
686 ╭─╯ # R Link
687 ╷ # R Ancestry
688 ╷ # R PostAncestry
689 ╷ # D Node
690 ╷ # D Ancestry
691 ╷ # D PostAncestry
692 o # P Node
693 # P PostAncestry"#
694 );
695 }
696
697 #[test]
698 fn test_reserved_parent_move() {
699 let shape = |allocator| {
700 let mut shaper = GraphRowShaper::new().with_line_id_allocator(allocator);
701 let head = shaper.next_row_shape("H", vec![Ancestor::Parent("N")]);
702 shaper.reserve("P");
703 vec![
704 head,
705 shaper.next_row_shape("N", vec![Ancestor::Parent("P")]),
706 shaper.next_row_shape("P", vec![]),
707 ]
708 };
709 let plain = shape(None);
710 assert_eq!(
711 render_graph(&plain, None),
712 r#"
713 o # H Node
714 │ # H PostAncestry
715 o # N Node
716 ├─╯ # N Link
717 │ # N PostAncestry
718 o # P Node
719 # P PostAncestry"#
720 );
721 let colored = shape(build_line_id_allocator_from_rules(COLOR_RULE_PRESETS[0], 8));
722 assert_eq!(
723 render_graph(&colored, Some(0)),
724 r#"
725 o # H Node
726 │ # H PostAncestry
727 o # N Node
728 ├─╯ # N Link
729 │ # N PostAncestry
730 o # P Node
731 # P PostAncestry"#
732 );
733 }
734
735 #[test]
736 fn test_id_range_and_exhaustion() {
737 let mut shared = GraphRowShaper::new().with_line_id_allocator(
738 build_line_id_allocator_from_rules(COLOR_RULE_PRESETS[0], 70),
739 );
740 for node in 1..=72 {
741 let colors = shared
742 .next_row_shape(node, vec![Ancestor::Parent(0)])
743 .line_ids
744 .unwrap();
745 assert_eq!(colors.after_link[0], ids([0]));
746 }
747
748 let mut shaper = GraphRowShaper::new().with_line_id_allocator(
749 build_line_id_allocator_from_rules(COLOR_RULE_PRESETS[0], 70),
750 );
751 for node in 1..=72 {
752 let colors = shaper
753 .next_row_shape(node, vec![Ancestor::Parent(1000 + node)])
754 .line_ids
755 .unwrap();
756 let allocated: LineIds = colors.after_link.iter().flat_map(LineIds::iter).collect();
757 assert!(allocated.iter().all(|id| id < 70));
758 assert_eq!(allocated.len(), node.min(70));
759 }
760 let mut disabled = GraphRowShaper::new()
761 .with_line_id_allocator(build_line_id_allocator_from_rules(COLOR_RULE_PRESETS[0], 0));
762 assert!(
763 disabled
764 .next_row_shape("A", vec![Ancestor::Parent("B")])
765 .line_ids
766 .is_none()
767 );
768 }
769
770 #[test]
771 fn test_custom_allocator() {
772 let allocator: Arc<LineIdAllocator<&str>> = Arc::new(|context| {
773 let target = match context.parent {
774 Ancestor::Parent(parent) | Ancestor::Ancestor(parent) => parent,
775 Ancestor::Anonymous => context.node,
776 };
777 if *target == "P" {
778 0
779 } else {
780 (1..4)
781 .find(|id| !context.allocated_line_ids.contains(*id))
782 .unwrap_or(1)
783 }
784 });
785 let graph = || {
786 [
787 ("H", vec![Ancestor::Parent("N"), Ancestor::Parent("P")]),
788 ("N", vec![Ancestor::Ancestor("P")]),
789 ("P", vec![]),
790 ]
791 };
792 let shape = |allocator| {
793 let mut shaper = GraphRowShaper::new().with_line_id_allocator(allocator);
794 graph()
795 .into_iter()
796 .map(|(node, parents)| shaper.next_row_shape(node, parents))
797 .collect::<Vec<_>>()
798 };
799 let plain = shape(None);
800 assert_eq!(
801 render_graph(&plain, None),
802 r#"
803 o # H Node
804 ├─╮ # H Link
805 │ │ # H PostAncestry
806 o │ # N Node
807 ├─╯ # N Link
808 │ # N PostAncestry
809 o # P Node
810 # P PostAncestry"#
811 );
812 let colored = shape(Some(allocator.clone()));
813 assert_eq!(
814 render_graph(&colored, Some(0)),
815 r#"
816 # H Node
817 ╰─╮ # H Link
818 │ # H PostAncestry
819 │ # N Node
820 ├─╯ # N Link
821 │ # N PostAncestry
822 o # P Node
823 # P PostAncestry"#
824 );
825 assert_eq!(
826 render_graph(&colored, Some(1)),
827 r#"
828 o # H Node
829 │ # H Link
830 │ # H PostAncestry
831 o # N Node
832 # N Link
833 # N PostAncestry
834 # P Node
835 # P PostAncestry"#
836 );
837
838 let mut other = GraphRowShaper::new().with_line_id_allocator(Some(allocator));
839 let colors = other
840 .next_row_shape("Q", vec![Ancestor::Parent("P")])
841 .line_ids
842 .unwrap();
843 assert_eq!(colors.after_link, vec![ids([0])]);
844 }
845
846 #[test]
847 fn test_isolated_node_does_not_allocate_line() {
848 let mut shaper = GraphRowShaper::new().with_line_id_allocator(Some(Arc::new(|_| {
849 panic!("isolated nodes have no parent connection")
850 })));
851 let colors = shaper.next_row_shape("A", vec![]).line_ids.unwrap();
852 assert_eq!(colors.before_link, vec![ids([])]);
853 assert_eq!(colors.after_link, vec![ids([])]);
854 }
855
856 #[test]
857 fn test_next_free_cursor() {
858 let mut shaper = GraphRowShaper::new()
859 .with_line_id_allocator(build_line_id_allocator_from_rules(COLOR_RULE_PRESETS[1], 3));
860 assert_eq!(
861 shaper
862 .next_row_shape("H", vec![Ancestor::Parent("A")])
863 .line_ids
864 .unwrap()
865 .after_link[0],
866 ids([0])
867 );
868 assert_eq!(
870 shaper
871 .next_row_shape("A", vec![Ancestor::Parent("B")])
872 .line_ids
873 .unwrap()
874 .after_link[0],
875 ids([0])
876 );
877 let row = shaper.next_row_shape("Z", vec![Ancestor::Parent("C")]);
878 assert_eq!(row.line_ids.unwrap().after_link[1], ids([1]));
879 shaper.next_row_shape("B", vec![]);
880 let row = shaper.next_row_shape("Q", vec![Ancestor::Parent("D")]);
881 assert_eq!(row.line_ids.unwrap().after_link[0], ids([2]));
882 shaper.next_row_shape("C", vec![]);
883 shaper.next_row_shape("D", vec![]);
884 assert_eq!(
885 shaper
886 .next_row_shape("R", vec![Ancestor::Parent("E")])
887 .line_ids
888 .unwrap()
889 .after_link[0],
890 ids([0])
891 );
892
893 let mut shaper = GraphRowShaper::new()
894 .with_line_id_allocator(build_line_id_allocator_from_rules("next-free", 2));
895 shaper.next_row_shape("H", vec![Ancestor::Parent("A")]);
896 shaper.next_row_shape("J", vec![Ancestor::Parent("B")]);
897 shaper.next_row_shape("Z", vec![Ancestor::Parent("C")]); for node in ["A", "B", "C"] {
899 shaper.next_row_shape(node, vec![]);
900 }
901 assert_eq!(
902 shaper
903 .next_row_shape("Q", vec![Ancestor::Parent("D")])
904 .line_ids
905 .unwrap()
906 .after_link[0],
907 ids([0])
908 );
909 }
910
911 #[test]
912 fn test_rule_syntax_and_negation() {
913 for rules in [
914 "",
915 " ",
916 ",",
917 "parent,",
918 "unknown",
919 "head:parent",
920 "single:",
921 ":parent",
922 "!head:lane",
923 "single:free:incoming",
924 ] {
925 assert!(
926 build_line_id_allocator_from_rules::<usize>(rules, 3).is_none(),
927 "{rules}"
928 );
929 }
930 let mut shaper = GraphRowShaper::new().with_line_id_allocator(
931 build_line_id_allocator_from_rules("!single:lane,node-lane", 3),
932 );
933 let row = shaper.next_row_shape("H", vec![Ancestor::Parent("A"), Ancestor::Parent("B")]);
934 assert_eq!(row.line_ids.unwrap().after_link, vec![ids([0]), ids([1])]);
935 let row = shaper.next_row_shape("A", vec![Ancestor::Parent("B")]);
936 assert_eq!(row.line_ids.unwrap().after_link[0], ids([0, 1]));
937 }
938
939 #[test]
940 fn test_column_allocator_move() {
941 let mut shaper = GraphRowShaper::new()
942 .with_line_id_allocator(build_line_id_allocator_from_rules(COLOR_RULE_PRESETS[2], 6));
943 shaper.next_row_shape("H", vec![Ancestor::Parent("N")]);
944 shaper.reserve("P");
945 let row = shaper.next_row_shape("N", vec![Ancestor::Ancestor("P")]);
946 assert_eq!(row.parent_columns, vec![0]);
947 assert_eq!(row.line_ids.unwrap().after_link[0], ids([0]));
948 }
949
950 #[test]
951 fn test_allocator_preset_limits() {
952 for rules in COLOR_RULE_PRESETS {
953 assert!(build_line_id_allocator_from_rules::<usize>(rules, 0).is_none());
954 for limit in [1, 3] {
955 let mut shaper = GraphRowShaper::new()
956 .with_line_id_allocator(build_line_id_allocator_from_rules(rules, limit));
957 for node in 0..12 {
958 let row = shaper.next_row_shape(
959 node,
960 vec![Ancestor::Parent(100 + node), Ancestor::Parent(200 + node)],
961 );
962 let colors = row.line_ids.unwrap();
963 assert!(
964 colors
965 .after_link
966 .iter()
967 .flat_map(LineIds::iter)
968 .all(|id| id < limit)
969 );
970 }
971 }
972 }
973 }
974
975 #[test]
976 fn test_allocation_context() {
977 let mut shaper = GraphRowShaper::new().with_line_id_allocator(Some(Arc::new(|context| {
978 assert_eq!(context.node_column, 0);
979 assert_eq!(
980 context.parent_count,
981 if *context.node == "H" { 2 } else { 1 }
982 );
983 match (*context.node, context.parent) {
984 ("H", Ancestor::Parent("A")) => {
985 assert_eq!(context.parent_column, 0);
986 assert_eq!(context.before_link, &[ids([])]);
987 assert_eq!(context.column_line_ids, &[ids([])]);
988 assert!(context.allocated_line_ids.is_empty());
989 0
990 }
991 ("H", Ancestor::Parent("B")) => {
992 assert_eq!(context.parent_column, 1);
993 assert_eq!(context.before_link, &[ids([]), ids([])]);
994 assert_eq!(context.column_line_ids, &[ids([0]), ids([])]);
995 assert_eq!(context.allocated_line_ids, &ids([0]));
996 1
997 }
998 ("A", Ancestor::Parent("B")) => {
999 assert_eq!(context.parent_column, 1);
1000 assert_eq!(context.before_link, &[ids([0]), ids([1])]);
1001 assert_eq!(context.column_line_ids, &[ids([]), ids([1])]);
1002 assert_eq!(context.allocated_line_ids, &ids([1]));
1003 2
1004 }
1005 _ => panic!("unexpected connection"),
1006 }
1007 })));
1008 shaper.next_row_shape("H", vec![Ancestor::Parent("A"), Ancestor::Parent("B")]);
1009 let row = shaper.next_row_shape("A", vec![Ancestor::Parent("B")]);
1010 assert_eq!(
1011 row.line_ids.as_ref().unwrap().after_link,
1012 vec![ids([1, 2]), ids([])]
1013 );
1014 let prefixes = BoxDrawingPrefixLineRenderer::<Curved>::new().next_prefix_lines(&row);
1015 let continuation = prefixes
1016 .iter()
1017 .find(|line| line.kind == PrefixLineKind::PostAncestry)
1018 .unwrap();
1019 assert_eq!(continuation.parts[0].1, Some(1));
1020 let row = shaper.next_row_shape("B", vec![]);
1021 let prefixes = BoxDrawingPrefixLineRenderer::<Curved>::new().next_prefix_lines(&row);
1022 let node = prefixes
1023 .iter()
1024 .find(|line| line.kind == PrefixLineKind::Node)
1025 .unwrap();
1026 assert_eq!(node.parts[0], (PrefixLinePart::NodeGlyph, None));
1027 }
1028
1029 #[test]
1030 fn test_line_ids_match_fixture_shapes() {
1031 use crate::pipeline::GraphRowShaper;
1032 use crate::render::LinkLine;
1033 use crate::render::NodeLine;
1034 use crate::render::PadLine;
1035 use crate::test_fixtures;
1036 use crate::test_utils::MiniDag;
1037
1038 for fixture in [
1039 test_fixtures::BASIC,
1040 test_fixtures::BRANCHES_AND_MERGES,
1041 test_fixtures::OCTOPUS_BRANCH_AND_MERGE,
1042 test_fixtures::RESERVED_COLUMN,
1043 test_fixtures::ANCESTORS,
1044 test_fixtures::SPLIT_PARENTS,
1045 test_fixtures::TERMINATIONS,
1046 ] {
1047 let mut dag = MiniDag::from_drawdag(fixture.dag);
1048 for head in fixture.heads {
1049 dag.assign_rev(head);
1050 }
1051 let mut plain = GraphRowShaper::new();
1052 let mut colored = GraphRowShaper::new().with_line_id_allocator(
1053 build_line_id_allocator_from_rules(COLOR_RULE_PRESETS[0], 8),
1054 );
1055 for node in fixture.reserve {
1056 plain.reserve(node.to_string());
1057 colored.reserve(node.to_string());
1058 }
1059 for node in dag.all() {
1060 if fixture.missing.contains(&node.as_str()) {
1061 continue;
1062 }
1063 let parents = || {
1064 dag.parent_names(&node)
1065 .into_iter()
1066 .map(|parent| {
1067 if fixture.missing.contains(&parent.as_str()) {
1068 Ancestor::Anonymous
1069 } else if fixture
1070 .ancestors
1071 .contains(&(node.as_str(), parent.as_str()))
1072 {
1073 Ancestor::Ancestor(parent)
1074 } else {
1075 Ancestor::Parent(parent)
1076 }
1077 })
1078 .collect()
1079 };
1080 let mut row = colored.next_row_shape(node.clone(), parents());
1081 let ids = row.line_ids.take().unwrap();
1082 assert_eq!(row, plain.next_row_shape(node.clone(), parents()));
1083 row.line_ids = Some(ids);
1084 let ids = row.line_ids.as_ref().unwrap();
1085 assert_eq!(ids.before_link.len(), row.node_line.len());
1086 assert_eq!(ids.after_link.len(), row.ancestry_line.len());
1087 for (line, ids) in row.node_line.iter().zip(&ids.before_link) {
1088 let isolated = *line == NodeLine::Node && row.is_head && row.is_root;
1089 assert_eq!(
1090 *line == NodeLine::Blank || isolated,
1091 ids.is_empty(),
1092 "{node}"
1093 );
1094 }
1095 for (index, (line, ids)) in
1096 row.ancestry_line.iter().zip(&ids.after_link).enumerate()
1097 {
1098 let terminated = row.term_line.as_ref().is_some_and(|terms| terms[index]);
1099 assert_eq!(
1100 *line == PadLine::Blank && !terminated,
1101 ids.is_empty(),
1102 "{node}"
1103 );
1104 }
1105 assert_eq!(row.link_line.is_some(), ids.link_line.is_some());
1106 if let (Some(line), Some(ids)) = (&row.link_line, &ids.link_line) {
1107 assert_eq!(line.len(), ids.len());
1108 for (cell, ids) in line.iter().zip(ids) {
1109 for (flag, ids) in [
1110 (LinkLine::VERTICAL, &ids.vertical),
1111 (LinkLine::HORIZONTAL, &ids.horizontal),
1112 (LinkLine::LEFT_FORK, &ids.left_fork),
1113 (LinkLine::RIGHT_FORK, &ids.right_fork),
1114 (LinkLine::LEFT_MERGE, &ids.left_merge),
1115 (LinkLine::RIGHT_MERGE, &ids.right_merge),
1116 ] {
1117 assert_eq!(cell.intersects(flag), !ids.is_empty(), "{node}: {cell:?}");
1118 assert!(ids.iter().all(|id| id < 8));
1119 }
1120 }
1121 }
1122 }
1123 }
1124 }
1125 fn strip_sgr(text: &str) -> String {
1126 let mut out = String::new();
1127 let mut rest = text;
1128 while let Some(start) = rest.find("\x1b[") {
1129 out.push_str(&rest[..start]);
1130 rest = &rest[start + 2..];
1131 let end = rest.find('m').unwrap();
1132 rest = &rest[end + 1..];
1133 }
1134 out.push_str(rest);
1135 out
1136 }
1137
1138 const COLORS: [&str; 6] = [
1139 "\x1b[31m", "\x1b[32m", "\x1b[33m", "\x1b[34m", "\x1b[35m", "\x1b[36m",
1140 ];
1141
1142 fn render_text_lines(lines: &[TextLine], palette: Option<&[&str]>) -> String {
1144 let mut out = String::new();
1145 for line in lines {
1146 for (text, ids) in line {
1147 if let Some(palette) = palette
1148 && let Some(id) = *ids
1149 {
1150 let leading = text.len() - text.trim_start_matches(' ').len();
1151 let body = text[leading..].trim_end_matches(' ');
1152 out.push_str(&text[..leading]);
1153 if !body.is_empty() {
1154 out.push_str(palette[id % palette.len()]);
1155 out.push_str(body);
1156 out.push_str("\x1b[39m");
1157 }
1158 out.push_str(&text[leading + body.len()..]);
1159 } else {
1160 out.push_str(text);
1161 }
1162 }
1163 out.push('\n');
1164 }
1165 out
1166 }
1167
1168 fn render_fixture_ids<P: PrefixLineRenderer<String> + Default + Send + Sync + 'static>(
1169 fixture: &crate::test_fixtures::TestFixture,
1170 allocator: Option<Arc<LineIdAllocator<String>>>,
1171 ) -> String {
1172 use crate::pipeline::GraphTextRenderer;
1173 use crate::test_utils::MiniDag;
1174
1175 let mut dag = MiniDag::from_drawdag(fixture.dag);
1176 for head in fixture.heads {
1177 dag.assign_rev(head);
1178 }
1179 let mut renderer = GraphTextRenderer::<String>::new::<P>()
1180 .with_line_id_allocator(allocator)
1181 .configure(|options| options.min_row_height = 0);
1182 for node in fixture.reserve {
1183 renderer.reserve(node.to_string());
1184 }
1185 let mut out = String::new();
1186 for node in dag.all() {
1187 if fixture.missing.contains(&node.as_str()) {
1188 continue;
1189 }
1190 let parents = dag
1191 .parent_names(&node)
1192 .into_iter()
1193 .map(|parent| {
1194 if fixture.missing.contains(&parent.as_str()) {
1195 Ancestor::Anonymous
1196 } else if fixture
1197 .ancestors
1198 .contains(&(node.as_str(), parent.as_str()))
1199 {
1200 Ancestor::Ancestor(parent)
1201 } else {
1202 Ancestor::Parent(parent)
1203 }
1204 })
1205 .collect();
1206 let message = fixture.messages.iter().find(|(name, _)| *name == node);
1207 let message =
1208 message.map_or_else(|| node.clone(), |(_, text)| format!("{node}\n{text}"));
1209 renderer.write_next_lines(
1210 |text, color| {
1211 if let Some(id) = *color {
1212 let digit = char::from_digit(id as u32, 10).unwrap();
1213 out.extend(text.chars().map(|ch| if ch == ' ' { ' ' } else { digit }));
1214 } else {
1215 out.push_str(text);
1216 }
1217 },
1218 node,
1219 parents,
1220 "o",
1221 &message,
1222 );
1223 }
1224 out
1225 }
1226
1227 fn allocator_gallery(fixture: &crate::test_fixtures::TestFixture) -> String {
1228 let columns: Vec<_> = [
1229 ("plain", None),
1230 (
1231 "A",
1232 build_line_id_allocator_from_rules(COLOR_RULE_PRESETS[0], 6),
1233 ),
1234 (
1235 "G",
1236 build_line_id_allocator_from_rules(COLOR_RULE_PRESETS[1], 6),
1237 ),
1238 (
1239 "D",
1240 build_line_id_allocator_from_rules(COLOR_RULE_PRESETS[2], 6),
1241 ),
1242 ]
1243 .into_iter()
1244 .map(|(name, allocator)| {
1245 let text =
1246 render_fixture_ids::<BoxDrawingPrefixLineRenderer<Curved>>(fixture, allocator);
1247 let lines: Vec<_> = text.lines().map(|line| format!(" {line}")).collect();
1248 (name, lines)
1249 })
1250 .collect();
1251 let width = columns
1252 .iter()
1253 .flat_map(|(_, lines)| lines)
1254 .map(|line| line.chars().count())
1255 .max()
1256 .unwrap()
1257 + 4;
1258 let mut out = columns
1259 .iter()
1260 .map(|(name, _)| format!(" {name:<w$}", w = width - 2))
1261 .collect::<String>();
1262 out.truncate(out.trim_end().len());
1263 out.push('\n');
1264 for row in 0..columns[0].1.len() {
1265 let line: String = columns
1266 .iter()
1267 .map(|(_, lines)| {
1268 assert_eq!(lines.len(), columns[0].1.len());
1269 format!("{:<width$}", lines[row])
1270 })
1271 .collect();
1272 out.push_str(line.trim_end());
1273 out.push('\n');
1274 }
1275 indent(&out)
1276 }
1277
1278 #[test]
1279 fn test_allocator_gallery() {
1280 use crate::test_fixtures;
1281 assert_eq!(
1282 allocator_gallery(&test_fixtures::BRANCHES_AND_MERGES),
1283 r#"
1284 plain A G D
1285 o W o W o W o W
1286 o V o V o V o V
1287 ├─╮ 011 011 011
1288 │ o U 0 o U 0 o U 0 o U
1289 │ ├─╮ 0 122 0 122 0 122
1290 │ │ o T 0 1 o T 0 1 o T 0 1 o T
1291 │ o │ S 0 o 2 S 0 o 2 S 0 o 2 S
1292 o │ R o 2 R o 2 R o 2 R
1293 o │ Q o 2 Q o 2 Q o 2 Q
1294 ├─╮ │ 011 2 033 2 011 2
1295 │ o │ P 0 o 2 P 0 o 2 P 0 o 2 P
1296 │ ├───╮ 0 13333 0 34444 0 13333
1297 │ │ │ o O 0 1 2 o O 0 3 2 o O 0 1 2 o O
1298 │ │ │ o N 0 1 2 o N 0 3 2 o N 0 1 2 o N
1299 │ │ │ ├─╮ 0 1 2 344 0 3 2 455 0 1 2 344
1300 │ o │ │ │ M 0 o 2 3 4 M 0 o 2 4 5 M 0 o 2 3 4 M
1301 │ o │ │ │ L 0 o 2 3 4 L 0 o 2 4 5 L 0 o 2 3 4 L
1302 o │ │ │ │ K o 1 2 3 4 K o 3 2 4 5 K o 1 2 3 4 K
1303 ├───────╯ 444444444 055555555 044444444
1304 o │ │ │ J o 1 2 3 J o 3 2 4 J o 1 2 3 J
1305 o │ │ │ I o 1 2 3 I o 3 2 4 I o 1 2 3 I
1306 ├─╯ │ │ 111 2 3 033 2 4 011 2 3
1307 o │ │ H o 2 3 H o 2 4 H o 2 3 H
1308 o │ │ G o 2 3 G o 2 4 G o 2 3 G
1309 ├─────╮ 1333333 0111111 0333333
1310 │ │ o F 1 2 o F 0 2 o F 0 2 o F
1311 │ ├─╯ 1 222 0 211 0 233
1312 │ o E 1 o E 0 o E 0 o E
1313 o │ D o 2 D o 1 D o 2 D
1314 o │ C o 2 C o 1 C o 2 C
1315 ├───╯ 22222 01111 02222
1316 o B o B o B o B
1317 o A o A o A o A"#
1318 );
1319 assert_eq!(
1320 allocator_gallery(&test_fixtures::OCTOPUS_BRANCH_AND_MERGE),
1321 r#"
1322 plain A G D
1323 o J o J o J o J
1324 ├─┬─╮ 01122 01122 01122
1325 │ │ o I 0 1 o I 0 1 o I 0 1 o I
1326 │ o │ H 0 o 2 H 0 o 2 H 0 o 2 H
1327 ╭─┼─┬─┬─╮ 001223344 551030400 001223344
1328 │ │ │ │ o G 0 1 2 3 o G 0 1 2 4 o G 0 1 2 3 o G
1329 │ │ │ o │ E 0 1 2 o 4 E 0 1 2 o 0 E 0 1 2 o 4 E
1330 │ │ │ ├─╯ 0 1 2 444 0 1 2 400 0 1 2 344
1331 │ │ o │ D 0 1 o 4 D 0 1 o 0 D 0 1 o 3 D
1332 │ │ ├─╮ 0 1 244 0 1 233 0 1 233
1333 │ o │ │ C 0 o 2 4 C 0 o 2 0 C 0 o 2 3 C
1334 │ ├───╯ 0 44444 0 10000 0 13333
1335 o │ │ F o 4 2 F o 0 2 F o 1 2 F
1336 ├─╯ │ 444 2 500 2 011 2
1337 o │ B o 2 B o 2 B o 2 B
1338 ├───╯ 22222 02222 02222
1339 o A o A o A o A"#
1340 );
1341 assert_eq!(
1342 allocator_gallery(&test_fixtures::SPLIT_PARENTS),
1343 r#"
1344 plain A G D
1345 o E o E o E o E
1346 ╭─┬─┬─┤ 1131210 1131210 0010203
1347 ╷ │ │ ╷ 1 3 2 0 1 3 2 0 0 1 2 3
1348 ╷ o │ ╷ D 1 o 2 0 D 1 o 2 0 D 0 o 2 3 D
1349 ╭─┴─╮ ╷ 11122 0 33344 0 00022 3
1350 │ │ ╷ 1 2 0 1 2 0 0 2 3
1351 │ o ╷ C 1 o 0 C 1 o 0 C 0 o 3 C
1352 │ ├─╯ 1 000 1 200 0 233
1353 o │ B o 0 B o 0 B o 2 B
1354 ├───╯ 00000 10000 02222
1355 o A o A o A o A"#
1356 );
1357 assert_eq!(
1358 allocator_gallery(&test_fixtures::ANCESTORS),
1359 r#"
1360 plain A G D
1361 o Z o Z o Z o Z
1362 o Y o Y o Y o Y
1363 ╭─╯ 000 000 111
1364 o F o F o F o F
1365 ╷ 0 0 0
1366 ╷ o X 0 o X 0 o X 0 o X
1367 ╭─╯ 000 111 111
1368 │ o W 0 o W 0 o W 0 o W
1369 ├─╯ 000 022 011
1370 o E o E o E o E
1371 ╷ 0 0 0
1372 o D o D o D o D
1373 ├─╮ 011 033 011
1374 │ ╷ 0 1 0 3 0 1
1375 │ o C 0 o C 0 o C 0 o C
1376 │ ╷ 0 1 0 3 0 1
1377 o ╷ B o 1 B o 3 B o 1 B
1378 ├─╯ 111 033 011
1379 o A o A o A o A"#
1380 );
1381 }
1382
1383 #[test]
1384 fn test_link_ids_follow_drawn_segments() {
1385 let mut shaper = GraphRowShaper::new()
1386 .with_line_id_allocator(build_line_id_allocator_from_rules(COLOR_RULE_PRESETS[0], 6));
1387 shaper.next_row_shape(
1388 "H",
1389 vec![
1390 Ancestor::Parent("A"),
1391 Ancestor::Parent("B"),
1392 Ancestor::Parent("C"),
1393 ],
1394 );
1395 let row = shaper.next_row_shape("A", vec![Ancestor::Parent("C"), Ancestor::Parent("D")]);
1396 let cell = &row.line_ids.as_ref().unwrap().link_line.as_ref().unwrap()[1];
1397 assert_eq!(cell.vertical, ids([1]));
1398 assert_eq!(cell.horizontal, ids([2]));
1399 let renderers: Vec<Box<dyn PrefixLineRenderer<&str>>> = vec![
1400 Box::new(BoxDrawingPrefixLineRenderer::<Curved>::new()),
1401 Box::new(crate::pipeline::Ascii::new()),
1402 ];
1403 for mut renderer in renderers {
1404 let prefixes = renderer.next_prefix_lines(&row);
1405 let link = prefixes
1406 .iter()
1407 .find(|line| line.kind == PrefixLineKind::Link)
1408 .unwrap();
1409 assert!(link.parts.iter().any(|(part, color)| {
1411 matches!(part, PrefixLinePart::Text(text) if text.contains("──") || text.contains("--"))
1412 && *color == Some(2)
1413 }));
1414 assert!(link.parts.iter().all(|(_, color)| *color != Some(1)));
1415 }
1416 }
1417
1418 #[test]
1419 fn test_text_line_ids() {
1420 use crate::pipeline::PrefixLinesToText;
1421
1422 let prefixes = vec![
1423 PrefixLine {
1424 parts: vec![
1425 (PrefixLinePart::Text("│ ".to_owned()), Some(0)),
1426 (PrefixLinePart::NodeGlyph, None),
1427 (PrefixLinePart::Text(" ╷ ".to_owned()), Some(1)),
1428 ],
1429 kind: PrefixLineKind::Node,
1430 },
1431 PrefixLine {
1432 parts: vec![(PrefixLinePart::Text("│ ".to_owned()), Some(0))],
1433 kind: PrefixLineKind::Term,
1434 },
1435 PrefixLine {
1436 parts: vec![(PrefixLinePart::Text("│ ".to_owned()), Some(0))],
1437 kind: PrefixLineKind::PostAncestry,
1438 },
1439 ];
1440 let mut renderer = PrefixLinesToText::new();
1441 let glyph = "\x1b[34m●\x1b[39m";
1442 let mut lines = renderer.next_lines(prefixes.clone(), false, glyph, "M", 0);
1443 assert_eq!(lines[0][1], (glyph.to_owned(), None));
1444 assert_eq!(lines[0].last().unwrap().1, None);
1445 let following = renderer.next_lines(
1446 vec![PrefixLine {
1447 parts: vec![(PrefixLinePart::NodeGlyph, None)],
1448 kind: PrefixLineKind::Node,
1449 }],
1450 false,
1451 "○",
1452 "N",
1453 0,
1454 );
1455 assert_eq!(following[0], vec![("│".to_owned(), Some(0))]);
1456 lines.extend(following);
1457 let render = |palette| render_text_lines(&lines, palette);
1458 let plain = render(None);
1459 assert_eq!(
1460 indent(&strip_sgr(&plain)),
1461 r#"
1462 │ ● ╷ M
1463 │
1464 │
1465 ○ N"#
1466 );
1467 let colored = render(Some(&COLORS));
1468 assert_eq!(strip_sgr(&colored), strip_sgr(&plain));
1469 assert_eq!(
1470 indent(&colored),
1471 r#"
1472 [31m│[39m [34m●[39m [32m╷[39m M
1473 [31m│[39m
1474 [31m│[39m
1475 ○ N"#
1476 );
1477 }
1478
1479 #[test]
1481 fn test_box_ansi_coloring() {
1482 use crate::pipeline::GraphTextRenderer;
1483
1484 let render = |palette| {
1485 let mut renderer = GraphTextRenderer::new::<BoxDrawingPrefixLineRenderer<Curved>>()
1486 .with_line_id_allocator(build_line_id_allocator_from_rules(
1487 COLOR_RULE_PRESETS[0],
1488 6,
1489 ));
1490 let mut out = renderer.next_lines(
1491 "H",
1492 vec![Ancestor::Parent("N"), Ancestor::Parent("P")],
1493 "o",
1494 "H\nfirst\nsecond",
1495 );
1496 out.extend(renderer.next_lines(
1497 "N",
1498 vec![Ancestor::Parent("P")],
1499 "o",
1500 "N\nmerge\nlast",
1501 ));
1502 out.extend(renderer.next_lines("P", vec![], "o", "P"));
1503 render_text_lines(&out, palette)
1504 };
1505 let plain = render(None);
1506 assert_eq!(
1507 indent(&plain),
1508 r#"
1509 o H
1510 ├─╮ first
1511 │ │ second
1512 o │ N
1513 ├─╯ merge
1514 │ last
1515 o P"#
1516 );
1517 let colored = render(Some(&COLORS));
1518 assert_eq!(strip_sgr(&colored), plain);
1519 assert_eq!(
1520 indent(&colored),
1521 r#"
1522 o H
1523 [31m├[39m[32m─╮[39m first
1524 [31m│[39m [32m│[39m second
1525 o [32m│[39m N
1526 [32m├─╯[39m merge
1527 [32m│[39m last
1528 o P"#
1529 );
1530 let colored = render(Some(&["\x1b[35m", "\x1b[36m"]));
1531 assert_eq!(strip_sgr(&colored), plain);
1532 assert_eq!(
1533 indent(&colored),
1534 r#"
1535 o H
1536 [35m├[39m[36m─╮[39m first
1537 [35m│[39m [36m│[39m second
1538 o [36m│[39m N
1539 [36m├─╯[39m merge
1540 [36m│[39m last
1541 o P"#
1542 );
1543 }
1544
1545 #[test]
1546 fn test_ascii_junction_ids() {
1547 use crate::pipeline::Ascii;
1548 use crate::pipeline::AsciiLarge;
1549 use crate::test_fixtures;
1550
1551 let small = render_fixture_ids::<Ascii>(
1552 &test_fixtures::SPLIT_PARENTS,
1553 build_line_id_allocator_from_rules(COLOR_RULE_PRESETS[0], 6),
1554 );
1555 assert_eq!(
1556 indent(&small),
1557 r#"
1558 o E
1559 1131210
1560 1 3 2 0
1561 1 o 2 0 D
1562 11 22 0
1563 1 2 0
1564 1 o 0 C
1565 1 00
1566 o 0 B
1567 00000
1568 o A"#
1569 );
1570 let large = render_fixture_ids::<AsciiLarge>(
1571 &test_fixtures::SPLIT_PARENTS,
1572 build_line_id_allocator_from_rules(COLOR_RULE_PRESETS[0], 6),
1573 );
1574 assert_eq!(
1575 indent(&large),
1576 r#"
1577 o E
1578 11111110
1579 1 3 2 0
1580 1 3 2 0
1581 1 o 2 0 D
1582 1 1 2 2 0
1583 11 22 0
1584 1 2 0
1585 1 o 0 C
1586 1 0 0
1587 1 00
1588 o 0 B
1589 0 0000
1590 00
1591 o A"#
1592 );
1593 }
1594
1595 #[test]
1596 fn test_ascii_ansi_coloring() {
1597 use crate::pipeline::Ascii;
1598 use crate::pipeline::AsciiLarge;
1599 use crate::pipeline::GraphTextRenderer;
1600
1601 let render = |large, palette| {
1602 let prefix: Box<dyn PrefixLineRenderer<&str> + Send + Sync> = if large {
1603 Box::new(AsciiLarge::new())
1604 } else {
1605 Box::new(Ascii::new())
1606 };
1607 let mut renderer = GraphTextRenderer::with_prefix_lines(prefix).with_line_id_allocator(
1608 build_line_id_allocator_from_rules(COLOR_RULE_PRESETS[0], 6),
1609 );
1610 let mut out = renderer.next_lines(
1611 "H",
1612 vec![Ancestor::Parent("N"), Ancestor::Parent("P")],
1613 "o",
1614 "H\nfirst\nsecond",
1615 );
1616 out.extend(renderer.next_lines(
1617 "N",
1618 vec![Ancestor::Parent("P")],
1619 "o",
1620 "N\nmerge\nlast",
1621 ));
1622 out.extend(renderer.next_lines("P", vec![], "o", "P"));
1623 render_text_lines(&out, palette)
1624 };
1625 let plain = render(false, None);
1626 assert_eq!(
1627 indent(&plain),
1628 r#"
1629 o H
1630 |\ first
1631 | | second
1632 o | N
1633 |/ merge
1634 | last
1635 o P"#
1636 );
1637 let colored = render(false, Some(&COLORS));
1638 assert_eq!(strip_sgr(&colored), plain);
1639 assert_eq!(
1640 indent(&colored),
1641 r#"
1642 o H
1643 [31m|[39m[32m\[39m first
1644 [31m|[39m [32m|[39m second
1645 o [32m|[39m N
1646 [32m|/[39m merge
1647 [32m|[39m last
1648 o P"#
1649 );
1650 let plain = render(true, None);
1651 assert_eq!(
1652 indent(&plain),
1653 r#"
1654 o H
1655 |\ first
1656 | \ second
1657 o | N
1658 | / merge
1659 |/ last
1660 o P"#
1661 );
1662 let colored = render(true, Some(&COLORS));
1663 assert_eq!(strip_sgr(&colored), plain);
1664 assert_eq!(
1665 indent(&colored),
1666 r#"
1667 o H
1668 [31m|[39m[32m\[39m first
1669 [31m|[39m [32m\[39m second
1670 o [32m|[39m N
1671 [32m|[39m [32m/[39m merge
1672 [32m|/[39m last
1673 o P"#
1674 );
1675 }
1676
1677 #[test]
1678 fn test_prefix_coloring_layout() {
1679 use crate::pipeline::PrefixLinesToText;
1680 use crate::pipeline::row_shape_to_prefix_lines::box_drawing::DecGraphics;
1681 use crate::pipeline::types::DashStyle;
1682 use crate::pipeline::types::GraphRowShapeOptions;
1683 use crate::pipeline::types::GraphRowShapeStyle;
1684 use crate::pipeline::types::LinkLinePlacement;
1685
1686 for dash_style in [DashStyle::Persistent, DashStyle::Once] {
1687 for column_spacing in [0, 3] {
1688 for placement in [LinkLinePlacement::Top, LinkLinePlacement::Bottom] {
1689 let options = GraphRowShapeOptions {
1690 graph_row_shape_style: GraphRowShapeStyle {
1691 dash_style,
1692 column_spacing,
1693 ..Default::default()
1694 },
1695 ..Default::default()
1696 };
1697 let mut shaper = GraphRowShaper::with_options(options).with_line_id_allocator(
1698 build_line_id_allocator_from_rules(COLOR_RULE_PRESETS[0], 6),
1699 );
1700 shaper.reserve("R");
1701 type PrefixRenderer = Box<dyn PrefixLineRenderer<&'static str>>;
1702 let prefixes: Vec<PrefixRenderer> = vec![
1703 Box::new(BoxDrawingPrefixLineRenderer::<Curved>::new()),
1704 Box::new(
1705 BoxDrawingPrefixLineRenderer::<Curved>::new().with_square_glyphs(),
1706 ),
1707 Box::new(BoxDrawingPrefixLineRenderer::<DecGraphics>::new()),
1708 Box::new(crate::pipeline::Ascii::new()),
1709 Box::new(crate::pipeline::AsciiLarge::new()),
1710 ];
1711 let mut renderers: Vec<_> = prefixes
1712 .into_iter()
1713 .map(|prefix| {
1714 (
1715 prefix,
1716 PrefixLinesToText::new().with_link_line_placement(placement),
1717 PrefixLinesToText::new().with_link_line_placement(placement),
1718 )
1719 })
1720 .collect();
1721 for (node, parents) in [
1722 ("H", vec![Ancestor::Parent("N"), Ancestor::Parent("P")]),
1723 ("N", vec![Ancestor::Ancestor("R"), Ancestor::Anonymous]),
1724 ("P", vec![Ancestor::Parent("R")]),
1725 ("R", vec![]),
1726 ] {
1727 let row = shaper.next_row_shape(node, parents);
1728 let mut untracked = row.clone();
1729 untracked.line_ids = None;
1730 for (prefix, plain, colored) in &mut renderers {
1731 let expected = prefix.next_prefix_lines(&untracked);
1732 let actual = prefix.next_prefix_lines(&row);
1733 assert_eq!(
1734 actual.iter().map(|line| line.kind).collect::<Vec<_>>(),
1735 expected.iter().map(|line| line.kind).collect::<Vec<_>>(),
1736 );
1737 for (part, id) in actual.iter().flat_map(|line| &line.parts) {
1738 match part {
1739 PrefixLinePart::NodeGlyph => assert!(id.is_none()),
1740 PrefixLinePart::Text(text) => {
1741 assert!(!text.contains("\x1b["));
1742 if id.is_some() {
1743 assert_eq!(text.trim_matches(' '), text);
1744 }
1745 }
1746 }
1747 }
1748 let message = "commit\n1\n2\n3\n4\n5";
1749 let render_row = |lines| {
1750 PrefixLinesToText::new()
1751 .with_link_line_placement(placement)
1752 .next_text(lines, false, "●", message, 0)
1753 };
1754 assert_eq!(render_row(actual.clone()), render_row(expected));
1755 let plain_text =
1757 plain.next_text(actual.clone(), false, "●", message, 0);
1758 let structured = colored.next_lines(actual, false, "●", message, 0);
1759 let colored_text = render_text_lines(&structured, Some(&COLORS));
1760 assert_eq!(strip_sgr(&colored_text), plain_text);
1761 assert!(
1762 prefix
1763 .next_prefix_lines(&untracked)
1764 .iter()
1765 .flat_map(|line| &line.parts)
1766 .all(|(_, ids)| ids.is_none())
1767 );
1768 }
1769 }
1770 }
1771 }
1772 }
1773 }
1774}