//! Deciding which column each commit sits in, and what lines cross each row. //! //! Columns are held by *reservations*: when a commit is placed, it reserves a //! column for each of its parents, and whichever parent eventually arrives //! takes that column over. The first parent inherits the commit's own column, //! which is what keeps a branch running straight down the screen instead of //! wandering sideways. Other parents get a column of their own, so a merge //! visibly forks. //! //! A column is freed the moment its reservation is taken up, and free columns //! are reused left-first, so the graph stays narrow. Columns are never shifted, //! only reused — that keeps every line that is merely passing through a row //! perfectly vertical, and means a row can be drawn knowing nothing about the //! rows around it. //! //! This is a simpler scheme than the one described in Pierre Vigier's article //! (see `NOTICE.md`), which additionally computes a set of forbidden columns to //! avoid edges crossing where a cheap alternative exists. That refinement would //! slot in at [`ColumnLayout::choose_column`]; it improves how the graph looks //! but is not needed for it to be correct. Tracked, along with the settings //! surface it wants to be switchable from, in //! . use gix::ObjectId; use serde::Serialize; /// How many distinct lane colours the frontend cycles through. The engine only /// ever emits an index — the actual colours are a styling concern. const LANE_COUNT: u16 = 10; /// What a commit looks like on its row. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub enum DotKind { /// Exactly one parent. Normal, /// More than one parent. Merge, /// No parents — the beginning of a history. Root, } impl DotKind { fn for_parents(parents: &[ObjectId]) -> Self { match parents.len() { 0 => Self::Root, 1 => Self::Normal, _ => Self::Merge, } } } /// How a line relates to the commit on the row it crosses. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub enum EdgeKind { /// Comes down from a child and ends at this commit's dot. ToCommit, /// Leaves this commit's dot heading down towards a parent. FromCommit, /// Another branch passing by, untouched by this commit. Through, } /// One line segment crossing a single row. /// /// Columns are measured at the row's edges: `from_column` where the line enters /// at the top, `to_column` where it leaves at the bottom. A `Through` segment /// always has both the same, so it draws as a straight vertical line. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct Edge { pub from_column: u16, pub to_column: u16, pub lane: u16, pub kind: EdgeKind, } /// Where a commit ended up, and what its row looks like. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct Placement { pub column: u16, pub lane: u16, pub dot: DotKind, pub edges: Vec, /// How many columns are in use across this row, so the frontend knows how /// wide to draw without measuring anything. pub width: u16, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct Reservation { /// The commit expected to take this column over. id: ObjectId, lane: u16, } #[derive(Debug, Default)] pub(crate) struct ColumnLayout { columns: Vec>, next_lane: u16, } impl ColumnLayout { pub(crate) fn new() -> Self { Self::default() } /// Place a commit and describe its row. pub(crate) fn place(&mut self, id: &ObjectId, parents: &[ObjectId]) -> Placement { // Every line that exists as the row begins. Done first, because // reserving columns for parents changes the picture underneath. let mut edges = self.lines_entering_the_row(id); let (column, lane) = self.choose_column(id); // Whichever column was chosen, every other reservation for this commit // is now satisfied and released; its edge was already recorded above. self.release_reservations_for(id); for (position, parent) in parents.iter().enumerate() { let is_first_parent = position == 0; let target = self.reserve_for_parent(parent, column, lane, is_first_parent); edges.push(Edge { from_column: column, to_column: target, lane: self.columns[usize::from(target)] .expect("just reserved") .lane, kind: EdgeKind::FromCommit, }); } self.trim_trailing_free_columns(); // Every edge recorded before the commit was placed pointed at a column // that was not yet known; fix up the ones that end at the dot. for edge in &mut edges { if edge.kind == EdgeKind::ToCommit { edge.to_column = column; } } Placement { column, lane, dot: DotKind::for_parents(parents), edges, width: u16::try_from(self.columns.len()) .unwrap_or(u16::MAX) .max(column + 1), } } /// The lines already in flight as this row starts: ones ending at this /// commit, and ones merely passing by. fn lines_entering_the_row(&self, id: &ObjectId) -> Vec { self.columns .iter() .enumerate() .filter_map(|(index, reservation)| { let reservation = (*reservation)?; let column = u16::try_from(index).ok()?; Some(if reservation.id == *id { Edge { from_column: column, // Filled in once the commit's own column is known. to_column: column, lane: reservation.lane, kind: EdgeKind::ToCommit, } } else { Edge { from_column: column, to_column: column, lane: reservation.lane, kind: EdgeKind::Through, } }) }) .collect() } /// Take the leftmost column reserved for this commit, or a free one. /// /// Taking the leftmost keeps a branch that was reserved from several places /// as far left as it can be, which is what stops long-lived branches from /// drifting rightwards over time. fn choose_column(&mut self, id: &ObjectId) -> (u16, u16) { let reserved = self.columns.iter().enumerate().find_map(|(index, slot)| { let slot = (*slot)?; (slot.id == *id).then_some((index, slot.lane)) }); if let Some((index, lane)) = reserved { return (u16::try_from(index).unwrap_or(u16::MAX), lane); } // Nothing was expecting this commit, so it starts a new strand: a ref // tip, or the first commit of an unmerged branch. let lane = self.allocate_lane(); (self.claim_free_column(), lane) } /// Reserve a column for a parent and return where it went. fn reserve_for_parent( &mut self, parent: &ObjectId, commit_column: u16, commit_lane: u16, is_first_parent: bool, ) -> u16 { // Another child already reserved a column for this parent, so route // there rather than opening a second column for the same commit. let existing = self .columns .iter() .position(|slot| slot.is_some_and(|reservation| reservation.id == *parent)); if let Some(index) = existing { return u16::try_from(index).unwrap_or(u16::MAX); } // The first parent continues this commit's line, so it inherits both // the column and the colour. That is what makes branches straight. let (column, lane) = if is_first_parent { (commit_column, commit_lane) } else { (self.claim_free_column(), self.allocate_lane()) }; let index = usize::from(column); if index >= self.columns.len() { self.columns.resize(index + 1, None); } self.columns[index] = Some(Reservation { id: *parent, lane }); column } fn release_reservations_for(&mut self, id: &ObjectId) { for slot in &mut self.columns { if slot.is_some_and(|reservation| reservation.id == *id) { *slot = None; } } } /// The leftmost unused column, growing the row only when it has to. fn claim_free_column(&mut self) -> u16 { match self.columns.iter().position(Option::is_none) { Some(index) => u16::try_from(index).unwrap_or(u16::MAX), None => { self.columns.push(None); u16::try_from(self.columns.len() - 1).unwrap_or(u16::MAX) } } } fn allocate_lane(&mut self) -> u16 { let lane = self.next_lane; self.next_lane = (self.next_lane + 1) % LANE_COUNT; lane } /// Keep the row as narrow as the content requires. Only trailing columns /// are dropped, so no existing column ever moves. fn trim_trailing_free_columns(&mut self) { while self.columns.last().is_some_and(Option::is_none) { self.columns.pop(); } } } #[cfg(test)] mod tests { use super::*; fn id(byte: u8) -> ObjectId { ObjectId::Sha1([byte; 20]) } /// Place commits in the given order, each with the given parents. fn lay_out(history: &[(u8, &[u8])]) -> Vec { let mut layout = ColumnLayout::new(); history .iter() .map(|(commit, parents)| { let parents: Vec = parents.iter().copied().map(id).collect(); layout.place(&id(*commit), &parents) }) .collect() } #[test] fn a_linear_history_stays_in_one_column() { let rows = lay_out(&[(3, &[2]), (2, &[1]), (1, &[])]); assert!(rows.iter().all(|row| row.column == 0)); assert!(rows.iter().all(|row| row.width == 1)); } #[test] fn a_linear_history_keeps_one_colour() { let rows = lay_out(&[(3, &[2]), (2, &[1]), (1, &[])]); let first = rows[0].lane; assert!( rows.iter().all(|row| row.lane == first), "a branch running straight down should not change colour" ); } #[test] fn dots_reflect_the_number_of_parents() { let rows = lay_out(&[(4, &[2, 3]), (3, &[1]), (2, &[1]), (1, &[])]); assert_eq!(rows[0].dot, DotKind::Merge); assert_eq!(rows[1].dot, DotKind::Normal); assert_eq!(rows[3].dot, DotKind::Root); } #[test] fn a_merge_sends_its_second_parent_to_a_new_column() { let rows = lay_out(&[(4, &[2, 3]), (3, &[1]), (2, &[1]), (1, &[])]); let merge = &rows[0]; assert_eq!(merge.column, 0); let leaving: Vec = merge .edges .iter() .filter(|edge| edge.kind == EdgeKind::FromCommit) .map(|edge| edge.to_column) .collect(); assert_eq!( leaving, vec![0, 1], "the first parent continues the column, the second forks right" ); } #[test] fn the_first_parent_inherits_the_colour_and_the_second_does_not() { let rows = lay_out(&[(4, &[2, 3]), (3, &[1]), (2, &[1]), (1, &[])]); let merge = &rows[0]; let leaving: Vec<&Edge> = merge .edges .iter() .filter(|edge| edge.kind == EdgeKind::FromCommit) .collect(); assert_eq!(leaving[0].lane, merge.lane, "the branch continues"); assert_ne!(leaving[1].lane, merge.lane, "the fork is a new strand"); } #[test] fn a_column_is_reused_once_its_branch_has_ended() { // The side branch occupies column 1, then merges away; a later // unrelated tip should take column 1 back rather than open column 2. let rows = lay_out(&[ (5, &[2, 3]), // merge, reserves 0 for 2 and 1 for 3 (3, &[1]), // side branch, column 1, reserves 1 for 1 (2, &[1]), // main branch, column 0, routes to the existing 1 (1, &[]), // shared parent, frees everything (9, &[]), // an unrelated tip ]); assert_eq!(rows[4].column, 0, "a freed column should be reused"); assert_eq!(rows[4].width, 1); } #[test] fn two_children_of_one_parent_route_to_the_same_column() { // Both 3 and 2 have parent 1. The second one to be placed must route // into the column already reserved for 1, not open another. let rows = lay_out(&[(3, &[1]), (2, &[1]), (1, &[])]); let target = |row: &Placement| { row.edges .iter() .find(|edge| edge.kind == EdgeKind::FromCommit) .expect("should point at its parent") .to_column }; assert_eq!( target(&rows[0]), target(&rows[1]), "one parent means one column" ); assert_eq!(rows[2].column, target(&rows[0])); } #[test] fn lines_passing_a_row_are_vertical() { let rows = lay_out(&[(5, &[2, 3]), (3, &[1]), (2, &[1]), (1, &[])]); for row in &rows { for edge in &row.edges { if edge.kind == EdgeKind::Through { assert_eq!( edge.from_column, edge.to_column, "a line merely passing a row must not bend" ); } } } } #[test] fn incoming_lines_end_at_the_commits_dot() { // Row 1 is the side branch in column 1; the merge above reserved it. let rows = lay_out(&[(5, &[2, 3]), (3, &[1]), (2, &[1]), (1, &[])]); for row in &rows { for edge in &row.edges { if edge.kind == EdgeKind::ToCommit { assert_eq!( edge.to_column, row.column, "a line arriving at a commit must end at its dot" ); } } } } #[test] fn a_root_commit_leaves_nothing_behind() { let rows = lay_out(&[(1, &[])]); assert!( rows[0] .edges .iter() .all(|edge| edge.kind != EdgeKind::FromCommit), "a root has no parents to point at" ); assert_eq!(rows[0].width, 1); } #[test] fn an_octopus_merge_forks_once_per_extra_parent() { let rows = lay_out(&[(5, &[2, 3, 4]), (4, &[1]), (3, &[1]), (2, &[1]), (1, &[])]); let leaving: Vec = rows[0] .edges .iter() .filter(|edge| edge.kind == EdgeKind::FromCommit) .map(|edge| edge.to_column) .collect(); assert_eq!(leaving, vec![0, 1, 2]); assert_eq!(rows[0].width, 3); } #[test] fn the_width_covers_every_column_the_row_uses() { let rows = lay_out(&[(5, &[2, 3, 4]), (4, &[1]), (3, &[1]), (2, &[1]), (1, &[])]); for row in &rows { assert!(row.width > row.column, "the dot must fit inside the width"); for edge in &row.edges { assert!( edge.from_column < row.width && edge.to_column < row.width, "every edge must fit inside the width" ); } } } #[test] fn lanes_stay_within_the_palette() { // More strands than there are lane colours, so the palette wraps. let history: Vec<(u8, &[u8])> = (1..=25u8).map(|commit| (commit, &[] as &[u8])).collect(); for row in lay_out(&history) { assert!( row.lane < LANE_COUNT, "lane {} is off the palette", row.lane ); } } }