Cotton code
365 lines · 12.9 KB · RustRaw
//! A story laid out as script pages, by screenplay rules: Courier 12 pt, ten//! characters an inch, six lines an inch, about 55 lines a page; action the//! full measure, a name at the centre, speech in its narrower column, asides//! narrower still, transitions to the right. A speech broken by a page ends//! `(MORE)` and goes on under the name with `(CONT'D)`; a heading or a name is//! never left alone at the foot of a page.use serde::{Deserialize, Serialize};use super::figures::LINES_PER_PAGE;use super::lines::{lines, unmarked, Kind, Line};/// Characters across the full measure (six inches).pub const ACTION_WIDTH: usize = 60;pub const DIALOGUE_INDENT: usize = 10;pub const DIALOGUE_WIDTH: usize = 35;pub const PARENTHETICAL_INDENT: usize = 16;pub const PARENTHETICAL_WIDTH: usize = 25;pub const CHARACTER_INDENT: usize = 22;#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct SceneRef {    pub id: String,    pub number: usize,}/// One printed line. `kind` is the element's kind, or `more` for a speech's/// `(MORE)`; `indent` is in characters from the left margin.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Row {    pub kind: String,    pub text: String,    pub indent: usize,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub scene: Option<SceneRef>,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Page {    pub number: usize,    pub lines: Vec<Row>,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct ScenePage {    pub id: String,    pub number: usize,    pub page: usize,}/// A scene to lay out: its id, heading and body.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct SceneIn {    pub id: String,    #[serde(default)]    pub heading: String,    #[serde(default)]    pub body: String,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Laid {    pub pages: Vec<Page>,    pub scenes: Vec<ScenePage>,}/// `text` wrapped at `width` characters on its spaces; a word longer than a/// line is cut. Never empty: an empty text is one empty line.pub fn wrap(text: &str, width: usize) -> Vec<String> {    let mut out = Vec::new();    let mut line = String::new();    let mut count = 0usize;    for word in text.split_whitespace() {        let mut word: Vec<char> = word.chars().collect();        while word.len() > width {            if count > 0 {                out.push(std::mem::take(&mut line));                count = 0;            }            out.push(word[..width].iter().collect());            word.drain(..width);        }        if word.is_empty() {            continue;        }        let needed = if count == 0 { word.len() } else { count + 1 + word.len() };        if needed > width && count > 0 {            out.push(std::mem::take(&mut line));            count = 0;        }        if count > 0 {            line.push(' ');            count += 1;        }        line.extend(word.iter());        count += word.len();    }    if count > 0 || out.is_empty() {        out.push(line);    }    out}/// One block of the page: rows that stand together, and how they may break.#[derive(Debug, Clone)]enum Block {    Heading(Row),    Action(Vec<Row>),    Speech { name: String, cue: Row, rows: Vec<Row> },    Single(Row),}impl Block {    fn len(&self) -> usize {        match self {            Block::Heading(_) | Block::Single(_) => 1,            Block::Action(rows) => rows.len(),            Block::Speech { rows, .. } => 1 + rows.len(),        }    }}fn row(kind: &str, text: String, indent: usize) -> Row {    Row { kind: kind.to_string(), text, indent, scene: None }}fn width_of(text: &str) -> usize {    text.chars().count()}/// The blocks of one scene: its heading (when it has one) and its body's/// elements. Notes, synopses and sections are not printed.fn blocks(heading: &str, scene: Option<SceneRef>, read: &[Line]) -> Vec<Block> {    let mut out = Vec::new();    let heading = heading.trim();    if !heading.is_empty() || scene.is_some() {        let mut head = row("heading", heading.to_uppercase(), 0);        head.scene = scene;        out.push(Block::Heading(head));    }    let mut index = 0;    while index < read.len() {        let line = &read[index];        match line.kind {            Kind::Blank | Kind::Note => index += 1,            Kind::Action => {                let mut rows = Vec::new();                while index < read.len() && read[index].kind == Kind::Action {                    for text in wrap(&unmarked(Kind::Action, &read[index].text), ACTION_WIDTH) {                        rows.push(row("action", text, 0));                    }                    index += 1;                }                out.push(Block::Action(rows));            }            Kind::Character => {                let cue_text = unmarked(Kind::Character, &line.text).to_uppercase();                let name = line.name.clone().unwrap_or_default().to_uppercase();                let cue = row("character", cue_text, CHARACTER_INDENT);                let mut rows = Vec::new();                index += 1;                while index < read.len() && matches!(read[index].kind, Kind::Dialogue | Kind::Parenthetical | Kind::Note) {                    let line = &read[index];                    match line.kind {                        Kind::Parenthetical => {                            let inner = unmarked(Kind::Parenthetical, &line.text);                            for text in wrap(&format!("({inner})"), PARENTHETICAL_WIDTH) {                                rows.push(row("parenthetical", text, PARENTHETICAL_INDENT));                            }                        }                        Kind::Dialogue => {                            for text in wrap(line.text.trim(), DIALOGUE_WIDTH) {                                rows.push(row("dialogue", text, DIALOGUE_INDENT));                            }                        }                        _ => {}                    }                    index += 1;                }                out.push(Block::Speech { name, cue, rows });            }            Kind::Dialogue | Kind::Parenthetical => {                // A speech line with no name above it (the chosen kind of a                // line being typed): laid out as speech without a name.                let text = line.text.trim().to_string();                out.push(Block::Single(row("dialogue", text, DIALOGUE_INDENT)));                index += 1;            }            Kind::Transition => {                let text = unmarked(Kind::Transition, &line.text).to_uppercase();                let indent = ACTION_WIDTH.saturating_sub(width_of(&text));                out.push(Block::Single(row("transition", text, indent)));                index += 1;            }            Kind::Centered => {                let text = unmarked(Kind::Centered, &line.text);                let indent = ACTION_WIDTH.saturating_sub(width_of(&text)) / 2;                out.push(Block::Single(row("centered", text, indent)));                index += 1;            }            Kind::Heading => {                out.push(Block::Heading(row("heading", unmarked(Kind::Heading, &line.text).to_uppercase(), 0)));                index += 1;            }        }    }    out}/// How many printed lines one scene takes, its blank lines between/// elements counted, on an endless page: what its pages are worked out from.pub fn scene_rows(heading: &str, read: &[Line]) -> usize {    let blocks = blocks(heading, None, read);    let rows: usize = blocks.iter().map(Block::len).sum();    rows + blocks.len().saturating_sub(1) + usize::from(!blocks.is_empty())}struct Pager {    pages: Vec<Page>,    current: Vec<Row>,}impl Pager {    fn room(&self) -> usize {        LINES_PER_PAGE - self.current.len()    }    /// The blank line an element wants above it; none at a page's head.    fn gap(&self) -> usize {        usize::from(!self.current.is_empty())    }    fn turn(&mut self) {        if !self.current.is_empty() {            let number = self.pages.len() + 1;            self.pages.push(Page { number, lines: std::mem::take(&mut self.current) });        }    }    fn put(&mut self, rows: impl IntoIterator<Item = Row>) {        if !self.current.is_empty() {            self.current.push(row("blank", String::new(), 0));        }        self.current.extend(rows);    }    fn page_number(&self) -> usize {        self.pages.len() + 1    }}/// The story's scenes laid out as numbered pages.pub fn script(scenes: &[SceneIn], names: &[String]) -> Laid {    let mut pager = Pager { pages: Vec::new(), current: Vec::new() };    let mut placed = Vec::new();    let mut all: Vec<(Option<usize>, Block)> = Vec::new();    for (at, scene) in scenes.iter().enumerate() {        let read = lines(&scene.body, names);        let reference = SceneRef { id: scene.id.clone(), number: at + 1 };        for (index, block) in blocks(&scene.heading, Some(reference), &read).into_iter().enumerate() {            all.push(((index == 0).then_some(at), block));        }    }    for index in 0..all.len() {        let (scene_at, block) = all[index].clone();        match block {            Block::Heading(head) => {                // A heading keeps two lines of what follows (or all of it).                let next = all.get(index + 1).map(|(_, next)| next.len().min(2)).unwrap_or(0);                let next_gap = usize::from(next > 0);                if pager.room() < pager.gap() + 1 + next_gap + next {                    pager.turn();                }                if let Some(at) = scene_at {                    placed.push(ScenePage { id: scenes[at].id.clone(), number: at + 1, page: pager.page_number() });                }                pager.put([head]);            }            Block::Single(single) => {                if pager.room() < pager.gap() + 1 {                    pager.turn();                }                pager.put([single]);            }            Block::Action(rows) => place_action(&mut pager, rows),            Block::Speech { name, cue, rows } => place_speech(&mut pager, &name, cue, rows),        }    }    pager.turn();    Laid { pages: pager.pages, scenes: placed }}/// Action breaks between its lines, two or more on each side; otherwise it/// goes whole to the next page.fn place_action(pager: &mut Pager, mut rows: Vec<Row>) {    loop {        let room = pager.room().saturating_sub(pager.gap());        if rows.len() <= room {            pager.put(rows);            return;        }        if room >= 2 && rows.len() - room >= 2 {            let rest = rows.split_off(room);            pager.put(rows);            pager.turn();            rows = rest;            continue;        }        if pager.current.is_empty() {            // Longer than a whole page: fill it and go on.            let rest = rows.split_off(LINES_PER_PAGE.min(rows.len()));            pager.put(rows);            pager.turn();            rows = rest;            continue;        }        pager.turn();    }}/// A speech stays with its name. Broken by a page, it keeps the name and two/// lines above `(MORE)`, never ends on an aside, and goes on under/// `NAME (CONT'D)`; with too little room it goes whole to the next page.fn place_speech(pager: &mut Pager, name: &str, mut cue: Row, mut rows: Vec<Row>) {    loop {        let room = pager.room().saturating_sub(pager.gap());        if 1 + rows.len() <= room {            let mut all = vec![cue];            all.extend(rows);            pager.put(all);            return;        }        // cue + k rows + (MORE), k >= 2, at least one row left over.        let mut k = room.saturating_sub(2);        while k > 0 && rows.get(k - 1).is_some_and(|last| last.kind == "parenthetical") {            k -= 1;        }        if k >= 2 && k < rows.len() {            let rest = rows.split_off(k);            let mut all = vec![cue];            all.extend(rows);            all.push(row("more", "(MORE)".to_string(), CHARACTER_INDENT));            pager.put(all);            pager.turn();            cue = row("character", format!("{name} (CONT'D)"), CHARACTER_INDENT);            rows = rest;            continue;        }        if pager.current.is_empty() {            // A speech longer than a page with nowhere better to break.            let k = (LINES_PER_PAGE - 2).min(rows.len());            let rest = rows.split_off(k);            let mut all = vec![cue];            all.extend(rows);            if !rest.is_empty() {                all.push(row("more", "(MORE)".to_string(), CHARACTER_INDENT));            }            pager.put(all);            pager.turn();            if rest.is_empty() {                return;            }            cue = row("character", format!("{name} (CONT'D)"), CHARACTER_INDENT);            rows = rest;            continue;        }        pager.turn();    }}