Cotton code
291 lines · 13.9 KB · RustRaw
//! A whole story as a Final Draft file (`.fdx`), the XML the common desktop//! screenwriting tool opens: a title page, then each scene's heading and its//! body's elements as paragraphs (Scene Heading, Action, Character,//! Parenthetical, Dialogue, Transition). Notes to self stay out. Text in any//! script is written as it is, only XML's own marks escaped.use quick_xml::events::Event;use quick_xml::Reader;use super::fountain::Doc;use super::lines::{lines, unmarked, Kind};use super::script_in::{doc_of, Element};fn escaped(text: &str) -> String {    let mut out = String::with_capacity(text.len());    for c in text.chars() {        match c {            '&' => out.push_str("&amp;"),            '<' => out.push_str("&lt;"),            '>' => out.push_str("&gt;"),            '"' => out.push_str("&quot;"),            // XML 1.0 takes no control characters but tab.            c if (c as u32) < 0x20 && c != '\t' => {}            c => out.push(c),        }    }    out}fn paragraph(out: &mut String, kind: &str, text: &str, centred: bool) {    let align = if centred { " Alignment=\"Center\"" } else { "" };    out.push_str(&format!("    <Paragraph Type=\"{kind}\"{align}>\n      <Text>{}</Text>\n    </Paragraph>\n", escaped(text)));}/// The story as a Final Draft document. `names` are the story's characters,/// so a speaker in a script without capitals is read as one.pub fn write(doc: &Doc, names: &[String]) -> String {    let mut out = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n<FinalDraft DocumentType=\"Script\" Template=\"No\" Version=\"5\">\n  <Content>\n");    for scene in &doc.scenes {        match scene.summary.as_deref().map(str::trim).filter(|s| !s.is_empty()) {            // A scene's one-line summary is Final Draft's own scene summary, never printed.            Some(summary) => out.push_str(&format!(                "    <Paragraph Type=\"Scene Heading\">\n      <SceneProperties Title=\"\">\n        <Summary>\n          <Paragraph>\n            <Text>{}</Text>\n          </Paragraph>\n        </Summary>\n      </SceneProperties>\n      <Text>{}</Text>\n    </Paragraph>\n",                escaped(summary),                escaped(scene.heading.trim())            )),            None => paragraph(&mut out, "Scene Heading", scene.heading.trim(), false),        }        let read = lines(&scene.body, names);        let mut at = 0;        while at < read.len() {            let line = &read[at];            let text = unmarked(line.kind, &line.text);            match line.kind {                Kind::Blank | Kind::Note => {}                Kind::Character => paragraph(&mut out, "Character", &text, false),                Kind::Parenthetical => paragraph(&mut out, "Parenthetical", &format!("({})", text.trim_start_matches('(').trim_end_matches(')')), false),                Kind::Transition => paragraph(&mut out, "Transition", &text, false),                Kind::Heading => paragraph(&mut out, "Scene Heading", &text, false),                Kind::Centered => paragraph(&mut out, "Action", &text, true),                Kind::Action | Kind::Dialogue => {                    // A run of the same element is one paragraph.                    let mut said = vec![text];                    while read.get(at + 1).is_some_and(|next| next.kind == line.kind) {                        at += 1;                        said.push(unmarked(line.kind, &read[at].text));                    }                    paragraph(&mut out, if line.kind == Kind::Action { "Action" } else { "Dialogue" }, &said.join(" "), false);                }            }            at += 1;        }    }    out.push_str("  </Content>\n  <TitlePage>\n    <Content>\n");    for (key, value) in &doc.title {        let key = key.to_lowercase();        if !matches!(key.as_str(), "title" | "credit" | "author" | "authors" | "draft date") {            continue;        }        for line in value.lines().map(str::trim).filter(|line| !line.is_empty()) {            out.push_str(&format!("      <Paragraph Alignment=\"Center\">\n        <Text>{}</Text>\n      </Paragraph>\n", escaped(line)));        }    }    out.push_str("    </Content>\n  </TitlePage>\n</FinalDraft>\n");    out}/// One `<Paragraph>` being read: its type, where it stands, its text and/// (a scene heading's) summary.struct Open {    kind: String,    centred: bool,    in_summary: bool,    in_title_page: bool,    text: String,    summary: Option<String>,}/// A Final Draft document read into a story: its paragraphs as elements/// (Scene Heading, Action, Character, Parenthetical, Dialogue, Transition;/// a Shot or General paragraph is action), a heading's own summary kept, and/// the title page's first line as the title and the line after "Written by"/// as the author. `None` when the text is not a Final Draft file.pub fn read(xml: &str) -> Option<Doc> {    let mut reader = Reader::from_str(xml);    let mut stack: Vec<Vec<u8>> = Vec::new();    let mut open: Vec<Open> = Vec::new();    let mut in_text = 0usize;    let mut elements = Vec::new();    let mut title_page: Vec<String> = Vec::new();    let mut seen_root = false;    loop {        match reader.read_event() {            Ok(Event::Start(start)) => {                let name = start.name().as_ref().to_vec();                if name == b"FinalDraft" {                    seen_root = true;                }                if name == b"Paragraph" {                    let attribute = |key: &[u8]| {                        start.attributes().flatten().find(|found| found.key.as_ref() == key).and_then(|found| crate::xml_text::attribute_value(&found))                    };                    open.push(Open {                        kind: attribute(b"Type").unwrap_or_default(),                        centred: attribute(b"Alignment").is_some_and(|align| align.eq_ignore_ascii_case("center")),                        in_summary: stack.iter().any(|name| name == b"Summary"),                        in_title_page: stack.iter().any(|name| name == b"TitlePage"),                        text: String::new(),                        summary: None,                    });                } else if name == b"Text" {                    in_text += 1;                }                stack.push(name);            }            Ok(Event::Empty(start)) => {                // `<Tab/>` inside a text run is a space.                if start.name().as_ref() == b"Tab" && in_text > 0 {                    if let Some(paragraph) = open.last_mut() {                        paragraph.text.push(' ');                    }                }            }            Ok(Event::Text(said)) if in_text > 0 => {                if let (Some(paragraph), Ok(said)) = (open.last_mut(), said.decode()) {                    paragraph.text.push_str(&said);                }            }            Ok(Event::GeneralRef(reference)) if in_text > 0 => {                if let Some(paragraph) = open.last_mut() {                    paragraph.text.push_str(&crate::xml_text::reference_text(&reference));                }            }            Ok(Event::CData(said)) if in_text > 0 => {                if let Some(paragraph) = open.last_mut() {                    paragraph.text.push_str(&String::from_utf8_lossy(&said));                }            }            Ok(Event::End(end)) => {                let name = end.name().as_ref().to_vec();                stack.pop();                if name == b"Text" {                    in_text = in_text.saturating_sub(1);                } else if name == b"Paragraph" {                    let Some(paragraph) = open.pop() else { continue };                    let text = paragraph.text.trim().to_string();                    if paragraph.in_summary {                        if let Some(parent) = open.last_mut() {                            if !text.is_empty() {                                parent.summary = Some(match parent.summary.take() {                                    Some(before) => format!("{before} {text}"),                                    None => text,                                });                            }                        }                        continue;                    }                    if paragraph.in_title_page {                        if !text.is_empty() {                            title_page.push(text);                        }                        continue;                    }                    let element = match paragraph.kind.as_str() {                        "Scene Heading" => Element::Heading(text),                        "Character" => Element::Character(text),                        "Parenthetical" => Element::Parenthetical(text),                        "Dialogue" => Element::Dialogue(text),                        "Transition" => Element::Transition(text),                        _ if paragraph.centred => Element::Centered(text),                        _ => Element::Action(text),                    };                    let heading = matches!(element, Element::Heading(_));                    elements.push(element);                    if heading {                        if let Some(summary) = paragraph.summary {                            elements.push(Element::Summary(summary));                        }                    }                }            }            Ok(Event::Eof) => break,            Err(_) => return None,            _ => {}        }    }    if !seen_root {        return None;    }    let title = title_page.first().map(String::as_str);    let author = title_page        .iter()        .position(|line| super::script_in::credit(line))        .and_then(|at| title_page.get(at + 1))        .map(String::as_str);    Some(doc_of(title, author, &elements))}#[cfg(test)]mod tests {    use super::*;    use crate::story::fountain::SceneDoc;    /// RULE: A story leaves as Final Draft XML with its headings, action, speakers, asides, speech and cuts as their own paragraphs, any script kept and XML's marks escaped.    #[test]    fn a_story_leaves_as_final_draft_paragraphs() {        let doc = Doc {            title: vec![("Title".into(), "The Night Bus".into()), ("Author".into(), "A. Writer".into())],            scenes: vec![SceneDoc {                heading: "EXT. BUS STOP - NIGHT".into(),                summary: Some("Asha waits".into()),                body: "Rain. Tea & biscuits.\n\nASHA\n(quietly)\nIs it <late>?\n\n@రవి\nఇంకా లేదు.\n\nCUT TO:".into(),            }],        };        let xml = write(&doc, &["రవి".to_string()]);        for want in [            "<Summary>\n          <Paragraph>\n            <Text>Asha waits</Text>",            "      <Text>EXT. BUS STOP - NIGHT</Text>",            "<Paragraph Type=\"Action\">\n      <Text>Rain. Tea &amp; biscuits.</Text>",            "<Paragraph Type=\"Character\">\n      <Text>ASHA</Text>",            "<Paragraph Type=\"Parenthetical\">\n      <Text>(quietly)</Text>",            "<Paragraph Type=\"Dialogue\">\n      <Text>Is it &lt;late&gt;?</Text>",            "<Paragraph Type=\"Character\">\n      <Text>రవి</Text>",            "<Paragraph Type=\"Dialogue\">\n      <Text>ఇంకా లేదు.</Text>",            "<Paragraph Type=\"Transition\">\n      <Text>CUT TO:</Text>",            "<Text>The Night Bus</Text>",        ] {            assert!(xml.contains(want), "{want} in\n{xml}");        }        assert!(xml.starts_with("<?xml") && xml.ends_with("</FinalDraft>\n"));    }    /// RULE: A Final Draft file comes in as the same story: headings with their summaries, action, speakers (a caseless name with `@`), asides, speech and cuts, and what this app writes reads back whole.    #[test]    fn a_final_draft_file_comes_in_as_the_story() {        let doc = Doc {            title: vec![("Title".into(), "The Night Bus".into())],            scenes: vec![SceneDoc {                heading: "EXT. BUS STOP - NIGHT".into(),                summary: Some("Asha waits".into()),                body: "Rain. Tea & biscuits.\n\nASHA\n(quietly)\nIs it <late>?\n\n@రవి\nఇంకా లేదు.\n\n@रीना\nचलो।\n\nCUT TO:".into(),            }],        };        let names = ["రవి".to_string(), "रीना".to_string()];        let back = read(&write(&doc, &names)).expect("reads");        assert_eq!(back.title, vec![("Title".to_string(), "The Night Bus".to_string())]);        assert_eq!(back.scenes, doc.scenes);        // A file from the desktop tool: runs of text, a tab, a title page with its author.        let xml = r#"<?xml version="1.0" encoding="UTF-8"?><FinalDraft DocumentType="Script" Version="4"><Content><Paragraph Type="Action"><Text>Words before any scene.</Text></Paragraph><Paragraph Type="Scene Heading"><Text>INT. TEA STALL</Text><Text Style="Bold"> - MORNING</Text></Paragraph><Paragraph Type="Character"><Text>Meera</Text></Paragraph><Paragraph Type="Dialogue"><Text>You took<Tab/>money?</Text></Paragraph><Paragraph Type="Shot"><Text>CLOSE ON THE COINS</Text></Paragraph><Paragraph Type="Transition"><Text>Fade out.</Text></Paragraph></Content><TitlePage><Content><Paragraph Alignment="Center"><Text>Last Ferry</Text></Paragraph><Paragraph Alignment="Center"><Text>Written by</Text></Paragraph><Paragraph Alignment="Center"><Text>A. Writer</Text></Paragraph></Content></TitlePage></FinalDraft>"#;        let doc = read(xml).expect("reads");        assert_eq!(doc.title, vec![("Title".to_string(), "Last Ferry".to_string()), ("Author".to_string(), "A. Writer".to_string())]);        assert_eq!(doc.scenes.len(), 2);        assert_eq!(doc.scenes[0].heading, "");        assert_eq!(doc.scenes[0].body, "Words before any scene.");        assert_eq!(doc.scenes[1].heading, "INT. TEA STALL - MORNING");        assert_eq!(doc.scenes[1].body, "@Meera\nYou took money?\n\nCLOSE ON THE COINS\n\n> Fade out.");        assert_eq!(read("<html><body>not a script</body></html>"), None);    }}