//! Cotton Story on the phone: every `story.*` method `apps/story/CORE.md` //! names, the rules the core's (`cotton_rules::story`), the rows this //! device's own copy (signed out too; a write queues for the object like any //! other). The shell draws what these answer and decides nothing. //! //! Writing: `story.lines`, `story.press`, `story.kind`, `story.names`, //! `story.scene.write`, `story.scene.new`, `story.scene.move`, //! `story.scene.duplicate`, `story.scene.near`, `story.rename`. //! The current story: `story.current`, `story.choose`, `story.start`. //! Cards: `story.card`, `story.chat`. The script: `story.script`. //! Out and in: `story.fountain.write`, `story.fountain.read`, //! `story.bring_in` (a Fountain, Final Draft or printed PDF file), `story.copy`. //! A scene card's Write: `story.write { id }` → `open_writer` (the shell //! opens the writer on that scene). use serde_json::{json, Map, Value}; use cotton_core::cotton_rules::story::{ chat, fdx, figures, fountain, heading, layout, lines::{self as story_lines, same_name, unmarked, Kind}, names as story_names, press, script_in, }; use cotton_tools::mcp::dispatch::Ctx; use cotton_tools::mcp::handlers::tables; use crate::handle::CottonHandle; use crate::methods::MethodError; pub const METHODS: [&str; 63] = [ "story.bring_in", "story.places", "story.place", "story.person", "story.pictures", "story.things", "story.costumes", "story.fdx.write", "story.drafts.list", "story.drafts.read", "story.drafts.changes", "story.scene.split", "story.scene.merge", "story.merge", "story.picture.add", "story.picture.remove", "story.picture.move", "story.drafts.mark", "story.drafts.restore", "story.card", "story.chat", "story.choose", "story.copy", "story.current", "story.fountain.read", "story.fountain.write", "story.kind", "story.lines", "story.names", "story.press", "story.rename", "story.scene.duplicate", "story.scene.move", "story.scene.near", "story.scene.new", "story.scene.write", "story.script", "story.start", "story.figures", "story.write", "story.answer", "story.character.add", "story.draft", "story.interval", "story.interview", "story.line.add", "story.line.edit", "story.line.remove", "story.line.move", "story.person.lines", "story.list", "story.scene", "story.scene.add", "story.scene.place", "story.scene.leave", "story.scene.remove", "story.scenes", "story.sequence.add", "story.sequence.edit", "story.sequence.remove", "story.skip", "story.theme.set", "story.themes", ]; #[path = "story_desk.rs"] mod desk; #[path = "story_ink.rs"] mod ink; #[path = "story_drafts.rs"] mod drafts; pub const STORY: &str = "story_story"; pub const SCENE: &str = "story_scene"; pub const CHARACTER: &str = "story_character"; pub const PLACE: &str = "story_place"; pub const NOTE: &str = "story_note"; fn bad(why: impl Into) -> MethodError { MethodError::new("bad_request", why.into()) } fn refused(code: &str, why: impl Into) -> MethodError { MethodError::new(code, why.into()) } /// A line of the story set, filled. pub(crate) fn line(name: &str, fills: &[(&str, &str)]) -> Result { cotton_core::rules::shell_lines::LineSet::shipped("story") .and_then(|lines| lines.say(name, fills)) .ok_or_else(|| MethodError::new("unreadable", format!("the story set says no line {name}"))) } /// Who a script is written by: what the person wrote there (nothing, when they /// cleared it), else, never written, the name they gave at sign-in /// (DECISIONS.md, Account: "the name asked once at first sign-in is the /// default Written by"; the Android walk, 25 Nov 2026, found it blank). pub(super) fn written_by(ctx: &Ctx<'_>, story: &Map) -> String { match story.get("written_by") { Some(Value::String(text)) => text.trim().to_string(), _ => own_name(ctx).unwrap_or_default(), } } /// The name of the person this database is: its owner, as the object names /// them (`read.you`), none before sign-in. fn own_name(ctx: &Ctx<'_>) -> Option { ctx.read .driver() .get( "SELECT p.full_name FROM cotton_workspaces w JOIN cotton_people p ON p.id = w.owner_person_id WHERE w.id = ? AND p.trashed_at IS NULL", &[rusqlite::types::Value::Text(ctx.workspace_id.to_string())], ) .ok() .flatten() .and_then(|row| row.text("full_name").map(str::trim).filter(|name| !name.is_empty()).map(str::to_string)) } /// A count's line (`{n}`, its plural picked by it). fn counted(name: &str, n: i64) -> Result { let said = cotton_core::rules::shell_lines::number(n); let form = cotton_core::rules::shell_lines::plural_form(&said); line(&format!("{name}.{form}"), &[("n", &said)]) } #[path = "story_themes.rs"] mod themes; pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result { match method { "story.lines" => with_read(handle, method, |ctx| lines_of(ctx, request)), "story.press" => with_read(handle, method, |ctx| pressed(ctx, request)), "story.kind" => with_read(handle, method, |ctx| kinded(ctx, request)), "story.names" => with_read(handle, method, |ctx| names_of(ctx, request)), "story.current" => with_read(handle, method, current).map(|answer| arriving(handle, answer, "stories")), "story.card" => with_read(handle, method, |ctx| card(ctx, request)), "story.chat" => with_read(handle, method, |ctx| chat_of(ctx, request)), "story.scene.near" => with_read(handle, method, |ctx| near(ctx, request)), "story.script" => with_read(handle, method, |ctx| script(ctx, request)), "story.fountain.write" => with_read(handle, method, |ctx| fountain_write(ctx, request)), "story.figures" => figures_of(request), "story.places" => with_read(handle, method, |ctx| ink::places(ctx, request)), "story.place" => with_read(handle, method, |ctx| ink::place(ctx, request)), "story.person" => with_read(handle, method, |ctx| ink::person(ctx, request)), "story.pictures" => with_read(handle, method, |ctx| ink::pictures(ctx, request)), "story.things" => with_read(handle, method, |ctx| ink::things(ctx, request)), "story.costumes" => with_read(handle, method, |ctx| ink::costumes(ctx, request)), "story.fdx.write" => with_read(handle, method, |ctx| ink::fdx_write(ctx, request)), "story.drafts.list" => with_read(handle, method, |ctx| drafts::list(ctx, request)), "story.drafts.read" => with_read(handle, method, |ctx| drafts::read(ctx, request)), "story.drafts.changes" => with_read(handle, method, |ctx| drafts::changes(ctx, request)), "story.scene.split" => with_write(handle, method, |ctx| ink::scene_split(ctx, request)), "story.scene.merge" => with_write(handle, method, |ctx| ink::scene_merge(ctx, request)), "story.merge" => with_write(handle, method, |ctx| ink::merge(ctx, request)), "story.picture.add" => with_write(handle, method, |ctx| ink::picture_add(ctx, request)), "story.picture.remove" => with_write(handle, method, |ctx| ink::picture_remove(ctx, request)), "story.picture.move" => with_write(handle, method, |ctx| ink::picture_move(ctx, request)), "story.drafts.mark" => with_write(handle, method, |ctx| drafts::mark(ctx, request)), "story.drafts.restore" => with_write(handle, method, |ctx| drafts::restore(ctx, request)), "story.list" => with_read(handle, method, desk::list).map(|answer| arriving(handle, answer, "stories")), "story.scenes" => with_read(handle, method, |ctx| desk::scenes(ctx, request)), "story.interview" => with_read(handle, method, |ctx| desk::interview(ctx, request)), "story.scene" => with_read(handle, method, |ctx| desk::scene(ctx, request)), "story.draft" => with_read(handle, method, |ctx| desk::draft(ctx, request)), "story.write" => with_read(handle, method, |ctx| { let id = id_of(request, "id")?; get(ctx, SCENE, id).ok_or_else(|| refused("not_found", line("refusal.no_scene", &[]).unwrap_or_default()))?; Ok(json!({ "platform_action": "open_writer", "scene": id })) }), "story.answer" => with_write(handle, method, |ctx| desk::answer(ctx, request)), "story.skip" => with_write(handle, method, |ctx| desk::skip(ctx, request)), "story.themes" => themes::answer(&handle.client()), "story.theme.set" => themes::set(&handle.client(), request), "story.character.add" => with_write(handle, method, |ctx| desk::character_add(ctx, request)), "story.interval" => with_write(handle, method, |ctx| desk::interval(ctx, request)), "story.line.add" => with_write(handle, method, |ctx| desk::line_add(ctx, request)), "story.line.edit" => with_write(handle, method, |ctx| desk::line_edit(ctx, request)), "story.line.remove" => with_write(handle, method, |ctx| desk::line_remove(ctx, request)), "story.line.move" => with_write(handle, method, |ctx| desk::line_move(ctx, request)), "story.person.lines" => with_read(handle, method, |ctx| desk::person_lines(ctx, request)), "story.scene.add" => with_write(handle, method, |ctx| desk::scene_add(ctx, request)), "story.scene.place" => with_write(handle, method, |ctx| desk::scene_place(ctx, request)), "story.scene.leave" => with_write(handle, method, |ctx| desk::scene_leave(ctx, request)), "story.scene.remove" => with_write(handle, method, |ctx| desk::scene_remove(ctx, request)), "story.sequence.add" => with_write(handle, method, |ctx| desk::sequence_add(ctx, request)), "story.sequence.edit" => with_write(handle, method, |ctx| desk::sequence_edit(ctx, request)), "story.sequence.remove" => with_write(handle, method, |ctx| desk::sequence_remove(ctx, request)), "story.choose" => with_write(handle, method, |ctx| choose(ctx, request)), "story.start" => with_write(handle, method, |ctx| start(ctx, request)), "story.scene.write" => with_write(handle, method, |ctx| scene_write(ctx, request)), "story.scene.new" => with_write(handle, method, |ctx| scene_new(ctx, request)), "story.scene.move" => with_write(handle, method, |ctx| scene_move(ctx, request)), "story.scene.duplicate" => with_write(handle, method, |ctx| scene_duplicate(ctx, request)), "story.rename" => with_write(handle, method, |ctx| rename(ctx, request)), "story.fountain.read" => with_write(handle, method, |ctx| fountain_read(ctx, request)), "story.bring_in" => bring_in(handle, method, request), "story.copy" => with_write(handle, method, |ctx| copy(ctx, request)), other => Err(MethodError::new("unknown_method", format!("`{other}` is not a story method"))), } } /// A signed-in phone whose pass to the personal object has not caught up, /// or whose scripts came down sealed before it held the key, holding no /// story yet: its scripts may still be coming, so the home says /// so (`arriving`, with `arriving_line`) instead of "Nothing here yet". A /// stopped sync loop is not arriving: the account says why it stopped. fn arriving(handle: &CottonHandle, mut answer: Value, count: &str) -> Value { let none = match &answer[count] { Value::Array(stories) => stories.is_empty(), Value::Number(n) => n.as_u64() == Some(0), _ => false, }; let client = handle.client(); // Scripts that came down sealed before this phone held the key wait parked, and open once it does. let parked = || { client .with_file(|file| { file.driver // A seek on the parks' own key (tbl first), one row read at most: never a count of every park // (FIRST SYNC 9). .get("SELECT count(*) AS n FROM (SELECT 1 FROM _seal_parked WHERE tbl >= 'story' AND tbl < 'storz' LIMIT 1)", &[]) .map_err(|error| error.to_string()) .map(|row| row.and_then(|row| row.int("n")).unwrap_or(0)) }) .unwrap_or(0) > 0 }; let coming = none && client.signed_in() && client.sync_status()["loop"]["stoppedReason"].as_str().is_none() && (client.sync_progress().is_some_and(|progress| !progress.state().caught_up) || parked()); answer["arriving"] = json!(coming); if coming { answer["arriving_line"] = json!(line("home.arriving", &[]).unwrap_or_default()); } answer } /// Cotton Story's fan cards and the card of the current screenplay. pub(crate) fn fan_cards(client: &crate::shell::client::ClientController) -> Result<(Vec, Option), MethodError> { let mut refusal: Option = None; let answer = client.read_rows("story.fan", &mut |ctx| { desk::fan_cards(ctx).map_err(|refused| { let said = refused.message.clone(); refusal = Some(refused); said }) }); let answer = answer.map_err(|why| refusal.take().unwrap_or_else(|| MethodError::new("unreadable", why)))?; Ok((answer["cards"].as_array().cloned().unwrap_or_default(), answer["current"].as_str().map(str::to_string))) } /// Run `body` over this copy's rows, a read. fn with_read(handle: &CottonHandle, label: &str, mut body: impl FnMut(&mut Ctx<'_>) -> Result) -> Result { let mut refusal: Option = None; let answer = handle.client().read_rows(label, &mut |ctx| { body(ctx).map_err(|refused| { let said = refused.message.clone(); refusal = Some(refused); said }) }); match (answer, refusal) { (Ok(answer), _) => Ok(answer), (Err(_), Some(refused)) => Err(refused), (Err(why), None) => Err(MethodError::new("unreadable", why)), } } /// Run `body` over this copy's rows as one write; it queues for the object. fn with_write(handle: &CottonHandle, label: &str, mut body: impl FnMut(&mut Ctx<'_>) -> Result) -> Result { let mut refusal: Option = None; let answer = handle.client().write_rows(label, &mut |ctx| { body(ctx).map_err(|refused| { let said = refused.message.clone(); refusal = Some(refused); said }) }); match (answer, refusal) { (Ok(answer), _) => Ok(crate::authoring::own_answer(answer)), (Err(_), Some(refused)) => Err(refused), (Err(why), None) => Err(MethodError::new("write_refused", why)), } } fn tool(failure: cotton_tools::mcp::protocol::ToolFailure) -> MethodError { MethodError::new("write_refused", failure.to_string()) } fn object(value: Value) -> Map { value.as_object().cloned().unwrap_or_default() } fn text<'a>(request: &'a Value, key: &str) -> Option<&'a str> { request.get(key).and_then(Value::as_str) } fn id_of<'a>(request: &'a Value, field: &str) -> Result<&'a str, MethodError> { text(request, field).map(str::trim).filter(|id| !id.is_empty()).ok_or_else(|| bad(format!("this names `{field}`"))) } // ── rows ──────────────────────────────────────────────────────────────────── /// Every live row of `table` where `filter` holds: its data with its id. fn rows(ctx: &mut Ctx<'_>, table: &str, filter: Value) -> Result>, MethodError> { let mut out = Vec::new(); let mut page = 0u64; loop { let ask = object(json!({ "table": table, "where": filter, "limit": 500, "page": page })); let listed = tables::list_records(ctx, &ask).map_err(tool)?; let records = listed["records"].as_array().cloned().unwrap_or_default(); let got = records.len(); for record in records { let mut data = object(record["data"].clone()); if let Some(id) = record["id"].as_str() { data.insert("id".into(), json!(id)); } if let Some(made) = record["created_at"].as_str() { data.entry("created_at").or_insert(json!(made)); } out.push(data); } match listed["next_page"].as_u64() { Some(next) if got > 0 && next > page => page = next, _ => break, } } Ok(out) } fn get(ctx: &mut Ctx<'_>, table: &str, id: &str) -> Option> { let got = tables::get_record_by_table(ctx, &object(json!({ "table": table, "id": id }))).ok()?; let record = if got.get("record").is_some() { &got["record"] } else { &got }; let mut data = object(record["data"].clone()); data.insert("id".into(), json!(id)); Some(data) } fn create(ctx: &mut Ctx<'_>, table: &str, data: Value) -> Result { let made = tables::create_produced_record(ctx, &object(json!({ "table": table, "data": data }))).map_err(tool)?; made["record"]["id"].as_str().or_else(|| made["id"].as_str()).map(str::to_string).ok_or_else(|| MethodError::new("write_refused", format!("no id for the new {table}"))) } /// Write what moved: a key the row already holds as it is is left out, so a /// writer saving the same body again (its debounce, leaving a field) is no /// write and no refusal. fn update(ctx: &mut Ctx<'_>, table: &str, id: &str, mut patch: Map) -> Result<(), MethodError> { if let Some(held) = get(ctx, table, id) { patch.retain(|key, value| held.get(key).unwrap_or(&Value::Null) != value); } if patch.is_empty() { return Ok(()); } tables::update_produced_record(ctx, &object(json!({ "table": table, "id": id, "patch": Value::Object(patch) }))).map_err(tool)?; Ok(()) } fn str_of<'a>(row: &'a Map, key: &str) -> &'a str { row.get(key).and_then(Value::as_str).unwrap_or_default() } fn num_of(row: &Map, key: &str) -> f64 { row.get(key).and_then(Value::as_f64).unwrap_or(0.0) } fn now_iso(ctx: &Ctx<'_>) -> String { let ms = cotton_tools::mcp::handlers::common::now_ms(ctx); chrono::DateTime::from_timestamp_millis(ms).unwrap_or_default().to_rfc3339_opts(chrono::SecondsFormat::Millis, true) } fn today(ctx: &Ctx<'_>) -> String { now_iso(ctx)[..10].to_string() } /// The story's scenes in order (by position, then when made). fn scenes_of(ctx: &mut Ctx<'_>, story: &str) -> Result>, MethodError> { let mut scenes = rows(ctx, SCENE, json!({ "story": story }))?; scenes.sort_by(|a, b| { num_of(a, "position").partial_cmp(&num_of(b, "position")).unwrap_or(std::cmp::Ordering::Equal).then_with(|| str_of(a, "created_at").cmp(str_of(b, "created_at"))) }); Ok(scenes) } /// The story's characters, most speeches first. fn characters_of(ctx: &mut Ctx<'_>, story: &str) -> Result>, MethodError> { let mut found = rows(ctx, CHARACTER, json!({ "story": story }))?; found.sort_by(|a, b| num_of(b, "lines").partial_cmp(&num_of(a, "lines")).unwrap_or(std::cmp::Ordering::Equal).then_with(|| str_of(a, "name").cmp(str_of(b, "name")))); Ok(found) } fn names_in(characters: &[Map]) -> Vec { characters.iter().map(|row| str_of(row, "name").to_string()).filter(|name| !name.trim().is_empty()).collect() } /// The current story: the latest chosen, else the newest; none with no story. fn current_story(ctx: &mut Ctx<'_>) -> Result<(Option>, usize), MethodError> { let stories = rows(ctx, STORY, json!({}))?; let count = stories.len(); let chosen = stories.iter().filter(|row| !str_of(row, "chosen_at").is_empty()).max_by(|a, b| str_of(a, "chosen_at").cmp(str_of(b, "chosen_at"))).cloned(); let newest = || stories.iter().max_by(|a, b| str_of(a, "made_at").cmp(str_of(b, "made_at")).then_with(|| str_of(a, "created_at").cmp(str_of(b, "created_at")))).cloned(); Ok((chosen.or_else(newest), count)) } /// The story a request names, or the current one. fn story_named(ctx: &mut Ctx<'_>, request: &Value) -> Result { if let Some(id) = text(request, "story").map(str::trim).filter(|id| !id.is_empty()) { return get(ctx, STORY, id).map(|_| id.to_string()).ok_or_else(|| refused("not_found", line("refusal.no_story", &[]).unwrap_or_default())); } match current_story(ctx)?.0 { Some(story) => Ok(str_of(&story, "id").to_string()), None => Err(refused("not_found", line("refusal.no_story", &[])?)), } } /// The names a request reads lines with: its own `names`, and the story's /// characters when it names a story or a scene. fn names_for(ctx: &mut Ctx<'_>, request: &Value) -> Result, MethodError> { let mut names: Vec = request.get("names").and_then(Value::as_array).map(|list| list.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default(); let story = match (text(request, "story"), text(request, "scene")) { (Some(story), _) if !story.trim().is_empty() => Some(story.trim().to_string()), (_, Some(scene)) if !scene.trim().is_empty() => get(ctx, SCENE, scene.trim()).map(|row| str_of(&row, "story").to_string()), _ => None, }; if let Some(story) = story { for name in names_in(&characters_of(ctx, &story)?) { if !names.iter().any(|known| same_name(known, &name)) { names.push(name); } } } Ok(names) } // ── writing ──────────────────────────────────────────────────────────────── fn kind_of(word: &str) -> Result { Kind::parse(word).ok_or_else(|| bad(line("refusal.not_a_kind", &[("kind", word)]).unwrap_or_default())) } fn lines_of(ctx: &mut Ctx<'_>, request: &Value) -> Result { let body = text(request, "body").unwrap_or_default(); let names = names_for(ctx, request)?; let chosen = match request.get("chosen") { Some(chosen) if chosen.is_object() => { let line = chosen["line"].as_u64().ok_or_else(|| bad("chosen names its line"))? as usize; Some((line, kind_of(chosen["kind"].as_str().unwrap_or_default())?)) } _ => None, }; Ok(json!({ "lines": story_lines::lines_chosen(body, &names, chosen) })) } fn pressed(ctx: &mut Ctx<'_>, request: &Value) -> Result { let body = text(request, "body").unwrap_or_default(); let cursor = request.get("cursor").and_then(Value::as_u64).ok_or_else(|| bad("this names the cursor"))? as usize; let key = match text(request, "key") { Some("return") => press::Key::Return, Some("tab") => press::Key::Tab, other => return Err(bad(line("refusal.not_a_key", &[("key", other.unwrap_or_default())])?)), }; let chosen = text(request, "kind").map(kind_of).transpose()?; let names = names_for(ctx, request)?; let answer = press::press(body, cursor, key, &names, chosen); with_names(answer, &names) } fn kinded(ctx: &mut Ctx<'_>, request: &Value) -> Result { let body = text(request, "body").unwrap_or_default(); let at = request.get("line").and_then(Value::as_u64).ok_or_else(|| bad("this names the line"))? as usize; let kind = kind_of(text(request, "kind").unwrap_or_default())?; let names = names_for(ctx, request)?; let answer = press::kind(body, at, kind, &names); with_names(answer, &names) } /// A press's answer, with the names to offer when its line is a name. fn with_names(answer: press::Pressed, names: &[String]) -> Result { let mut out = json!({ "body": answer.body, "cursor": answer.cursor, "kind": answer.kind, "line": answer.line }); if answer.kind == Kind::Character { let read = story_lines::lines(&answer.body, names); let typed = read.get(answer.line).map(|line| unmarked(Kind::Character, &line.text)).unwrap_or_default(); let offered: Vec = story_names::offered(&read, answer.line, names, &typed).into_iter().filter(|name| !same_name(name, &typed)).collect(); out["names"] = json!(offered); } Ok(out) } fn names_of(ctx: &mut Ctx<'_>, request: &Value) -> Result { let story = story_named(ctx, request)?; let names = names_in(&characters_of(ctx, &story)?); let scene_body = match text(request, "scene").map(str::trim).filter(|id| !id.is_empty()) { Some(scene) => get(ctx, SCENE, scene).map(|row| str_of(&row, "body").to_string()).unwrap_or_default(), None => String::new(), }; let read = story_lines::lines(&scene_body, &names); let before = request.get("before").and_then(Value::as_u64).map(|n| n as usize).unwrap_or(read.len()); Ok(json!({ "names": story_names::offered(&read, before, &names, text(request, "prefix").unwrap_or_default()) })) } fn figures_of(request: &Value) -> Result { let names: Vec = request.get("names").and_then(Value::as_array).map(|list| list.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default(); let found = figures::of_scene(text(request, "heading").unwrap_or_default(), text(request, "body").unwrap_or_default(), &names); Ok(json!(found)) } /// Find the story's place by name, making it when it has none. fn place_named(ctx: &mut Ctx<'_>, story: &str, name: &str, made: &mut Vec) -> Result, MethodError> { let name = name.trim(); if name.is_empty() { return Ok(None); } let places = rows(ctx, PLACE, json!({ "story": story }))?; if let Some(place) = places.iter().find(|row| same_name(str_of(row, "name"), name)) { return Ok(Some(str_of(place, "id").to_string())); } let id = create(ctx, PLACE, json!({ "story": story, "name": name }))?; made.push(id.clone()); Ok(Some(id)) } /// Recount every character's scenes and speeches over the story's scenes, /// making a character for a speaker the story has no row for. fn recount(ctx: &mut Ctx<'_>, story: &str, made: &mut Vec) -> Result<(), MethodError> { let characters = characters_of(ctx, story)?; let names = names_in(&characters); let mut tally: Vec<(String, u64, u64)> = Vec::new(); for scene in scenes_of(ctx, story)? { let read = story_lines::lines(str_of(&scene, "body"), &names); for (name, speeches) in story_names::speeches(&read) { match tally.iter_mut().find(|(seen, _, _)| same_name(seen, &name)) { Some((_, scenes, lines)) => { *scenes += 1; *lines += speeches; } None => tally.push((name, 1, speeches)), } } } let mut cast_grew = false; for (name, _, _) in &tally { if !characters.iter().any(|row| same_name(str_of(row, "name"), name)) { let id = create(ctx, CHARACTER, json!({ "story": story, "name": name, "scenes": 0, "lines": 0 }))?; made.push(id); cast_grew = true; } } if cast_grew { refigure(ctx, story)?; } for character in characters_of(ctx, story)? { let (scenes, lines) = tally.iter().find(|(name, _, _)| same_name(name, str_of(&character, "name"))).map(|(_, scenes, lines)| (*scenes, *lines)).unwrap_or((0, 0)); let mut patch = Map::new(); if num_of(&character, "scenes") as u64 != scenes || character.get("scenes").is_none() { patch.insert("scenes".into(), json!(scenes)); } if num_of(&character, "lines") as u64 != lines || character.get("lines").is_none() { patch.insert("lines".into(), json!(lines)); } update(ctx, CHARACTER, str_of(&character, "id"), patch)?; } Ok(()) } /// Every scene's figures worked out again with the story's names as they now stand, written where they changed. A /// scene's figures are worked out when its heading or body is written, with the names then known; the names steer the /// reading (a cue is a known name), so a character added since can change them. The lists read the figures as kept /// (`desk::minutes_of`) rather than reading every body again at launch, so a new name refigures the story here. pub(super) fn refigure(ctx: &mut Ctx<'_>, story: &str) -> Result<(), MethodError> { let names = names_in(&characters_of(ctx, story)?); for scene in scenes_of(ctx, story)? { let figured = derived(str_of(&scene, "heading"), str_of(&scene, "body"), &names); // A number is the same number however it was written (a kept 2 and a worked-out 2.0). let same = |kept: Option<&Value>, now: &Value| match (kept.and_then(Value::as_f64), now.as_f64()) { (Some(a), Some(b)) => a == b, _ => kept == Some(now), }; let patch: Map = figured.into_iter().filter(|(key, value)| !same(scene.get(key), value)).collect(); if !patch.is_empty() { update(ctx, SCENE, str_of(&scene, "id"), patch)?; } } Ok(()) } /// A scene's derived columns from its heading and body. fn derived(heading_text: &str, body: &str, names: &[String]) -> Map { let found = figures::of_scene(heading_text, body, names); object(json!({ "words": found.words, "pages": found.pages, "minutes": found.minutes, "speakers": found.speakers.join("\n"), })) } fn scene_answer(ctx: &mut Ctx<'_>, id: &str, made_characters: Vec, made_places: Vec) -> Result { let row = get(ctx, SCENE, id).ok_or_else(|| refused("not_found", line("refusal.no_scene", &[]).unwrap_or_default()))?; Ok(json!({ "scene": { "id": id, "heading": row.get("heading").cloned().unwrap_or(Value::Null), "setting": row.get("setting").cloned().unwrap_or(Value::Null), "place": row.get("place").cloned().unwrap_or(Value::Null), "time": row.get("time").cloned().unwrap_or(Value::Null), "words": row.get("words").cloned().unwrap_or(json!(0)), "pages": row.get("pages").cloned().unwrap_or(json!(0)), "minutes": row.get("minutes").cloned().unwrap_or(json!(0)), "speakers": row.get("speakers").cloned().unwrap_or(json!("")), }, "made": { "characters": made_characters, "places": made_places }, })) } /// Write a scene: what the request sends, the heading and its parts kept in /// step, the figures worked out, new places and speakers made. fn write_scene(ctx: &mut Ctx<'_>, id: &str, request: &Value) -> Result<(Vec, Vec), MethodError> { let row = get(ctx, SCENE, id).ok_or_else(|| refused("not_found", line("refusal.no_scene", &[]).unwrap_or_default()))?; let story = str_of(&row, "story").to_string(); let mut patch = Map::new(); let mut made_places = Vec::new(); let mut made_characters = Vec::new(); for key in ["summary", "status", "body"] { if let Some(value) = request.get(key).filter(|value| value.is_string() || value.is_null()) { patch.insert(key.into(), value.clone()); } } if let Some(day) = request.get("day").filter(|day| day.is_number() || day.is_null()) { patch.insert("day".into(), day.clone()); } let current_place_name = match row.get("place").and_then(Value::as_str) { Some(place) => get(ctx, PLACE, place).map(|place| str_of(&place, "name").to_string()).unwrap_or_default(), None => String::new(), }; let parts = if let Some(typed) = text(request, "heading") { let mut parts = heading::parse(typed); if parts.setting.is_none() && !typed.trim().starts_with('.') { parts.setting = Some(str_of(&row, "setting").to_string()).filter(|setting| !setting.is_empty()); } patch.insert("heading".into(), json!(typed.trim())); Some(parts) } else if ["setting", "place", "time"].iter().any(|key| request.get(*key).is_some()) { let mut parts = heading::Parts { setting: Some(str_of(&row, "setting").to_string()).filter(|setting| !setting.is_empty()), place: current_place_name.clone(), time: Some(str_of(&row, "time").to_string()).filter(|time| !time.is_empty()), }; if let Some(setting) = text(request, "setting") { parts.setting = Some(setting.to_string()); } if let Some(place) = text(request, "place") { parts.place = place.to_string(); } if request.get("time").is_some() { parts.time = text(request, "time").map(str::to_string).filter(|time| !time.trim().is_empty()); } patch.insert("heading".into(), json!(heading::compose(&parts))); Some(parts) } else { None }; if let Some(parts) = parts { if let Some(setting) = parts.setting.as_deref().filter(|setting| matches!(*setting, "INT." | "EXT." | "INT./EXT.")) { patch.insert("setting".into(), json!(setting)); } patch.insert("time".into(), parts.time.as_deref().map(|time| json!(time)).unwrap_or(Value::Null)); let place = place_named(ctx, &story, &parts.place, &mut made_places)?; patch.insert("place".into(), place.map(Value::from).unwrap_or(Value::Null)); } let heading_now = patch.get("heading").and_then(Value::as_str).unwrap_or(str_of(&row, "heading")).to_string(); let body_now = patch.get("body").and_then(Value::as_str).unwrap_or(str_of(&row, "body")).to_string(); let names = names_in(&characters_of(ctx, &story)?); let before = story_names::speeches(&story_lines::lines(str_of(&row, "body"), &names)); let after = story_names::speeches(&story_lines::lines(&body_now, &names)); patch.extend(derived(&heading_now, &body_now, &names)); update(ctx, SCENE, id, patch)?; if before != after { recount(ctx, &story, &mut made_characters)?; } Ok((made_characters, made_places)) } /// `story.scene.write { id, body?, base?, … }`. `base`, the body the writer last loaded: a body /// saved from a writer opened on an older scene (another device or the assistant changed it since) /// is merged into the newer one line by line, never put over it (STALE, 21 Nov 2026), and the answer /// carries the scene's `body` for the writer to take, with `merged`, `both_kept` and `said`. fn scene_write(ctx: &mut Ctx<'_>, request: &Value) -> Result { let id = id_of(request, "id")?.to_string(); let mut request = request.clone(); let mut merged = None; let based = text(&request, "base").map(str::to_string); if let (Some(sent), Some(base)) = (text(&request, "body").map(str::to_string), based.as_deref()) { let row = get(ctx, SCENE, &id).ok_or_else(|| refused("not_found", line("refusal.no_scene", &[]).unwrap_or_default()))?; let (kept, both) = crate::phone::notes::laid_over(str_of(&row, "body"), &sent, Some(base)); request["body"] = json!(kept); merged = both; } let (characters, places) = write_scene(ctx, &id, &request)?; if request.get("body").is_some_and(Value::is_string) { desk::adopted(ctx, &id)?; } let mut answer = scene_answer(ctx, &id, characters, places)?; if based.is_some() { answer["scene"]["body"] = get(ctx, SCENE, &id).and_then(|row| row.get("body").cloned()).unwrap_or(Value::Null); } if let Some(both_kept) = merged { answer["merged"] = json!(true); answer["both_kept"] = json!(both_kept); answer["said"] = json!(line(if both_kept { "writer.merged_both" } else { "writer.merged" }, &[])?); } Ok(answer) } /// Shift the positions of the story's scenes at or after `from` by one. fn make_room(ctx: &mut Ctx<'_>, story: &str, from: f64) -> Result<(), MethodError> { for scene in scenes_of(ctx, story)? { let position = num_of(&scene, "position"); if position >= from { update(ctx, SCENE, str_of(&scene, "id"), object(json!({ "position": position + 1.0 })))?; } } desk::marks_shift(ctx, story, from) } fn scene_new(ctx: &mut Ctx<'_>, request: &Value) -> Result { let (story, position) = match text(request, "after").map(str::trim).filter(|id| !id.is_empty()) { Some(after) => { let row = get(ctx, SCENE, after).ok_or_else(|| refused("not_found", line("refusal.no_scene", &[]).unwrap_or_default()))?; let story = str_of(&row, "story").to_string(); let position = num_of(&row, "position") + 1.0; make_room(ctx, &story, position)?; (story, position) } None => { let story = story_named(ctx, request)?; let last = scenes_of(ctx, &story)?.iter().map(|scene| num_of(scene, "position")).fold(0.0, f64::max); (story, last + 1.0) } }; let id = create(ctx, SCENE, json!({ "story": story, "position": position, "setting": "INT.", "status": "draft", "words": 0, "pages": 0, "minutes": 0, "speakers": "" }))?; // The writer opens on it where Plus made it (`ListCreate::method`). Ok(json!({ "scene": id, "position": position, "platform_action": "open_writer" })) } fn renumber(ctx: &mut Ctx<'_>, ordered: &[Map]) -> Result, MethodError> { let mut out = Vec::new(); for (at, scene) in ordered.iter().enumerate() { let position = (at + 1) as f64; if num_of(scene, "position") != position { update(ctx, SCENE, str_of(scene, "id"), object(json!({ "position": position })))?; } out.push(json!({ "id": str_of(scene, "id"), "position": position })); } Ok(out) } fn scene_move(ctx: &mut Ctx<'_>, request: &Value) -> Result { let id = id_of(request, "id")?; let row = get(ctx, SCENE, id).ok_or_else(|| refused("not_found", line("refusal.no_scene", &[]).unwrap_or_default()))?; let mut ordered = scenes_of(ctx, str_of(&row, "story"))?; let at = ordered.iter().position(|scene| str_of(scene, "id") == id).unwrap_or(0); let to = if let Some(by) = request.get("by").and_then(Value::as_i64) { (at as i64 + by).clamp(0, ordered.len() as i64 - 1) as usize } else if let Some(to) = request.get("to").and_then(Value::as_u64) { (to.max(1) as usize - 1).min(ordered.len() - 1) } else { return Err(bad("this names `by` (-1 or 1) or `to` (a position from 1)")); }; let story = str_of(&row, "story").to_string(); let marks = desk::marks_held(ctx, &story, &ordered)?; let moving = ordered.remove(at); ordered.insert(to, moving); let positions = renumber(ctx, &ordered)?; desk::marks_put(ctx, &story, marks)?; Ok(json!({ "positions": positions })) } fn scene_duplicate(ctx: &mut Ctx<'_>, request: &Value) -> Result { let id = id_of(request, "id")?; let row = get(ctx, SCENE, id).ok_or_else(|| refused("not_found", line("refusal.no_scene", &[]).unwrap_or_default()))?; let story = str_of(&row, "story").to_string(); let position = num_of(&row, "position") + 1.0; make_room(ctx, &story, position)?; let mut data = Map::new(); for key in ["story", "setting", "place", "time", "heading", "summary", "body", "status", "words", "pages", "minutes", "speakers"] { if let Some(value) = row.get(key).filter(|value| !value.is_null()) { data.insert(key.into(), value.clone()); } } data.insert("position".into(), json!(position)); let copy = create(ctx, SCENE, Value::Object(data))?; desk::adopted(ctx, ©)?; let mut made = Vec::new(); recount(ctx, &story, &mut made)?; Ok(json!({ "scene": copy })) } fn near(ctx: &mut Ctx<'_>, request: &Value) -> Result { let id = id_of(request, "id")?; let row = get(ctx, SCENE, id).ok_or_else(|| refused("not_found", line("refusal.no_scene", &[]).unwrap_or_default()))?; let ordered = scenes_of(ctx, str_of(&row, "story"))?; let at = ordered.iter().position(|scene| str_of(scene, "id") == id).unwrap_or(0); let id_at = |index: Option| index.and_then(|index| ordered.get(index)).map(|scene| json!(str_of(scene, "id"))).unwrap_or(Value::Null); Ok(json!({ "previous": id_at(at.checked_sub(1)), "next": id_at(Some(at + 1)), "number": at + 1, "of": ordered.len() })) } /// Rewrite a character line's name, keeping its marks and extensions. fn renamed_line(line_text: &str, old: &str, new: &str) -> Option { let trimmed = line_text.trim(); let forced = trimmed.starts_with('@'); let inner = trimmed.trim_start_matches('@'); let bare = story_lines::bare_name(inner); if !same_name(&bare, old) { return None; } let rest = &inner[bare.len()..]; let caps = bare.chars().any(char::is_uppercase) && !bare.chars().any(char::is_lowercase); let name = if caps { new.to_uppercase() } else { new.to_string() }; let mut out = String::new(); let upper = name.chars().any(char::is_uppercase) && !name.chars().any(char::is_lowercase); if forced || !(upper || story_lines::caps_name(&name)) { out.push('@'); } out.push_str(&name); out.push_str(rest); Some(out) } fn rename(ctx: &mut Ctx<'_>, request: &Value) -> Result { let table = text(request, "table").unwrap_or_default(); let id = id_of(request, "id")?; let new = text(request, "name").map(str::trim).filter(|name| !name.is_empty()).ok_or_else(|| bad("this names the new `name`"))?.to_string(); if !matches!(table, CHARACTER | PLACE) { return Err(bad("`table` is story_character or story_place")); } let row = get(ctx, table, id).ok_or_else(|| refused("not_found", format!("no {table} {id}")))?; let story = str_of(&row, "story").to_string(); let old = str_of(&row, "name").to_string(); update(ctx, table, id, object(json!({ "name": new })))?; let mut changed = 0usize; let names = names_in(&characters_of(ctx, &story)?); let mut with_old = names.clone(); with_old.push(old.clone()); for scene in scenes_of(ctx, &story)? { let scene_id = str_of(&scene, "id").to_string(); if table == CHARACTER { let body = str_of(&scene, "body"); let read = story_lines::lines(body, &with_old); let mut out_lines: Vec = read.iter().map(|line| line.text.clone()).collect(); let mut touched = false; for (index, line) in read.iter().enumerate() { if line.kind == Kind::Character { if let Some(rewritten) = renamed_line(&line.text, &old, &new) { out_lines[index] = rewritten; touched = true; } } } if touched { changed += 1; write_scene(ctx, &scene_id, &json!({ "body": out_lines.join("\n") }))?; desk::adopted(ctx, &scene_id)?; } } else { let parts = heading::parse(str_of(&scene, "heading")); if same_name(&parts.place, &old) || str_of(&scene, "place") == id { let composed = heading::compose(&heading::Parts { place: new.clone(), ..parts }); changed += 1; let mut patch = Map::new(); patch.insert("heading".into(), json!(composed)); patch.insert("place".into(), json!(id)); let body = str_of(&scene, "body").to_string(); patch.extend(derived(&composed, &body, &names)); update(ctx, SCENE, &scene_id, patch)?; } } } Ok(json!({ "scenes": changed })) } // ── the current story ────────────────────────────────────────────────────── fn current(ctx: &mut Ctx<'_>) -> Result { let (story, count) = current_story(ctx)?; let story = story.map(|row| json!({ "id": str_of(&row, "id"), "title": str_of(&row, "title"), "language": str_of(&row, "language"), "format": str_of(&row, "format") })); Ok(json!({ "story": story, "stories": count })) } fn choose(ctx: &mut Ctx<'_>, request: &Value) -> Result { let id = id_of(request, "story")?; get(ctx, STORY, id).ok_or_else(|| refused("not_found", line("refusal.no_story", &[]).unwrap_or_default()))?; let now = now_iso(ctx); update(ctx, STORY, id, object(json!({ "chosen_at": now })))?; Ok(json!({ "story": id })) } fn start(ctx: &mut Ctx<'_>, request: &Value) -> Result { let title = text(request, "title").map(str::trim).filter(|title| !title.is_empty()).ok_or_else(|| bad("this names the story's `title`"))?; let (made_at, chosen_at) = (today(ctx), now_iso(ctx)); let id = create(ctx, STORY, json!({ "title": title, "language": "English", "format": "feature", "made_at": made_at, "chosen_at": chosen_at }))?; Ok(json!({ "story": id })) } // ── cards ────────────────────────────────────────────────────────────────── fn length_words(pages: f64) -> Result { if pages < 1.0 { return line("length.under_a_page", &[]); } counted("length.pages", pages.round() as i64) } fn card(ctx: &mut Ctx<'_>, request: &Value) -> Result { let id = id_of(request, "id")?; let row = get(ctx, SCENE, id).ok_or_else(|| refused("not_found", line("refusal.no_scene", &[]).unwrap_or_default()))?; let story = str_of(&row, "story").to_string(); let ordered = scenes_of(ctx, &story)?; let number = ordered.iter().position(|scene| str_of(scene, "id") == id).map(|at| at + 1).unwrap_or(0); let names = names_in(&characters_of(ctx, &story)?); let opening: Vec = story_lines::lines(str_of(&row, "body"), &names) .into_iter() .filter(|line| !matches!(line.kind, Kind::Blank | Kind::Note)) .take(4) .map(|line| json!({ "kind": line.kind, "text": unmarked(line.kind, &line.text) })) .collect(); let summary = Some(str_of(&row, "summary").trim()).filter(|summary| !summary.is_empty()); let status = Some(str_of(&row, "status")).filter(|status| !status.is_empty()).unwrap_or("draft"); Ok(json!({ "number": number, "heading": str_of(&row, "heading"), "summary": summary, "opening": opening, "length": length_words(num_of(&row, "pages"))?, "status": status, "status_word": line(&format!("status.{status}"), &[])?, })) } fn chat_of(ctx: &mut Ctx<'_>, request: &Value) -> Result { let id = id_of(request, "id")?; let row = get(ctx, SCENE, id).ok_or_else(|| refused("not_found", line("refusal.no_scene", &[]).unwrap_or_default()))?; let story = str_of(&row, "story").to_string(); let names = names_in(&characters_of(ctx, &story)?); Ok(json!(chat::chat(str_of(&row, "body"), &names))) } // ── the script ───────────────────────────────────────────────────────────── /// The paper a script is laid on: Letter where it is the custom, else A4. fn paper(request: &Value) -> Value { let named = text(request, "paper").map(str::to_lowercase); let region = text(request, "region").map(str::to_uppercase).unwrap_or_default(); let letter = match named.as_deref() { Some("letter") => true, Some("a4") => false, _ => matches!(region.as_str(), "US" | "CA" | "PH" | "MX" | "CL" | "CO" | "VE"), }; if letter { json!({ "name": "letter", "width_pt": 612, "height_pt": 792, "margins_pt": { "top": 72, "bottom": 72, "left": 108, "right": 72 } }) } else { json!({ "name": "a4", "width_pt": 595, "height_pt": 842, "margins_pt": { "top": 72, "bottom": 72, "left": 108, "right": 55 } }) } } fn script(ctx: &mut Ctx<'_>, request: &Value) -> Result { let id = story_named(ctx, request)?; let story = get(ctx, STORY, &id).unwrap_or_default(); let names = names_in(&characters_of(ctx, &id)?); let scenes: Vec = scenes_of(ctx, &id)? .iter() .map(|scene| layout::SceneIn { id: str_of(scene, "id").to_string(), heading: str_of(scene, "heading").to_string(), body: str_of(scene, "body").to_string() }) .collect(); let laid = layout::script(&scenes, &names); let logline = str_of(&story, "logline").trim(); Ok(json!({ "paper": paper(request), "title_page": { "title": str_of(&story, "title"), "credit": line("script.title_page_by", &[])?, "author": written_by(ctx, &story), "lines": if logline.is_empty() { json!([]) } else { json!([logline]) }, }, "pages": laid.pages, "scenes": laid.scenes, })) } // ── out of the door and back ─────────────────────────────────────────────── fn file_name(title: &str) -> String { let cleaned: String = title.chars().map(|c| if matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') { ' ' } else { c }).collect(); let cleaned = cleaned.trim(); format!("{}.fountain", if cleaned.is_empty() { "Story" } else { cleaned }) } /// The story as Fountain's parts: its title page and scenes in order. fn doc_of(ctx: &mut Ctx<'_>, id: &str) -> Result<(fountain::Doc, String), MethodError> { let story = get(ctx, STORY, id).ok_or_else(|| refused("not_found", line("refusal.no_story", &[]).unwrap_or_default()))?; let mut title = vec![("Title".to_string(), str_of(&story, "title").to_string())]; let author = written_by(ctx, &story); if !author.is_empty() { title.push(("Credit".to_string(), line("script.title_page_by", &[])?)); title.push(("Author".to_string(), author.to_string())); } let made = str_of(&story, "made_at").trim(); if !made.is_empty() { title.push(("Draft date".to_string(), made.to_string())); } let scenes = scenes_of(ctx, id)? .iter() .map(|scene| fountain::SceneDoc { heading: str_of(scene, "heading").to_string(), summary: Some(str_of(scene, "summary").to_string()).filter(|summary| !summary.trim().is_empty()), body: str_of(scene, "body").to_string(), }) .collect(); Ok((fountain::Doc { title, scenes }, str_of(&story, "title").to_string())) } fn fountain_write(ctx: &mut Ctx<'_>, request: &Value) -> Result { let id = story_named(ctx, request)?; let (doc, title) = doc_of(ctx, &id)?; Ok(json!({ "text": fountain::write(&doc), "name": file_name(&title) })) } fn title_value<'a>(doc: &'a fountain::Doc, key: &str) -> Option<&'a str> { doc.title.iter().find(|(name, _)| name.eq_ignore_ascii_case(key)).map(|(_, value)| value.as_str()).filter(|value| !value.trim().is_empty()) } fn fountain_read(ctx: &mut Ctx<'_>, request: &Value) -> Result { let doc = fountain::read(text(request, "text").unwrap_or_default()); story_of(ctx, doc, text(request, "name")) } /// The most a script file may weigh: a feature's PDF is well under this. const BRING_IN_CEILING: u64 = 32 * 1024 * 1024; /// `story.bring_in { path, name? }` → `{ story, scenes, characters, places, /// from, check? }`: a script file the person picked, read by what it is (a /// PDF by its first bytes, a Final Draft file by its root, else Fountain or /// plain text) into a new story. A printed PDF is read by where its lines /// stand, so its answer carries `check`: the line asking the person to read /// it through. A locked PDF, a PDF with no words and a file with no script /// are refused by name. One at a time: a second while one is under way is /// refused `busy` with the same words the phone shows while it waits /// (`bring_in.busy`). fn bring_in(handle: &CottonHandle, method: &str, request: &Value) -> Result { let Some(_held) = BringingIn::hold(handle) else { return Err(refused("busy", line("bring_in.busy", &[])?)); }; let path = text(request, "path").ok_or_else(|| bad("this names the `path` of the picked file"))?; let name = text(request, "name").map(str::to_string).or_else(|| std::path::Path::new(path).file_name().map(|name| name.to_string_lossy().into_owned())); let size = std::fs::metadata(path).map_err(|error| MethodError::new("unreadable", format!("the picked file could not be read: {}", error.kind())))?.len(); if size > BRING_IN_CEILING { return Err(refused("too_big", line("bring_in.too_big", &[])?)); } let bytes = std::fs::read(path).map_err(|error| MethodError::new("unreadable", format!("the picked file could not be read: {}", error.kind())))?; let (doc, from) = if bytes.starts_with(b"%PDF") { (pdf_doc(&bytes)?, "pdf") } else { let said = String::from_utf8(bytes).unwrap_or_else(|error| error.into_bytes().iter().map(|byte| char::from(*byte)).collect()); match fdx::read(&said) { Some(doc) => (doc, "fdx"), None => (fountain::read(&said), "fountain"), } }; let mut answer = with_write(handle, method, |ctx| story_of(ctx, doc.clone(), name.as_deref()))?; answer["from"] = json!(from); if from == "pdf" { answer["check"] = json!(line("bring_in.check", &[])?); } Ok(answer) } /// One script file read in at a time on this handle: held for the length of /// a `story.bring_in`, let go when it answers, refused or not. pub(crate) struct BringingIn<'a>(&'a std::sync::atomic::AtomicBool); impl<'a> BringingIn<'a> { /// The hold, or None while another bring-in is under way. pub(crate) fn hold(handle: &'a CottonHandle) -> Option { use std::sync::atomic::Ordering; let flag = handle.story_bringing(); flag.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).ok().map(|_| Self(flag)) } } impl Drop for BringingIn<'_> { fn drop(&mut self) { self.0.store(false, std::sync::atomic::Ordering::Release); } } /// A printed screenplay's PDF read into a story by its columns. fn pdf_doc(bytes: &[u8]) -> Result { use cotton_core::health::lab::pdf::{pages_of, PdfError}; let pages = match pages_of(bytes) { Ok(pages) => pages, Err(PdfError::Locked) => return Err(refused("locked", line("bring_in.locked", &[])?)), Err(_) => return Err(refused("unreadable", line("fountain.unreadable", &[])?)), }; if pages.iter().all(|page| page.lines.is_empty()) { return Err(refused("no_text", line("bring_in.no_text", &[])?)); } let printed: Vec> = pages .iter() .map(|page| { page.lines .iter() .map(|row| script_in::PrintedLine { y: row.y, size: row.size, cells: row.cells.iter().map(|cell| (cell.x0, cell.text.clone())).collect() }) .collect() }) .collect(); let (elements, title, author) = script_in::pdf_elements(&printed); Ok(script_in::doc_of(title.as_deref(), author.as_deref(), &elements)) } /// A story made from a read script: its scenes, places and characters. fn story_of(ctx: &mut Ctx<'_>, doc: fountain::Doc, name: Option<&str>) -> Result { if doc.scenes.is_empty() && doc.title.is_empty() { return Err(refused("unreadable", line("fountain.unreadable", &[])?)); } let from_name = name.map(|name| name.rsplit_once('.').map(|(stem, _)| stem).unwrap_or(name).trim().to_string()).filter(|name| !name.is_empty()); let title = title_value(&doc, "Title").map(|title| title.replace('\n', " ")).or(from_name).unwrap_or_else(|| "Story".to_string()); let author = title_value(&doc, "Author").or_else(|| title_value(&doc, "Authors")).unwrap_or_default().to_string(); let drafted = title_value(&doc, "Draft date").map(str::trim).filter(|day| chrono::NaiveDate::parse_from_str(day, "%Y-%m-%d").is_ok()).map(str::to_string); let (made_at, chosen_at) = (drafted.unwrap_or_else(|| today(ctx)), now_iso(ctx)); let story = create(ctx, STORY, json!({ "title": title, "written_by": author, "language": "English", "format": "feature", "made_at": made_at, "chosen_at": chosen_at }))?; let (mut places, mut characters) = (Vec::new(), Vec::new()); for (at, scene) in doc.scenes.iter().enumerate() { let parts = heading::parse(&scene.heading); let place = place_named(ctx, &story, &parts.place, &mut places)?; let mut data = object(json!({ "story": story, "position": at + 1, "heading": scene.heading, "setting": parts.setting.clone().filter(|setting| matches!(setting.as_str(), "INT." | "EXT." | "INT./EXT.")).unwrap_or_else(|| "INT.".to_string()), "body": scene.body, "status": "draft", })); if let Some(place) = place { data.insert("place".into(), json!(place)); } if let Some(time) = parts.time { data.insert("time".into(), json!(time)); } if let Some(summary) = &scene.summary { data.insert("summary".into(), json!(summary)); } data.extend(derived(&scene.heading, &scene.body, &[])); create(ctx, SCENE, Value::Object(data))?; } recount(ctx, &story, &mut characters)?; ink::lay_story(ctx, &story)?; Ok(json!({ "story": story, "scenes": doc.scenes.len(), "characters": characters.len(), "places": places.len() })) } fn copy(ctx: &mut Ctx<'_>, request: &Value) -> Result { let id = id_of(request, "story")?; let language = text(request, "language").map(str::trim).filter(|language| !language.is_empty()).ok_or_else(|| bad("this names the `language`"))?; let story = get(ctx, STORY, id).ok_or_else(|| refused("not_found", line("refusal.no_story", &[]).unwrap_or_default()))?; let title = line("stories.copy_title", &[("title", str_of(&story, "title")), ("language", language)])?; let (made_at, chosen_at) = (today(ctx), now_iso(ctx)); let mut data = Map::new(); for key in ["logline", "written_by", "format", "interval_at"] { if let Some(value) = story.get(key).filter(|value| !value.is_null()) { data.insert(key.into(), value.clone()); } } data.insert("title".into(), json!(title)); data.insert("language".into(), json!(language)); data.insert("translation_of".into(), json!(id)); data.insert("made_at".into(), json!(made_at)); data.insert("chosen_at".into(), json!(chosen_at)); let copy = create(ctx, STORY, Value::Object(data))?; let mut places = std::collections::BTreeMap::new(); for place in rows(ctx, PLACE, json!({ "story": id }))? { let made = create(ctx, PLACE, json!({ "story": copy, "name": str_of(&place, "name"), "about": place.get("about").cloned().unwrap_or(Value::Null) }))?; places.insert(str_of(&place, "id").to_string(), made); } for character in rows(ctx, CHARACTER, json!({ "story": id }))? { let mut data = Map::new(); for key in ["name", "role", "about", "want", "picture", "scenes", "lines", "tint"] { if let Some(value) = character.get(key).filter(|value| !value.is_null()) { data.insert(key.into(), value.clone()); } } data.insert("story".into(), json!(copy)); create(ctx, CHARACTER, Value::Object(data))?; } let mut scenes = std::collections::BTreeMap::new(); for scene in scenes_of(ctx, id)? { let mut data = Map::new(); for key in ["position", "setting", "time", "day", "heading", "summary", "question", "body", "status", "words", "pages", "minutes", "speakers"] { if let Some(value) = scene.get(key).filter(|value| !value.is_null()) { data.insert(key.into(), value.clone()); } } data.insert("story".into(), json!(copy)); if let Some(place) = scene.get("place").and_then(Value::as_str).and_then(|place| places.get(place)) { data.insert("place".into(), json!(place)); } let made = create(ctx, SCENE, Value::Object(data))?; scenes.insert(str_of(&scene, "id").to_string(), made); } for note in rows(ctx, NOTE, json!({ "story": id }))? { let mut data = object(json!({ "story": copy })); for key in ["title", "body"] { if let Some(value) = note.get(key).filter(|value| !value.is_null()) { data.insert(key.into(), value.clone()); } } if let Some(scene) = note.get("scene").and_then(Value::as_str).and_then(|scene| scenes.get(scene)) { data.insert("scene".into(), json!(scene)); } create(ctx, NOTE, Value::Object(data))?; } for sequence in rows(ctx, desk::SEQUENCE, json!({ "story": id }))? { create(ctx, desk::SEQUENCE, json!({ "story": copy, "title": str_of(&sequence, "title"), "position": num_of(&sequence, "position"), "folded": sequence.get("folded").cloned().unwrap_or(json!(false)) }))?; } for answer in rows(ctx, desk::ANSWER, json!({ "story": id }))? { let mut data = object(json!({ "story": copy })); for key in ["question", "answer", "skipped", "answered_at"] { if let Some(value) = answer.get(key).filter(|value| !value.is_null()) { data.insert(key.into(), value.clone()); } } let made = create(ctx, desk::ANSWER, Value::Object(data))?; for scene in scenes_of(ctx, id)?.iter().filter(|scene| str_of(scene, "answer") == str_of(&answer, "id")) { if let Some(copied) = scenes.get(str_of(scene, "id")) { update(ctx, SCENE, copied, object(json!({ "answer": made })))?; } } } ink::lay_story(ctx, ©)?; Ok(json!({ "story": copy })) } #[cfg(test)] #[path = "story_tests.rs"] mod tests;