//! Lines keep who they are. A scene's lines are rows with ids of their own; //! a body written whole (an assistant's rewrite, a Fountain file, a rename) //! is laid over the rows the scene holds so that a line left as it was, or //! edited where it stands, keeps its id, and only a line that is truly new //! takes one ([`reconcile`]). A draft is compared with the story now by the //! same ids, never by position ([`changes`]). use serde::{Deserialize, Serialize}; use super::beats::{Beat, BeatKind}; /// A line the scene holds: its id and what it says. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Held { pub id: String, #[serde(flatten)] pub beat: Beat, } /// A line of the scene as it is to stand: the id of the row it keeps, or /// none for a new row. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Placed { pub id: Option, #[serde(flatten)] pub beat: Beat, } /// The rows the new lines are laid over, and the ids that go. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Laid { pub lines: Vec, pub removed: Vec, } fn same_beat(a: &Beat, b: &Beat) -> bool { a.kind == b.kind && a.text.trim() == b.text.trim() && a.form == b.form && who_of(a) == who_of(b) && a.aside == b.aside } fn who_of(beat: &Beat) -> Option { beat.who.as_deref().map(|who| who.trim().to_lowercase()) } /// Close enough to be one line edited: the same kind and, for speech, the /// same speaker, or the same words with a different speaker. fn edited(a: &Beat, b: &Beat) -> bool { if a.kind != b.kind { return false; } match a.kind { BeatKind::Dialogue | BeatKind::Enters => who_of(a) == who_of(b) || a.text.trim() == b.text.trim(), _ => true, } } /// The new lines laid over the held ones: an unchanged line keeps its row /// (longest common run, in order); between two kept lines, the lines left on /// each side are paired in order where one reads as the other edited; every /// other new line is new and every other held row goes. pub fn reconcile(held: &[Held], new: &[Beat]) -> Laid { let (n, m) = (held.len(), new.len()); // Longest common subsequence by an unchanged line. let mut run = vec![vec![0u32; m + 1]; n + 1]; for i in (0..n).rev() { for j in (0..m).rev() { run[i][j] = if same_beat(&held[i].beat, &new[j]) { run[i + 1][j + 1] + 1 } else { run[i + 1][j].max(run[i][j + 1]) }; } } let mut pairs: Vec<(usize, usize)> = Vec::new(); let (mut i, mut j) = (0, 0); while i < n && j < m { if same_beat(&held[i].beat, &new[j]) { pairs.push((i, j)); i += 1; j += 1; } else if run[i + 1][j] >= run[i][j + 1] { i += 1; } else { j += 1; } } let mut kept: Vec> = vec![None; m]; let mut used = vec![false; n]; for (i, j) in &pairs { kept[*j] = Some(*i); used[*i] = true; } // A line moved, unchanged, to another place keeps its row too. for j in 0..m { if kept[j].is_none() { if let Some(i) = (0..n).find(|i| !used[*i] && same_beat(&held[*i].beat, &new[j])) { kept[j] = Some(i); used[i] = true; } } } // The gaps between kept lines: pair what is left in order, as edits. let mut bounds: Vec<(usize, usize)> = vec![(0, 0)]; bounds.extend(pairs.iter().map(|(i, j)| (i + 1, j + 1))); let mut ends: Vec<(usize, usize)> = pairs.clone(); ends.push((n, m)); for ((i0, j0), (i1, j1)) in bounds.into_iter().zip(ends) { let mut olds: Vec = (i0..i1).filter(|i| !used[*i]).collect(); for j in j0..j1 { if kept[j].is_some() { continue; } if let Some(at) = olds.iter().position(|i| edited(&held[*i].beat, &new[j])) { let i = olds.remove(at); // Earlier leftovers are passed over: their lines went. kept[j] = Some(i); used[i] = true; olds.retain(|other| *other > i); } } } Laid { lines: new.iter().zip(&kept).map(|(beat, at)| Placed { id: at.map(|i| held[i].id.clone()), beat: beat.clone() }).collect(), removed: held.iter().zip(&used).filter(|(_, used)| !**used).map(|(row, _)| row.id.clone()).collect(), } } // ── a draft and now ───────────────────────────────────────────────────────── /// A scene as a draft holds it, or as it stands now. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct SceneAt { pub scene: String, #[serde(default)] pub heading: String, #[serde(default)] pub summary: Option, #[serde(default)] pub lines: Vec, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Change { Added, Removed, Moved, Changed, Same, } #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct LineCount { pub added: usize, pub removed: usize, pub changed: usize, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SceneChange { pub scene: String, pub number_then: Option, pub number_now: Option, pub change: Change, #[serde(skip_serializing_if = "Option::is_none")] pub heading_then: Option, #[serde(skip_serializing_if = "Option::is_none")] pub heading_now: Option, pub lines: LineCount, } #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Since { pub scenes_added: usize, pub scenes_removed: usize, pub scenes_changed: usize, pub scenes_moved: usize, pub lines_added: usize, pub lines_removed: usize, pub lines_changed: usize, } #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Changes { pub scenes: Vec, pub since: Since, } fn line_count(then: &[Held], now: &[Held]) -> LineCount { let mut count = LineCount::default(); for line in now { match then.iter().find(|old| old.id == line.id) { None => count.added += 1, Some(old) if !same_beat(&old.beat, &line.beat) => count.changed += 1, Some(_) => {} } } count.removed = then.iter().filter(|old| !now.iter().any(|line| line.id == old.id)).count(); count } /// What changed from a draft to now, scene by scene in today's order (a /// scene gone since stands where it stood then), by the scenes' and lines' /// ids. A scene is `moved` when the scenes it stood among stand in another /// order around it, and nothing in it changed. pub fn changes(then: &[SceneAt], now: &[SceneAt]) -> Changes { let mut out = Changes::default(); let both_then: Vec<&str> = then.iter().map(|s| s.scene.as_str()).filter(|id| now.iter().any(|s| s.scene == *id)).collect(); let both_now: Vec<&str> = now.iter().map(|s| s.scene.as_str()).filter(|id| then.iter().any(|s| s.scene == *id)).collect(); // The scenes kept in their order: the longest run in both orders. let (a, b) = (both_then.len(), both_now.len()); let mut run = vec![vec![0u32; b + 1]; a + 1]; for i in (0..a).rev() { for j in (0..b).rev() { run[i][j] = if both_then[i] == both_now[j] { run[i + 1][j + 1] + 1 } else { run[i + 1][j].max(run[i][j + 1]) }; } } let mut steady: Vec<&str> = Vec::new(); let (mut i, mut j) = (0, 0); while i < a && j < b { if both_then[i] == both_now[j] { steady.push(both_then[i]); i += 1; j += 1; } else if run[i + 1][j] >= run[i][j + 1] { i += 1; } else { j += 1; } } let mut push = |change: SceneChange, out: &mut Changes| { match change.change { Change::Added => out.since.scenes_added += 1, Change::Removed => out.since.scenes_removed += 1, Change::Changed => out.since.scenes_changed += 1, Change::Moved => out.since.scenes_moved += 1, Change::Same => {} } out.since.lines_added += change.lines.added; out.since.lines_removed += change.lines.removed; out.since.lines_changed += change.lines.changed; out.scenes.push(change); }; let gone = |at_then: usize| then.get(at_then).filter(|old| !now.iter().any(|s| s.scene == old.scene)); let mut next_then = 0usize; for (at_now, scene) in now.iter().enumerate() { let found = then.iter().position(|old| old.scene == scene.scene); // Scenes gone since that stood before this one then. if let Some(at_then) = found { while next_then < at_then { if let Some(old) = gone(next_then) { push(removed(old, next_then), &mut out); } next_then += 1; } next_then = next_then.max(at_then + 1); } let change = match found { None => SceneChange { scene: scene.scene.clone(), number_then: None, number_now: Some(at_now + 1), change: Change::Added, heading_then: None, heading_now: Some(scene.heading.clone()), lines: LineCount { added: scene.lines.len(), ..LineCount::default() }, }, Some(at_then) => { let old = &then[at_then]; let lines = line_count(&old.lines, &scene.lines); let headed = old.heading.trim() != scene.heading.trim() || old.summary != scene.summary; let order_moved = old.lines.iter().filter(|l| scene.lines.iter().any(|n| n.id == l.id)).map(|l| &l.id).ne(scene.lines.iter().filter(|l| old.lines.iter().any(|o| o.id == l.id)).map(|l| &l.id)); let changed = headed || lines != LineCount::default() || order_moved; let moved = !steady.contains(&scene.scene.as_str()); SceneChange { scene: scene.scene.clone(), number_then: Some(at_then + 1), number_now: Some(at_now + 1), change: if changed { Change::Changed } else if moved { Change::Moved } else { Change::Same }, heading_then: headed.then(|| old.heading.clone()), heading_now: headed.then(|| scene.heading.clone()), lines, } } }; push(change, &mut out); } while next_then < then.len() { if let Some(old) = gone(next_then) { push(removed(old, next_then), &mut out); } next_then += 1; } out } fn removed(old: &SceneAt, at_then: usize) -> SceneChange { SceneChange { scene: old.scene.clone(), number_then: Some(at_then + 1), number_now: None, change: Change::Removed, heading_then: Some(old.heading.clone()), heading_now: None, lines: LineCount { removed: old.lines.len(), ..LineCount::default() }, } } #[cfg(test)] #[path = "identity_tests.rs"] mod tests;