//! 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("&"), '<' => out.push_str("<"), '>' => out.push_str(">"), '"' => out.push_str("""), // 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!(" \n {}\n \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("\n\n \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!( " \n \n \n \n {}\n \n \n \n {}\n \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(" \n \n \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!(" \n {}\n \n", escaped(line))); } } out.push_str(" \n \n\n"); out } /// One `` 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, } /// 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 { let mut reader = Reader::from_str(xml); let mut stack: Vec> = Vec::new(); let mut open: Vec = Vec::new(); let mut in_text = 0usize; let mut elements = Vec::new(); let mut title_page: Vec = 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)) => { // `` 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 ?\n\n@రవి\nఇంకా లేదు.\n\nCUT TO:".into(), }], }; let xml = write(&doc, &["రవి".to_string()]); for want in [ "\n \n Asha waits", " EXT. BUS STOP - NIGHT", "\n Rain. Tea & biscuits.", "\n ASHA", "\n (quietly)", "\n Is it <late>?", "\n రవి", "\n ఇంకా లేదు.", "\n CUT TO:", "The Night Bus", ] { assert!(xml.contains(want), "{want} in\n{xml}"); } assert!(xml.starts_with("\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 ?\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#" Words before any scene. INT. TEA STALL - MORNING Meera You tookmoney? CLOSE ON THE COINS Fade out. Last Ferry Written by A. Writer "#; 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("not a script"), None); } }