Cotton code
209 lines · 7.1 KB · RustRaw
//! A scene as the writer sets it down, beat by beat: action, speech, a note//! to self, someone entering. A scene's Fountain body and its beats say the//! same thing: an old scene is read from its body, and a scene written beat//! by beat keeps its body from them, so the script, Fountain and every//! figure read one text.use serde::{Deserialize, Serialize};use super::lines::{lines, unmarked, Kind};/// The smallest gap two order keys may keep; closer than this, the scene's/// keys are written afresh.pub const SMALLEST_GAP: f64 = 1e-6;#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum BeatKind {    Action,    Dialogue,    Note,    Enters,}impl BeatKind {    pub fn parse(word: &str) -> Option<BeatKind> {        match word {            "action" => Some(BeatKind::Action),            "dialogue" => Some(BeatKind::Dialogue),            "note" => Some(BeatKind::Note),            "enters" => Some(BeatKind::Enters),            _ => None,        }    }    pub fn word(self) -> &'static str {        match self {            BeatKind::Action => "action",            BeatKind::Dialogue => "dialogue",            BeatKind::Note => "note",            BeatKind::Enters => "enters",        }    }}/// One beat. `who` is the speaker or the one entering; `aside` how a speech/// is said; `form` keeps an old body's `transition` or `centered` line as it/// was set.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Beat {    pub kind: BeatKind,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub who: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub aside: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub form: Option<String>,    #[serde(default)]    pub text: String,}impl Beat {    fn plain(kind: BeatKind, text: String) -> Beat {        Beat { kind, who: None, aside: None, form: None, text }    }}/// A speech being read: who speaks, how, and what they have said so far.#[derive(Default)]struct Speech {    who: Option<String>,    aside: Option<String>,    said: Vec<String>,}impl Speech {    fn flush(&mut self, out: &mut Vec<Beat>) {        if let Some(who) = self.who.clone() {            out.push(Beat { kind: BeatKind::Dialogue, who: Some(who), aside: self.aside.take(), form: None, text: self.said.join("\n") });        }        self.said.clear();    }    fn end(&mut self, out: &mut Vec<Beat>) {        self.flush(out);        self.who = None;    }}fn flush_action(action: &mut Vec<String>, out: &mut Vec<Beat>) {    if !action.is_empty() {        out.push(Beat::plain(BeatKind::Action, action.join("\n")));        action.clear();    }}/// A body read as beats, in order. Nothing the writer wrote is dropped.pub fn read(body: &str, names: &[String]) -> Vec<Beat> {    let mut out = Vec::new();    let mut speech = Speech::default();    let mut action: Vec<String> = Vec::new();    for line in lines(body, names) {        let said = unmarked(line.kind, &line.text);        match line.kind {            Kind::Blank => {                speech.end(&mut out);                flush_action(&mut action, &mut out);            }            Kind::Character => {                speech.end(&mut out);                flush_action(&mut action, &mut out);                speech.who = Some(line.name.clone().unwrap_or(said));            }            Kind::Parenthetical if speech.who.is_some() => {                if !speech.said.is_empty() {                    speech.flush(&mut out);                }                speech.aside = Some(said);            }            Kind::Dialogue if speech.who.is_some() => speech.said.push(said),            Kind::Transition | Kind::Centered => {                speech.end(&mut out);                flush_action(&mut action, &mut out);                let form = if line.kind == Kind::Transition { "transition" } else { "centered" };                out.push(Beat { form: Some(form.to_string()), ..Beat::plain(BeatKind::Action, said) });            }            Kind::Note => {                speech.end(&mut out);                flush_action(&mut action, &mut out);                out.push(Beat::plain(BeatKind::Note, said));            }            Kind::Action | Kind::Heading | Kind::Dialogue | Kind::Parenthetical => {                speech.end(&mut out);                action.push(said);            }        }    }    speech.end(&mut out);    flush_action(&mut action, &mut out);    out}/// A speaker's name as a character line: capitals where the script has/// them, forced with `@` where it has none.fn cue(name: &str) -> String {    let upper = name.trim().to_uppercase();    if upper.chars().any(char::is_uppercase) {        upper    } else {        format!("@{}", name.trim())    }}/// Text with no blank line inside it: a blank line would end the element.fn tight(text: &str) -> String {    text.lines().map(str::trim).filter(|line| !line.is_empty()).collect::<Vec<_>>().join("\n")}/// Action text, forced with `!` where it would read as anything else.fn action_text(text: &str, names: &[String]) -> String {    let text = tight(text);    let plain = lines(&text, names).iter().all(|line| line.kind == Kind::Action);    if plain {        return text;    }    text.lines().map(|line| format!("!{line}")).collect::<Vec<_>>().join("\n")}/// The beats as a Fountain body. `enters` words someone's entrance.pub fn compose(beats: &[Beat], names: &[String], enters: &dyn Fn(&str) -> String) -> String {    let mut blocks: Vec<String> = Vec::new();    for beat in beats {        let block = match beat.kind {            BeatKind::Action => match beat.form.as_deref() {                Some("transition") => format!(">{}", tight(&beat.text)),                Some("centered") => format!(">{}<", tight(&beat.text)),                _ => action_text(&beat.text, names),            },            BeatKind::Dialogue => {                let mut speech = vec![cue(beat.who.as_deref().unwrap_or_default())];                if let Some(aside) = beat.aside.as_deref().map(str::trim).filter(|aside| !aside.is_empty()) {                    speech.push(format!("({aside})"));                }                speech.push(tight(&beat.text));                speech.join("\n")            }            BeatKind::Note => format!("[[{}]]", tight(&beat.text).replace('\n', " ")),            BeatKind::Enters => action_text(&enters(beat.who.as_deref().unwrap_or_default()), names),        };        if !block.trim().is_empty() {            blocks.push(block);        }    }    blocks.join("\n\n")}/// The order key between two neighbours: none when they stand too close and/// the keys must be written afresh.pub fn between(before: Option<f64>, after: Option<f64>) -> Option<f64> {    match (before, after) {        (Some(low), Some(high)) => (high - low > SMALLEST_GAP).then_some(low + (high - low) / 2.0),        (Some(low), None) => Some(low + 1.0),        (None, Some(high)) => Some(high - 1.0),        (None, None) => Some(1.0),    }}#[cfg(test)]#[path = "beats_tests.rs"]mod tests;