//! A script brought in from another tool, read into a story: a Final Draft//! file's paragraphs ([`super::fdx::read`]) or a printed screenplay PDF's//! lines ([`pdf_elements`]) become the same list of elements, and the//! elements become a [`Doc`] whose scene bodies are the Fountain the writer//! keeps. Text in any script is kept as it is: a speaker whose name has no//! capitals (a caseless script, or a name written in lower case) is written//! with Fountain's `@`, never upper-cased.usesuper::fountain::{Doc, SceneDoc};usesuper::heading;/// One element of a script, in reading order.#[derive(Debug, Clone, PartialEq, Eq)]pubenumElement {Heading(String),/// A scene's one-line summary (Final Draft keeps one on its heading).Summary(String),Action(String),Centered(String),Character(String),Parenthetical(String),Dialogue(String),Transition(String),}/// Whether `name` would be read back as a speaker without `@`: it has/// cased letters and every one is a capital.fn reads_as_speaker(name: &str) -> bool {let core = name.split('(').next().unwrap_or(name);letmut cased = false;for c in core.chars() {if c.is_lowercase() {returnfalse; }if c.is_uppercase() { cased = true; } } cased}/// A title page's credit line, the author's name under it: a few words/// ending "by" ("Written by", "Screenplay by", "by").pub(crate) fn credit(line: &str) -> bool {let words: Vec<&str> = line.split_whitespace().collect(); (1..=3).contains(&words.len()) && words.last().is_some_and(|word| word.eq_ignore_ascii_case("by"))}fn one_line(text: &str) -> String { text.split_whitespace().collect::<Vec<_>>().join(" ")}/// The story the elements make: `title` and `author` on its title page,/// a scene at each heading (words before the first are a scene with no/// heading).pubfn doc_of(title: Option<&str>, author: Option<&str>, elements: &[Element]) -> Doc {letmut doc = Doc::default();ifletSome(title) = title.map(one_line).filter(|title| !title.is_empty()) { doc.title.push(("Title".into(), title)); }ifletSome(author) = author.map(one_line).filter(|author| !author.is_empty()) { doc.title.push(("Author".into(), author)); }// Each scene's blocks: a block is lines with no blank between them.letmut scenes: Vec<(SceneDoc, Vec<Vec<String>>)> = Vec::new();letmut speaking = false;for element in elements {if !matches!(element, Element::Heading(_)) && scenes.is_empty() { scenes.push((SceneDoc::default(), Vec::new())); }match element {Element::Heading(text) => { scenes.push((SceneDoc { heading: one_line(text), summary: None, body: String::new() }, Vec::new())); speaking = false;continue; } _ => {} }letSome((scene, blocks)) = scenes.last_mut() else { continue };match element {Element::Heading(_) => {}Element::Summary(text) => {let text = one_line(text);if !text.is_empty() { scene.summary = Some(text); } }Element::Action(text) => {let lines: Vec<String> = text.split('\n').map(str::trim_end).map(str::to_string).filter(|line| !line.trim().is_empty()).collect();if !lines.is_empty() { blocks.push(lines); } speaking = false; }Element::Centered(text) => {let text = one_line(text);if !text.is_empty() { blocks.push(vec![format!("> {text} <")]); } speaking = false; }Element::Transition(text) => {let text = one_line(text);if !text.is_empty() {// Fountain reads an upper-case line ending `TO:` as a cut; any other is forced.let plain = text.ends_with("TO:") && text == text.to_uppercase(); blocks.push(vec![if plain { text } else { format!("> {text}") }]); } speaking = false; }Element::Character(text) => {let name = one_line(text);if name.is_empty() {continue; } blocks.push(vec![if reads_as_speaker(&name) { name } else { format!("@{name}") }]); speaking = true; }Element::Parenthetical(text) | Element::Dialogue(text) => {letmut text = one_line(text);if text.is_empty() {continue; }if matches!(element, Element::Parenthetical(_)) && !text.starts_with('(') { text = format!("({})", text.trim_end_matches(')')); }if speaking {ifletSome(block) = blocks.last_mut() { block.push(text);continue; } }// Speech with nobody named before it stays as words in the scene. blocks.push(vec![text]); } } }for (mut scene, blocks) in scenes { scene.body = blocks.iter().map(|block| block.join("\n")).collect::<Vec<_>>().join("\n\n");if scene.heading.is_empty() && scene.body.is_empty() && scene.summary.is_none() {continue; } doc.scenes.push(scene); } doc}/// One printed line of a PDF page: its baseline from the top, font size,/// and its cells (runs of text with their left edge), in points.#[derive(Debug, Clone, PartialEq)]pubstructPrintedLine {pub y: f32,pub size: f32,pub cells: Vec<(f32, String)>,}/// A scene number printed in a margin: `12`, `12A`, `12.`, `A12`.fn scene_number(text: &str) -> bool {let text = text.trim().trim_end_matches('.'); !text.is_empty() && text.len() <= 6 && text.chars().any(|c| c.is_ascii_digit()) && text.chars().all(|c| c.is_ascii_alphanumeric())}fn furniture(text: &str) -> bool {let upper = text.trim().to_uppercase(); matches!(upper.as_str(), "(MORE)" | "(CONTINUED)" | "CONTINUED:" | "CONTINUED" | "(CONTINUED:)") || upper.starts_with("CONTINUED:")}fn without_contd(name: &str) -> String {letmut name = name.trim().to_string();for mark in ["(CONT'D)", "(CONT’D)", "(cont'd)", "(CONT.)", "(CONT)"] {ifletSome(at) = name.find(mark) { name.replace_range(at..at + mark.len(), ""); } } one_line(&name)}#[derive(Debug, Clone, Copy, PartialEq, Eq)]enumColumn {Margin,Dialogue,Parenthetical,Character,Right,}/// A printed screenplay's pages read into elements by where each line/// starts: the left margin (headings and action), the speech column, the/// aside column, the name column and the right (cuts), measured in/// characters of the page's own type from the most-used leftmost edge./// Scene numbers in the margins, page numbers, `(MORE)` and `CONTINUED`/// are left out; `(CONT'D)` is taken off a name. Returns the elements and/// the title page's title and author when the first page is one.pubfn pdf_elements(pages: &[Vec<PrintedLine>]) -> (Vec<Element>, Option<String>, Option<String>) {// Each line's own text, numbers in the margins taken off.letmut kept: Vec<Vec<(f32, f32, f32, String)>> = Vec::new(); // (x, y, size, text)// Whether each page's foot said `(MORE)`: its last speech goes on over the page.letmut more: Vec<bool> = Vec::new();for page in pages {letmut out = Vec::new(); more.push(false);let count = page.len();for (index, line) in page.iter().enumerate() {letmut cells: Vec<&(f32, String)> = line.cells.iter().filter(|(_, text)| !text.trim().is_empty()).collect();if cells.is_empty() {continue; }// A page number alone at the top or foot.if cells.len() == 1 && (index == 0 || index + 1 == count) && scene_number(&cells[0].1) && cells[0].1.trim().ends_with('.') {continue; }if cells.len() > 1 && scene_number(&cells[0].1) { cells.remove(0); }if cells.len() > 1 && cells.last().is_some_and(|(_, text)| scene_number(text)) { cells.pop(); }let text = cells.iter().map(|(_, text)| text.trim()).collect::<Vec<_>>().join(" ");if furniture(&text) {if text.trim().eq_ignore_ascii_case("(MORE)") { *more.last_mut().expect("pushed") = true; }continue; } out.push((cells[0].0, line.y, line.size.max(1.0), text)); } kept.push(out); }// The left margin: the leftmost edge many lines share.letmut edges: Vec<i32> = kept.iter().flatten().map(|(x, ..)| x.round() as i32).collect(); edges.sort_unstable();let total = edges.len();let floor = (total / 20).max(2).min(total.max(1));letmut margin = edges.first().copied().unwrap_or(0) as f32;letmut at = 0;while at < edges.len() {let near = edges.iter().filter(|edge| (**edge - edges[at]).abs() <= 3).count();if near >= floor { margin = edges[at] as f32;break; } at += 1; }let column = |x: f32, size: f32, text: &str| -> Column {let chars = (x - margin) / (size * 0.6);if chars < 5.0 {Column::Margin } elseif text.starts_with('(') && chars < 20.0 {Column::Parenthetical } elseif chars < 13.0 {Column::Dialogue } elseif chars < 19.0 {Column::Parenthetical } elseif chars < 32.0 {Column::Character } else {Column::Right } };// A title page: a first page with no heading, before pages with one.let heading_on = |page: &Vec<(f32, f32, f32, String)>| page.iter().any(|(x, _, size, text)| column(*x, *size, text) == Column::Margin && heading::is_heading(text));letmut title = None;letmut author = None;letmut first = 0;if kept.len() > 1 && !kept[0].is_empty() && !heading_on(&kept[0]) && kept[1..].iter().any(heading_on) {let page = &kept[0]; title = page.first().map(|(.., text)| text.clone());ifletSome(at) = page.iter().position(|(.., text)| credit(text)) { author = page.get(at + 1).map(|(.., text)| text.clone()); } first = 1; }letmut elements: Vec<Element> = Vec::new();// The element being gathered: its column and the last line's baseline.letmut open: Option<(Column, f32, f32)> = None;for (index, page) in kept.iter().enumerate().skip(first) {let more_before = index > 0 && more[index - 1];letmut previous_y: Option<f32> = None;for (x, y, size, text) in page {let col = column(*x, *size, text);let gap = previous_y.map(|before| y - before); previous_y = Some(*y);// Lines run on when they are in the same column with no blank line between.let runs_on = matches!(open, Some((open_col, _, open_size)) if open_col == col && gap.is_none_or(|gap| gap < open_size * 1.6)) && matches!(col, Column::Margin | Column::Dialogue | Column::Parenthetical) && !(col == Column::Margin && heading::is_heading(text));if runs_on {ifletSome(last) = elements.last_mut() {match last {// A printed line ends where the page's measure did, not where the writer's did.Element::Action(words) | Element::Dialogue(words) | Element::Parenthetical(words) => { words.push(' '); words.push_str(text); } _ => {} }continue; } }let element = match col {Column::Marginif heading::is_heading(text) => Element::Heading(text.clone()),Column::Margin => Element::Action(text.clone()),Column::Dialogue => Element::Dialogue(text.clone()),Column::Parenthetical => Element::Parenthetical(text.clone()),Column::Characterif text.trim_end().ends_with("TO:") => Element::Transition(text.clone()),Column::Character => Element::Character(without_contd(text)),Column::Right => Element::Transition(text.clone()), };// A name continued over a page break is the same speech: no second name.iflet (Element::Character(name), Some(Element::Dialogue(_) | Element::Parenthetical(_))) = (&element, elements.last()) {let speaker = elements.iter().rev().find_map(|element| match element {Element::Character(name) => Some(name.clone()),Element::Action(_) | Element::Heading(_) | Element::Transition(_) => Some(String::new()), _ => None, });if gap.is_none() && more_before && speaker.as_deref() == Some(name.as_str()) { open = Some((col, *y, *size));continue; } } open = Some((col, *y, *size)); elements.push(element); }// A page break ends action, so a heading on the next page starts afresh; speech carries on.ifletSome((col, y, size)) = open {if col == Column::Margin { open = None; } else { open = Some((col, y, size)); } } } (elements, title, author)}#[cfg(test)]#[path = "script_in_tests.rs"]mod tests;