//! A scene read as a conversation (the owner's idea, `scene.chat`): each //! speech a bubble under its speaker's name, action as narration between. use serde::{Deserialize, Serialize}; use super::lines::{lines, same_name, unmarked, Kind}; use super::names; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Item { /// `speech`, `action` or `transition`. pub kind: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub who: Option, /// `left` or `right` in a two-hander; none otherwise. #[serde(default, skip_serializing_if = "Option::is_none")] pub side: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub aside: Option, pub text: String, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Chat { pub speakers: Vec, pub two_hander: bool, pub items: Vec, } fn item(kind: &str, text: String) -> Item { Item { kind: kind.to_string(), who: None, side: None, aside: None, text } } /// The scene as a chat. A speech is one bubble; an aside before its words is /// the bubble's aside, and one in the middle starts a new bubble from the /// same speaker. pub fn chat(body: &str, names_known: &[String]) -> Chat { let read = lines(body, names_known); let speakers = names::speakers(&read); let two_hander = speakers.len() == 2; let side = |who: &str| -> Option { two_hander.then(|| if same_name(&speakers[0], who) { "left" } else { "right" }.to_string()) }; let mut items = Vec::new(); let mut index = 0; while index < read.len() { let line = &read[index]; match line.kind { Kind::Blank | Kind::Note | Kind::Heading => index += 1, Kind::Action | Kind::Centered => { let mut text = Vec::new(); while index < read.len() && matches!(read[index].kind, Kind::Action | Kind::Centered) { text.push(unmarked(read[index].kind, &read[index].text)); index += 1; } items.push(item("action", text.join("\n"))); } Kind::Transition => { items.push(item("transition", unmarked(Kind::Transition, &line.text))); index += 1; } Kind::Character | Kind::Dialogue | Kind::Parenthetical => { let who = if line.kind == Kind::Character { index += 1; line.name.clone().unwrap_or_default() } else { String::new() }; let mut aside: Option = None; let mut said: Vec = Vec::new(); let flush = |items: &mut Vec, aside: &mut Option, said: &mut Vec| { if said.is_empty() && aside.is_none() { return; } items.push(Item { kind: "speech".to_string(), who: (!who.is_empty()).then(|| who.clone()), side: side(&who), aside: aside.take(), text: std::mem::take(said).join("\n"), }); }; while index < read.len() && matches!(read[index].kind, Kind::Dialogue | Kind::Parenthetical | Kind::Note) { let line = &read[index]; match line.kind { Kind::Parenthetical => { if !said.is_empty() { flush(&mut items, &mut aside, &mut said); } aside = Some(unmarked(Kind::Parenthetical, &line.text)); } Kind::Dialogue => said.push(line.text.trim().to_string()), _ => {} } index += 1; } flush(&mut items, &mut aside, &mut said); } } } Chat { speakers, two_hander, items } }