Cotton code
236 lines · 8.7 KB · RustRaw
//! What each line of a scene's body is.use serde::{Deserialize, Serialize};use super::heading;/// What one line of a scene is: how the writer sets it and how the script/// lays it out.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum Kind {    Action,    Character,    Dialogue,    Parenthetical,    Transition,    Heading,    Centered,    Note,    Blank,}impl Kind {    pub const ALL: [Kind; 9] = [        Kind::Action,        Kind::Character,        Kind::Dialogue,        Kind::Parenthetical,        Kind::Transition,        Kind::Heading,        Kind::Centered,        Kind::Note,        Kind::Blank,    ];    /// The kind's word, as the methods and the `story` lines' `kind.*` say it.    pub fn word(self) -> &'static str {        match self {            Kind::Action => "action",            Kind::Character => "character",            Kind::Dialogue => "dialogue",            Kind::Parenthetical => "parenthetical",            Kind::Transition => "transition",            Kind::Heading => "heading",            Kind::Centered => "centered",            Kind::Note => "note",            Kind::Blank => "blank",        }    }    pub fn parse(word: &str) -> Option<Kind> {        Kind::ALL.into_iter().find(|kind| kind.word() == word)    }    /// A line of a speech: the name, an aside or what is said.    pub fn in_speech(self) -> bool {        matches!(self, Kind::Character | Kind::Dialogue | Kind::Parenthetical)    }}/// One line of a body: its kind, its text as written, its UTF-16 offsets in/// the body (`end` exclusive, before the line break) and, on a character/// line, the bare name.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Line {    pub kind: Kind,    pub text: String,    pub start: usize,    pub end: usize,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub name: Option<String>,}/// The body's lines as written, each with its byte start: split on `\n`, a/// `\r` before it left out of the line's text.pub(crate) fn raw_lines(body: &str) -> Vec<(usize, &str)> {    let mut out = Vec::new();    let mut start = 0;    for piece in body.split('\n') {        let text = piece.strip_suffix('\r').unwrap_or(piece);        out.push((start, text));        start += piece.len() + 1;    }    out}/// A character line's bare name: no forcing `@`, no dual `^`, no/// extensions such as `(V.O.)` or `(CONT'D)`.pub fn bare_name(text: &str) -> String {    let mut name = text.trim();    name = name.strip_prefix('@').unwrap_or(name).trim();    name = name.strip_suffix('^').unwrap_or(name).trim();    while name.ends_with(')') {        match name.rfind('(') {            Some(open) if open > 0 => name = name[..open].trim_end(),            _ => break,        }    }    name.to_string()}/// Two names are one name: alike once trimmed and lower-cased (a Latin name/// in any case; a script without case compared as written).pub fn same_name(a: &str, b: &str) -> bool {    let (a, b) = (a.trim(), b.trim());    a == b || a.to_lowercase() == b.to_lowercase()}/// Is `name` one of `names`?pub fn known(name: &str, names: &[String]) -> bool {    !name.is_empty() && names.iter().any(|known| same_name(known, name))}/// A name written in capitals, as English screenplays write a character:/// at least one capital letter, no small letter, only the marks a name/// takes, and short. A line in a script without capitals is never this.pub fn caps_name(name: &str) -> bool {    let chars = name.chars().count();    (1..=40).contains(&chars)        && name.chars().any(char::is_uppercase)        && !name.chars().any(char::is_lowercase)        && !name.ends_with(':')        && name.chars().all(|c| c.is_alphanumeric() || matches!(c, ' ' | '.' | '\'' | '-' | '#' | '&' | '’'))}/// A transition as written without its forcing `>`: in capitals and ending/// `TO:` (`CUT TO:`), or one of the few that end otherwise.pub fn transition_shaped(trimmed: &str) -> bool {    let caps = trimmed.chars().any(char::is_uppercase) && !trimmed.chars().any(char::is_lowercase);    caps && (trimmed.ends_with("TO:") || matches!(trimmed, "FADE OUT." | "FADE TO BLACK." | "FADE IN:" | "THE END"))}fn forced_heading(trimmed: &str) -> bool {    trimmed.strip_prefix('.').is_some_and(|rest| !rest.starts_with('.'))}/// Each line of `body`, what it is. `names` are the story's characters;/// `chosen` is the kind the person picked for one line still being typed/// (the bar's word for it): it stands while the text alone reads that line/// as action or blank.pub fn lines_chosen(body: &str, names: &[String], chosen: Option<(usize, Kind)>) -> Vec<Line> {    let raw = raw_lines(body);    let count = raw.len();    let blank = |index: usize| raw.get(index).is_none_or(|(_, text)| text.trim().is_empty());    let mut out = Vec::with_capacity(count);    // The line under is chosen as speech while it is typed: this one names    // its speaker.    let below_spoken = |index: usize| chosen.is_some_and(|(line, kind)| line == index + 1 && matches!(kind, Kind::Dialogue | Kind::Parenthetical));    let mut in_speech = false;    let mut units = 0usize;    let mut last_byte = 0usize;    for (index, (byte, text)) in raw.iter().enumerate() {        units += super::utf16_len(&body[last_byte..*byte]);        last_byte = *byte;        let start = units;        let end = start + super::utf16_len(text);        let trimmed = text.trim();        let after_blank = index == 0 || blank(index - 1);        let last = index + 1 == count;        let mut kind = if trimmed.is_empty() {            in_speech = false;            Kind::Blank        } else if trimmed.starts_with("[[") && trimmed.ends_with("]]") {            Kind::Note        } else if trimmed.starts_with('#') || (trimmed.starts_with('=') && !trimmed.starts_with("===")) {            in_speech = false;            Kind::Note        } else if trimmed.starts_with('!') {            in_speech = false;            Kind::Action        } else if trimmed.starts_with('@') {            in_speech = true;            Kind::Character        } else if trimmed.starts_with('>') {            in_speech = false;            if trimmed.ends_with('<') && trimmed.len() > 1 { Kind::Centered } else { Kind::Transition }        } else if in_speech {            if trimmed.starts_with('(') && trimmed.ends_with(')') { Kind::Parenthetical } else { Kind::Dialogue }        } else if after_blank && (forced_heading(trimmed) || heading::is_heading(trimmed)) {            Kind::Heading        } else if after_blank && (blank(index + 1)) && transition_shaped(trimmed) {            Kind::Transition        } else if after_blank && (!blank(index + 1) || last || (index + 2 == count) || below_spoken(index)) && {            let name = bare_name(trimmed);            caps_name(&name) || known(&name, names)        } {            in_speech = true;            Kind::Character        } else {            Kind::Action        };        if let Some((line, wanted)) = chosen {            if line == index && wanted != kind && matches!(kind, Kind::Action | Kind::Blank) {                kind = wanted;                in_speech = wanted.in_speech();            }        }        let name = (kind == Kind::Character).then(|| bare_name(trimmed));        out.push(Line { kind, text: text.to_string(), start, end, name });    }    out}/// Each line of `body`, what it is ([`lines_chosen`] with nothing chosen).pub fn lines(body: &str, names: &[String]) -> Vec<Line> {    lines_chosen(body, names, None)}/// The text of a line without the marks that force its kind: `!`, `@`,/// `>` and a centred `<`, a heading's `.`, an aside's brackets, a note's/// `[[ ]]`.pub fn unmarked(kind: Kind, text: &str) -> String {    let trimmed = text.trim();    let out = match kind {        Kind::Action => trimmed.strip_prefix('!').unwrap_or(trimmed),        Kind::Character => trimmed.strip_prefix('@').unwrap_or(trimmed),        Kind::Transition => trimmed.strip_prefix('>').unwrap_or(trimmed),        Kind::Centered => {            let inner = trimmed.strip_prefix('>').unwrap_or(trimmed);            inner.strip_suffix('<').unwrap_or(inner)        }        Kind::Heading => {            if forced_heading(trimmed) { &trimmed[1..] } else { trimmed }        }        Kind::Parenthetical => {            let inner = trimmed.strip_prefix('(').unwrap_or(trimmed);            inner.strip_suffix(')').unwrap_or(inner)        }        Kind::Note => {            let inner = trimmed.strip_prefix("[[").unwrap_or(trimmed);            inner.strip_suffix("]]").unwrap_or(inner)        }        Kind::Dialogue | Kind::Blank => trimmed,    };    out.trim().to_string()}