From f2c4a49a3548aa108b8d0c46b0f22944a4d93bf4 Mon Sep 17 00:00:00 2001 From: Whatever Industries <273006022+whatever-industries@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:55:58 -0800 Subject: [PATCH] Improve Lined Script tabs, take annotations and interactive Help (#5364) * ui: expand the Lined Script workspace and practice script * ui: protect Lined Script edits and route Help monitor commands by target * Script: record live marks during take playback * Script: place take playback beside the Edit pencil * Script: stop Program when screening a practice take * Script: keep Space on the running take after selecting another candle A Play or Record pass now owns the Source transport until it stops, so selecting a different candle no longer hands Space to Program playback. Play or Record on the newly selected candle stops the old pass and starts that take; the toolbar shows the stop state only for the selected take's pass. Keyboard Add Mark records only into the running take. * Script: refuse Add Mark on a candle outside the running take While a Play or Record pass runs, Add Mark on another selected candle would take the running Source frame or swap the Source clip out from under the pass. The command now refuses with a message, and the toolbar button is disabled with the same hint until the pass stops. --------- Co-authored-by: whatever-industries <77seventy77@users.noreply.github.com> --- README.md | 1 + crates/engine/src/autosave.rs | 3 + crates/engine/src/commands.rs | 4 +- crates/engine/src/lib.rs | 8 + crates/engine/src/script_commands.rs | 147 +- crates/engine/src/settings/schema.rs | 1 + crates/format/src/lib.rs | 3 + crates/project/src/lib.rs | 5 +- crates/project/src/script.rs | 45 +- crates/project/src/view.rs | 24 +- crates/ui-egui/README.md | 18 +- crates/ui-egui/src/app.rs | 22 +- crates/ui-egui/src/app/keys.rs | 9 +- crates/ui-egui/src/app/textures.rs | 16 +- crates/ui-egui/src/app/window.rs | 3 + crates/ui-egui/src/dock.rs | 209 ++- crates/ui-egui/src/i18n/tests.rs | 6 +- crates/ui-egui/src/icons.rs | 10 + crates/ui-egui/src/legacy_dropdown.rs | 16 +- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/links.rs | 2 + crates/ui-egui/src/menus.rs | 87 +- crates/ui-egui/src/panels.rs | 8 +- crates/ui-egui/src/panels/keyboard.rs | 8 +- crates/ui-egui/src/panels/media_dialogs.rs | 4 +- crates/ui-egui/src/panels/project_views.rs | 4 +- crates/ui-egui/src/panels/script.rs | 465 ++++-- crates/ui-egui/src/panels/script/canvas.rs | 949 +++++++----- crates/ui-egui/src/panels/script/layout.rs | 216 ++- crates/ui-egui/src/panels/script/playback.rs | 79 + crates/ui-egui/src/panels/script/practice.rs | 524 +++++++ crates/ui-egui/src/panels/script/recovery.rs | 8 +- crates/ui-egui/src/panels/script/selection.rs | 49 +- crates/ui-egui/src/panels/script/tabs.rs | 187 +++ crates/ui-egui/src/panels/script/toolbar.rs | 868 +++++++---- crates/ui-egui/src/panels/shortcuts_dialog.rs | 17 +- crates/ui-egui/src/panels/workspaces.rs | 7 +- crates/ui-egui/src/source_playback.rs | 3 + crates/ui-egui/src/widgets.rs | 12 +- crates/ui-egui/tests/it/script_ui.rs | 1311 +++++++++++++++-- crates/ui-egui/tests/it/workspaces_ui.rs | 28 +- docs/keyboard.md | 2 +- docs/lined-script.md | 67 + docs/project-files.md | 12 +- docs/script-window-settings.md | 36 - 45 files changed, 4357 insertions(+), 1147 deletions(-) create mode 100644 crates/ui-egui/src/panels/script/playback.rs create mode 100644 crates/ui-egui/src/panels/script/practice.rs create mode 100644 crates/ui-egui/src/panels/script/tabs.rs create mode 100644 docs/lined-script.md delete mode 100644 docs/script-window-settings.md diff --git a/README.md b/README.md index 2b5607ce9..a3bcef518 100644 --- a/README.md +++ b/README.md @@ -283,6 +283,7 @@ The control protocol is documented in [docs/control-protocol.md](docs/control-pr | [docs/testing.md](docs/testing.md) | Unit, property and ffmpeg-oracle tests, accuracy criteria, benchmarks | | [docs/agents.md](docs/agents.md) | Driving FilmCraft over MCP and the control channel; how agents develop it | | [docs/control-protocol.md](docs/control-protocol.md) | Control-channel and MCP reference | +| [Lined Script guide](docs/lined-script.md) | Import screenplay text, organize takes, mark dialogue and compare readings | | [docs/project-files.md](docs/project-files.md) | `.fcproj` format, schema migrations, auto-save and crash recovery | | [docs/graphics.md](docs/graphics.md) · [docs/captions.md](docs/captions.md) | Text engine, graphic clips and tools; caption tracks and formats | | [ROADMAP.md](ROADMAP.md) | Stage, parity numbers, languages, what's next and the progress log | diff --git a/crates/engine/src/autosave.rs b/crates/engine/src/autosave.rs index ec058d64f..53b934a4a 100644 --- a/crates/engine/src/autosave.rs +++ b/crates/engine/src/autosave.rs @@ -85,6 +85,8 @@ impl AutoSavePrefs { pub struct PlaybackPrefs { /// "Preroll: N seconds" (Play Around, trim-mode loop playback). pub preroll_seconds: f64, + /// Lead-in for Lined Script mark and row cues in the Source monitor. + pub lined_script_preroll_seconds: f64, /// "Postroll: N seconds". pub postroll_seconds: f64, /// "Step forward/back many: N frames" (Shift+Right / Shift+Left). @@ -107,6 +109,7 @@ impl Default for PlaybackPrefs { fn default() -> Self { Self { preroll_seconds: 3.0, + lined_script_preroll_seconds: 0.5, postroll_seconds: 2.0, step_many_frames: 5, pause_encoder_queue: true, diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index bcba3716a..207fd5f03 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -3305,7 +3305,7 @@ fn build() -> Vec { .ok_or_else(|| bad("source.open", "need `item` (or a Project panel selection)"))?; let source = s.project.item(id).ok_or_else(|| bad("source.open", "no such item"))?; if matches!(source.kind, ItemKind::Script(_)) { - return Err(bad("source.open", "Scripts open in the Script panel, not the Source monitor")); + return Err(bad("source.open", "Scripts open in the Lined Script panel")); } s.state.source_item = Some(id); // a subclip opens at its In point @@ -5482,7 +5482,7 @@ fn open_project(s: &mut Session, path: &str) -> Result { let (from, migrated) = (loaded.schema_version, loaded.migrated()); crate::masks::discard_jobs(s); install_project(s, loaded.project, Some(path.to_string()), true); - if let Some(view) = loaded.view.filter(|_| s.prefs.timeline.restore_open_sequences) { + if let Some(view) = loaded.view { s.restore_project_view(view); } // the frontend shows the project's active sequence (with its own view, when one was restored) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 03128f3ea..7f477b05e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -407,6 +407,9 @@ pub struct EditorState { /// off: a sequence edits in as its clips instead of one nested clip. #[serde(default)] pub sequences_as_clips: bool, + /// Lined Script tab identities, independent of document edits. + #[serde(default)] + pub script_tabs: filmcraft_project::ScriptTabsView, /// Open sequences (timeline tabs), in tab order. pub open_sequences: Vec, /// How each sequence is shown in the Timeline panel (zoom, scroll, track heights): every @@ -974,6 +977,7 @@ impl Session { pub fn project_view(&self) -> filmcraft_project::ProjectView { let is_seq = |id: &ItemId| self.project.sequence(*id).is_some(); filmcraft_project::ProjectView { + script_tabs: self.state.script_tabs.clone().checked(&self.project), open_sequences: self.state.open_sequences.iter().copied().filter(is_seq).collect(), active_sequence: self.state.active_sequence.filter(is_seq), sequences: self.state.timeline_views.iter().filter(|(id, _)| is_seq(id)).map(|(id, v)| (*id, *v)).collect(), @@ -987,6 +991,10 @@ impl Session { /// view without any open sequence leaves the project on its first sequence: a project saved /// by a session that never showed one (a script, the CLI) should not open on an empty Timeline. pub fn restore_project_view(&mut self, view: filmcraft_project::ProjectView) { + self.state.script_tabs = view.script_tabs.checked(&self.project); + if !self.prefs.timeline.restore_open_sequences { + return; + } let mut open: Vec = Vec::new(); for id in view.open_sequences { if self.project.sequence(id).is_some() && !open.contains(&id) { diff --git a/crates/engine/src/script_commands.rs b/crates/engine/src/script_commands.rs index 7a1f817a3..c68adcb42 100644 --- a/crates/engine/src/script_commands.rs +++ b/crates/engine/src/script_commands.rs @@ -3,8 +3,8 @@ use std::sync::Arc; use filmcraft_project::{ - BinId, ItemId, ItemKind, Label, MediaIdentity, MediaRef, Project, ScriptColor, ScriptDocument, ScriptLine, ScriptLineColor, ScriptLineId, ScriptMark, - ScriptMarkId, ScriptSlate, ScriptSlateId, ScriptTake, ScriptTakeId, + BinId, ItemId, ItemKind, Label, MediaIdentity, MediaRef, Project, ScriptColor, ScriptDocument, ScriptElement, ScriptLine, ScriptLineColor, ScriptLineId, + ScriptMark, ScriptMarkId, ScriptSlate, ScriptSlateId, ScriptTake, ScriptTakeId, }; use filmcraft_time::Tick; use serde::{Deserialize, Serialize}; @@ -65,8 +65,10 @@ fn create(s: &mut Session, p: &Value, import: bool) -> Result { ScriptDocument::from_text(text(p, "text", cmd, ScriptDocument::MAX_TEXT_BYTES)?).map_err(|e| bad(cmd, e))? } else { let mut doc = ScriptDocument::new(); - let id = ScriptLineId(doc.alloc_id().map_err(|e| bad(cmd, e))?); - doc.lines.push(ScriptLine { id, text: String::new(), scene: None, page: None }); + for _ in 0..=ScriptDocument::LEADING_SETUP_ROWS { + let id = ScriptLineId(doc.alloc_id().map_err(|e| bad(cmd, e))?); + doc.lines.push(ScriptLine { id, text: String::new(), element: None, scene: None, page: None }); + } doc }; let count = doc.lines.len(); @@ -249,6 +251,7 @@ fn paste_text(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "pasted text exceeds the 50,000-line limit")); } let mut created = Vec::with_capacity(count); + let mut element = original.and_then(|_| draft.lines[insert_at].element); for (index, row) in rows.split('\n').enumerate() { if row.len() > ScriptDocument::MAX_LINE_BYTES { return Err(bad(cmd, "a pasted script line exceeds the 16 KiB limit")); @@ -260,8 +263,15 @@ fn paste_text(s: &mut Session, p: &Value) -> Result { } else { ScriptLineId(draft.alloc_id().map_err(|e| bad(cmd, e))?) }; - let old = (index == 0).then(|| original.and_then(|id| draft.lines.iter().find(|line| line.id == id))).flatten(); - created.push(ScriptLine { id, text: row.to_owned(), scene: old.and_then(|line| line.scene.clone()), page: old.and_then(|line| line.page.clone()) }); + let old = original.filter(|_| index == 0).map(|_| &draft.lines[insert_at]); + created.push(ScriptLine { + id, + text: row.to_owned(), + element, + scene: old.and_then(|line| line.scene.clone()), + page: old.and_then(|line| line.page.clone()), + }); + element = element.map(ScriptElement::following); } let first = created.first().ok_or_else(|| bad(cmd, "there is no text to paste"))?.id; let last = created.last().ok_or_else(|| bad(cmd, "there is no text to paste"))?; @@ -330,8 +340,10 @@ fn split_line(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "script text would exceed the 4 MiB limit")); } let created = ScriptLineId(doc.alloc_id().map_err(|e| bad(cmd, e))?); + let role = doc.lines[index].element; + let element = if after.is_empty() { role.map(ScriptElement::following) } else { role }; doc.lines[index].text = before.to_owned(); - doc.lines.insert(index + 1, ScriptLine { id: created, text: after.to_owned(), scene: None, page: None }); + doc.lines.insert(index + 1, ScriptLine { id: created, text: after.to_owned(), element, scene: None, page: None }); for take in doc.slates.iter_mut().flat_map(|slate| &mut slate.takes) { if take.end_line == line { take.end_line = created; @@ -371,6 +383,9 @@ fn merge_with_previous(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "script text would exceed the 4 MiB limit")); } let previous = prior.id; + if prior.text.is_empty() { + doc.lines[index - 1].element = doc.lines[index].element; + } doc.lines[index - 1].text = merged.clone(); // delete_line removes the old row's marks and keeps marks already on // the preceding row, while adjusting candle endpoints atomically. @@ -438,15 +453,32 @@ fn move_take(s: &mut Session, p: &Value) -> Result { let cmd = "script.moveTake"; let item = item(p, cmd)?; let take = ScriptTakeId(id(p, "take", cmd)?); - let direction = p.get("direction").and_then(Value::as_i64).filter(|value| matches!(value, -1 | 1)).ok_or_else(|| bad(cmd, "direction must be -1 or 1"))?; let index = s.edit("Reorder Script Candle", |project, _| { let doc = script_mut(project, item, cmd)?; - let slate = - doc.slates.iter_mut().find(|slate| slate.takes.iter().any(|candidate| candidate.id == take)).ok_or_else(|| bad(cmd, "take does not exist"))?; - let index = slate.takes.iter().position(|candidate| candidate.id == take).ok_or_else(|| bad(cmd, "take does not exist"))?; - let next = - index.checked_add_signed(direction as isize).filter(|index| *index < slate.takes.len()).ok_or_else(|| bad(cmd, "take is already at that edge"))?; - slate.takes.swap(index, next); + let (slate, index) = doc + .slates + .iter_mut() + .find_map(|slate| { + let index = slate.takes.iter().position(|candidate| candidate.id == take)?; + Some((slate, index)) + }) + .ok_or_else(|| bad(cmd, "take does not exist"))?; + let next = match (p.get("toTake"), p.get("direction")) { + (Some(_), None) => { + let target = ScriptTakeId(id(p, "toTake", cmd)?); + slate.takes.iter().position(|candidate| candidate.id == target).ok_or_else(|| bad(cmd, "target must be in the same setup"))? + } + (None, Some(direction)) => { + let direction = direction.as_i64().filter(|n| matches!(n, -1 | 1)).ok_or_else(|| bad(cmd, "direction must be -1 or 1"))?; + index + .checked_add_signed(direction as isize) + .filter(|index| *index < slate.takes.len()) + .ok_or_else(|| bad(cmd, "take is already at that edge"))? + } + _ => return Err(bad(cmd, "provide either toTake or direction")), + }; + let moved = slate.takes.remove(index); + slate.takes.insert(next, moved); Ok(next) })?; Ok(json!({"index":index})) @@ -465,6 +497,19 @@ fn set_thumbnail_time(s: &mut Session, p: &Value) -> Result { Ok(json!({"time":time})) } +fn set_tree_outline_color(s: &mut Session, p: &Value) -> Result { + let cmd = "script.setTreeOutlineColor"; + let item = item(p, cmd)?; + let id = ScriptSlateId(id(p, "slate", cmd)?); + let color = p.get("color").and_then(Value::as_str).and_then(ScriptColor::from_name).ok_or_else(|| bad(cmd, "color must be a known script color"))?; + s.edit("Set Tree Outline Color", |project, _| { + let slate = script_mut(project, item, cmd)?.slates.iter_mut().find(|slate| slate.id == id).ok_or_else(|| bad(cmd, "setup does not exist"))?; + slate.outline_color = color; + Ok(()) + })?; + Ok(Value::Null) +} + fn move_thumbnail(s: &mut Session, p: &Value) -> Result { let cmd = "script.moveThumbnail"; let item = item(p, cmd)?; @@ -508,7 +553,8 @@ fn insert_line(s: &mut Session, p: &Value) -> Result { None => 0, }; let created = ScriptLineId(doc.alloc_id().map_err(|e| bad(cmd, e))?); - doc.lines.insert(index, ScriptLine { id: created, text: value, scene: None, page: None }); + let element = index.checked_sub(1).and_then(|i| doc.lines[i].element).map(ScriptElement::following); + doc.lines.insert(index, ScriptLine { id: created, text: value, element, scene: None, page: None }); Ok(created) })?; Ok(json!({"line":created.0})) @@ -600,7 +646,7 @@ fn add_slate(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "script already has the maximum number of slates")); } let slate = ScriptSlateId(doc.alloc_id().map_err(|e| bad(cmd, e))?); - doc.slates.push(ScriptSlate { id: slate, name, thumbnail_line: None, thumbnail_x: None, takes: Vec::new() }); + doc.slates.push(ScriptSlate { id: slate, outline_color: ScriptColor::Default, name, thumbnail_line: None, thumbnail_x: None, takes: Vec::new() }); Ok(slate) })?; Ok(json!({"slate":slate.0})) @@ -647,7 +693,14 @@ fn add_take(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "script already has the maximum number of slates")); } let slate = ScriptSlateId(doc.alloc_id().map_err(|e| bad(cmd, e))?); - doc.slates.push(ScriptSlate { id: slate, name: source_name.clone(), thumbnail_line: None, thumbnail_x: x, takes: Vec::new() }); + doc.slates.push(ScriptSlate { + id: slate, + outline_color: ScriptColor::Default, + name: source_name.clone(), + thumbnail_line: None, + thumbnail_x: x, + takes: Vec::new(), + }); slate }; let take = ScriptTakeId(doc.alloc_id().map_err(|e| bad(cmd, e))?); @@ -960,6 +1013,15 @@ fn move_mark(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// The Source monitor clamps to the visible source span and snaps down to its frame grid. +fn open_script_cue(s: &mut Session, source: ItemId, at: Tick, focus: bool) -> Result { + let lead = Tick::from_seconds_f64(s.prefs.playback.lined_script_preroll_seconds); + let time = at.0.saturating_sub(lead.0); + s.execute("source.open", json!({"item":source.0,"focus":focus}))?; + s.execute("source.setPlayhead", json!({"time":time}))?; + Ok(json!({"item":source.0,"time":s.state.source_playhead.0})) +} + fn cue_mark(s: &mut Session, p: &Value) -> Result { let cmd = "script.cueMark"; let doc = script(&s.project, item(p, cmd)?, cmd)?; @@ -977,9 +1039,7 @@ fn cue_mark(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, "mark is outside the linked source's visible span after relink; review the footage or rebind the take")); } let focus = p.get("focus").and_then(Value::as_bool).unwrap_or(true); - s.execute("source.open", json!({"item":source.0,"focus":focus}))?; - s.execute("source.setPlayhead", json!({"time":at.0}))?; - Ok(json!({"item":source.0,"time":s.state.source_playhead.0})) + open_script_cue(s, source, at, focus) } /// Cue a take at a script row. Marks anchor the source time; rows between two marks use @@ -1021,9 +1081,7 @@ fn cue_line(s: &mut Session, p: &Value) -> Result { if at < view.start || at >= view.end { return Err(bad(cmd, "cue is outside the linked source's visible span after relink; review the footage or rebind the take")); } - s.execute("source.open", json!({"item":source.0}))?; - s.execute("source.setPlayhead", json!({"time":at.0}))?; - Ok(json!({"item":source.0,"time":s.state.source_playhead.0})) + open_script_cue(s, source, at, true) } pub fn commands() -> Vec { @@ -1044,6 +1102,7 @@ pub fn commands() -> Vec { spec("script.splitLine", "Split Script Line", r#"{"item":id,"line":id,"text":str,"at":number}"#, split_line, true), spec("script.mergeWithPrevious", "Join Script Lines", r#"{"item":id,"line":id,"text":str}"#, merge_with_previous, true), spec("script.shiftSlate", "Move Script Setup", r#"{"item":id,"slate":id,"delta":number,"x":number?}"#, shift_slate, true), + spec("script.setTreeOutlineColor", "Set Tree Outline Color", r#"{"item":id,"slate":id,"color":name}"#, set_tree_outline_color, true), spec("script.moveThumbnail", "Move Script Thumbnail", r#"{"item":id,"slate":id,"line":id,"x":number?}"#, move_thumbnail, true), spec("script.insertLine", "Insert Script Line", r#"{"item":id,"after":id?,"text":str}"#, insert_line, true), spec("script.deleteLine", "Delete Script Line", r#"{"item":id,"line":id}"#, delete_line, true), @@ -1052,7 +1111,7 @@ pub fn commands() -> Vec { spec("script.deleteSlate", "Delete Script Setup", r#"{"item":id,"slate":id}"#, delete_slate, true), spec("script.addTake", "Add Script Take", r#"{"item":id,"slate":id?,"source":id,"startLine":id,"endLine":id,"x":number?}"#, add_take, true), spec("script.deleteTake", "Delete Script Take", r#"{"item":id,"take":id}"#, delete_take, true), - spec("script.moveTake", "Reorder Script Take", r#"{"item":id,"take":id,"direction":-1|1}"#, move_take, true), + spec("script.moveTake", "Reorder Script Take", r#"{"item":id,"take":id,"direction":-1|1?, "toTake":id?}"#, move_take, true), spec("script.setThumbnailTime", "Set Script Thumbnail Frame", r#"{"item":id,"take":id,"time":ticks}"#, set_thumbnail_time, true), spec("script.rebindTake", "Rebind Script Take", r#"{"item":id,"take":id,"source":id,"discardMarks":bool?,"allMatching":bool?}"#, rebind_take, true), spec("script.setCoverage", "Set Script Take Coverage", r#"{"item":id,"take":id,"startLine":id,"endLine":id}"#, set_coverage, true), @@ -1101,6 +1160,35 @@ mod tests { ) } + #[test] + fn screenplay_elements_survive_save_and_section_copy_and_follow_edits() { + use ScriptElement::{Action, Character, Dialogue, Parenthetical, SceneHeading, Transition}; + let mut s = Session::default(); + let mut doc = ScriptDocument::from_text("INT. ROOM - DAY\nA door opens.\nUSER\n(quietly)\nCome in.\nCUT TO:").unwrap(); + let roles = [SceneHeading, Action, Character, Parenthetical, Dialogue, Transition]; + for (line, role) in doc.lines.iter_mut().zip(roles) { + line.element = Some(role); + } + doc.lines[0].scene = Some("12A".into()); + doc.lines[4].page = Some("9B".into()); + let cue = doc.lines[2].id.0; + let item = Arc::make_mut(&mut s.project).add_item("Scene", Label::Blue, ItemKind::Script(Arc::new(doc.clone())), None).0; + let reopened = filmcraft_format::decode(&filmcraft_format::encode(&s.project, false)).unwrap(); + assert_eq!(reopened.project.item(ItemId(item)).unwrap().as_script().unwrap(), &doc); + let section = s.execute("script.copySection", json!({"item":item,"startLine":doc.lines[0].id,"endLine":doc.lines[5].id,"slates":[]})).unwrap(); + s.execute("script.pasteSection", json!({"item":item,"section":section})).unwrap(); + let copy = &s.project.item(ItemId(item)).unwrap().as_script().unwrap().lines[6..]; + for (row, old) in copy.iter().zip(&doc.lines) { + assert_eq!((&row.element, &row.scene, &row.page), (&old.element, &old.scene, &old.page)); + assert_ne!(row.id, old.id); + } + let result = s.execute("script.splitLine", json!({"item":item,"line":cue,"text":"USER","at":4})).unwrap(); + s.execute("script.pasteText", json!({"item":item,"line":result["line"],"baseText":"","start":0,"end":0,"text":"One\nTwo"})).unwrap(); + let edited = &s.project.item(ItemId(item)).unwrap().as_script().unwrap().lines; + assert_eq!(edited[2].element, Some(Character)); + assert!(edited[3..5].iter().all(|row| row.element == Some(Dialogue) && row.page.is_none() && row.scene.is_none())); + } + #[test] fn text_paste_splits_at_unicode_caret_shifts_rows_and_preserves_annotations() { let mut s = Session::default(); @@ -1210,6 +1298,10 @@ mod tests { "lineColors":[{"line":rows[1],"color":"Rose"}],"offscreenLines":[rows[2]]}), ) .unwrap(); + s.execute("script.setTreeOutlineColor", json!({"item":origin,"slate":slate,"color":"Blue"})).unwrap(); + s.execute("script.setTreeOutlineColor", json!({"item":origin,"slate":slate,"color":"Default"})).unwrap(); + assert_eq!(s.project.item(ItemId(origin)).unwrap().as_script().unwrap().slates[0].outline_color, ScriptColor::Default); + s.execute("edit.undo", json!({})).unwrap(); let section = s.execute("script.copySection", json!({"item":origin,"startLine":rows[1],"endLine":rows[2],"slates":[slate]})).unwrap(); assert_eq!(section["lines"].as_array().unwrap().len(), 2); assert_eq!(section["slates"][0]["takes"][0]["marks"].as_array().unwrap().len(), 1); @@ -1221,6 +1313,7 @@ mod tests { assert_eq!(doc.lines.iter().map(|line| line.text.as_str()).collect::>(), ["Before", "B", "C", "After"]); assert_eq!(doc.lines[1].scene.as_deref(), Some("2A")); assert_eq!(doc.lines[1].id.0, result["startLine"].as_u64().unwrap()); + assert_eq!(doc.slates[0].outline_color, ScriptColor::Blue); let pasted = &doc.slates[0].takes[0]; assert_eq!(pasted.source, Some(media)); assert_eq!(pasted.start_line, doc.lines[1].id); @@ -1751,6 +1844,12 @@ mod tests { let mark = s.execute("script.addMark", json!({"item":script,"take":take,"line":line,"sourceTime":rate.tick_of(30).0})).unwrap()["mark"].as_u64().unwrap(); let cued = s.execute("script.cueMark", json!({"item":script,"take":take,"mark":mark})).unwrap(); + assert_eq!(cued["time"], rate.tick_of(24).0, "pre-roll stops at the subclip In"); + s.execute("prefs.set", json!({"key":"playback.linedScriptPrerollSeconds","value":0.1})).unwrap(); + let cued = s.execute("script.cueLine", json!({"item":script,"take":take,"line":line})).unwrap(); + assert_eq!(cued["time"], rate.tick_of(27).0, "a fractional-frame lead-in rounds down"); + s.execute("prefs.set", json!({"key":"playback.linedScriptPrerollSeconds","value":0.0})).unwrap(); + let cued = s.execute("script.cueMark", json!({"item":script,"take":take,"mark":mark})).unwrap(); assert_eq!(cued["time"], rate.tick_of(30).0); Arc::make_mut(&mut s.project).shift_media_time(parent, rate.tick_of(5)); let shifted = s.project.item(ItemId(script)).unwrap().as_script().unwrap().take(ScriptTakeId(take)).unwrap().marks[0].source_time; diff --git a/crates/engine/src/settings/schema.rs b/crates/engine/src/settings/schema.rs index bfc714de5..4712ee81f 100644 --- a/crates/engine/src/settings/schema.rs +++ b/crates/engine/src/settings/schema.rs @@ -527,6 +527,7 @@ pub(super) static CATEGORIES: &[Category] = &[ title: "Playback", rows: &[ f("playback.prerollSeconds", "Preroll", float(0.0, 60.0, 0, "seconds"), true), + f("playback.linedScriptPrerollSeconds", "Lined Script Pre-Roll Playback", float(0.0, 5.0, 1, "seconds"), true), f("playback.postrollSeconds", "Postroll", float(0.0, 60.0, 0, "seconds"), true), f("playback.stepManyFrames", "Step forward/back many", int(1.0, 1000.0, "frames"), true), b("playback.pauseEncoderQueue", "Pause Media Encoder queue during playback", false), diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 4dcf4fa7d..14c044d28 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -330,6 +330,7 @@ mod tests { let doc = p.item_mut(script).unwrap().as_script_mut().unwrap(); doc.next_id = 5; doc.slates.push(ScriptSlate { + outline_color: ScriptColor::Rose, id: ScriptSlateId(3), name: "setup".into(), thumbnail_line: None, @@ -352,6 +353,7 @@ mod tests { p.next_id = script.0; let repaired = decode(&encode(&p, false)).unwrap(); assert!(repaired.project.next_id > script.0); + assert_eq!(repaired.project.item(script).unwrap().as_script().unwrap().slates[0].outline_color, ScriptColor::Rose); let take = &repaired.project.item(script).unwrap().as_script().unwrap().slates[0].takes[0]; assert_eq!(take.source, None); assert_eq!(take.source_name, "gone"); @@ -381,6 +383,7 @@ mod tests { let mut p = Project::new("Tabs"); let seq = p.new_sequence("Sequence 01", SequenceSettings::default(), 1, 1, None); let view = ProjectView { + script_tabs: Default::default(), open_sequences: vec![seq], active_sequence: Some(seq), sequences: [(seq, SequenceView { pps: 80.0, scroll: 1.5, v_scroll: 0.0, a_scroll: 4.0, video_track_h: 60.0, audio_track_h: 56.0 })].into(), diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs index eef62a617..6054d9878 100644 --- a/crates/project/src/lib.rs +++ b/crates/project/src/lib.rs @@ -47,7 +47,8 @@ pub use mixer::{AutomationMode, InputMap, MixerStrip, TrackSend}; pub use multicam::{Camera, MergedClip, MulticamAudio, MulticamSel, MulticamSource}; pub use narration::{Narration, VocalPitch}; pub use script::{ - ScriptColor, ScriptDocument, ScriptLine, ScriptLineColor, ScriptLineId, ScriptMark, ScriptMarkId, ScriptSlate, ScriptSlateId, ScriptTake, ScriptTakeId, + ScriptColor, ScriptDocument, ScriptElement, ScriptLine, ScriptLineColor, ScriptLineId, ScriptMark, ScriptMarkId, ScriptSlate, ScriptSlateId, ScriptTake, + ScriptTakeId, }; pub use transcript::{Speaker, Transcript, Word}; @@ -79,7 +80,7 @@ pub use source::resolve_auto_points; pub use track::{ AudioChannels, FieldOptions, FieldProcessing, Marker, MarkerKind, TimeInterpolation, Track, TrackItem, TrackKind, Transition, TransitionAlign, }; -pub use view::{MAX_LUT_TEXT_BYTES, ProjectLut, ProjectView, SequenceView}; +pub use view::{MAX_LUT_TEXT_BYTES, ProjectLut, ProjectView, ScriptTabsView, SequenceView}; id_type!(ItemId); id_type!(BinId); id_type!(TrackId); diff --git a/crates/project/src/script.rs b/crates/project/src/script.rs index 8bda61df6..63948f5c4 100644 --- a/crates/project/src/script.rs +++ b/crates/project/src/script.rs @@ -35,6 +35,10 @@ pub enum ScriptColor { } impl ScriptColor { + fn is_default(&self) -> bool { + *self == Self::Default + } + pub const ALL: [Self; 19] = [ Self::Default, Self::White, @@ -118,11 +122,34 @@ script_id!(ScriptSlateId); script_id!(ScriptTakeId); script_id!(ScriptMarkId); +/// Screenplay formatting attached to a logical row, independent of its production labels. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum ScriptElement { + SceneHeading, + Action, + Character, + Dialogue, + Parenthetical, + Transition, +} + +impl ScriptElement { + /// Default for a new row entered after a typed screenplay element. + pub fn following(self) -> Self { + match self { + Self::Character | Self::Parenthetical | Self::Dialogue => Self::Dialogue, + Self::SceneHeading | Self::Transition | Self::Action => Self::Action, + } + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ScriptLine { pub id: ScriptLineId, pub text: String, #[serde(default, skip_serializing_if = "Option::is_none")] + pub element: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] pub scene: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub page: Option, @@ -170,6 +197,9 @@ pub struct ScriptTake { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ScriptSlate { pub id: ScriptSlateId, + /// Default follows the theme outline. Each take and row retains its own fill. + #[serde(default, skip_serializing_if = "ScriptColor::is_default")] + pub outline_color: ScriptColor, pub name: String, /// Optional independent row for the setup thumbnail; defaults to its first candle. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -188,6 +218,9 @@ pub struct ScriptDocument { } impl ScriptDocument { + /// Editable setup rows above the writing position in a new screenplay. + pub const LEADING_SETUP_ROWS: usize = 4; + /// Maximum accepted plain text size and logical line count. Source text is untrusted input. pub const MAX_TEXT_BYTES: usize = 4 * 1024 * 1024; pub const MAX_LINES: usize = 50_000; @@ -225,7 +258,7 @@ impl ScriptDocument { if content.len() > Self::MAX_LINE_BYTES { return Err("a script line exceeds the 16 KiB limit"); } - doc.lines.push(ScriptLine { id, text: content.to_owned(), scene: None, page: None }); + doc.lines.push(ScriptLine { id, text: content.to_owned(), element: None, scene: None, page: None }); } Ok(doc) } @@ -453,6 +486,14 @@ impl ScriptDocument { mod tests { use super::*; + #[test] + fn legacy_row_labels_and_indentation_round_trip_without_a_role() { + let legacy = serde_json::json!({"id":1,"text":" A line","scene":"1A","page":"3"}); + let row: ScriptLine = serde_json::from_value(legacy.clone()).unwrap(); + assert!(row.element.is_none()); + assert_eq!(serde_json::to_value(row).unwrap(), legacy); + } + #[test] fn text_import_preserves_logical_rows() { let doc = ScriptDocument::from_text("\u{feff} A\r\n\r\nA\n").unwrap(); @@ -465,6 +506,7 @@ mod tests { fn deleting_a_line_discards_its_marks_but_keeps_remaining_coverage() { let mut doc = ScriptDocument::from_text("one\ntwo\nthree").unwrap(); doc.slates.push(ScriptSlate { + outline_color: ScriptColor::Default, id: ScriptSlateId(4), name: "setup".into(), thumbnail_line: None, @@ -503,6 +545,7 @@ mod tests { assert!(doc.validate().is_err()); doc.next_id = 4; doc.slates.push(ScriptSlate { + outline_color: ScriptColor::Default, id: ScriptSlateId(3), name: "setup".into(), thumbnail_line: None, diff --git a/crates/project/src/view.rs b/crates/project/src/view.rs index d651bc5b8..9622e06b8 100644 --- a/crates/project/src/view.rs +++ b/crates/project/src/view.rs @@ -36,11 +36,33 @@ impl SequenceView { } } -/// What was open when a project was saved: the Timeline's sequence tabs in order, the active one, +/// Open Lined Script tabs in order and the selected tab. A null ID denotes the internal Help +/// script. Only tab identities belong here, never a copy of the practice document. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ScriptTabsView { + pub open: Vec>, + pub active: Option, +} + +impl ScriptTabsView { + pub fn checked(mut self, project: &super::Project) -> Self { + let mut seen = std::collections::HashSet::new(); + self.open.retain(|tab| tab.is_none_or(|id| project.item(id).is_some_and(|item| item.as_script().is_some())) && seen.insert(*tab)); + if !self.open.contains(&self.active) { + self.active = self.open.first().copied().flatten(); + } + self + } +} + +/// What was open when a project was saved: the Lined Script tabs, the Timeline's sequence tabs, /// how each sequence was shown and where its playhead was. Stored beside the project in its file, /// not in it: it is not part of the edit and never an undo step. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct ProjectView { + #[serde(default)] + pub script_tabs: ScriptTabsView, #[serde(default)] pub open_sequences: Vec, #[serde(default)] diff --git a/crates/ui-egui/README.md b/crates/ui-egui/README.md index 14be499e2..73a8c6144 100644 --- a/crates/ui-egui/README.md +++ b/crates/ui-egui/README.md @@ -3,21 +3,19 @@ The egui frontend draws panels and dialogs, and dispatches project changes through the engine. Interactive controls keep stable automation ids regardless of the interface language. -## Script coverage +## Lined Script coverage -Before a script is created or imported, the Script panel shows a short getting-started guide for -text import, Project clip drops, candle coverage and Source playback, and frame-linked marks. -The guide wraps and scrolls in small panels and disappears when a script is open. A ? button at the -right of the Script toolbar opens the same guide in a scrollable help popover at any time. +Lined Script opens project items in tabs. Its internal Help tab appears when the last script closes and can be reopened from the question-mark menu. Practice edits and marks reset when the user leaves Help. +USER asks HELP how to use a lined script. HELP walks through four numbered steps in dialogue. +The scene wraps and scrolls in small panels. The **?** button includes quick instructions and a link to the [Lined Script guide](../../docs/lined-script.md). Toolbar controls wrap onto additional rows when the panel is narrow, keeping Scene/Page labels with their menus and placing search and the document below the measured toolbar height. -Plain text copied from another app can be pasted directly into Script. With no script open, -paste creates a script; otherwise it inserts rows after the selected range (or appends). +Plain text copied from another app can be pasted directly into Lined Script. Paste inserts rows after the selected range (or appends). Choose **Blank** first to keep pasted text as a project script. While editing a row, paste replaces the text selection at the caret. Each hard line break adds a row, including blank and terminal rows, with CRLF treated as one break. Later rows retain stable IDs, labels, candles and marks. A single Undo removes the paste while keeping -text typed beforehand. Clicking outside a Script text field commits the edit and releases input +text typed beforehand. Clicking outside a Lined Script text field commits the edit and releases input focus, including clicks into blank canvas or another panel. Oversized text, lines and invalid offsets fail before any paste edit. @@ -27,7 +25,7 @@ Hidden marks cannot be selected or used to cue Source and do not choose the defa Scene and Page menus retain repeated labels as separate navigation points in script order. Double-clicking a candle, its mark or a setup thumbnail cues the linked clip and activates Source for playback shortcuts. Thumbnails open the displayed candle at its thumbnail frame (or first -visible mark, then source start). A single mark click cues Source while retaining Script editing focus. +visible mark, then source start). A single mark click cues Source while retaining Lined Script editing focus. Setup thumbnails and take-number boxes sit above the first covered row; candle caps, endpoint handles, off-screen notation and marks align with that row, including blank and wrapped lines. Candles extend to the exact top and bottom boundaries of their covered rows. The short gray end @@ -60,7 +58,7 @@ or fingerprint, only the targeted candle can be identified safely. `script.rebin this batch behavior through optional `allMatching:true`; its default remains a single take. Script `layout.rs` shares row measurements and candle geometry across painting, endpoint targets and off-screen notation. `selection.rs` owns document-local state transitions: switching scripts through -the toolbar, commands, creation/import or Find in Script clears old edits, drags and replacement +the toolbar, commands, creation/import or Find in Lined Script clears old edits, drags and replacement confirmations while retaining view preferences and the section clipboard. The `script_ui` integration tests cover endpoint drags, hidden-mark targets and repeated labels; engine tests cover saved data, undo/redo, section copies and deleting hidden lines. diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index a50ce74bc..aaaa13b59 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -19,10 +19,14 @@ mod window; impl FilmcraftApp { /// Build the app around one shared `FrameServer`, falling back to the default language on an unparsable preference, loading workspaces from the prefs /// directory and seeding IME epoch/sequence identity. - pub fn new(mut session: Session) -> Self { + pub fn new(session: Session) -> Self { + let frames = Arc::new(FrameServer::new(session.media.clone(), session.services.clone(), session.previews.clone(), FrameServer::default_workers())); + Self::with_frames(session, frames) + } + + pub(crate) fn with_frames(mut session: Session, frames: Arc) -> Self { session.shortcuts.register_external(menus::external_commands()); let recovery = !session.recovery_candidates().is_empty(); - let frames = Arc::new(FrameServer::new(session.media.clone(), session.services.clone(), session.previews.clone(), FrameServer::default_workers())); let workspaces = session.prefs_path.as_ref().and_then(|p| p.parent()).map(|d| dock::WorkspacePrefs::load(&d.join(dock::WORKSPACES_FILE))).unwrap_or_default(); let language = i18n::Language::parse(&session.prefs.general.interface_language).unwrap_or_default(); @@ -30,6 +34,7 @@ impl FilmcraftApp { let ime_active_sequence = session.state.active_sequence; Self { session, + script_practice: None, ui: UiState { language, ..UiState::default() }, tokens: Tokens::for_kind(ThemeKind::Dark), frames, @@ -300,6 +305,7 @@ impl FilmcraftApp { let _ = self.apply_dock(craft_behavior::dock::Action::activate(PanelKind::Timeline)); } filmcraft_engine::Event::OpenSource(_) | filmcraft_engine::Event::CueSource(_) => { + panels::script::close_example(self); let cue = matches!(ev, filmcraft_engine::Event::CueSource(_)); let focused = self.ui.focused; // a closed Source panel reopens, and another panel's maximize would hide it @@ -335,7 +341,9 @@ impl FilmcraftApp { self.logic_session_events(); self.logic_command_inbox(ctx); self.advance_playback(ctx); - self.advance_source_playback(ctx); + if panels::script::with_example_monitor(self, |preview| preview.advance_source_playback(ctx)).is_none() { + self.advance_source_playback(ctx); + } self.poll_jobs(ctx); capture::drain(self, ctx); capture::request_hidden_paint(self, ctx); @@ -386,7 +394,7 @@ impl FilmcraftApp { self.auto.begin_frame(); self.apply_prefs(&ctx); self.sync_timeline_view(); - self.ui.script.sync_project(&self.session.project_instance); + self.ui.script.sync_project(&self.session.project_instance, &self.session.state.script_tabs); panels::metadata::follow_selection(self); self.handle_drops(&ctx); panels::script::finish_edit_on_click_away(self, &ctx); @@ -407,6 +415,12 @@ impl FilmcraftApp { self.playback.playing = false; } if !ctx.will_discard() { + if self.auto.find_current("script.tabs").is_none() { + self.ui.script.leave_practice(); + } + if !self.ui.script.is_practicing() && panels::script::example_monitor(self).is_none() { + self.script_practice = None; + } self.cancel_value_drag(&ctx); } self.error_window(ui.ctx()); diff --git a/crates/ui-egui/src/app/keys.rs b/crates/ui-egui/src/app/keys.rs index 051d3094d..80edda981 100644 --- a/crates/ui-egui/src/app/keys.rs +++ b/crates/ui-egui/src/app/keys.rs @@ -22,6 +22,9 @@ impl FilmcraftApp { ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(restore)); return; } + if self.ui.clip_dialog.is_some() { + return; + } if self.ui.focused == PanelKind::Script && panels::script::has_text_paste_undo(self) && ctx.text_edit_focused() @@ -32,7 +35,9 @@ impl FilmcraftApp { } return; } + let mut take_focused = false; if self.ui.focused == PanelKind::Script && !ctx.text_edit_focused() && self.dialog.is_none() { + take_focused = panels::script::preview_arrow_keys(self, ctx); let pasted = ctx.input_mut(|input| { let mut pasted = Vec::new(); input.events.retain(|event| { @@ -56,7 +61,7 @@ impl FilmcraftApp { } // The runtime keeps egui's focus on the framework stop or the hosted canvas a press reached, // so egui's own `egui_wants_keyboard_input` would end every shortcut after a click on a panel. - if crate::framework::keyboard_taken(ctx) || self.dialog == Some(Dialog::Shortcuts) || self.ui.clip_dialog.is_some() { + if (!take_focused && crate::framework::keyboard_taken(ctx)) || self.dialog == Some(Dialog::Shortcuts) { return; } // A focused text field takes every unmodified key, including the ones our shortest @@ -87,7 +92,7 @@ impl FilmcraftApp { // most specific chords still go first across both scopes (the sort is stable, so the // panel still wins a tie). Before matching was exact, the Timeline's `Delete` (Clear) // swallowed the app-wide `Shift+Delete` (Ripple Delete) this way (#680). - let focused = self.ui.focused.title(); + let focused = self.ui.focused.context_name(); let mut fire = Vec::new(); let modifiers = i.modifiers; // With no text on the system clipboard, egui-winit drops the Ctrl+V press but still diff --git a/crates/ui-egui/src/app/textures.rs b/crates/ui-egui/src/app/textures.rs index 1339fe7c9..8e6593187 100644 --- a/crates/ui-egui/src/app/textures.rs +++ b/crates/ui-egui/src/app/textures.rs @@ -94,7 +94,19 @@ impl FilmcraftApp { } pub fn thumbnail(&mut self, ctx: &egui::Context, item: filmcraft_project::ItemId, t: Tick, width: u32) -> Option<(egui::TextureId, egui::Vec2)> { - let pi = self.session.project.item(item)?; + self.thumbnail_in(ctx, self.session.project.clone(), item, t, width, self.item_revision(item)) + } + + pub(crate) fn thumbnail_in( + &mut self, + ctx: &egui::Context, + project: Arc, + item: filmcraft_project::ItemId, + t: Tick, + width: u32, + rev: u64, + ) -> Option<(egui::TextureId, egui::Vec2)> { + let pi = project.item(item)?; let src_w = match &pi.kind { filmcraft_project::ItemKind::Media(m) => m.info.video.as_ref()?.width, filmcraft_project::ItemKind::Sequence(s) => s.settings.width, @@ -102,7 +114,6 @@ impl FilmcraftApp { }; let rate = pi.frame_rate(); let frame = rate.frame_at(t); - let rev = self.item_revision(item); let key = FrameKey { target: Target::Item(item), frame, size: width, revision: rev, draft: false }; let name = format!("thumb-{}-{}-{}", item.0, frame, width); if let Some(img) = self.frames.get(&key) { @@ -111,7 +122,6 @@ impl FilmcraftApp { return Some((id, egui::vec2(img.w as f32, img.h as f32))); } let scale = width as f32 / src_w.max(1) as f32; - let project = self.session.project.clone(); self.frames.request(key, rate.tick_of(frame), scale, &project, 50); let shown = self.texture_existing(&name); if shown.is_some() { diff --git a/crates/ui-egui/src/app/window.rs b/crates/ui-egui/src/app/window.rs index 2f5b813ea..b97b0aa7b 100644 --- a/crates/ui-egui/src/app/window.rs +++ b/crates/ui-egui/src/app/window.rs @@ -57,6 +57,9 @@ impl FilmcraftApp { } pub fn set_workspace(&mut self, name: &str) { + if self.ui.workspace != name { + self.ui.script.leave_practice(); + } self.ui.workspace = name.to_string(); self.ui.dock = dock::saved_docking(&self.workspaces, name); self.dock_focus = None; diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 3f719b942..91d0a80f9 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -78,6 +78,10 @@ impl PanelKind { PanelKind::ProjectNotes, ]; pub fn title(self) -> &'static str { + display_name(self.context_name()) + } + /// Panel name used in saved shortcut contexts and control responses. + pub fn context_name(self) -> &'static str { match self { PanelKind::Project => "Project", PanelKind::MediaBrowser => "Media Browser", @@ -165,8 +169,16 @@ fn vsplit(size: SplitSize, a: Node, b: Node) -> Node &str { + match name { + "Script" => "Lined Script", + other => other, + } +} + +pub const WORKSPACES: [&str; 10] = + ["Editing", "Assembly", "Color", "Effects", "Audio", "Captions and Graphics", "Vertical", "Learning", "Review", "All Panels"]; /// The user's workspaces file, beside `preferences.json` in the data directory. pub const WORKSPACES_FILE: &str = "workspaces.json"; @@ -225,7 +237,16 @@ impl WorkspacePrefs { }) else { return Self::default(); }; - serde_json::from_slice(&bytes).unwrap_or_default() + let mut prefs: Self = serde_json::from_slice(&bytes).unwrap_or_default(); + // Reopen the retired factory workspace's last arrangement under Editing. Explicitly + // saved layouts are still user workspaces, including one named Script. + if prefs.current == "Script" && !prefs.saved.iter().any(|entry| entry.name == "Script") { + prefs.current = "Editing".into(); + if let Some(last) = prefs.last.as_mut().filter(|last| last.name == "Script") { + last.name = prefs.current.clone(); + } + } + prefs } pub fn save(&self, path: &std::path::Path) -> std::io::Result<()> { if let Some(d) = path.parent() { @@ -267,7 +288,8 @@ pub fn names(prefs: &WorkspacePrefs) -> Vec { /// The workspace called `query` (any case, spaces optional). pub fn find(prefs: &WorkspacePrefs, query: &str) -> Option { - names(prefs).into_iter().find(|n| slug(n) == slug(query)) + let key = slug(query); + names(prefs).into_iter().find(|n| slug(n) == key) } /// A workspace as saved: the user's saved version, else the built-in default. An entry that @@ -658,11 +680,6 @@ fn workspace_root(name: &str) -> Node { ), tabs(&[EssentialGraphics, Properties], 0), ), - "Script" => vsplit( - Ratio(0.76), - hsplit(Ratio(0.67), tabs(&[Script], 0), vsplit(Ratio(0.58), tabs(&[Source, Program, Text], 0), tabs(&[Project, MediaBrowser], 0))), - bottom_editing(), - ), // Vertical (9:16 editing, #1822): the Program monitor runs the full height on the right, beside // the source and project panels and the timeline "Vertical" => hsplit( @@ -786,19 +803,103 @@ pub enum SeqAction { Menu(u64, egui::Pos2), } +/// The shared appearance of document tabs in Timeline and Lined Script. +pub(crate) struct DocumentTab { + label: std::sync::Arc, + selected: bool, + show_close: bool, +} + +impl DocumentTab { + pub(crate) const STRIP_INSET: f32 = 12.0; + pub(crate) const GAP: f32 = 8.0; + + pub(crate) fn new(painter: &egui::Painter, name: &str, selected: bool, closable: bool) -> Self { + let label = painter.layout_no_wrap(name.to_owned(), Tokens::ui(12.0), egui::Color32::WHITE); + Self { label, selected, show_close: selected && closable } + } + + fn label_offset(&self) -> f32 { + 8.0 + if self.show_close { 16.0 } else { 0.0 } + } + + pub(crate) fn width(&self) -> f32 { + self.label_offset() + self.label.size().x + 8.0 + } + + /// Draw inside the caller's tab hit target. The caller handles document-specific actions. + pub(crate) fn show(self, ui: &mut egui::Ui, painter: &egui::Painter, tab: &egui::Response, close_id: egui::Id, t: &Tokens) -> Option { + tab.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, tab.enabled(), self.selected, self.label.text())); + ui.ctx().accesskit_node_builder(tab.id, |node| { + node.set_role(egui::accesskit::Role::Tab); + node.set_selected(self.selected); + }); + paint_widget_focus(painter, tab, t); + let rect = tab.rect; + let label_x = rect.left() + self.label_offset(); + let label_right = (label_x + self.label.size().x).min(rect.right() - 8.0); + let col = if self.selected || tab.hovered() { t.tab_text_active } else { t.tab_text }; + let text = painter.with_clip_rect(Rect::from_min_max(rect.min, pos2(rect.right() - 8.0, rect.bottom()))); + text.galley_with_override_text_color(pos2(label_x, rect.center().y - self.label.size().y / 2.0), self.label, col); + if self.selected && label_right > label_x { + let y = rect.bottom() - 2.0; + painter.line_segment([pos2(label_x, y), pos2(label_right, y)], Stroke::new(1.0, t.tab_text_active)); + } + if !self.show_close { + return None; + } + let cross = Rect::from_center_size(pos2(rect.left() + 10.0, rect.center().y), vec2(8.0, 8.0)); + let close = ui.interact(cross.expand(4.0), close_id, Sense::click()); + let stroke = Stroke::new(1.2, if close.hovered() { t.tab_text_active } else { t.tab_text }); + painter.line_segment([cross.left_top(), cross.right_bottom()], stroke); + painter.line_segment([cross.right_top(), cross.left_bottom()], stroke); + paint_widget_focus(painter, &close, t); + Some(close) + } +} + +/// Return a move in the full document order. Timeline may render a slice starting at `first`. +pub(crate) fn document_tab_drag(tabs: &[egui::Response], first: usize) -> Option<(usize, usize)> { + for (i, tab) in tabs.iter().enumerate() { + let index = first + i; + let home = tab.id.with("drag-origin"); + let dragging = tab.dragged_by(egui::PointerButton::Primary); + if !dragging && !tab.drag_stopped() { + continue; + } + if tab.drag_started_by(egui::PointerButton::Primary) { + tab.ctx.data_mut(|d| d.insert_temp(home, index)); + } + let cancelled = crate::framework::escape_pressed(&tab.ctx) || crate::framework::escape_arrived(&tab.ctx); + if cancelled || tab.drag_stopped() { + let origin = tab.ctx.data_mut(|d| d.remove_temp::(home)); + if cancelled && let Some(origin) = origin { + if dragging { + tab.ctx.stop_dragging(); + } + return Some((index, origin)); + } + continue; + } + if let Some(pointer) = tab.interact_pointer_pos() { + if i.checked_sub(1).and_then(|prev| tabs.get(prev)).is_some_and(|prev| pointer.x < prev.rect.center().x) { + return Some((index, index - 1)); + } + if tabs.get(i + 1).is_some_and(|next| pointer.x > next.rect.center().x) { + return Some((index, index + 1)); + } + } + } + None +} + fn sequence_widths(ui: &egui::Ui, seqs: &SeqTabs) -> Vec { - seqs.open - .iter() - .map(|(id, name)| { - let label = ui.painter().layout_no_wrap(name.clone(), Tokens::ui(12.0), egui::Color32::WHITE).size().x; - label + 16.0 + if seqs.active == Some(*id) { 16.0 } else { 0.0 } - }) - .collect() + seqs.open.iter().map(|(id, name)| DocumentTab::new(ui.painter(), name, seqs.active == Some(*id), true).width()).collect() } /// The width [`sequence_tabs`] needs to show every open sequence. pub fn sequence_tabs_width(ui: &egui::Ui, seqs: &SeqTabs) -> f32 { - sequence_widths(ui, seqs).iter().map(|w| w + 8.0).sum::() + 12.0 + sequence_widths(ui, seqs).iter().map(|w| w + DocumentTab::GAP).sum::() + DocumentTab::STRIP_INSET } /// Draw the Timeline panel's sequence tabs in `strip`: one tab per open sequence, × on the active @@ -808,12 +909,11 @@ pub fn sequence_tabs(ui: &mut egui::Ui, strip: Rect, seqs: &SeqTabs, t: &Tokens, let mut actions = Vec::new(); let painter = ui.painter_at(strip); let active_at = seqs.open.iter().position(|(id, _)| seqs.active == Some(*id)).unwrap_or(0); - let text_y = strip.center().y; // Which tabs fit. The active tab is always shown: tabs before it are left out until it // fits, then as many after it as there is room for. The » list reaches the rest. let widths = sequence_widths(ui, seqs); - let span = |from: usize, to: usize| widths.get(from..=to).map_or(0.0, |w| w.iter().sum::() + 8.0 * w.len() as f32); - let room = strip.width() - 12.0; + let span = |from: usize, to: usize| widths.get(from..=to).map_or(0.0, |w| w.iter().sum::() + DocumentTab::GAP * w.len() as f32); + let room = strip.width() - DocumentTab::STRIP_INSET; let all_fit = span(0, seqs.open.len().saturating_sub(1)) <= room; let room = if all_fit { room } else { room - 24.0 }; let mut first = 0; @@ -856,60 +956,24 @@ pub fn sequence_tabs(ui: &mut egui::Ui, strip: Rect, seqs: &SeqTabs, t: &Tokens, } else { ui.ctx().data_mut(|d| d.remove::(wheel_id)); } - let mut x = strip.min.x + 12.0; - let mut seq_rects: Vec<(u64, Rect)> = Vec::new(); - let mut dragged: Option = None; + let mut x = strip.min.x + DocumentTab::STRIP_INSET; + let mut tab_responses = Vec::new(); for (i, (id, name)) in seqs.open.iter().enumerate().take(last + 1).skip(first) { let is_active = seqs.active == Some(*id); - let galley = painter.layout_no_wrap(name.clone(), Tokens::ui(12.0), if is_active { t.tab_text_active } else { t.tab_text }); - let close_w = if is_active { 16.0 } else { 0.0 }; + let tab = DocumentTab::new(&painter, name, is_active, true); let w = widths.get(i).copied().unwrap_or(0.0); let tab_rect = Rect::from_min_size(pos2(x, strip.min.y), vec2(w, strip.height())); // a sequence tab keeps its identity when the tabs are reordered under the pointer let resp = ui.interact(tab_rect, egui::Id::unique(("tab-seq", *id)), Sense::click_and_drag()); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, resp.enabled(), is_active, name)); - ui.ctx().accesskit_node_builder(resp.id, |node| { - node.set_role(egui::accesskit::Role::Tab); - node.set_selected(is_active); - }); - paint_widget_focus(&painter, &resp, t); - seq_rects.push((*id, tab_rect)); - if resp.dragged_by(egui::PointerButton::Primary) { - dragged = Some(*id); - } - // Escape puts a dragged tab back where it was (egui ends the drag on Escape, #580) - let home = egui::Id::unique(("tab-seq-home", *id)); - if resp.drag_started_by(egui::PointerButton::Primary) { - ui.data_mut(|d| d.insert_temp(home, i)); - } - if resp.drag_stopped() - && let Some(at) = ui.data_mut(|d| d.remove_temp::(home)) - && ui.input(|input| input.key_pressed(egui::Key::Escape)) - { - actions.push(SeqAction::Move(*id, at)); - } reg.add_response(&format!("timeline.tab.{id}"), &resp, name); - let label_x = tab_rect.min.x + 8.0 + close_w; - let col = if is_active || resp.hovered() { t.tab_text_active } else { t.tab_text }; - let label_w = galley.size().x; - painter.galley_with_override_text_color(pos2(label_x, text_y - galley.size().y / 2.0), galley, col); let mut closed = false; - if is_active { - // × closes the sequence's tab (the sequence stays in the project) - let cr = Rect::from_center_size(pos2(tab_rect.min.x + 10.0, text_y), vec2(8.0, 8.0)); - let cresp = ui.interact(cr.expand(4.0), egui::Id::unique(("tab-close", *id)), Sense::click()); - cresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, cresp.enabled(), "close sequence")); - reg.add_response(&format!("timeline.tab.{id}.close"), &cresp, "close sequence"); - let cc = if cresp.hovered() { t.tab_text_active } else { t.tab_text }; - painter.line_segment([cr.left_top(), cr.right_bottom()], Stroke::new(1.2, cc)); - painter.line_segment([cr.right_top(), cr.left_bottom()], Stroke::new(1.2, cc)); - paint_widget_focus(&painter, &cresp, t); - if cresp.clicked() { + if let Some(close) = tab.show(ui, &painter, &resp, egui::Id::unique(("tab-close", *id)), t) { + close.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, close.enabled(), tl!("close sequence"))); + reg.add_response(&format!("timeline.tab.{id}.close"), &close, tl!("close sequence")); + if close.clicked() { actions.push(SeqAction::Close(*id)); closed = true; } - let uy = strip.max.y - 2.0; - painter.line_segment([pos2(label_x, uy), pos2(label_x + label_w, uy)], Stroke::new(1.0, t.tab_text_active)); } if (resp.clicked() || resp.drag_started_by(egui::PointerButton::Primary)) && !closed && !is_active { actions.push(SeqAction::Open(*id)); @@ -926,22 +990,13 @@ pub fn sequence_tabs(ui: &mut egui::Ui, strip: Rect, seqs: &SeqTabs, t: &Tokens, let ppp = ui.ctx().pixels_per_point().max(1e-3); actions.push(SeqAction::Menu(*id, pos2((at.x * ppp).round() / ppp, ((at.y * ppp).floor() + 1.0) / ppp))); } - x += w + 8.0; + tab_responses.push(resp); + x += w + DocumentTab::GAP; } - // Dragging a sequence tab sideways: it changes places with a neighbour when the pointer - // passes that neighbour's middle. - if let Some(id) = dragged - && let Some(px) = ui.input(|i| i.pointer.latest_pos()).map(|p| p.x) - && let Some(at) = seq_rects.iter().position(|(s, _)| *s == id) - && let Some(index) = seqs.open.iter().position(|(s, _)| *s == id) + if let Some((from, to)) = document_tab_drag(&tab_responses, first) + && let Some((id, _)) = seqs.open.get(from) { - let before = at.checked_sub(1).and_then(|k| seq_rects.get(k)); - let after = seq_rects.get(at + 1); - if before.is_some_and(|(_, r)| px < r.center().x) { - actions.push(SeqAction::Move(id, index.saturating_sub(1))); - } else if after.is_some_and(|(_, r)| px > r.center().x) { - actions.push(SeqAction::Move(id, index + 1)); - } + actions.push(SeqAction::Move(*id, to)); } // the » list: every open sequence, the shown one ticked let list_open = ui.ctx().data(|d| d.get_temp::(list_id)).unwrap_or(false); diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index cc3fde824..4639de4ce 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -250,9 +250,11 @@ fn tl_literals(text: &str) -> Vec { let mut out = Vec::new(); let mut rest = text; loop { - let next = ["tl!(\"", "tlf!(\""].into_iter().filter_map(|p| Some((rest.find(p)?, p.len()))).min(); + let next = ["tl!(", "tlf!("].into_iter().filter_map(|p| Some((rest.find(p)?, p.len()))).min(); let Some((at, len)) = next else { break }; rest = &rest[at + len..]; + let Some(after_quote) = rest.trim_start().strip_prefix('"') else { continue }; + rest = after_quote; let mut lit = String::new(); let mut chars = rest.char_indices(); let mut end = rest.len(); @@ -462,7 +464,7 @@ fn dynamic_names() -> Vec { #[test] fn tl_literals_are_found_and_unescaped() { - let src = "a(tl!(\"Save\")); b(tl!(\"Say \\\"hi\\\"\\n\")); tl!(x); tlf!(\"{n} file(s)\", n);"; + let src = "a(tl!(\"Save\")); b(tl!(\"Say \\\"hi\\\"\\n\")); tl!(x); tlf!(\n \"{n} file(s)\", n);"; assert_eq!(tl_literals(src), ["Save", "Say \"hi\"\n", "{n} file(s)"]); } diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 0a8ee61f9..42254bbec 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -5,6 +5,16 @@ use egui::epaint::{PathShape, PathStroke}; use egui::{Color32, Painter, Pos2, Rect, Stroke, pos2, vec2}; use serde::{Deserialize, Serialize}; +/// Draw two filled semicircles with their flat edges facing the gap. +pub(crate) fn paint_script_mark(painter: &Painter, center: Pos2, radius: f32, gap: f32, color: Color32) { + let offset = vec2(gap * 0.5, 0.0); + let left = center - offset; + let right = center + offset; + let clip = painter.clip_rect(); + painter.with_clip_rect(clip.with_max_x(left.x)).circle_filled(left, radius, color); + painter.with_clip_rect(clip.with_min_x(right.x)).circle_filled(right, radius, color); +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum Icon { Selection, diff --git a/crates/ui-egui/src/legacy_dropdown.rs b/crates/ui-egui/src/legacy_dropdown.rs index 6f0d3427f..115d1dd24 100644 --- a/crates/ui-egui/src/legacy_dropdown.rs +++ b/crates/ui-egui/src/legacy_dropdown.rs @@ -12,11 +12,12 @@ pub(crate) struct Dropdown<'a> { width: Option, height: Option, truncate: bool, + corners: Option, } impl<'a> Dropdown<'a> { pub(crate) fn from_id_salt(salt: impl AsIdSalt) -> Self { - Self { salt: IdSalt::new(salt), selected: Atoms::default(), width: None, height: None, truncate: false } + Self { salt: IdSalt::new(salt), selected: Atoms::default(), width: None, height: None, truncate: false, corners: None } } pub(crate) fn selected_text(mut self, text: impl IntoAtoms<'a>) -> Self { @@ -39,6 +40,12 @@ impl<'a> Dropdown<'a> { self } + /// Join the field to an adjacent control using the supplied corners. + pub(crate) fn joined(mut self, corners: egui::CornerRadius) -> Self { + self.corners = Some(corners); + self + } + pub(crate) fn show_ui(mut self, ui: &mut Ui, body: impl FnOnce(&mut Ui) -> R) -> InnerResponse> { let name = self.selected.text().map(String::from).unwrap_or_default(); let rtl = ui.style().right_to_left; @@ -56,7 +63,12 @@ impl<'a> Dropdown<'a> { if self.truncate { button = button.truncate(); } - let response = ui.push_id(self.salt, |ui| ui.add(button)).inner; + let response = ui + .push_id(self.salt, |ui| match self.corners { + Some(corners) => ui.add_sized(egui::vec2(width, 24.0), button.corner_radius(corners).truncate()), + None => ui.add(button), + }) + .inner; response.widget_info(|| { let mut info = WidgetInfo::new(Role::ComboBox); info.enabled = ui.is_enabled(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e6424bafb..8b43b83db 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -211,6 +211,7 @@ struct NativeTimelineDrop { pub struct FilmcraftApp { pub session: Session, + pub(crate) script_practice: Option, pub ui: UiState, pub tokens: Tokens, pub frames: Arc, diff --git a/crates/ui-egui/src/links.rs b/crates/ui-egui/src/links.rs index efab6f6d0..06caafc1e 100644 --- a/crates/ui-egui/src/links.rs +++ b/crates/ui-egui/src/links.rs @@ -14,6 +14,8 @@ pub const WEBSITE: &str = "https://getartcraft.com"; pub const APP_PAGE: &str = "https://getartcraft.com/apps/filmcraft"; /// FilmCraft's source repository. pub const GITHUB: &str = "https://github.com/storytold/filmcraft"; +/// Lined Script's user guide in FilmCraft Help. +pub const LINED_SCRIPT_HELP: &str = "https://github.com/storytold/filmcraft/blob/main/docs/lined-script.md"; /// New issue on FilmCraft's repository. pub const ISSUES: &str = "https://github.com/storytold/filmcraft/issues"; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index a365fb6c1..ca9c07552 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -129,13 +129,15 @@ pub const UI_COMMANDS: &[UiCommand] = &[ uic!("window.workspace.effects", "Effects", ["Window", "Workspaces"], Some("Alt+Shift+4")), uic!("window.workspace.audio", "Audio", ["Window", "Workspaces"], Some("Alt+Shift+5")), uic!("window.workspace.captionsandgraphics", "Captions and Graphics", ["Window", "Workspaces"], Some("Alt+Shift+6")), - uic!("window.workspace.script", "Lined Script", ["Window", "Workspaces"], None), - uic!("script.openPanel", "Open Script", [], None), - uic!("script.findInScript", "Find in Script", [], None), + uic!("script.openPanel", "Open in Lined Script", [], None), + uic!("script.findInScript", "Find in Lined Script", [], None), + uic!("script.playTake", "Play Lined Script Take", [], None), + uic!("script.recordMarks", "Record Lined Script Marks", [], None), uic!("script.addMarkAtSelection", "Add Script Mark", [], None), - uic!("script.toggleOffscreen", "Toggle Script Offscreen", [], None), - uic!("script.thumbnailBack", "Script Thumbnail Back", [], None), - uic!("script.thumbnailForward", "Script Thumbnail Forward", [], None), + uic!("script.toggleOffscreen", "Toggle Lined Script Offscreen", [], None), + uic!("script.applyCandleColor", "Apply Candle Color", [], None), + uic!("script.thumbnailBack", "Lined Script Thumbnail Back", [], None), + uic!("script.thumbnailForward", "Lined Script Thumbnail Forward", [], None), uic!("window.workspace.allpanels", "All Panels", ["Window", "Workspaces"], None), uic!("window.workspace.vertical", "Vertical", ["Window", "Workspaces"], None), uic!("window.workspace.reset", "Reset to Saved Layout", ["Window", "Workspaces"], Some("Alt+Shift+0")), @@ -188,13 +190,6 @@ pub const UI_COMMANDS: &[UiCommand] = &[ uic!("app.settings.trim", "Trim…", ["Edit", "Preferences"], None), ]; -fn panel_menu_label(panel: PanelKind) -> &'static str { - match panel { - PanelKind::Script => "Lined Script", - _ => panel.title(), - } -} - pub fn panel_command_id(p: PanelKind) -> String { format!("window.panel.{}", p.id()) } @@ -246,10 +241,30 @@ fn export_preview_command<'a>(app: &FilmcraftApp, id: &'a str, params: &Value) - /// Execute a UI or engine command by id. pub fn invoke_command(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, mut params: Value) -> Result { - app.ui.script.sync_project(&app.session.project_instance); + app.ui.script.sync_project(&app.session.project_instance, &app.session.state.script_tabs); if let Some(command) = export_preview_command(app, id, ¶ms) { return crate::panels::export_mode::preview_command(app, command, ¶ms); } + if matches!(id, "source.insert" | "source.overwrite") && crate::panels::script::example_visible(app) { + return Err(tl!("Open a project clip in Source to insert or overwrite.").into()); + } + if id == "playback.toggle" + && params.get("monitor").is_none() + && app.ui.focused == PanelKind::Script + && crate::panels::script::active_screening(app).is_some() + { + params["monitor"] = json!("source"); + } + let source_target = targets_source(app, ¶ms); + let source_marker = + filmcraft_engine::source_monitor::source_command(id) && params.get("target").and_then(Value::as_str).map_or(source_target, |target| target == "source"); + let example_transport = id.starts_with("source.playback.") + || id == "source.setPlayhead" + || source_marker + || (source_target && (id.starts_with("playback.") || id.starts_with("playhead."))); + if example_transport && let Some(result) = crate::panels::script::with_example_monitor(app, |preview| invoke_command(preview, ctx, id, params.clone())) { + return result; + } // Select All / Deselect All act on the Project panel's items when it has focus (#168), only // what the shown bin lists (#456). Here and not in the key handling: on macOS the native menu // takes Cmd+A once Select All is enabled (a sequence is open) and sends the id here (#1752). @@ -380,7 +395,7 @@ pub fn invoke_command(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, mut if app.session.project.item(filmcraft_project::ItemId(item)).and_then(|item| item.as_script()).is_none() { return Err("that project item is not a script".into()); } - app.ui.script.open_document(Some(item)); + crate::panels::script::activate_tab(app, Some(item)); app.show_panel(PanelKind::Script); return Ok(json!({"item": item})); } @@ -389,11 +404,12 @@ pub fn invoke_command(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, mut params.get("item").and_then(Value::as_u64).or_else(|| app.session.state.project_selection.first().map(|id| id.0)).ok_or("select a project clip")?; return crate::panels::script::find_source(app, filmcraft_project::ItemId(source)); } - if id == "script.addMarkAtSelection" { - return crate::panels::script::add_mark_at_selection(app); - } - if id == "script.toggleOffscreen" { - return crate::panels::script::toggle_offscreen_selection(app); + match id { + "script.playTake" | "script.recordMarks" => return crate::panels::script::toggle_screening(app, ctx, id == "script.recordMarks"), + "script.addMarkAtSelection" => return crate::panels::script::add_mark_at_selection(app), + "script.toggleOffscreen" => return crate::panels::script::toggle_offscreen_selection(app), + "script.applyCandleColor" => return crate::panels::script::apply_candle_color(app), + _ => {} } if app.ui.focused == PanelKind::Script && id == "edit.clear" && params.as_object().is_none_or(|map| map.is_empty()) { if ctx.text_edit_focused() { @@ -407,6 +423,9 @@ pub fn invoke_command(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, mut if app.ui.focused == PanelKind::Script && id == "edit.undo" && crate::panels::script::has_text_paste_undo(app) { return crate::panels::script::undo_text_paste(app, ctx); } + if menu && app.ui.focused == PanelKind::Script && crate::panels::script::history_enabled(app, id).is_some() { + return crate::panels::script::execute(app, id, params); + } if app.ui.focused == PanelKind::Script && params.as_object().is_none_or(|map| map.is_empty()) && matches!(id, "edit.copy" | "edit.paste") { if ctx.text_edit_focused() { if id == "edit.copy" { @@ -418,21 +437,7 @@ pub fn invoke_command(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, mut } return Ok(Value::Null); } - if id == "edit.copy" { - let result = crate::panels::script::copy_paste_section(app, true)?; - if let Some(text) = crate::panels::script::copied_plain_text(app) { - ctx.copy_text(text); - } - return Ok(result); - } - if let Some(text) = app.hooks.clipboard_text.as_mut().and_then(|read| read()) { - return crate::panels::script::paste_plain_text(app, &text); - } - if app.ui.script.section_clipboard.is_some() { - return crate::panels::script::copy_paste_section(app, false); - } - ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaste); - return Ok(Value::Null); + return crate::panels::script::section_clipboard_action(app, ctx, id == "edit.copy"); } if let Some(r) = crate::panels::workspaces::route(app, id, ¶ms) { return r; @@ -1088,6 +1093,7 @@ pub fn menu_items(app: &FilmcraftApp) -> Vec { for it in &mut v { it.label = app.ui.language.tr(&it.label).to_string(); match it.id.as_str() { + "source.insert" | "source.overwrite" if crate::panels::script::example_visible(app) => it.enabled = false, "app.language.english" => it.checked = Some(app.ui.language == crate::i18n::Language::En), "app.language.japanese" => it.checked = Some(app.ui.language == crate::i18n::Language::Ja), "app.language.spanish" => it.checked = Some(app.ui.language == crate::i18n::Language::Es), @@ -1107,6 +1113,11 @@ pub fn menu_items(app: &FilmcraftApp) -> Vec { "app.language.turkish" => it.checked = Some(app.ui.language == crate::i18n::Language::Tr), _ => {} } + if app.ui.focused == PanelKind::Script + && let Some(enabled) = crate::panels::script::history_enabled(app, &it.id) + { + it.enabled = enabled; + } if let Some(on) = engine_toggle(&app.session, &it.id) { it.checked = Some(on); } @@ -1204,7 +1215,7 @@ pub fn menu_items_for(session: &filmcraft_engine::Session) -> Vec { for p in PanelKind::ALL { out.push(MenuItem { id: panel_command_id(p), - label: panel_menu_label(p).into(), + label: p.title().into(), path: vec!["Window".into()], shortcut: session.shortcuts.primary(&panel_command_id(p)), enabled: true, @@ -1375,7 +1386,7 @@ pub fn external_commands() -> Vec { let mut v: Vec = UI_COMMANDS.iter().chain(crate::panels::keyboard::COMMANDS).map(|c| CommandInfo::new(c.id, c.label, c.menu, c.shortcut)).collect(); for p in PanelKind::ALL { - v.push(CommandInfo::new(&panel_command_id(p), panel_menu_label(p), &["Window"], p.window_shortcut())); + v.push(CommandInfo::new(&panel_command_id(p), p.title(), &["Window"], p.window_shortcut())); } v } @@ -1723,7 +1734,7 @@ mod tests { let id = format!("window.workspace.{}", crate::dock::slug(name)); assert!(ws.iter().any(|it| it.id == id && it.checked.is_none()), "no workspace {name}"); } - assert!(ws.iter().any(|it| it.id == "window.workspace.script" && it.label == "Lined Script")); + assert!(!ws.iter().any(|it| it.id == "window.workspace.script")); assert!(items.iter().any(|it| it.id == "window.panel.Script" && it.path == ["Window"] && it.label == "Lined Script")); let editing = ws.iter().position(|it| it.label == "Editing"); let reset = ws.iter().position(|it| it.id == "window.workspace.reset"); diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index a4225fc45..247985dd9 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -142,7 +142,11 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, p: PanelKind, rect: Rect) PanelKind::Program if slip_monitor::active(app) => slip_monitor::show(app, ui, rect), PanelKind::Program if !app.session.state.edit_points.is_empty() => trim_monitor::show(app, ui, rect), PanelKind::Program => monitor::show(app, ui, rect, monitor::Which::Program), - PanelKind::Source => monitor::show(app, ui, rect, monitor::Which::Source), + PanelKind::Source => { + if script::with_example_monitor(app, |preview| monitor::show(preview, ui, rect, monitor::Which::Source)).is_none() { + monitor::show(app, ui, rect, monitor::Which::Source); + } + } PanelKind::Timeline => timeline::show(app, ui, rect), PanelKind::Project => project::show(app, ui, rect), PanelKind::Tools => tools::show(app, ui, rect), @@ -471,7 +475,7 @@ pub(crate) fn panel_items(app: &mut FilmcraftApp, ui: &mut egui::Ui, p: PanelKin } if p == PanelKind::Source { ui.separator(); - close |= monitor::source_panel_menu(app, ui); + close |= script::with_example_monitor(app, |preview| monitor::source_panel_menu(preview, ui)).unwrap_or_else(|| monitor::source_panel_menu(app, ui)); } if p == PanelKind::LumetriColor { ui.separator(); diff --git a/crates/ui-egui/src/panels/keyboard.rs b/crates/ui-egui/src/panels/keyboard.rs index b65a80726..cb64e55e5 100644 --- a/crates/ui-egui/src/panels/keyboard.rs +++ b/crates/ui-egui/src/panels/keyboard.rs @@ -182,7 +182,7 @@ pub fn route(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: &Val "window.toggleMonitorFocus" => { let p = if app.ui.focused == PanelKind::Program { PanelKind::Source } else { PanelKind::Program }; app.show_panel(p); - Ok(json!({"focused": p.title()})) + Ok(json!({"focused": p.context_name()})) } "window.openSearch" => { app.show_panel(PanelKind::Project); @@ -267,7 +267,7 @@ pub(crate) fn toggle_maximize(app: &mut FilmcraftApp, p: PanelKind) -> Value { let _ = app.apply_dock(craft_behavior::dock::Action::activate(p)); app.ui.focused = p; } - json!({"maximized": app.ui.keys.maximized.map(|p| p.title())}) + json!({"maximized": app.ui.keys.maximized.map(|p| p.context_name())}) } /// The visible panel under the pointer (from last frame's automation rects). Each native @@ -301,7 +301,7 @@ fn cycle_panel(app: &mut FilmcraftApp, next: bool) -> Value { let i = v.iter().position(|p| *p == app.ui.focused).unwrap_or(0); let j = if next { (i + 1) % v.len() } else { (i + v.len() - 1) % v.len() }; app.ui.focused = v[j]; - json!({"focused": v[j].title()}) + json!({"focused": v[j].context_name()}) } /// Ask the focused panel's search field for keyboard focus (`widgets::search_field` takes it). @@ -310,7 +310,7 @@ fn focus_find_box(app: &mut FilmcraftApp, ctx: &egui::Context) -> Value { let rect = app.auto.find(&format!("panel.{}", p.id())).map(|e| egui::Rect::from_min_size(egui::pos2(e.rect[0], e.rect[1]), egui::vec2(e.rect[2], e.rect[3]))); ctx.data_mut(|d| d.insert_temp(egui::Id::unique(FOCUS_SEARCH), rect.unwrap_or(egui::Rect::EVERYTHING))); - json!({"panel": p.title()}) + json!({"panel": p.context_name()}) } /// egui temp-data key: the panel rect whose search field should take focus. diff --git a/crates/ui-egui/src/panels/media_dialogs.rs b/crates/ui-egui/src/panels/media_dialogs.rs index 3d6aa8f04..bc34095a8 100644 --- a/crates/ui-egui/src/panels/media_dialogs.rs +++ b/crates/ui-egui/src/panels/media_dialogs.rs @@ -687,8 +687,8 @@ fn review_script_mark_relink(app: &mut FilmcraftApp, ctx: &egui::Context, d: &mu let mut confirm = false; let mut cancel = false; egui::Window::new(tl!("Review Script marks")).collapsible(false).resizable(false).show(ctx, |ui| { - ui.label(tl!("FilmCraft cannot confirm this is the same footage used by linked Script takes.")); - ui.label(tl!("If it is the same footage, confirm the relink to preserve their marks. Otherwise cancel and replace the takes in Script.")); + ui.label(tl!("FilmCraft cannot confirm this is the same footage used by linked Lined Script takes.")); + ui.label(tl!("If it is the same footage, confirm the relink to preserve their marks. Otherwise cancel and replace the takes in Lined Script.")); ui.label(path); ui.horizontal(|ui| { let no = ui.button(tl!("Cancel relink")); diff --git a/crates/ui-egui/src/panels/project_views.rs b/crates/ui-egui/src/panels/project_views.rs index 625d05c09..a02ef0f27 100644 --- a/crates/ui-egui/src/panels/project_views.rs +++ b/crates/ui-egui/src/panels/project_views.rs @@ -292,11 +292,11 @@ fn script_and_source_menu(ui: &mut egui::Ui, id: ItemId, kind: &ItemKind, action ui.close(); } if matches!(kind, ItemKind::Script(_)) { - if ui.button(tl!("Open Script")).clicked() { + if ui.button(tl!("Open in Lined Script")).clicked() { actions.push(("script.openPanel".into(), json!({"item": id.0}))); ui.close(); } - } else if ui.button(tl!("Find in Script")).clicked() { + } else if ui.button(tl!("Find in Lined Script")).clicked() { actions.push(("script.findInScript".into(), json!({"item": id.0}))); ui.close(); } diff --git a/crates/ui-egui/src/panels/script.rs b/crates/ui-egui/src/panels/script.rs index 3b96626f4..1add49506 100644 --- a/crates/ui-egui/src/panels/script.rs +++ b/crates/ui-egui/src/panels/script.rs @@ -13,11 +13,17 @@ use crate::FilmcraftApp; use crate::dock::PanelKind; use crate::native_dialogs::FileDialog; use crate::theme::Tokens; +use crate::widgets::CenteredDialog as _; -const MIN_ROW_H: f32 = 20.0; +const MAX_ROW_SPACING: u8 = 12; +const DEFAULT_LINE_H: f32 = 16.0; const MAX_VISUAL_LINES: f32 = 12.0; const SCRIPT_FONT_SIZE: f32 = 12.5; -const TAKE_W: f32 = 27.0; +const DEFAULT_CANDLE_W: f32 = 5.0; +const DEFAULT_SWATCH: ScriptColor = ScriptColor::Green; +const MIN_CANDLE_W: f32 = 2.0; +const MAX_CANDLE_W: f32 = 12.0; +const CANDLE_DISTANCE: std::ops::RangeInclusive = 2..=10; const DEFAULT_THUMB_W: f32 = 96.0; const MIN_THUMB_W: f32 = 64.0; const MAX_THUMB_W: f32 = 192.0; @@ -33,8 +39,15 @@ const REBIND_SPAN_WARNING: &str = "replacement source span excludes existing mar mod canvas; mod layout; +mod practice; mod recovery; +use practice::document; +pub(crate) use practice::{Practice, close_example, example_monitor, example_visible, execute, history_enabled, with_example_monitor}; +mod playback; mod selection; +pub(crate) use playback::{active_screening, toggle_screening}; +mod tabs; +pub(crate) use tabs::activate as activate_tab; mod toolbar; use layout::{candle_row_bounds, coverage_rows, first_visible, row_layout, thumbnail_height, thumbnail_width}; @@ -44,6 +57,9 @@ use selection::{current_line, select_line, selected_range, take_by_id}; #[serde(default)] pub struct ScriptUi { pub item: Option, + tabs: Vec, + #[serde(skip)] + practicing: bool, #[serde(skip)] project: Option>, #[serde(skip)] @@ -53,15 +69,23 @@ pub struct ScriptUi { pub selected_slate: Option, pub selected_take: Option, pub selected_mark: Option, + #[serde(skip)] + screening: Option, /// Thumbnail selection is distinct from its display take for delete routing. pub selected_thumbnail: Option, #[serde(skip)] + drag_take_number: Option, + #[serde(skip)] + preview_focus: Option<(egui::Id, u64, u64)>, + #[serde(skip)] thumbnail_shuttle_at: f64, #[serde(skip)] thumbnail_shuttle_count: u32, #[serde(skip)] thumbnail_shuttle_direction: i8, #[serde(skip)] + thumbnail_shuttle_take: Option, + #[serde(skip)] pub selected_section_slates: Vec, #[serde(skip)] pub section_clipboard: Option, @@ -69,7 +93,8 @@ pub struct ScriptUi { lasso_start: Option, #[serde(skip)] lasso_end: Option, - pub paint_color: ScriptColor, + pub paint_color: Option, + pub edit_mode: bool, pub edit_line: Option, pub edit_text: String, #[serde(skip)] @@ -107,9 +132,15 @@ pub struct ScriptUi { pub text_column_width: Option, pub text_inset: Option, pub font_size: Option, + pub row_spacing: Option, pub thumbnail_width: Option, + pub candle_width: Option, + pub candle_distance: Option, pub show_row_colors: Option, pub show_line_numbers: Option, + pub hide_page_numbers: bool, + pub show_page_controls: bool, + pub keep_thumbnails_visible: bool, pub search: String, #[serde(skip)] search_results: Vec, @@ -124,7 +155,7 @@ pub struct ScriptUi { /// Only the take columns move horizontally; script text stays in view. pub take_scroll: f32, pub pending_rebind: Option<(u64, u64)>, - /// Source selected by Project ▸ Find in Script; a chooser is shown for multiple matches. + /// Source selected by Project ▸ Find in Lined Script; a chooser is shown for multiple matches. pub find_source: Option, /// Request to bring this logical line into the viewport on the next frame. #[serde(skip)] @@ -140,9 +171,15 @@ pub struct ScriptUi { #[serde(skip)] layout_font_size: u32, #[serde(skip)] + layout_row_spacing: u8, + #[serde(skip)] + single_row_height: f32, + #[serde(skip)] layout_thumbnail_width: u32, #[serde(skip)] row_tops: Vec, + #[serde(skip)] + layout_space_width: f32, } #[derive(Clone, Debug)] @@ -160,12 +197,13 @@ enum Action { PasteText { line: u64, text: String, start: usize, end: usize }, AddMarkAtSelection, ToggleOffscreenSelection, + ApplyCandleColor, FinishSlateDrag, } pub(crate) fn add_mark_at_selection(app: &mut FilmcraftApp) -> Result { - let item = app.ui.script.item.ok_or("open a script first")?; - let doc = app.session.project.item(ItemId(item)).and_then(|item| item.as_script()).ok_or("open a script first")?; + let item = app.ui.script.item; + let doc = document(app).ok_or("open a script first")?; let take = take_by_id(doc, app.ui.script.selected_take).ok_or("select a candle first")?; let line = current_line(doc, &app.ui.script).ok_or("select a script line first")?; let in_candle = doc @@ -175,23 +213,33 @@ pub(crate) fn add_mark_at_selection(app: &mut FilmcraftApp) -> Result Result { - let Some(item) = app.ui.script.item else { return Ok(Value::Null) }; + let item = app.ui.script.item; let (command, params) = if let (Some(take), Some(mark)) = (app.ui.script.selected_take, app.ui.script.selected_mark) { ("script.deleteMark", json!({"item":item,"take":take,"mark":mark})) } else if let Some(slate) = app.ui.script.selected_thumbnail.filter(|slate| Some(*slate) == app.ui.script.selected_slate) { @@ -201,14 +249,14 @@ pub(crate) fn delete_selection(app: &mut FilmcraftApp) -> Result } else { return Ok(Value::Null); }; - let result = app.session.execute(command, params).map_err(|error| error.to_string())?; + let result = execute(app, command, params)?; app.ui.script.clear_object_selection(); Ok(result) } pub(crate) fn toggle_offscreen_selection(app: &mut FilmcraftApp) -> Result { - let item = app.ui.script.item.ok_or("open a script first")?; - let doc = app.session.project.item(ItemId(item)).and_then(|item| item.as_script()).ok_or("open a script first")?; + let item = app.ui.script.item; + let doc = document(app).ok_or("open a script first")?; let take = take_by_id(doc, app.ui.script.selected_take).ok_or("select a candle first")?; let ids = selected_take_lines(doc, &app.ui.script, take); if ids.is_empty() { @@ -224,65 +272,141 @@ pub(crate) fn toggle_offscreen_selection(app: &mut FilmcraftApp) -> Result>()})) - .map_err(|error| error.to_string()) + execute(app, "script.setTakeStyle", json!({"item":item,"take":take.id.0,"offscreenLines":updated.iter().map(|id|id.0).collect::>()})) +} + +pub(crate) fn apply_candle_color(app: &mut FilmcraftApp) -> Result { + let doc = document(app).ok_or(tl!("Open a lined script first."))?; + let take = take_by_id(doc, app.ui.script.selected_take).ok_or(tl!("Select the candle rows to color."))?; + let rows = selected_take_lines(doc, &app.ui.script, take); + if rows.is_empty() { + return Err(tl!("Select the candle rows to color.").into()); + } + + let color = app.ui.script.paint_color.unwrap_or(DEFAULT_SWATCH); + let selected: std::collections::HashSet<_> = rows.iter().copied().collect(); + let mut updated = take.line_colors.clone(); + updated.retain(|entry| !selected.contains(&entry.line)); + if color != take.color { + updated.extend(rows.into_iter().map(|line| filmcraft_project::ScriptLineColor { line, color })); + } + execute(app, "script.setTakeStyle", json!({"item":app.ui.script.item, "take":take.id, "lineColors":updated})) +} + +/// A focused take owns horizontal arrows before the application-wide playhead shortcuts. +pub(crate) fn preview_arrow_keys(app: &mut FilmcraftApp, ctx: &egui::Context) -> bool { + let Some((id, slate, take)) = app.ui.script.preview_focus else { return false }; + if !ctx.memory(|m| m.has_focus(id)) || egui::Popup::is_any_open(ctx) { + return false; + } + let mut presses = Vec::new(); + ctx.input_mut(|input| { + input.events.retain(|event| { + if let egui::Event::Key { key, pressed: true, repeat, modifiers, .. } = event + && modifiers.is_none() + && matches!(key, egui::Key::ArrowLeft | egui::Key::ArrowRight) + { + presses.push((if *key == egui::Key::ArrowLeft { -1 } else { 1 }, *repeat)); + return false; + } + true + }) + }); + for (direction, repeat) in presses { + app.ui.script.clear_object_selection(); + app.ui.script.selected_thumbnail = (id == egui::Id::unique(("script.thumbnail", slate))).then_some(slate); + app.ui.script.selected_slate = Some(slate); + app.ui.script.selected_take = Some(take); + if let Err(error) = advance_thumbnail(app, ctx, direction, Some(repeat)) { + app.ui.status = error; + break; + } + } + true } pub(crate) fn shuttle_thumbnail(app: &mut FilmcraftApp, ctx: &egui::Context, direction: i8) -> Result { - let item = app.ui.script.item.ok_or("open a script first")?; + advance_thumbnail(app, ctx, direction, None) +} + +// Plain arrows step by frame, while the assigned shuttle commands start at a second per step. +fn advance_thumbnail(app: &mut FilmcraftApp, ctx: &egui::Context, direction: i8, arrow_repeat: Option) -> Result { + let item = app.ui.script.item; let slate_id = app.ui.script.selected_slate.ok_or("select a thumbnail first")?; - let doc = app.session.project.item(ItemId(item)).and_then(|item| item.as_script()).ok_or("open a script first")?; + let doc = document(app).ok_or("open a script first")?; let slate = doc.slates.iter().find(|slate| slate.id.0 == slate_id).ok_or("select a thumbnail first")?; let take = slate.takes.iter().find(|take| app.ui.script.selected_take == Some(take.id.0)).or_else(|| slate.takes.first()).ok_or("thumbnail has no candles")?; let source = take.source.ok_or("reattach this candle's source first")?; - let view = filmcraft_engine::clip_ops::source_view(&app.session, source).ok_or("linked source is unavailable")?; + let view = filmcraft_engine::clip_ops::source_view(practice::source_session(app, source), source).ok_or("linked source is unavailable")?; let first = take.thumbnail_time.or_else(|| doc.first_visible_mark_time(take)).unwrap_or(view.start); let take_id = take.id.0; let now = ctx.input(|input| input.time); - if app.ui.script.thumbnail_shuttle_direction == direction && now - app.ui.script.thumbnail_shuttle_at < 0.25 { - app.ui.script.thumbnail_shuttle_count = app.ui.script.thumbnail_shuttle_count.saturating_add(1); + let state = &mut app.ui.script; + let repeating = arrow_repeat.unwrap_or(now - state.thumbnail_shuttle_at < 0.25); + if repeating && state.thumbnail_shuttle_direction == direction && state.thumbnail_shuttle_take == Some(take_id) { + state.thumbnail_shuttle_count = state.thumbnail_shuttle_count.saturating_add(1); } else { - app.ui.script.thumbnail_shuttle_count = 0; + state.thumbnail_shuttle_count = 0; } - app.ui.script.thumbnail_shuttle_at = now; - app.ui.script.thumbnail_shuttle_direction = direction; - let seconds = match app.ui.script.thumbnail_shuttle_count { - 0..=5 => 1_i64, - 6..=17 => 2, - _ => 5, + state.thumbnail_shuttle_at = now; + state.thumbnail_shuttle_direction = direction; + state.thumbnail_shuttle_take = Some(take_id); + let step = match (arrow_repeat, state.thumbnail_shuttle_count) { + (Some(false), _) => view.rate.frame_duration().0, + (Some(true), 0..=5) => view.rate.frame_duration().0.saturating_mul(5), + (_, 0..=5) => TICKS_PER_SECOND, + (_, 6..=17) => TICKS_PER_SECOND * 2, + _ => TICKS_PER_SECOND * 5, }; let last = (view.end - view.rate.frame_duration()).max(view.start); - let ticks = first.0.saturating_add(i64::from(direction).saturating_mul(seconds.saturating_mul(TICKS_PER_SECOND))); + let ticks = first.0.saturating_add(i64::from(direction).saturating_mul(step)); let target = Tick(ticks).clamp(view.start, last); let frame = view.rate.frame_at(Tick(target.0.saturating_add(view.rate.frame_duration().0 / 2))); let target = view.rate.tick_of(frame).clamp(view.start, last); - app.session.execute("script.setThumbnailTime", json!({"item":item,"take":take_id,"time":target.0})).map_err(|error| error.to_string()) + if target == first { + return Ok(json!({"time":target.0})); + } + execute(app, "script.setThumbnailTime", json!({"item":item,"take":take_id,"time":target.0})) +} + +/// Clipboard actions on the script selection for Edit menu commands and shortcuts. +pub(crate) fn section_clipboard_action(app: &mut FilmcraftApp, ctx: &egui::Context, copy: bool) -> Result { + if copy { + let result = copy_paste_section(app, true)?; + if let Some(text) = copied_plain_text(app) { + ctx.copy_text(text); + } + return Ok(result); + } + if let Some(text) = app.hooks.clipboard_text.as_mut().and_then(|read| read()) { + return paste_plain_text(app, &text); + } + if app.ui.script.section_clipboard.is_some() { + return copy_paste_section(app, false); + } + ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaste); + Ok(Value::Null) } /// Route the ordinary Edit menu shortcuts to Script when this panel has focus. /// Text fields keep their native clipboard handling before shortcuts reach here. pub(crate) fn copy_paste_section(app: &mut FilmcraftApp, copy: bool) -> Result { - let item = app.ui.script.item.ok_or("open a script first")?; + let item = app.ui.script.item; if copy { - let doc = app.session.project.item(ItemId(item)).and_then(|item| item.as_script()).ok_or("open a script first")?; + let doc = document(app).ok_or("open a script first")?; let (a, b) = selected_range(doc, app.ui.script.selected_lines).ok_or("select script rows to copy")?; let params = json!({"item":item,"startLine":doc.lines[a].id.0, "endLine":doc.lines[b].id.0,"slates":app.ui.script.selected_section_slates}); - let section = app.session.execute("script.copySection", params).map_err(|error| error.to_string())?; + let section = execute(app, "script.copySection", params)?; app.ui.script.section_clipboard = Some(section); app.ui.status = tl!("Script section copied").into(); Ok(Value::Null) } else { + require_text_editing(app)?; let section = app.ui.script.section_clipboard.clone().ok_or("copy a script section first")?; - let after = app - .session - .project - .item(ItemId(item)) - .and_then(|item| item.as_script()) - .and_then(|doc| selected_range(doc, app.ui.script.selected_lines).map(|(_, b)| doc.lines[b].id.0)); - let result = app.session.execute("script.pasteSection", json!({"item":item,"afterLine":after,"section":section})).map_err(|error| error.to_string())?; + let after = document(app).and_then(|doc| selected_range(doc, app.ui.script.selected_lines).map(|(_, b)| doc.lines[b].id.0)); + let result = execute(app, "script.pasteSection", json!({"item":item,"afterLine":after,"section":section}))?; if let (Some(first), Some(last)) = (result["startLine"].as_u64(), result["endLine"].as_u64()) { app.ui.script.selected_lines = Some((first, last)); app.ui.script.selected_section_slates.clear(); @@ -299,6 +423,10 @@ pub(crate) fn copied_plain_text(app: &FilmcraftApp) -> Option { Some(text?.join("\n")) } +fn require_text_editing(app: &FilmcraftApp) -> Result<(), String> { + if app.ui.script.edit_mode { Ok(()) } else { Err(tl!("Turn on Edit to paste script text.").into()) } +} + pub(crate) fn paste_plain_text(app: &mut FilmcraftApp, text: &str) -> Result { if text.len() > ScriptDocument::MAX_TEXT_BYTES { return Err(tl!("Pasted text exceeds the 4 MiB limit.").into()); @@ -306,19 +434,17 @@ pub(crate) fn paste_plain_text(app: &mut FilmcraftApp, text: &str) -> Result bool { + let item = app.ui.script.item; + let params = document(app).and_then(|doc| { if let Some(line) = app.ui.script.edit_line { let row = doc.lines.iter().find(|row| row.id.0 == line)?; return (row.text != app.ui.script.edit_text).then(|| ("script.editLine", json!({"item":item,"line":line,"text":app.ui.script.edit_text}))); @@ -369,24 +498,24 @@ pub(crate) fn finish_edit_on_click_away(app: &mut FilmcraftApp, ctx: &egui::Cont None }); if let Some((command, params)) = params - && let Err(error) = app.session.execute(command, params) + && let Err(error) = execute(app, command, params) { app.ui.status = error.to_string(); - return; + return false; } app.ui.script.edit_line = None; app.ui.script.edit_caret = None; app.ui.script.edit_scene = None; app.ui.script.edit_page = None; - ctx.memory_mut(|memory| memory.surrender_focus(id)); + true } pub(crate) fn has_text_paste_undo(app: &FilmcraftApp) -> bool { - app.ui.script.edit_line.is_some() && app.ui.script.text_paste_revision == Some(app.session.revision) + app.ui.script.edit_line.is_some() && app.ui.script.text_paste_revision == Some(practice::revision(app)) } pub(crate) fn undo_text_paste(app: &mut FilmcraftApp, ctx: &egui::Context) -> Result { - let result = app.session.execute("edit.undo", json!({})).map_err(|error| error.to_string())?; + let result = execute(app, "edit.undo", json!({}))?; app.ui.script.text_paste_revision = None; app.ui.script.edit_line = None; app.ui.script.edit_text.clear(); @@ -401,7 +530,7 @@ pub(crate) fn undo_text_paste(app: &mut FilmcraftApp, ctx: &egui::Context) -> Re } fn command(app: &mut FilmcraftApp, id: &str, params: Value) -> Option { - match app.session.execute(id, params) { + match execute(app, id, params) { Ok(value) => Some(value), Err(error) => { app.ui.status = error.to_string(); @@ -418,17 +547,11 @@ fn run_actions(app: &mut FilmcraftApp, actions: Vec) { } Action::Create => { if let Some(value) = command(app, "script.create", json!({"name": tl!("Untitled Script")})) { - app.ui.script.open_document(value["item"].as_u64()); - if let Some(line) = app - .ui - .script - .item - .and_then(|id| app.session.project.item(ItemId(id))) - .and_then(|item| item.as_script()) - .and_then(|doc| doc.lines.first()) - { - app.ui.script.selected_lines = Some((line.id.0, line.id.0)); - app.ui.script.edit_line = Some(line.id.0); + activate_tab(app, value["item"].as_u64()); + app.ui.script.edit_mode = true; + if let Some(id) = document(app).and_then(|doc| doc.lines.last()).map(|line| line.id.0) { + app.ui.script.selected_lines = Some((id, id)); + app.ui.script.edit_line = Some(id); app.ui.script.edit_text.clear(); app.ui.script.edit_caret = Some(0); } @@ -445,6 +568,11 @@ fn run_actions(app: &mut FilmcraftApp, actions: Vec) { app.ui.status = error; } } + Action::ApplyCandleColor => { + if let Err(error) = apply_candle_color(app) { + app.ui.status = error; + } + } Action::FinishSlateDrag => { app.ui.script.drag_slate = None; app.ui.script.drag_slate_target = None; @@ -458,11 +586,11 @@ fn run_actions(app: &mut FilmcraftApp, actions: Vec) { } Action::Rebind { take, source } => { let params = json!({"item": app.ui.script.item, "take": take, "source": source, "allMatching": true}); - match app.session.execute("script.rebindTake", params) { + match execute(app, "script.rebindTake", params) { Ok(value) => { app.ui.script.pending_rebind = None; if let Some(count) = value["rebound"].as_u64() { - app.ui.status = tlf!("Reconnected {count} Script candle(s)", count); + app.ui.status = tlf!("Reconnected {count} Lined Script candle(s)", count); } } Err(error) if error.to_string().contains(REBIND_WARNING) || error.to_string().contains(REBIND_SPAN_WARNING) => { @@ -480,7 +608,11 @@ fn run_actions(app: &mut FilmcraftApp, actions: Vec) { } } Action::CueThumbnail { source, time } => { - if command(app, "source.open", json!({"item": source.0})).is_some() + if practice::examples(app, source).is_some() { + if let Err(error) = practice::open_example(app, source, Some(time.unwrap_or(Tick::ZERO)), true) { + app.ui.status = error; + } + } else if command(app, "source.open", json!({"item": source.0})).is_some() && time.is_none_or(|time| command(app, "source.setPlayhead", json!({"time": time.0})).is_some()) { app.show_panel(PanelKind::Source); @@ -492,15 +624,7 @@ fn run_actions(app: &mut FilmcraftApp, actions: Vec) { { app.ui.script.selected_lines = Some((created, created)); app.ui.script.scroll_to_line = Some(created); - if let Some(new_text) = app - .ui - .script - .item - .and_then(|id| app.session.project.item(ItemId(id))) - .and_then(|item| item.as_script()) - .and_then(|doc| doc.lines.iter().find(|line| line.id.0 == created)) - .map(|line| line.text.clone()) - { + if let Some(new_text) = document(app).and_then(|doc| doc.lines.iter().find(|line| line.id.0 == created)).map(|line| line.text.clone()) { app.ui.script.edit_line = Some(created); app.ui.script.edit_text = new_text; app.ui.script.edit_caret = Some(0); @@ -514,14 +638,8 @@ fn run_actions(app: &mut FilmcraftApp, actions: Vec) { } // Keep typing before this paste as its own edit, so one Undo removes // only the paste instead of also discarding the pending typed text. - let pending = app - .ui - .script - .item - .and_then(|item| app.session.project.item(ItemId(item))) - .and_then(|item| item.as_script()) - .and_then(|doc| doc.lines.iter().find(|row| row.id.0 == line)) - .is_some_and(|row| row.text != app.ui.script.edit_text); + let pending = + document(app).and_then(|doc| doc.lines.iter().find(|row| row.id.0 == line)).is_some_and(|row| row.text != app.ui.script.edit_text); if pending && command(app, "script.editLine", json!({"item":app.ui.script.item,"line":line,"text":app.ui.script.edit_text})).is_none() { continue; } @@ -531,7 +649,7 @@ fn run_actions(app: &mut FilmcraftApp, actions: Vec) { json!({"item":app.ui.script.item,"line":line,"baseText":app.ui.script.edit_text,"text":text,"start":start,"end":end}), ) && let (Some(last), Some(text), Some(at)) = (value["endLine"].as_u64(), value["text"].as_str(), value["at"].as_u64()) { - app.ui.script.text_paste_revision = Some(app.session.revision); + app.ui.script.text_paste_revision = Some(practice::revision(app)); app.ui.script.edit_line = Some(last); app.ui.script.edit_text = text.to_owned(); app.ui.script.edit_caret = usize::try_from(at).ok(); @@ -595,7 +713,7 @@ fn import_text(app: &mut FilmcraftApp) { } let padded_text = format!("{IMPORT_LEADING_LINES}{body}"); if let Some(value) = command(app, "script.importText", json!({"name": name, "text": padded_text})) { - app.ui.script.open_document(value["item"].as_u64()); + activate_tab(app, value["item"].as_u64()); } }); } @@ -610,90 +728,85 @@ fn shift_click(ui: &egui::Ui) -> bool { pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) { let t = app.tokens; ui.painter().rect_filled(rect, 0.0, t.panel_bg); - let scripts: Vec<(ItemId, String)> = - app.session.project.items.values().filter(|item| item.as_script().is_some()).map(|item| (item.id, item.name.clone())).collect(); - if app.ui.script.item.is_none_or(|id| !scripts.iter().any(|entry| entry.0.0 == id)) { - app.ui.script.open_document(scripts.first().map(|entry| entry.0.0)); - } - let document = |app: &FilmcraftApp| { - app.ui.script.item.and_then(|id| app.session.project.item(ItemId(id))).and_then(|item| match &item.kind { - ItemKind::Script(doc) => Some(std::sync::Arc::clone(doc)), - _ => None, - }) - }; - let mut doc = document(app); - let item_before_header = app.ui.script.item; + tabs::reconcile(app); + let strip = Rect::from_min_max(rect.min, pos2(rect.right(), (rect.top() + t.tab_h).min(rect.bottom()))); + tabs::show(app, ui, strip); + app.ui.script.screening = active_screening(app); let mut actions = Vec::new(); - let body_top = toolbar::header(app, ui, rect, &scripts, doc.as_ref(), &mut actions); - // The document chooser can change the active script during this frame. - if app.ui.script.item != item_before_header { - doc = document(app); - } - if let Some(doc) = doc.as_ref() { + let body_top = toolbar::header(app, ui, Rect::from_min_max(strip.left_bottom(), rect.max), &mut actions); + if let Some(doc) = document(app).cloned().as_ref() { toolbar::coverage_hotkeys(app, ui, doc, &mut actions); let body = Rect::from_min_max(pos2(rect.min.x, body_top), rect.max); if body.is_positive() { canvas::content(app, ui, body, doc, &mut actions); } - } else { - getting_started(app, ui, Rect::from_min_max(pos2(rect.min.x, body_top), rect.max)); } run_actions(app, actions); rebind_confirmation(app, ui.ctx()); } -fn getting_started(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) { - let available = rect.shrink2(vec2(20.0, 12.0)); - if !available.is_positive() { - return; - } - let width = available.width().min(640.0); - let top = available.top() + (available.height() - 320.0).max(0.0) * 0.4; - let guide = Rect::from_min_max(pos2(available.center().x - width * 0.5, top), pos2(available.center().x + width * 0.5, available.bottom())); - let mut guide_ui = ui.new_child(egui::UiBuilder::new().max_rect(guide).layout(egui::Layout::top_down(egui::Align::LEFT))); - egui::ScrollArea::vertical().id_salt("script.getStarted").auto_shrink([false, false]).show(&mut guide_ui, |ui| { - guide_contents(app, ui, "script.getStarted"); - }); +fn guide_steps() -> [(&'static str, &'static str, &'static str, &'static str); 4] { + [ + ( + "import", + tl!("Step #1: Import a script"), + tl!("How do I get my script in?"), + tl!("Choose “Import” and open a UTF-8 plain-text file. Or choose “Blank” and paste script text inside."), + ), + ( + "clips", + tl!("Step #2: Add clips"), + tl!("How do I add a take?"), + tl!("Select the rows the take covers. Drag a clip or group from the Project panel onto that selection."), + ), + ( + "candles", + tl!("Step #3: Follow candles"), + tl!("What’s the vertical line?"), + tl!( + "That’s the candle. It shows which rows the take covers. Double-click the candle or its thumbnail to open the take in Source. Press Space to play." + ), + ), + ( + "marks", + tl!("Step #4: Add marks"), + tl!("How do I get back to a line?"), + tl!("Select the candle row, find the frame in Source, and click “Add script mark”. Click the mark to cue Source half a second early by default."), + ), + ] } fn guide_contents(app: &mut FilmcraftApp, ui: &mut egui::Ui, prefix: &str) { let t = app.tokens; - let title = ui.label(egui::RichText::new(tl!("Get started with Script")).size(19.0).strong().color(t.text)); - app.auto.add(prefix, title.rect, "Get started with Script"); + let title = ui.label(egui::RichText::new(tl!("Get started with Lined Script")).size(19.0).strong().color(t.text)); + app.auto.add(prefix, title.rect, "Get started with Lined Script"); ui.add_space(12.0); - for (key, heading, description) in [ - ( - "export", - tl!("0. Export Script text"), - tl!( - "Final Draft export:\n • macOS: File → Export → Script → Avid Script-Based Editing (.txt).\n • Windows: File → Export → Document → Save as Type → Avid Script-Based Editing (.txt)." - ), - ), - ("import", tl!("1. Import Text"), tl!("Save your .txt file as UTF-8 plain text, then choose Import Text… above. Or choose New to write a script.")), - ("clips", tl!("2. Add clips"), tl!("Select rows, then drag a clip from the Project panel onto the selection.")), - ( - "candles", - tl!("3. Follow candles"), - tl!("A candle shows a take's row coverage. Double-click a candle or thumbnail to open Source; press Space to play."), - ), - ( - "marks", - tl!("4. Add marks"), - tl!("Select a candle row, find the matching frame in Source, then click the diamond Mark button in Script. Click a mark to return to that frame."), - ), - ] { + let guide = tl!("Read the Lined Script guide"); + let link = ui.link(guide); + app.auto.add_response("script.help.openGuide", &link, guide); + if link.clicked() { + crate::links::open(app, ui.ctx(), crate::links::LINED_SCRIPT_HELP); + ui.close(); + } + ui.add_space(12.0); + for (key, heading, _, description) in guide_steps() { ui.label(egui::RichText::new(heading).strong().color(t.text)); let text = ui.add(egui::Label::new(egui::RichText::new(description).color(t.text_dim)).wrap()); app.auto.add(&format!("{prefix}.{key}"), text.rect, description); ui.add_space(12.0); } + ui.label(tl!("To mark during playback, select a candle and choose Record. Click its rows as you hear each line. Click Record again to stop.")); } fn rebind_confirmation(app: &mut FilmcraftApp, ctx: &egui::Context) { let Some((take, source)) = app.ui.script.pending_rebind else { return }; - egui::Window::new(tl!("Replace take?")).collapsible(false).resizable(false).show(ctx, |ui| { + egui::Window::new(tl!("Replace take?")).centered(ctx).collapsible(false).resizable(false).show(ctx, |ui| { ui.label(tl!("This replacement could be different footage. Old script marks would point to the wrong frames.")); - ui.label(tl!("This updates every matching candle in all scripts.")); + if app.ui.script.practicing { + ui.label(tl!("This updates matching candles in Help.")); + } else { + ui.label(tl!("This updates every matching candle in all scripts.")); + } ui.label(tl!("Replace matching candles and clear their marks?")); ui.horizontal(|ui| { let cancel = ui.button(tl!("Cancel")); @@ -721,7 +834,7 @@ pub fn find_source(app: &mut FilmcraftApp, source: ItemId) -> Result Vec { matches } -fn select_source_match(state: &mut ScriptUi, entry: &SourceMatch) { - state.open_document(Some(entry.item.0)); +fn select_source_match(app: &mut FilmcraftApp, entry: &SourceMatch) { + activate_tab(app, Some(entry.item.0)); + let state = &mut app.ui.script; state.selected_take = Some(entry.take); state.selected_thumbnail = None; state.selected_mark = None; @@ -814,16 +928,45 @@ fn doc_ids(doc: &ScriptDocument, range: (usize, usize)) -> impl Iterator String { - let mut chars = text.chars(); - let head: String = chars.by_ref().take(max_chars).collect(); - if chars.next().is_some() { format!("{head}…") } else { head } -} - #[cfg(test)] mod tests { use super::*; + #[test] + fn help_ends_with_one_editable_blank_row() { + let mut app = FilmcraftApp::new(filmcraft_engine::Session::default()); + practice::open(&mut app); + let doc = document(&app).expect("Help script"); + let [.., dialogue, blank] = doc.lines.as_slice() else { panic!("missing final rows") }; + assert!(!dialogue.text.is_empty()); + assert!(blank.text.is_empty()); + assert_ne!(dialogue.id, blank.id); + use filmcraft_project::ScriptElement; + assert_eq!(dialogue.element, Some(ScriptElement::Dialogue)); + let heading = doc.lines.iter().find(|line| line.scene.as_deref() == Some("1")).unwrap(); + assert_eq!(heading.element, Some(ScriptElement::SceneHeading)); + assert!(heading.page.is_none()); + assert!(doc.lines.iter().filter(|line| line.text == "USER" || line.text == "HELP").all(|line| line.element == Some(ScriptElement::Character))); + } + + #[test] + fn parenthetical_is_indented_from_dialogue_and_a_wrapped_transition_aligns_right() { + use filmcraft_project::ScriptElement::{Dialogue, Parenthetical, Transition}; + let column = |role| layout::row_column(Some(role), 64.0, 448.0, 4.0).0; + assert!(column(Dialogue) < column(Parenthetical)); + + let mut doc = ScriptDocument::from_text("DISSOLVE TO THE NEXT SCENE").unwrap(); + let line = &mut doc.lines[0]; + line.element = Some(Transition); + let ctx = egui::Context::default(); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + let galley = layout::row_galley(ui, line, Tokens::ui(12.0), Color32::WHITE, 65.0); + assert!(galley.rows.len() > 1); + assert!(galley.rect.left() < 0.0 && galley.rect.right().abs() < 1.0, "the galley ends at its ruler anchor"); + }); + output.textures_delta.clear(); + } + #[test] fn document_caches_survive_unrelated_edits_and_refresh_for_same_length_text_changes() { let mut app = FilmcraftApp::new(filmcraft_engine::Session::default()); diff --git a/crates/ui-egui/src/panels/script/canvas.rs b/crates/ui-egui/src/panels/script/canvas.rs index 1dc6113bf..9ec879218 100644 --- a/crates/ui-egui/src/panels/script/canvas.rs +++ b/crates/ui-egui/src/panels/script/canvas.rs @@ -1,14 +1,40 @@ //! Synchronized script rows, setup thumbnails, candles, and mark interactions. use super::{ - Action, Align2, Arc, CANDLE_CAP_H, Color32, DEFAULT_TEXT_INSET, FilmcraftApp, HashMap, ItemId, MIN_ROW_H, Rect, SCRIPT_FONT_SIZE, SLATE_GAP, ScriptColor, - ScriptDocument, ScriptLine, ScriptTake, Sense, Stroke, TAKE_HEADER_H, TAKE_NUMBER_H, TAKE_W, Tick, Tokens, candle_row_bounds, coverage_rows, first_visible, - json, pos2, recovery, row_layout, script_color, select_line, selected_range, selected_take_lines, shift_click, thumbnail_height, thumbnail_width, - toggle_offscreen, truncate, vec2, + Action, Align2, Arc, CANDLE_CAP_H, Color32, FilmcraftApp, HashMap, ItemId, Rect, SLATE_GAP, ScriptColor, ScriptDocument, ScriptLine, ScriptTake, Sense, + Stroke, TAKE_HEADER_H, TAKE_NUMBER_H, Tick, Tokens, candle_row_bounds, coverage_rows, first_visible, json, pos2, recovery, row_layout, script_color, + select_line, selected_range, selected_take_lines, shift_click, thumbnail_height, thumbnail_width, toggle_offscreen, vec2, }; +struct TakeBox { + full_label: String, + text: Arc, + width: f32, + column_width: f32, +} + +impl TakeBox { + fn measure(app: &FilmcraftApp, ui: &egui::Ui, take: &ScriptTake, ordinal: usize, candle_column: f32) -> Self { + let full_label = take + .source + .and_then(|id| super::practice::source_session(app, id).project.item(id)) + .and_then(|item| item.metadata.get("Take")) + .map(|value| value.trim()) + .filter(|value| !value.is_empty()) + .map_or_else(|| (ordinal + 1).to_string(), str::to_owned); + let visible = full_label.chars().take(2).collect(); + let text = ui.painter().layout_job(egui::text::LayoutJob::simple_singleline(visible, Tokens::ui(9.5), app.tokens.text)); + let width = (text.size().x.ceil() + 5.0).max(16.0_f32.min(candle_column - 2.0)); + Self { full_label, text, width, column_width: candle_column.max(width + 2.0) } + } +} + struct SlateHeader<'a> { + take_boxes: Vec, id: u64, + slate: &'a filmcraft_project::ScriptSlate, + outline: Color32, + pin_offset: f32, first_column: usize, center_x: f32, start_index: usize, @@ -19,6 +45,27 @@ struct SlateHeader<'a> { display_take: &'a ScriptTake, } +fn pin_visible_headers(state: &super::ScriptUi, headers: &mut [SlateHeader<'_>], viewport: Rect, indices: &HashMap, tops: &[f32], width: f32) { + if !state.keep_thumbnails_visible { + return; + } + // Work in scroll-content coordinates. At the end of coverage the header and numbers scroll away with the last candle. + let pinned = viewport.min.y + thumbnail_height(width) + TAKE_HEADER_H; + for header in headers { + let visible_end = header + .slate + .takes + .iter() + .filter_map(|take| coverage_rows(state, take, indices)) + .filter(|&(start, end)| tops[start] < viewport.max.y && tops[end + 1] > viewport.min.y) + .map(|(_, end)| tops[end + 1]) + .reduce(f32::max); + if let Some(bottom) = visible_end { + header.pin_offset = (pinned.min(bottom) - tops[header.start_index]).max(0.0); + } + } +} + enum ProjectDropTarget { Rebind(u64), Thumbnail { slate: u64, start: u64, end: u64 }, @@ -27,14 +74,10 @@ enum ProjectDropTarget { pub(super) fn content(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, doc: &Arc, actions: &mut Vec) { let t = app.tokens; let thumb_w = thumbnail_width(&app.ui.script); - let min_left = 180.0_f32.min((rect.width() - 85.0).max(100.0)); - let max_left = (rect.width() - 85.0).max(min_left); - let default_left = (rect.width() * if rect.width() < 520.0 { 0.63 } else { 0.49 }).clamp(min_left, 490.0_f32.max(min_left)).min(max_left); - let left_w = app.ui.script.text_column_width.unwrap_or(default_left).clamp(min_left, max_left); - let min_inset = 54.0_f32.min((left_w - 48.0).max(42.0)); - let max_inset = (left_w - 48.0).max(min_inset); - let text_inset = app.ui.script.text_inset.unwrap_or(DEFAULT_TEXT_INSET).clamp(min_inset, max_inset); + let margins = super::layout::Margins::new(app, ui, rect.width()); + let (text_inset, left_w) = (margins.left, margins.right); row_layout(app, ui, doc, left_w, text_inset); + let column_width = app.ui.script.take_column_width(); let line_indices: HashMap = doc.lines.iter().enumerate().map(|(index, line)| (line.id.0, index)).collect(); // A coverage trim keeps annotations in the model, but a previously selected or // dragged mark must stop being interactive as soon as its row is hidden. @@ -58,33 +101,36 @@ pub(super) fn content(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, doc .slates .iter() .flat_map(|slate| { - if slate.takes.is_empty() { - vec![(slate.id.0, None, slate.name.as_str())] - } else { - slate.takes.iter().map(|take| (slate.id.0, Some(take), slate.name.as_str())).collect() - } + let outline = outline_color(app, slate.outline_color); + if slate.takes.is_empty() { vec![(slate.id.0, None, outline)] } else { slate.takes.iter().map(|take| (slate.id.0, Some(take), outline)).collect() } }) .collect(); - // Keep setup placement independent of the two text margin markers. The - // default happens to start near the initial wrap edge, but moving that edge - // must only reflow text, never slide thumbnails or candles horizontally. - // Reserve a small page-number gutter between the initial text margin and - // the first setup. Both stay anchored if the user later moves a margin. - let take_origin = default_left + 70.0; + // Setups have their own starting position so moving a ruler only reflows the text. + let take_origin = margins.setup_origin; let mut first_column = 0; let mut next_group_x = 0.0; + let mut take_left = 0.0_f32; let mut take_right = 0.0_f32; let mut column_centers = Vec::with_capacity(columns.len()); let mut slate_headers = Vec::new(); for slate in &doc.slates { let count = slate.takes.len().max(1); - let group_width = (count as f32 * TAKE_W).max(thumb_w + 8.0); + let take_boxes: Vec<_> = slate.takes.iter().enumerate().map(|(ordinal, take)| TakeBox::measure(app, ui, take, ordinal, column_width)).collect(); + let candles_width = take_boxes.iter().map(|b| b.column_width).sum::().max(column_width); + let group_width = candles_width.max(thumb_w + 8.0); let preview_x = if app.ui.script.drag_slate == Some(slate.id.0) { app.ui.script.drag_slate_delta.x } else { 0.0 }; - let center_x = slate.thumbnail_x.map_or(take_origin + next_group_x + group_width * 0.5, |x| x * canvas.width()) + preview_x; + let default_center = super::practice::example_lane(app, slate.id.0) + .map_or(take_origin + next_group_x + group_width * 0.5, |lane| left_w + thumb_w * 0.5 + lane as f32 * (thumb_w + SLATE_GAP)); + let center_x = slate.thumbnail_x.map_or(default_center, |x| x * canvas.width()) + preview_x; take_right = take_right.max(center_x + group_width * 0.5 + SLATE_GAP); - let candle_left = center_x - count as f32 * TAKE_W * 0.5; - for column in 0..count { - column_centers.push(candle_left + (column as f32 + 0.5) * TAKE_W); + let mut candle_left = center_x - candles_width * 0.5; + take_left = take_left.min(center_x - candles_width.max(thumb_w) * 0.5); + if take_boxes.is_empty() { + column_centers.push(center_x); + } + for take_box in &take_boxes { + column_centers.push(candle_left + take_box.column_width * 0.5); + candle_left += take_box.column_width; } if let (Some(last_take), Some(first_candle_index)) = ( slate.takes.last(), @@ -104,7 +150,11 @@ pub(super) fn content(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, doc let start_index = slate.thumbnail_line.and_then(|line| line_indices.get(&line.0).copied()).unwrap_or(first_candle_index); let display_take = slate.takes.iter().find(|take| app.ui.script.selected_take == Some(take.id.0)).or_else(|| slate.takes.first()); slate_headers.push(SlateHeader { + take_boxes, id: slate.id.0, + slate, + outline: outline_color(app, slate.outline_color), + pin_offset: 0.0, first_column, center_x, start_index, @@ -118,17 +168,17 @@ pub(super) fn content(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, doc first_column += count; next_group_x += group_width + SLATE_GAP; } - let take_total = take_right.max(canvas.width()); - let max_scroll = (take_total - canvas.width()).max(0.0); - app.ui.script.take_scroll = if app.ui.script.take_scroll.is_finite() { app.ui.script.take_scroll.clamp(0.0, max_scroll) } else { 0.0 }; + let max_scroll = (take_right - canvas.width()).max(0.0); + let scroll_span = max_scroll - take_left; + app.ui.script.take_scroll = if app.ui.script.take_scroll.is_finite() { app.ui.script.take_scroll.clamp(take_left, max_scroll) } else { 0.0 }; let canvas = Rect::from_min_max(pos2(rect.min.x, rect.min.y + 16.0), rect.max); - let body = if max_scroll > 0.0 { Rect::from_min_max(canvas.min, pos2(canvas.max.x, canvas.max.y - 18.0)) } else { canvas }; + let body = if scroll_span > 0.0 { Rect::from_min_max(canvas.min, pos2(canvas.max.x, canvas.max.y - 18.0)) } else { canvas }; let slider_r = Rect::from_min_max(pos2(canvas.min.x, body.max.y + 2.0), pos2(canvas.max.x, canvas.max.y - 2.0)); - if slider_r.width() > 48.0 && max_scroll > 0.0 { - take_scrollbar(app, ui, slider_r, canvas.width(), take_total, max_scroll); + if slider_r.width() > 48.0 && scroll_span > 0.0 { + take_scrollbar(app, ui, slider_r, canvas.width(), take_left, scroll_span); } - margin_ruler(app, ui, Rect::from_min_max(rect.min, pos2(rect.max.x, canvas.min.y)), left_w, text_inset, min_left, max_left, min_inset, max_inset); - if body.height() < MIN_ROW_H { + margin_ruler(app, ui, Rect::from_min_max(rect.min, pos2(rect.max.x, canvas.min.y)), &margins); + if body.height() < 20.0 { return; } let (pointer, alt_pressed, primary_down, released) = ui.input(|input| { @@ -158,191 +208,202 @@ pub(super) fn content(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, doc let mut scroll_origin = body.min.y; let range = selected_range(doc, app.ui.script.selected_lines); let tops = app.ui.script.row_tops.clone(); - egui::ScrollArea::vertical().id_salt("script.rows").auto_shrink([false, false]).show_viewport(&mut scroll_ui, |ui, viewport| { - let total = tops.last().copied().unwrap_or_default(); - ui.set_height(total); - let base_y = ui.max_rect().top(); - scroll_origin = base_y; - let start = first_visible(&tops, viewport.min.y).min(doc.lines.len()); - let end = first_visible(&tops, viewport.max.y).saturating_add(2).min(doc.lines.len()); - // A Project drag belongs to its source widget, so ordinary widget hover is - // suppressed. Hit-test the whole canvas, including the open take columns. - let project_drop_row = pointer - .filter(|_| project_drag && ui.rect_contains_pointer(body) && !doc.lines.is_empty()) - .map(|pointer| first_visible(&tops, (pointer.y - base_y).max(0.0)).min(doc.lines.len() - 1)); - let object_drop = pointer.filter(|_| project_drop_row.is_some()).and_then(|pointer| { - project_object_drop_target(app, pointer, body, base_y, &slate_headers, &columns, &column_centers, &line_indices, &tops, thumb_w) - }); - if let Some((object, target)) = &object_drop { - ui.painter().rect_stroke(target.intersect(body), 3.0, Stroke::new(2.0, t.accent), egui::StrokeKind::Inside); - match object { - ProjectDropTarget::Rebind(_) => app.auto.add("script.rebindPreview", target.intersect(body), "Reconnect matching candles"), - ProjectDropTarget::Thumbnail { .. } => app.auto.add("script.addCandlePreview", target.intersect(body), "Add candle to this setup"), - } - ui.ctx().set_cursor_icon(egui::CursorIcon::Copy); - if released && let Some(source) = crate::panels::dragged_project_item(ui) { + egui::ScrollArea::vertical() + .id_salt(("script.rows", Arc::as_ptr(&app.session.project_instance) as usize, app.ui.script.item)) + .auto_shrink([false, false]) + .show_viewport(&mut scroll_ui, |ui, viewport| { + let total = tops.last().copied().unwrap_or_default(); + ui.set_height(total); + let base_y = ui.max_rect().top(); + scroll_origin = base_y; + pin_visible_headers(&app.ui.script, &mut slate_headers, viewport, &line_indices, &tops, thumb_w); + let start = first_visible(&tops, viewport.min.y).min(doc.lines.len()); + let end = first_visible(&tops, viewport.max.y).saturating_add(2).min(doc.lines.len()); + // A Project drag belongs to its source widget, so ordinary widget hover is + // suppressed. Hit-test the whole canvas, including the open take columns. + let project_drop_row = pointer + .filter(|_| project_drag && ui.rect_contains_pointer(body) && !doc.lines.is_empty()) + .map(|pointer| first_visible(&tops, (pointer.y - base_y).max(0.0)).min(doc.lines.len() - 1)); + let object_drop = pointer.filter(|_| project_drop_row.is_some()).and_then(|pointer| { + project_object_drop_target(app, pointer, body, base_y, &slate_headers, &columns, &column_centers, &line_indices, &tops, thumb_w) + }); + if let Some((object, target)) = &object_drop { + ui.painter().rect_stroke(target.intersect(body), 3.0, Stroke::new(2.0, t.accent), egui::StrokeKind::Inside); match object { - ProjectDropTarget::Rebind(take) => actions.push(Action::Rebind { take: *take, source: source.0 }), - ProjectDropTarget::Thumbnail { slate, start, end } => { - let (start, end) = range.and_then(|(a, b)| doc.lines.get(a).zip(doc.lines.get(b))).map_or((*start, *end), |(a, b)| (a.id.0, b.id.0)); - actions.push(Action::Command( - "script.addTake", - json!({"item": app.ui.script.item, "slate": slate, "source": source.0, "startLine": start, "endLine": end}), - )); - } + ProjectDropTarget::Rebind(_) => app.auto.add("script.rebindPreview", target.intersect(body), "Reconnect matching candles"), + ProjectDropTarget::Thumbnail { .. } => app.auto.add("script.addCandlePreview", target.intersect(body), "Add candle to this setup"), } - crate::panels::clear_drag(ui); - } - } - let project_drop_range = project_drop_row.filter(|_| object_drop.is_none()).map(|index| range.unwrap_or((index, index))); - if let Some((a, b)) = project_drop_range - && let Some((&y0, &y1)) = tops.get(a).zip(tops.get(b + 1)) - { - let preview = Rect::from_min_max(pos2(body.left(), base_y + y0), pos2(body.right(), base_y + y1)).intersect(body); - if preview.is_positive() { - ui.painter().rect_filled(preview, 0.0, t.accent.gamma_multiply(0.18)); - ui.painter().rect_stroke(preview, 0.0, Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); - app.auto.add("script.dropPreview", preview, "Drop clip on these script lines"); - } - ui.ctx().set_cursor_icon(egui::CursorIcon::Copy); - if released && let Some(source) = crate::panels::dragged_project_item(ui) { - let x = pointer.map_or(0.0, |pointer| { - ((pointer.x - body.left() + app.ui.script.take_scroll) / body.width().max(1.0)).clamp(0.0, ScriptDocument::MAX_THUMBNAIL_X) - }); - canvas_drop = Some((source, a, b, x)); - // Selected rows anchor the new setup even when the pointer is over - // another row or a candle. Thumbnails own explicit setup drops. - if range.is_some() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Copy); + if released && let Some(source) = crate::panels::dragged_project_item(ui) { + match object { + ProjectDropTarget::Rebind(take) => actions.push(Action::Rebind { take: *take, source: source.0 }), + ProjectDropTarget::Thumbnail { slate, start, end } => { + let (start, end) = + range.and_then(|(a, b)| doc.lines.get(a).zip(doc.lines.get(b))).map_or((*start, *end), |(a, b)| (a.id.0, b.id.0)); + actions.push(Action::Command( + "script.addTake", + json!({"item": app.ui.script.item, "slate": slate, "source": source.0, "startLine": start, "endLine": end}), + )); + } + } crate::panels::clear_drag(ui); } } - } - let drag_hover_row = - app.ui.script.drag_mark.and_then(|_| ui.input(|input| input.pointer.hover_pos())).filter(|pointer| body.contains(*pointer)).and_then(|pointer| { - let row = first_visible(&tops, (pointer.y - base_y).max(0.0)).min(doc.lines.len().saturating_sub(1)); - let (take_id, _) = app.ui.script.drag_mark?; - let take = doc.slates.iter().flat_map(|slate| &slate.takes).find(|take| take.id.0 == take_id)?; - let (&start, &end) = line_indices.get(&take.start_line.0).zip(line_indices.get(&take.end_line.0))?; - Some(row.clamp(start, end)) - }); - if app.ui.script.drag_mark.is_some() { - if let Some(target) = drag_hover_row { - app.ui.script.drag_mark_target = Some(target); + let project_drop_range = project_drop_row.filter(|_| object_drop.is_none()).map(|index| range.unwrap_or((index, index))); + if let Some((a, b)) = project_drop_range + && let Some((&y0, &y1)) = tops.get(a).zip(tops.get(b + 1)) + { + let preview = Rect::from_min_max(pos2(body.left(), base_y + y0), pos2(body.right(), base_y + y1)).intersect(body); + if preview.is_positive() { + ui.painter().rect_filled(preview, 0.0, t.accent.gamma_multiply(0.18)); + ui.painter().rect_stroke(preview, 0.0, Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); + app.auto.add("script.dropPreview", preview, "Drop clip on these script lines"); + } + ui.ctx().set_cursor_icon(egui::CursorIcon::Copy); + if released && let Some(source) = crate::panels::dragged_project_item(ui) { + let x = pointer.map_or(0.0, |pointer| { + ((pointer.x - body.left() + app.ui.script.take_scroll) / body.width().max(1.0)).clamp(0.0, ScriptDocument::MAX_THUMBNAIL_X) + }); + canvas_drop = Some((source, a, b, x)); + // Selected rows anchor the new setup even when the pointer is over + // another row or a candle. Thumbnails own explicit setup drops. + if range.is_some() { + crate::panels::clear_drag(ui); + } + } } - ui.ctx().request_repaint(); - } - for index in start..end { - let (Some(&y0), Some(&y1)) = (tops.get(index), tops.get(index + 1)) else { continue }; - let row = Rect::from_min_max(pos2(body.left(), base_y + y0), pos2(body.right(), base_y + y1)); - if app.ui.script.show_row_colors.unwrap_or(true) && index % 2 == 1 { - let stripe = if t.field_bg.r() < 128 { Color32::from_white_alpha(4) } else { Color32::from_black_alpha(6) }; - ui.painter().rect_filled(row.intersect(body), 0.0, stripe); - } - if range.is_some_and(|(a, b)| (a..=b).contains(&index)) { - ui.painter().rect_filled(row.intersect(body), 0.0, t.hover.gamma_multiply(0.7)); - } - if drag_hover_row == Some(index) { - ui.painter().rect_filled(row.intersect(body), 0.0, t.hover.gamma_multiply(0.9)); - } - } - paint_take_connectors( - app, - ui, - doc, - &slate_headers, - ConnectorLayout { column_centers: &column_centers, line_indices: &line_indices, tops: &tops, base_y, body }, - ); - for index in start..end { - let (Some(line), Some(&y0), Some(&y1)) = (doc.lines.get(index), tops.get(index), tops.get(index + 1)) else { continue }; - let row = Rect::from_min_size(pos2(ui.max_rect().left(), base_y + y0), vec2(body.width().max(1.0), y1 - y0)); - if row.intersects(body) { - row_view( - app, - ui, - row, - left_w, - text_inset, - index, - line, - &columns, - &column_centers, - &line_indices, - &tops, - &mut clicked_mark, - &mut clicked_candle, - &mut foreground_click, - &mut take_click, - actions, + let drag_hover_row = + app.ui.script.drag_mark.and_then(|_| ui.input(|input| input.pointer.hover_pos())).filter(|pointer| body.contains(*pointer)).and_then( + |pointer| { + let row = first_visible(&tops, (pointer.y - base_y).max(0.0)).min(doc.lines.len().saturating_sub(1)); + let (take_id, _) = app.ui.script.drag_mark?; + let take = doc.slates.iter().flat_map(|slate| &slate.takes).find(|take| take.id.0 == take_id)?; + let (&start, &end) = line_indices.get(&take.start_line.0).zip(line_indices.get(&take.end_line.0))?; + Some(row.clamp(start, end)) + }, ); + if app.ui.script.drag_mark.is_some() { + if let Some(target) = drag_hover_row { + app.ui.script.drag_mark_target = Some(target); + } + ui.ctx().request_repaint(); } - } - // Avid's off-screen notation sits on top of the take line. Keep the - // straight candle and its script marks beneath this narrow overlay. - paint_offscreen_paths(app, ui, doc, &columns, &column_centers, &line_indices, &tops, base_y, body, start, end); - for header in &slate_headers { - let Some(&row_y) = tops.get(header.start_index) else { continue }; - let thumbnail = thumbnail_rect(body.min.x, base_y + row_y, header, app.ui.script.take_scroll, thumb_w); - if thumbnail.intersects(body) { - thumbnail_interaction(app, ui, header, thumbnail, body, &tops, base_y, doc, &mut foreground_click, &mut take_click, actions); + for index in start..end { + let (Some(&y0), Some(&y1)) = (tops.get(index), tops.get(index + 1)) else { continue }; + let row = Rect::from_min_max(pos2(body.left(), base_y + y0), pos2(body.right(), base_y + y1)); + if app.ui.script.show_row_colors.unwrap_or(true) && index % 2 == 1 { + let stripe = if t.field_bg.r() < 128 { Color32::from_white_alpha(4) } else { Color32::from_black_alpha(6) }; + ui.painter().rect_filled(row.intersect(body), 0.0, stripe); + } + if range.is_some_and(|(a, b)| (a..=b).contains(&index)) { + ui.painter().rect_filled(row.intersect(body), 0.0, t.hover.gamma_multiply(0.7)); + } + if drag_hover_row == Some(index) { + ui.painter().rect_filled(row.intersect(body), 0.0, t.hover.gamma_multiply(0.9)); + } } - } - for index in start..end { - let (Some(&y0), Some(&y1)) = (tops.get(index), tops.get(index + 1)) else { continue }; - let row = Rect::from_min_size(pos2(ui.max_rect().left(), base_y + y0), vec2(body.width().max(1.0), y1 - y0)); - if !row.intersects(body) { - continue; + paint_take_connectors( + app, + ui, + &slate_headers, + ConnectorLayout { column_centers: &column_centers, line_indices: &line_indices, tops: &tops, base_y, body }, + ); + for index in start..end { + let (Some(line), Some(&y0), Some(&y1)) = (doc.lines.get(index), tops.get(index), tops.get(index + 1)) else { continue }; + let row = Rect::from_min_size(pos2(ui.max_rect().left(), base_y + y0), vec2(body.width().max(1.0), y1 - y0)); + if row.intersects(body) { + row_view( + app, + ui, + row, + &margins, + index, + range.is_some_and(|(a, b)| (a..=b).contains(&index)), + line, + &columns, + &column_centers, + &line_indices, + &tops, + &mut clicked_mark, + &mut clicked_candle, + &mut foreground_click, + &mut take_click, + actions, + ); + } } - for (column, (slate, maybe_take, _)) in columns.iter().enumerate() { - let Some(take) = maybe_take else { continue }; - if app.ui.script.drag_slate == Some(*slate) && app.ui.script.drag_slate_group { + // Avid's off-screen notation sits on top of the take line. Keep the + // straight candle and its script marks beneath this narrow overlay. + paint_offscreen_paths(app, ui, doc, &columns, &column_centers, &line_indices, &tops, base_y, body, start, end); + // At their saved positions, candle endpoints retain drag priority over overlapping thumbnails. + for header in slate_headers.iter().filter(|header| header.pin_offset == 0.0) { + let thumbnail = thumbnail_rect(body.left(), base_y + tops[header.start_index], header, app.ui.script.take_scroll, thumb_w); + if thumbnail.intersects(body) { + thumbnail_interaction(app, ui, header, thumbnail, body, &tops, base_y, doc, &mut foreground_click, &mut take_click, actions); + } + } + for index in start..end { + let (Some(&y0), Some(&y1)) = (tops.get(index), tops.get(index + 1)) else { continue }; + let row = Rect::from_min_size(pos2(ui.max_rect().left(), base_y + y0), vec2(body.width().max(1.0), y1 - y0)); + if !row.intersects(body) { continue; } - let (Some(&take_start), Some(&take_end)) = (line_indices.get(&take.start_line.0), line_indices.get(&take.end_line.0)) else { continue }; - if index != take_start && index != take_end { - continue; + for (column, (slate, maybe_take, _)) in columns.iter().enumerate() { + let Some(take) = maybe_take else { continue }; + if app.ui.script.drag_slate == Some(*slate) && app.ui.script.drag_slate_group { + continue; + } + let (Some(&take_start), Some(&take_end)) = (line_indices.get(&take.start_line.0), line_indices.get(&take.end_line.0)) else { continue }; + if app.ui.script.screening.is_some_and(|pass| pass.records(take.id.0)) || (index != take_start && index != take_end) { + continue; + } + let cx = body.min.x + column_centers[column] - app.ui.script.take_scroll; + if cx + column_width * 0.5 < body.min.x || cx - column_width * 0.5 > body.max.x { + continue; + } + endpoint_interaction( + app, + ui, + take, + row, + body, + cx, + index, + take_start, + take_end, + &tops, + base_y, + doc, + &mut foreground_click, + &mut take_click, + actions, + ); } - let cx = body.min.x + column_centers[column] - app.ui.script.take_scroll; - if cx + TAKE_W * 0.5 < body.min.x || cx - TAKE_W * 0.5 > body.max.x { - continue; + } + // A pinned header owns hits on the rows it temporarily covers. + for header in &slate_headers { + let thumbnail = thumbnail_rect(body.left(), base_y + tops[header.start_index], header, app.ui.script.take_scroll, thumb_w); + if header.pin_offset > 0.0 && thumbnail.intersects(body) { + thumbnail_interaction(app, ui, header, thumbnail, body, &tops, base_y, doc, &mut foreground_click, &mut take_click, actions); } - endpoint_interaction( - app, - ui, - take, - row, - body, - cx, - index, - take_start, - take_end, - &tops, - base_y, - doc, - &mut foreground_click, - &mut take_click, - actions, - ); + if thumbnail.intersects(body) { + thumbnail_paint(app, ui, header, thumbnail, body); + } + let number_activated = take_numbers(app, ui, header, &column_centers, thumbnail, body, actions); + foreground_click |= number_activated; + take_click |= number_activated; } - } - // Paint last so a setup may sit over the script text, like a floating slate. - for header in &slate_headers { - let Some(&row_y) = tops.get(header.start_index) else { continue }; - let thumbnail = thumbnail_rect(body.min.x, base_y + row_y, header, app.ui.script.take_scroll, thumb_w); - if thumbnail.intersects(body) { - thumbnail_paint(app, ui, header, thumbnail, body); - take_metadata_paint(app, ui, doc, header, &column_centers, thumbnail, body); + if let Some(target) = app.ui.script.scroll_to_line + && let Some(index) = doc.lines.iter().position(|line| line.id.0 == target) + && let (Some(&y0), Some(&y1)) = (tops.get(index), tops.get(index + 1)) + { + let target_rect = Rect::from_min_max(pos2(ui.max_rect().left(), base_y + y0), pos2(ui.max_rect().right(), base_y + y1)); + ui.scroll_to_rect(target_rect, Some(egui::Align::Center)); + app.ui.script.scroll_to_line = None; } - } - if let Some(target) = app.ui.script.scroll_to_line - && let Some(index) = doc.lines.iter().position(|line| line.id.0 == target) - && let (Some(&y0), Some(&y1)) = (tops.get(index), tops.get(index + 1)) - { - let target_rect = Rect::from_min_max(pos2(ui.max_rect().left(), base_y + y0), pos2(ui.max_rect().right(), base_y + y1)); - ui.scroll_to_rect(target_rect, Some(egui::Align::Center)); - app.ui.script.scroll_to_line = None; - } - }); + }); if let (Some(start), Some(end)) = (app.ui.script.lasso_start, app.ui.script.lasso_end) { + ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); let lasso = Rect::from_two_pos(start, end).intersect(body); ui.painter().rect_filled(lasso, 0.0, t.accent.gamma_multiply(0.14)); ui.painter().rect_stroke(lasso, 0.0, Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); @@ -367,8 +428,8 @@ pub(super) fn content(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, doc let Some((&a, &b)) = line_indices.get(&take.start_line.0).zip(line_indices.get(&take.end_line.0)) else { return false }; let cx = body.left() + column_centers[header.first_column + local] - app.ui.script.take_scroll; let candle = Rect::from_min_max( - pos2(cx - TAKE_W * 0.5, scroll_origin + tops[a]), - pos2(cx + TAKE_W * 0.5, scroll_origin + tops[b + 1]), + pos2(cx - column_width * 0.5, scroll_origin + tops[a]), + pos2(cx + column_width * 0.5, scroll_origin + tops[b + 1]), ); candle.intersects(lasso) }) @@ -381,6 +442,9 @@ pub(super) fn content(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, doc app.ui.script.lasso_end = None; } } + if released { + app.ui.script.drag_take_number = None; + } if empty_canvas.clicked() && !foreground_click { app.ui.script.selected_lines = None; } @@ -428,7 +492,7 @@ fn project_object_drop_target( body: Rect, base_y: f32, headers: &[SlateHeader<'_>], - columns: &[(u64, Option<&ScriptTake>, &str)], + columns: &[(u64, Option<&ScriptTake>, Color32)], centers: &[f32], indices: &HashMap, tops: &[f32], @@ -446,13 +510,14 @@ fn project_object_drop_target( return Some((target, rect)); } } + let column_width = app.ui.script.take_column_width(); for (column, (_, take, _)) in columns.iter().enumerate().rev() { let Some(take) = take else { continue }; let Some((start, end)) = coverage_rows(&app.ui.script, take, indices) else { continue }; let Some((&top, &bottom)) = tops.get(start).zip(tops.get(end.saturating_add(1))) else { continue }; let Some(¢er) = centers.get(column) else { continue }; let x = body.left() + center - app.ui.script.take_scroll; - let rect = Rect::from_min_max(pos2(x - TAKE_W * 0.5, base_y + top), pos2(x + TAKE_W * 0.5, base_y + bottom)); + let rect = Rect::from_min_max(pos2(x - column_width * 0.5, base_y + top), pos2(x + column_width * 0.5, base_y + bottom)); if rect.contains(pointer) { return recovery::needs_rebind(app, take).then_some((ProjectDropTarget::Rebind(take.id.0), rect)); } @@ -460,7 +525,8 @@ fn project_object_drop_target( None } -fn take_scrollbar(app: &mut FilmcraftApp, ui: &mut egui::Ui, bar: Rect, visible: f32, total: f32, max_scroll: f32) { +fn take_scrollbar(app: &mut FilmcraftApp, ui: &mut egui::Ui, bar: Rect, visible: f32, left: f32, scroll_span: f32) { + let total = visible + scroll_span; // Match the Timeline's rounded track and thumb, with standard egui scrolling // and no zoom handles. Only take columns move; script text stays fixed. let mut scroll_ui = ui.new_child(egui::UiBuilder::new().max_rect(bar)); @@ -485,32 +551,21 @@ fn take_scrollbar(app: &mut FilmcraftApp, ui: &mut egui::Ui, bar: Rect, visible: .max_height(bar.height()) .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible) .scroll_source(egui::scroll_area::ScrollSource::SCROLL_BAR) - .horizontal_scroll_offset(app.ui.script.take_scroll) + .horizontal_scroll_offset(app.ui.script.take_scroll - left) .animated(false) .show(&mut scroll_ui, |ui| { ui.allocate_space(vec2(total, 1.0)); }); - app.ui.script.take_scroll = output.state.clamped_offset().x.clamp(0.0, max_scroll); + let offset = output.state.clamped_offset().x.clamp(0.0, scroll_span); + app.ui.script.take_scroll = left + offset; let track = Rect::from_min_max(pos2(bar.left(), output.inner_rect.bottom() + style.bar_inner_margin), bar.max); let width = (track.width() * visible / total.max(1.0)).max(style.handle_min_length).min(track.width()); - let thumb = - Rect::from_min_size(pos2(track.left() + (track.width() - width) * app.ui.script.take_scroll / max_scroll, track.top()), vec2(width, track.height())); + let thumb = Rect::from_min_size(pos2(track.left() + (track.width() - width) * offset / scroll_span, track.top()), vec2(width, track.height())); app.auto.add("script.takeScroll", track, "Scroll take columns"); app.auto.add("script.takeScroll.thumb", thumb, "Visible take columns"); } -#[allow(clippy::too_many_arguments)] -fn margin_ruler( - app: &mut FilmcraftApp, - ui: &mut egui::Ui, - rect: Rect, - left_w: f32, - text_inset: f32, - min_left: f32, - max_left: f32, - min_inset: f32, - max_inset: f32, -) { +fn margin_ruler(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, margins: &super::layout::Margins) { let t = app.tokens; let paint = ui.painter(); paint.line_segment([pos2(rect.left(), rect.bottom() - 1.0), pos2(rect.right(), rect.bottom() - 1.0)], Stroke::new(1.0, t.separator.gamma_multiply(0.55))); @@ -523,8 +578,8 @@ fn margin_ruler( paint.line_segment([pos2(x, rect.bottom() - 2.0), pos2(x, rect.bottom() - length - 2.0)], Stroke::new(1.0, t.text_dim.gamma_multiply(0.45))); } for (id, x, description, left_marker) in [ - ("script.margin.left", rect.left() + text_inset, tl!("Drag to change the script's left margin"), true), - ("script.margin.right", rect.left() + left_w, tl!("Drag to change script wrapping"), false), + ("script.margin.left", rect.left() + margins.left, tl!("Drag to change the script's left margin"), true), + ("script.margin.right", rect.left() + margins.right, tl!("Drag to change script wrapping"), false), ] { let marker = Rect::from_center_size(pos2(x, rect.center().y), vec2(16.0, rect.height())); let response = ui.interact(marker, egui::Id::unique(id), Sense::drag()).on_hover_cursor(egui::CursorIcon::ResizeHorizontal).on_hover_text(description); @@ -536,19 +591,29 @@ fn margin_ruler( )); if response.dragged() { if left_marker { - app.ui.script.text_inset = Some((text_inset + response.drag_delta().x).clamp(min_inset, max_inset)); + app.ui.script.text_inset = Some(margins.left_range.clamp(margins.left + response.drag_delta().x)); } else { - app.ui.script.text_column_width = Some((left_w + response.drag_delta().x).clamp(min_left, max_left)); + app.ui.script.text_column_width = Some(margins.right_range.clamp(margins.right + response.drag_delta().x)); } ui.ctx().request_repaint(); } } } +fn outline_color(app: &FilmcraftApp, color: ScriptColor) -> Color32 { + if color == ScriptColor::Default { + return app.tokens.text_dim; + } + let swatch = craft_theme::Rgba(script_color(app, color).to_array()); + let background = craft_theme::Rgba(app.tokens.panel_bg.to_array()); + let [r, g, b, _] = craft_theme::ensure_contrast(swatch, background, 3.0).0; + Color32::from_rgb(r, g, b) +} + fn thumbnail_rect(right_x: f32, row_y: f32, header: &SlateHeader<'_>, scroll: f32, width: f32) -> Rect { let group_center = right_x + header.center_x - scroll; let height = thumbnail_height(width); - Rect::from_min_size(pos2(group_center - width * 0.5, row_y - TAKE_HEADER_H - height), vec2(width, height)) + Rect::from_min_size(pos2(group_center - width * 0.5, row_y + header.pin_offset - TAKE_HEADER_H - height), vec2(width, height)) } /// Paint one narrow overlay for each contiguous off-screen passage. Restarting on every @@ -558,7 +623,7 @@ fn paint_offscreen_paths( app: &FilmcraftApp, ui: &egui::Ui, doc: &ScriptDocument, - columns: &[(u64, Option<&ScriptTake>, &str)], + columns: &[(u64, Option<&ScriptTake>, Color32)], column_centers: &[f32], line_indices: &HashMap, tops: &[f32], @@ -568,17 +633,26 @@ fn paint_offscreen_paths( visible_end: usize, ) { let paint = ui.painter().with_clip_rect(clip); + let column_width = app.ui.script.take_column_width(); + let candle_width = app.ui.script.candle_stroke_width(); + let zigzag = candle_width * 0.5 + 2.5; + let core_width = egui::remap_clamp(candle_width, super::MIN_CANDLE_W..=super::DEFAULT_CANDLE_W, 1.0..=1.25); + let core = Stroke::new(core_width, Color32::BLACK); + let outline = Stroke::new(core_width * 2.0, Color32::LIGHT_GRAY); for (column, (slate, maybe_take, _)) in columns.iter().enumerate() { let Some(take) = maybe_take else { continue }; let Some((start, end)) = coverage_rows(&app.ui.script, take, line_indices) else { continue }; let cx = clip.left() + column_centers[column] - app.ui.script.take_scroll; - if cx + TAKE_W * 0.5 < clip.left() || cx - TAKE_W * 0.5 > clip.right() { + if cx + column_width * 0.5 < clip.left() || cx - column_width * 0.5 > clip.right() { continue; } let mut overlay = Vec::new(); let flush = |overlay: &mut Vec| { if overlay.len() > 1 { - paint.add(egui::Shape::line(std::mem::take(overlay), Stroke::new(2.25, app.tokens.text_dim.gamma_multiply(0.9)))); + // Two strokes on the same path keep a thin, continuous edge through each bend. + let path = std::mem::take(overlay); + paint.add(egui::Shape::line(path.clone(), outline)); + paint.add(egui::Shape::line(path, core)); } }; let preview_y = if app.ui.script.drag_slate == Some(*slate) && app.ui.script.drag_slate_group { app.ui.script.drag_slate_delta.y } else { 0.0 }; @@ -591,7 +665,7 @@ fn paint_offscreen_paths( let row = Rect::from_min_max(pos2(cx, base_y + tops[index] + preview_y), pos2(cx, base_y + tops[index + 1] + preview_y)); let (y0, y1) = candle_row_bounds(row); let delta = (y1 - y0).max(0.0); - let points = [pos2(cx, y0), pos2(cx - 5.0, y0 + delta / 3.0), pos2(cx + 5.0, y0 + delta * 2.0 / 3.0), pos2(cx, y1)]; + let points = [pos2(cx, y0), pos2(cx - zigzag, y0 + delta / 3.0), pos2(cx + zigzag, y0 + delta * 2.0 / 3.0), pos2(cx, y1)]; overlay.extend(points.iter().copied().skip(usize::from(!overlay.is_empty()))); } flush(&mut overlay); @@ -603,11 +677,11 @@ fn row_view( app: &mut FilmcraftApp, ui: &mut egui::Ui, row: Rect, - left_w: f32, - text_inset: f32, + margins: &super::layout::Margins, index: usize, + selected: bool, line: &ScriptLine, - columns: &[(u64, Option<&ScriptTake>, &str)], + columns: &[(u64, Option<&ScriptTake>, Color32)], column_centers: &[f32], line_indices: &HashMap, tops: &[f32], @@ -618,10 +692,15 @@ fn row_view( actions: &mut Vec, ) { let t = app.tokens; + let (text_inset, left_w) = (margins.left, margins.right); let left = Rect::from_min_size(row.min, vec2(left_w, row.height())); let right = row; let interaction = ui.interact(row, egui::Id::unique(("script.line", line.id.0)), Sense::click()); - app.auto.add(&format!("script.line.{}", line.id.0), interaction.rect, &line.text); + interaction.widget_info(|| { + let name = if line.text.trim().is_empty() { tlf!("Blank line {number}", number = index + 1) } else { line.text.clone() }; + egui::WidgetInfo::selected(egui::Role::ListBoxOption, true, selected, name) + }); + app.auto.add_response(&format!("script.line.{}", line.id.0), &interaction, &line.text); // Select on press: a slight pointer slip or releasing Shift before the // mouse button must not leave the range at the previous row. let select_pressed = @@ -631,49 +710,65 @@ fn row_view( select_line(&mut app.ui.script, line, shift_click(ui)); } *foreground_click |= select_pressed || interaction.clicked(); - if interaction.double_clicked() { - app.ui.script.edit_line = Some(line.id.0); - app.ui.script.edit_text = line.text.clone(); - } - interaction.clone().context_menu(|ui| { - if ui.button(tl!("Edit Line")).clicked() { + if app.ui.script.edit_mode { + let mut edit = interaction.has_focus() && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::F2)); + interaction.clone().context_menu(|ui| { + if ui.button(tl!("Edit Line")).clicked() { + edit = true; + ui.close(); + } + if ui.button(tl!("Insert Line Below")).clicked() { + actions.push(Action::Command("script.insertLine", json!({"item": app.ui.script.item, "after": line.id.0, "text": ""}))); + ui.close(); + } + if ui.button(tl!("Delete Line")).clicked() { + actions.push(Action::Command("script.deleteLine", json!({"item": app.ui.script.item, "line": line.id.0}))); + ui.close(); + } + }); + if edit && super::finish_script_fields(app) { + select_line(&mut app.ui.script, line, false); app.ui.script.edit_line = Some(line.id.0); app.ui.script.edit_text = line.text.clone(); - ui.close(); + app.ui.script.edit_caret = Some(line.text.chars().count()); } - if ui.button(tl!("Insert Line Below")).clicked() { - actions.push(Action::Command("script.insertLine", json!({"item": app.ui.script.item, "after": line.id.0, "text": ""}))); - ui.close(); + } + let (offset, width) = super::layout::row_column(line.element, text_inset, left_w, app.ui.script.layout_space_width); + let galley = super::layout::row_galley(ui, line, super::layout::script_font(&app.ui.script), t.text, width); + let padding = f32::from(app.ui.script.row_spacing()) * 0.5; + let text_rect = Rect::from_min_size(pos2(left.min.x + offset, left.min.y + padding), vec2(width, left.height() - 2.0 * padding)); + let origin = super::layout::row_alignment(line.element).pos_in_rect(&text_rect); + let text_area = Rect::from_min_max(pos2(left.left() + text_inset, row.top()), left.max); + if app.ui.script.edit_mode + && interaction.hovered() + && ui.input(|input| input.modifiers.is_none()) + && let Some(pointer) = ui.ctx().pointer_hover_pos().filter(|pos| text_area.contains(*pos)) + { + ui.ctx().set_cursor_icon(egui::CursorIcon::Text); + if interaction.clicked_by(egui::PointerButton::Primary) && app.ui.script.edit_line != Some(line.id.0) { + app.ui.script.edit_line = Some(line.id.0); + app.ui.script.edit_text = line.text.clone(); + app.ui.script.edit_caret = Some(galley.cursor_from_pos(pointer - origin).index.into()); } - if ui.button(tl!("Delete Line")).clicked() { - actions.push(Action::Command("script.deleteLine", json!({"item": app.ui.script.item, "line": line.id.0}))); - ui.close(); - } - }); - row_labels(app, ui, line, RowLabelLayout { left, text_inset, index }, foreground_click, actions); - let text_x = left.min.x + text_inset; - if app.ui.script.edit_line == Some(line.id.0) { - let edit_rect = Rect::from_min_max(pos2(text_x, left.min.y + 2.0), pos2(left.max.x, left.max.y - 2.0)); - row_text_editor(app, ui, line, index, edit_rect, actions); + } + if app.ui.script.edit_mode && app.ui.script.edit_line == Some(line.id.0) { + row_text_editor(app, ui, line, index, text_rect, actions); } else { - let text_rect = Rect::from_min_max(pos2(text_x, left.min.y + 2.0), pos2(left.max.x, left.max.y - 2.0)); - let galley = ui.painter().layout( - line.text.clone(), - Tokens::ui(app.ui.script.font_size.unwrap_or(SCRIPT_FONT_SIZE).clamp(10.0, 24.0)), - t.text, - text_rect.width().max(48.0), - ); let clipped = galley.size().y > text_rect.height(); - ui.painter().with_clip_rect(text_rect).galley(text_rect.min, galley, t.text); + ui.painter().with_clip_rect(text_rect).galley(origin, galley, t.text); if clipped { interaction.on_hover_text(&line.text); } } + // Paint the margin editor over any script text it temporarily covers. + row_labels(app, ui, line, RowLabelLayout { left, text_inset, scene_start: margins.scene_start, index }, foreground_click); let clip = Rect::from_min_max(right.min, row.max); - for (column, (slate, maybe_take, _name)) in columns.iter().enumerate() { + let column_width = app.ui.script.take_column_width(); + let fill_width = app.ui.script.candle_stroke_width(); + for (column, (slate, maybe_take, outline)) in columns.iter().enumerate() { let Some(take) = maybe_take else { continue }; let cx = right.min.x + column_centers[column] - app.ui.script.take_scroll; - if cx + TAKE_W * 0.5 < right.min.x || cx - TAKE_W * 0.5 > right.max.x { + if cx + column_width * 0.5 < right.min.x || cx - column_width * 0.5 > right.max.x { continue; } let Some((start, end)) = coverage_rows(&app.ui.script, take, line_indices) else { continue }; @@ -686,10 +781,10 @@ fn row_view( let row_color = take.line_colors.iter().find(|entry| entry.line == line.id).map_or(take.color, |entry| entry.color); let color = script_color(app, row_color); let selected_take = app.ui.script.selected_take == Some(take.id.0); - let stroke = Stroke::new(5.0, color); - // Strokes are centered on the same path: selection adds a thicker gray + let stroke = Stroke::new(fill_width, color); + // Strokes are centered on the same path: selection adds a thicker // outline equally on both sides of the colored candle. - let halo = Stroke::new(if selected_take { 9.0 } else { 7.0 }, t.text_dim); + let halo = Stroke::new(fill_width + if selected_take { 4.0 } else { 2.0 }, *outline); let paint = ui.painter().with_clip_rect(draw_clip); let (candle_top, candle_bottom) = candle_row_bounds(draw_row); paint.line_segment([pos2(cx, candle_top), pos2(cx, candle_bottom)], halo); @@ -704,18 +799,27 @@ fn row_view( CANDLE_CAP_H.min(first_span).min(last_span) }; if index == start { - paint.rect_filled(Rect::from_min_size(pos2(cx - halo.width * 0.5, candle_top), vec2(halo.width, cap_height)), 0.0, t.text_dim); + paint.rect_filled(Rect::from_min_size(pos2(cx - halo.width * 0.5, candle_top), vec2(halo.width, cap_height)), 0.0, *outline); } if index == end { - paint.rect_filled(Rect::from_min_size(pos2(cx - halo.width * 0.5, candle_bottom - cap_height), vec2(halo.width, cap_height)), 0.0, t.text_dim); + paint.rect_filled(Rect::from_min_size(pos2(cx - halo.width * 0.5, candle_bottom - cap_height), vec2(halo.width, cap_height)), 0.0, *outline); } - let candle = Rect::from_min_size(pos2(cx - TAKE_W * 0.5, draw_row.min.y), vec2(TAKE_W, draw_row.height())); + let candle = Rect::from_min_size(pos2(cx - column_width * 0.5, draw_row.min.y), vec2(column_width, draw_row.height())); let response = ui.interact(candle.intersect(draw_clip), egui::Id::unique(("script.candle", take.id.0, line.id.0)), Sense::click()); app.auto.add(&format!("script.take.{}.line.{}", take.id.0, line.id.0), response.rect, "Take coverage"); + preview_focus(app, ui, &response, *slate, take.id.0); + let recording = app.ui.script.screening.is_some_and(|pass| pass.records(take.id.0)); + if recording { + let name = tlf!("Record script mark on row {row}", row = index + 1); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &name)); + response.clone().on_hover_text(name); + } if response.clicked() { + response.request_focus(); *foreground_click = true; *take_click = true; - let extend = shift_click(ui) + let extend = !recording + && shift_click(ui) && app.ui.script.selected_take == Some(take.id.0) && app.ui.script.selected_lines.is_some_and(|(anchor, _)| line_indices.get(&anchor).is_some_and(|at| (start..=end).contains(at))); let anchor = if extend { app.ui.script.selected_lines.map_or(line.id.0, |pair| pair.0) } else { line.id.0 }; @@ -724,8 +828,12 @@ fn row_view( app.ui.script.selected_take = Some(take.id.0); app.ui.script.selected_lines = Some((anchor, line.id.0)); app.ui.script.selected_mark = None; + if recording { + actions.push(Action::AddMarkAtSelection); + } } - if response.double_clicked() && !shift_click(ui) { + if !recording && response.double_clicked() && !shift_click(ui) { + response.surrender_focus(); *clicked_candle = Some((take.id.0, line.id.0)); } response.clone().context_menu(|ui| take_menu(app, ui, take, actions)); @@ -746,18 +854,15 @@ fn row_view( let mark = dragged_here.or_else(|| take.marks.iter().find(|mark| app.ui.script.drag_mark != Some((take.id.0, mark.id.0)) && mark.line == line.id)); if let Some(mark) = mark { let mark_y = draw_row.center().y; - let mark_rect = Rect::from_center_size(pos2(cx, mark_y), vec2(23.0, 18.0)); - let marker = ui.painter().with_clip_rect(draw_clip); - marker.add(egui::Shape::convex_polygon( - vec![pos2(cx - 4.0, mark_y - 5.0), pos2(cx - 11.0, mark_y), pos2(cx - 4.0, mark_y + 5.0)], - t.text_dim, - Stroke::NONE, - )); - marker.add(egui::Shape::convex_polygon( - vec![pos2(cx + 4.0, mark_y - 5.0), pos2(cx + 11.0, mark_y), pos2(cx + 4.0, mark_y + 5.0)], - t.text_dim, - Stroke::NONE, - )); + let gap = app.ui.script.script_mark_gap(); + let radius = app.ui.script.script_mark_radius().min(draw_row.height() * 0.5); + let hit_size = vec2(gap + 2.0 * radius + 2.0, (2.0 * radius).max(18.0).min(draw_row.height())); + let mark_rect = Rect::from_center_size(pos2(cx, mark_y), hit_size); + crate::icons::paint_script_mark(&paint, mark_rect.center(), radius, gap, t.text_dim); + // During a recording pass the entire row, including the painted mark, accepts one timing click. + if recording { + continue; + } let response = ui .interact(mark_rect.intersect(draw_clip), egui::Id::unique(("script.mark", mark.id.0)), Sense::click_and_drag()) .on_hover_text(tl!("Click to cue Source; Command/Ctrl-drag to move this mark to another script line")); @@ -816,7 +921,7 @@ fn endpoint_interaction( if (top && index != start) || (!top && index != end) { continue; } - let handle = Rect::from_center_size(pos2(cx, y), vec2(24.0, 14.0)).intersect(clip); + let handle = Rect::from_center_size(pos2(cx, y), vec2(app.ui.script.take_column_width().min(24.0), 14.0)).intersect(clip); let response = ui .interact(handle, egui::Id::unique(("script.endpoint", take.id.0, top)), Sense::click_and_drag()) .on_hover_cursor(egui::CursorIcon::ResizeVertical) @@ -875,10 +980,14 @@ fn thumbnail_interaction( take_click: &mut bool, actions: &mut Vec, ) { - let response = ui - .interact(thumbnail.intersect(clip), egui::Id::unique(("script.thumbnail", header.id)), Sense::click_and_drag()) - .on_hover_cursor(egui::CursorIcon::Grab); - app.auto.add(&format!("script.slate.{}.thumbnail", header.id), response.rect, "Setup thumbnail"); + let response = ui.interact(thumbnail.intersect(clip), egui::Id::unique(("script.thumbnail", header.id)), Sense::click_and_drag()); + if response.hovered() || response.is_pointer_button_down_on() || response.dragged() { + let move_setup = if app.ui.script.drag_slate == Some(header.id) { app.ui.script.drag_slate_group } else { ui.input(|i| i.modifiers.command) }; + ui.ctx().set_cursor_icon(if move_setup { egui::CursorIcon::Move } else { egui::CursorIcon::Grab }); + } + let label = tlf!("Setup thumbnail: {name}", name = header.slate.name); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, response.enabled(), &label)); + app.auto.add_response(&format!("script.slate.{}.thumbnail", header.id), &response, &label); if response.clicked() || response.drag_started() { *foreground_click = true; *take_click = true; @@ -896,7 +1005,7 @@ fn thumbnail_interaction( } if app.ui.script.drag_slate == Some(header.id) { if let Some(pointer) = response.interact_pointer_pos() { - let bottom_y = (pointer.y - app.ui.script.drag_slate_grab_y + TAKE_HEADER_H - base_y).max(0.0); + let bottom_y = (pointer.y - app.ui.script.drag_slate_grab_y + TAKE_HEADER_H - header.pin_offset - base_y).max(0.0); let lower = first_visible(tops, bottom_y).min(doc.lines.len().saturating_sub(1)); let upper = (lower + 1).min(doc.lines.len().saturating_sub(1)); let mut target = if (tops[upper] - bottom_y).abs() < (tops[lower] - bottom_y).abs() { upper } else { lower }; @@ -937,6 +1046,7 @@ fn thumbnail_interaction( } if response.clicked() { app.ui.script.selected_slate = Some(header.id); + response.request_focus(); app.ui.script.selected_thumbnail = Some(header.id); app.ui.script.selected_mark = None; if let Some(slate) = doc.slates.iter().find(|slate| slate.id.0 == header.id) @@ -946,14 +1056,29 @@ fn thumbnail_interaction( } app.ui.script.thumbnail_shuttle_count = 0; } + preview_focus(app, ui, &response, header.id, header.display_take.id.0); if response.double_clicked() && !shift_click(ui) { if let Some(source) = header.source { + response.surrender_focus(); actions.push(Action::CueThumbnail { source, time: header.source_time }); } else { app.ui.status = tl!("Reattach this candle's source first.").into(); } } - response.clone().context_menu(|ui| { + header_menu(ui, &response).show(|ui| { + let title = tl!("Tree Outline Color"); + let palette = ui.menu_button(title, |ui| { + for color in ScriptColor::ALL { + let label = if color == ScriptColor::Default { tl!("Theme Default") } else { crate::i18n::t(color.name()) }; + let choice = ui.selectable_label(header.slate.outline_color == color, label); + app.auto.add_response(&format!("script.slate.{}.outline.{}", header.id, color.name()), &choice, label); + if choice.clicked() { + actions.push(Action::Command("script.setTreeOutlineColor", json!({"item":app.ui.script.item, "slate":header.id, "color":color.name()}))); + ui.close(); + } + } + }); + app.auto.add_response(&format!("script.slate.{}.outline", header.id), &palette.response, title); recovery::source_menu(app, ui, header.display_take, actions); if let Some(source) = header.last_take.source && ui.button(tl!("Add Another Candle")).clicked() @@ -968,6 +1093,18 @@ fn thumbnail_interaction( }); } +fn header_menu(ui: &egui::Ui, response: &egui::Response) -> egui::Popup<'static> { + let popup = egui::Popup::context_menu(response); + if response.has_focus() && ui.input_mut(|i| i.consume_key(egui::Modifiers::SHIFT, egui::Key::F10)) { + popup.at_position(response.rect.left_bottom()).open_memory(egui::SetOpenCommand::Bool(true)) + } else if popup.is_open() && egui::Popup::position_of_id(ui.ctx(), popup.get_id()).is_none() { + // A keyboard-opened menu has no saved pointer position on subsequent frames. + popup.at_position(response.rect.left_bottom()) + } else { + popup + } +} + fn thumbnail_paint(app: &mut FilmcraftApp, ui: &egui::Ui, header: &SlateHeader<'_>, thumbnail: Rect, clip: Rect) { let t = app.tokens; let shown = if app.ui.script.drag_slate == Some(header.id) { thumbnail.translate(vec2(0.0, app.ui.script.drag_slate_delta.y)) } else { thumbnail }; @@ -977,7 +1114,13 @@ fn thumbnail_paint(app: &mut FilmcraftApp, ui: &egui::Ui, header: &SlateHeader<' paint.rect_filled(shown, 3.0, t.field_bg); let selected = app.ui.script.selected_slate == Some(header.id) || app.ui.script.selected_section_slates.contains(&header.id); paint.rect_filled(chin, 1.0, if selected { t.hover } else { t.field_bg }); - if let Some(source) = header.source.and_then(|id| app.session.project.item(id)) { + if let Some(source) = header.source + && let Some(examples) = super::practice::examples(app, source) + { + if let Some((texture, size)) = app.thumbnail_in(ui.ctx(), examples, source, header.source_time.unwrap_or(Tick::ZERO), shown.width().round() as u32, 0) { + paint.image(texture, crate::panels::monitor::fit(picture, size.x, size.y), Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + } + } else if let Some(source) = header.source.and_then(|id| app.session.project.item(id)) { let resolved = app.session.project.resolve_media(source.id); let thumb_item = resolved.map_or(source.id, |value| value.0); let thumb_time = header.source_time.unwrap_or_else(|| resolved.and_then(|(_, _, span)| span.map(|range| range.start)).unwrap_or(Tick::ZERO)); @@ -992,39 +1135,100 @@ fn thumbnail_paint(app: &mut FilmcraftApp, ui: &egui::Ui, header: &SlateHeader<' Tokens::ui(10.0), t.text, ); - paint.rect_stroke(shown, 3.0, Stroke::new(if selected { 1.75 } else { 1.25 }, t.text_dim), egui::StrokeKind::Middle); + paint.rect_stroke(shown, 3.0, Stroke::new(if selected { 1.75 } else { 1.25 }, header.outline), egui::StrokeKind::Middle); +} + +fn preview_focus(app: &mut FilmcraftApp, ui: &egui::Ui, response: &egui::Response, slate: u64, take: u64) { + if response.has_focus() { + ui.memory_mut(|m| m.set_focus_lock_filter(response.id, egui::EventFilter { horizontal_arrows: true, ..Default::default() })); + app.ui.script.preview_focus = Some((response.id, slate, take)); + } } /// Each candle's take number hangs from the shared setup thumbnail, even when the /// thumbnail floats above or below the candle's first script line. -fn take_metadata_paint(app: &mut FilmcraftApp, ui: &egui::Ui, doc: &ScriptDocument, header: &SlateHeader<'_>, centers: &[f32], thumbnail: Rect, clip: Rect) { - let Some(slate) = doc.slates.iter().find(|slate| slate.id.0 == header.id) else { return }; +fn take_numbers( + app: &mut FilmcraftApp, + ui: &mut egui::Ui, + header: &SlateHeader<'_>, + centers: &[f32], + thumbnail: Rect, + clip: Rect, + actions: &mut Vec, +) -> bool { + let slate = header.slate; let preview_y = if app.ui.script.drag_slate == Some(header.id) { app.ui.script.drag_slate_delta.y } else { 0.0 }; let bottom = thumbnail.bottom() + preview_y; let paint = ui.painter().with_clip_rect(clip); - for (ordinal, take) in slate.takes.iter().enumerate() { - let Some(¢er) = centers.get(header.first_column + ordinal) else { continue }; - let cx = clip.left() + center - app.ui.script.take_scroll; - let take_number = take - .source - .and_then(|id| app.session.project.item(id)) - .and_then(|item| item.metadata.get("Take")) - .and_then(|value| value.trim().parse::().ok()) - .map_or_else(|| (ordinal + 1).to_string(), |value| value.to_string()); - let meta = take_metadata_rect(cx, bottom); - paint.rect_filled(meta, 2.0, app.tokens.panel_bg); - paint.rect_stroke(meta, 2.0, Stroke::new(1.25, app.tokens.text_dim), egui::StrokeKind::Inside); - paint.text(meta.center(), Align2::CENTER_CENTER, &take_number, Tokens::ui(if take_number.len() > 2 { 7.0 } else { 9.5 }), app.tokens.text); - app.auto.add(&format!("script.take.{}.metadata", take.id.0), meta, "Take metadata"); + if bottom + TAKE_NUMBER_H < clip.top() || bottom > clip.bottom() { + return false; } -} - -fn take_metadata_rect(cx: f32, thumbnail_bottom: f32) -> Rect { - Rect::from_min_size(pos2(cx - 8.0, thumbnail_bottom), vec2(16.0, TAKE_NUMBER_H)) + let mut activated = false; + let origin_x = clip.left() - app.ui.script.take_scroll; + let centers = ¢ers[header.first_column..header.first_column + header.take_boxes.len()]; + for (ordinal, ((take, take_box), center)) in slate.takes.iter().zip(&header.take_boxes).zip(centers).enumerate() { + let cx = origin_x + center; + let meta = Rect::from_min_size(pos2(cx - take_box.width * 0.5, bottom), vec2(take_box.width, TAKE_NUMBER_H)); + let hit = meta.intersect(clip); + if !hit.is_positive() { + continue; + } + let response = ui.interact(hit, egui::Id::unique(("script.take.number", take.id.0)), Sense::click_and_drag()); + let selected = app.ui.script.selected_take == Some(take.id.0); + let label = tlf!("{number} – Take", number = take_box.full_label); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, &label)); + app.auto.add_response(&format!("script.take.{}.metadata", take.id.0), &response, &label); + let can_reorder = header.slate.takes.len() > 1 && ui.input(|i| i.modifiers.command && !i.modifiers.alt); + if response.drag_started_by(egui::PointerButton::Primary) && can_reorder { + app.ui.script.drag_take_number = Some(take.id.0); + } + let dragging = app.ui.script.drag_take_number == Some(take.id.0); + if response.clicked() || (response.drag_started() && dragging) { + activated = true; + response.request_focus(); + app.ui.script.selected_slate = Some(header.id); + app.ui.script.selected_take = Some(take.id.0); + app.ui.script.selected_thumbnail = None; + app.ui.script.selected_mark = None; + app.ui.script.thumbnail_shuttle_count = 0; + } + if dragging || (can_reorder && response.hovered()) { + ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); + } + if dragging { + let target = response + .interact_pointer_pos() + .filter(|pos| clip.contains(*pos) && (pos.y - meta.center().y).abs() <= TAKE_NUMBER_H) + .and_then(|pos| centers.iter().zip(&header.take_boxes).position(|(center, slot)| (pos.x - origin_x - center).abs() <= slot.column_width * 0.5)) + .filter(|&slot| slot != ordinal); + if app.escape_cancel || ui.input(|i| i.key_pressed(egui::Key::Escape)) { + app.ui.script.drag_take_number = None; + } else if let Some(slot) = target { + let edge = if slot < ordinal { -0.5 } else { 0.5 }; + let x = origin_x + centers[slot] + edge * header.take_boxes[slot].column_width; + paint.vline(x, meta.y_range(), Stroke::new(2.0, app.tokens.accent)); + if response.drag_stopped() { + actions + .push(Action::Command("script.moveTake", json!({"item":app.ui.script.item, "take":take.id.0, "toTake":header.slate.takes[slot].id.0}))); + } + } + } + let fill = if selected { app.tokens.hover } else { app.tokens.panel_bg }; + paint.rect_filled(meta, 2.0, fill); + paint.rect_stroke(meta, 2.0, Stroke::new(if selected || response.has_focus() { 2.0 } else { 1.25 }, header.outline), egui::StrokeKind::Inside); + let origin = meta.center() - take_box.text.size() * 0.5; + paint.with_clip_rect(hit).galley(origin, Arc::clone(&take_box.text), app.tokens.text); + preview_focus(app, ui, &response, header.id, take.id.0); + header_menu(ui, &response).show(|ui| take_menu(app, ui, take, actions)); + response + .on_hover_text(label) + .on_hover_text(tl!("Left/Right changes the thumbnail frame. Hold to shuttle faster. Command-drag (Mac) or Ctrl-drag (Windows/Linux) to reorder.")); + } + activated } fn take_menu(app: &mut FilmcraftApp, ui: &mut egui::Ui, take: &ScriptTake, actions: &mut Vec) { - if let Some(doc) = app.ui.script.item.and_then(|id| app.session.project.item(ItemId(id))).and_then(|item| item.as_script()) + if let Some(doc) = super::document(app).cloned() && let Some(slate) = doc.slates.iter().find(|slate| slate.takes.iter().any(|candidate| candidate.id == take.id)) && slate.takes.len() > 1 { @@ -1052,13 +1256,7 @@ fn take_menu(app: &mut FilmcraftApp, ui: &mut egui::Ui, take: &ScriptTake, actio } } }); - let selected_ids = app - .ui - .script - .item - .and_then(|id| app.session.project.item(ItemId(id))) - .and_then(|item| item.as_script()) - .map(|doc| selected_take_lines(doc, &app.ui.script, take)); + let selected_ids = super::document(app).map(|doc| selected_take_lines(doc, &app.ui.script, take)); if let Some(ids) = selected_ids.filter(|ids| !ids.is_empty()) { let all_offscreen = ids.iter().all(|id| take.offscreen_lines.contains(id)); if ui.button(if all_offscreen { tl!("Clear Offscreen") } else { tl!("Mark Offscreen") }).clicked() { @@ -1082,10 +1280,10 @@ fn row_text_editor(app: &mut FilmcraftApp, ui: &mut egui::Ui, line: &ScriptLine, None }; let paste_cursor = egui::text_edit::TextEditState::load(ui.ctx(), edit_id).and_then(|state| state.cursor.char_range()); - let response = crate::widgets::accessible_name( - ui.put(edit_rect, egui::TextEdit::singleline(&mut app.ui.script.edit_text).id(edit_id).desired_width(edit_rect.width())), - "Edit script line", - ); + let font = super::layout::script_font(&app.ui.script); + let editor = egui::TextEdit::singleline(&mut app.ui.script.edit_text).id(edit_id).font(font).margin(0).desired_width(edit_rect.width()); + let editor = if line.element.is_some() { editor.align(super::layout::row_alignment(line.element)) } else { editor }; + let response = crate::widgets::accessible_name(ui.put(edit_rect, editor), "Edit script line"); app.auto.add_response(&format!("script.line.{}.edit", line.id.0), &response, "Edit script line"); if response.changed() { app.ui.script.text_paste_revision = None; @@ -1121,11 +1319,8 @@ fn row_text_editor(app: &mut FilmcraftApp, ui: &mut egui::Ui, line: &ScriptLine, let at = cursor.map_or(app.ui.script.edit_text.chars().count(), |range| range.primary.index.into()); actions.push(Action::SplitLine { line: line.id.0, text: app.ui.script.edit_text.clone(), at }); app.ui.script.edit_line = None; - } else if response.lost_focus() { - if app.ui.script.edit_text != line.text { - actions.push(Action::Command("script.editLine", json!({"item": app.ui.script.item, "line": line.id.0, "text": app.ui.script.edit_text}))); - } - app.ui.script.edit_line = None; + } else if response.lost_focus() && !super::finish_script_fields(app) { + response.request_focus(); } } @@ -1137,17 +1332,16 @@ struct ConnectorLayout<'a> { body: Rect, } -fn paint_take_connectors(app: &FilmcraftApp, ui: &egui::Ui, doc: &ScriptDocument, slate_headers: &[SlateHeader<'_>], layout: ConnectorLayout<'_>) { +fn paint_take_connectors(app: &FilmcraftApp, ui: &egui::Ui, slate_headers: &[SlateHeader<'_>], layout: ConnectorLayout<'_>) { let ConnectorLayout { column_centers, line_indices, tops, base_y, body } = layout; - let t = app.tokens; // Each take has its own connector from its number box to its candle. // During a drag, use the stepped preview rows so every connector stays attached. for header in slate_headers { - let Some(slate) = doc.slates.iter().find(|slate| slate.id.0 == header.id) else { continue }; + let slate = header.slate; let shown_index = if app.ui.script.drag_slate == Some(header.id) { app.ui.script.drag_slate_target.unwrap_or(header.start_index) } else { header.start_index }; let Some(&shown_top) = tops.get(shown_index).or_else(|| tops.get(header.start_index)) else { continue }; - let box_top = base_y + shown_top; + let box_top = base_y + shown_top + header.pin_offset; let preview_y = if app.ui.script.drag_slate == Some(header.id) && app.ui.script.drag_slate_group { app.ui.script.drag_slate_delta.y } else { 0.0 }; for (ordinal, take) in slate.takes.iter().enumerate() { let Some(¢er) = column_centers.get(header.first_column + ordinal) else { continue }; @@ -1157,10 +1351,10 @@ fn paint_take_connectors(app: &FilmcraftApp, ui: &egui::Ui, doc: &ScriptDocument if cx < body.left() || cx > body.right() { continue; } - let box_bottom = take_metadata_rect(cx, box_top - TAKE_HEADER_H).bottom(); + let box_bottom = box_top - TAKE_HEADER_H + TAKE_NUMBER_H; let candle_top = base_y + row_top + preview_y; if (box_bottom - candle_top).abs() > 1.0 { - ui.painter().with_clip_rect(body).line_segment([pos2(cx, box_bottom), pos2(cx, candle_top)], Stroke::new(1.0, t.text_dim)); + ui.painter().with_clip_rect(body).line_segment([pos2(cx, box_bottom), pos2(cx, candle_top)], Stroke::new(1.0, header.outline)); } } } @@ -1168,50 +1362,56 @@ fn paint_take_connectors(app: &FilmcraftApp, ui: &egui::Ui, doc: &ScriptDocument struct RowLabelLayout { left: Rect, + scene_start: f32, text_inset: f32, index: usize, } -fn row_labels(app: &mut FilmcraftApp, ui: &mut egui::Ui, line: &ScriptLine, layout: RowLabelLayout, foreground_click: &mut bool, actions: &mut Vec) { - let RowLabelLayout { left, text_inset, index } = layout; +fn row_labels(app: &mut FilmcraftApp, ui: &mut egui::Ui, line: &ScriptLine, layout: RowLabelLayout, foreground_click: &mut bool) { + let RowLabelLayout { left, text_inset, scene_start, index } = layout; let t = app.tokens; let label_y = left.center().y; - let mut scene_start = 6.0; if app.ui.script.show_line_numbers.unwrap_or(true) { let number = (index + 1).to_string(); let font = Tokens::ui(10.0); - scene_start += ui.painter().layout_no_wrap(number.clone(), font.clone(), t.text_dim).size().x + 5.0; - ui.painter().text(pos2(left.min.x + 6.0, label_y), Align2::LEFT_CENTER, number, font, t.text_dim.gamma_multiply(0.55)); + ui.painter().text(pos2(left.min.x + super::layout::ROW_NUMBER_INSET, label_y), Align2::LEFT_CENTER, number, font, t.text_dim.gamma_multiply(0.55)); } - let page_rect = Rect::from_min_size(pos2(left.max.x, left.min.y + 1.0), vec2(52.0, MIN_ROW_H - 2.0)); - let scene_rect = - Rect::from_min_size(pos2(left.min.x + scene_start, left.min.y + 1.0), vec2((text_inset - scene_start - 4.0).clamp(1.0, 72.0), MIN_ROW_H - 2.0)); + let label_height = left.height().min(20.0) - 2.0; + let page_rect = Rect::from_min_size(pos2(left.max.x, left.min.y + 1.0), vec2(52.0, label_height)); + let scene_rect = Rect::from_min_size( + pos2(left.min.x + scene_start, left.min.y + 1.0), + vec2((text_inset - scene_start - super::layout::SCENE_TRAILING_GAP).max(1.0), label_height), + ); if app.ui.script.edit_page == Some(line.id.0) { let response = ui.put(page_rect, egui::TextEdit::singleline(&mut app.ui.script.page_text).hint_text(tl!("Page"))); *foreground_click |= response.clicked(); - if app.ui.script.label_focus == Some(2) { + let opening = app.ui.script.label_focus == Some(2); + if opening { response.request_focus(); app.ui.script.label_focus = None; } + crate::widgets::select_all_on_focus(ui, &response, &app.ui.script.page_text); app.auto.add_response(&format!("script.page.{}.edit", line.id.0), &response, "Edit page label"); - if response.lost_focus() || response.has_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter)) { - let page = app.ui.script.page_text.trim(); - actions.push(Action::Command( - "script.setLabel", - json!({"item": app.ui.script.item, "line": line.id.0, - "scene": line.scene.as_deref(), "page": if page.is_empty() { None } else { Some(page) }}), - )); - app.ui.script.edit_page = None; + if !opening + && (response.lost_focus() || response.has_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter))) + && !super::finish_script_fields(app) + { + response.request_focus(); } - } else if let Some(page) = &line.page { + } else if !app.ui.script.hide_page_numbers + && let Some(page) = &line.page + { let response = ui .put( page_rect, - egui::Label::new(egui::RichText::new(format!("Pg {}", truncate(page, 3))).italics().color(t.text_dim).size(10.5)).sense(Sense::click()), + egui::Label::new(egui::RichText::new(page.trim()).italics().color(t.text_dim).size(10.5)) + .halign(egui::Align::LEFT) + .truncate() + .sense(Sense::click()), ) .on_hover_text(tl!("Double-click to edit Page")); *foreground_click |= response.clicked(); - app.auto.add(&format!("script.page.{}", line.id.0), response.rect, "Page label"); + app.auto.add(&format!("script.page.{}", line.id.0), response.rect, page.trim()); if response.double_clicked() { select_line(&mut app.ui.script, line, false); app.ui.script.edit_page = Some(line.id.0); @@ -1219,31 +1419,38 @@ fn row_labels(app: &mut FilmcraftApp, ui: &mut egui::Ui, line: &ScriptLine, layo } } if app.ui.script.edit_scene == Some(line.id.0) { - let response = ui.put(scene_rect, egui::TextEdit::singleline(&mut app.ui.script.scene_text).hint_text(tl!("Scene"))); + let hint = tl!("Scene"); + let font = egui::TextStyle::Body.resolve(ui.style()); + let hint_width = ui.painter().layout_no_wrap(hint.to_owned(), font, t.text).size().x; + let edit_width = scene_rect.width().max((hint_width + 2.0 * ui.spacing().button_padding.x).ceil()); + let edit_rect = Rect::from_min_size(scene_rect.min, vec2(edit_width, scene_rect.height())); + let response = ui.put(edit_rect, egui::TextEdit::singleline(&mut app.ui.script.scene_text).hint_text(hint)); *foreground_click |= response.clicked(); - if app.ui.script.label_focus == Some(1) { + let opening = app.ui.script.label_focus == Some(1); + if opening { response.request_focus(); app.ui.script.label_focus = None; } + crate::widgets::select_all_on_focus(ui, &response, &app.ui.script.scene_text); app.auto.add_response(&format!("script.scene.{}.edit", line.id.0), &response, "Edit scene label"); - if response.lost_focus() || response.has_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter)) { - let scene = app.ui.script.scene_text.trim(); - actions.push(Action::Command( - "script.setLabel", - json!({"item": app.ui.script.item, "line": line.id.0, - "scene": if scene.is_empty() { None } else { Some(scene) }, "page": line.page.as_deref()}), - )); - app.ui.script.edit_scene = None; + if !opening + && (response.lost_focus() || response.has_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter))) + && !super::finish_script_fields(app) + { + response.request_focus(); } } else if let Some(scene) = &line.scene { let response = ui .put( scene_rect, - egui::Label::new(egui::RichText::new(format!("Sc {scene}")).italics().color(t.text_dim).size(11.0)).truncate().sense(Sense::click()), + egui::Label::new(egui::RichText::new(scene.trim()).italics().color(t.text_dim).font(super::layout::scene_font())) + .halign(egui::Align::LEFT) + .truncate() + .sense(Sense::click()), ) .on_hover_text(tl!("Double-click to edit Scene")); *foreground_click |= response.clicked(); - app.auto.add(&format!("script.scene.{}", line.id.0), response.rect, "Scene label"); + app.auto.add(&format!("script.scene.{}", line.id.0), response.rect, scene.trim()); if response.double_clicked() { select_line(&mut app.ui.script, line, false); app.ui.script.edit_scene = Some(line.id.0); diff --git a/crates/ui-egui/src/panels/script/layout.rs b/crates/ui-egui/src/panels/script/layout.rs index 6825808af..2c547695d 100644 --- a/crates/ui-egui/src/panels/script/layout.rs +++ b/crates/ui-egui/src/panels/script/layout.rs @@ -1,10 +1,49 @@ //! Shared row measurements and candle geometry; painting and hit targets use the same coordinates. +use egui::Align2; +use filmcraft_project::{ScriptElement, ScriptLine}; + use super::{ - Arc, DEFAULT_THUMB_W, FilmcraftApp, HashMap, MAX_THUMB_W, MAX_VISUAL_LINES, MIN_ROW_H, MIN_THUMB_W, Rect, SCRIPT_FONT_SIZE, ScriptDocument, ScriptTake, - ScriptUi, TAKE_HEADER_H, THUMB_CHIN_H, Tokens, + Arc, DEFAULT_LINE_H, DEFAULT_THUMB_W, FilmcraftApp, HashMap, MAX_THUMB_W, MAX_VISUAL_LINES, MIN_THUMB_W, Rect, SCRIPT_FONT_SIZE, ScriptDocument, + ScriptTake, ScriptUi, TAKE_HEADER_H, THUMB_CHIN_H, Tokens, }; +impl ScriptUi { + /// Total extra height per logical row, split evenly above and below the text. + pub(super) fn row_spacing(&self) -> u8 { + self.row_spacing.unwrap_or(if self.practicing { 2 } else { 4 }).min(super::MAX_ROW_SPACING) + } + + pub(super) fn candle_stroke_width(&self) -> f32 { + self.candle_width.unwrap_or(super::DEFAULT_CANDLE_W).clamp(super::MIN_CANDLE_W, super::MAX_CANDLE_W) + } + + pub(super) fn script_mark_gap(&self) -> f32 { + // Put the flat edges halfway into the 1 pt outline so rounding can't expose the background. + self.candle_stroke_width() + 1.0 + } + + pub(super) fn script_mark_radius(&self) -> f32 { + let width = self.candle_stroke_width(); + if width <= super::DEFAULT_CANDLE_W { + egui::remap_clamp(width, super::MIN_CANDLE_W..=super::DEFAULT_CANDLE_W, 4.5..=5.5) + } else { + // The widest candle uses four sevenths of the growth from the default mark to a full row. + let max_radius = egui::lerp(5.5..=self.single_row_height * 0.5, 4.0 / 7.0); + egui::remap_clamp(width, super::DEFAULT_CANDLE_W..=super::MAX_CANDLE_W, 5.5..=max_radius) + } + } + + pub(super) fn candle_distance(&self) -> u8 { + let range = super::CANDLE_DISTANCE; + self.candle_distance.unwrap_or(3).clamp(*range.start(), *range.end()) + } + + pub(super) fn take_column_width(&self) -> f32 { + self.script_mark_gap() + 2.0 * self.script_mark_radius() + f32::from(self.candle_distance()) + } +} + pub(super) fn thumbnail_width(state: &ScriptUi) -> f32 { state.thumbnail_width.unwrap_or(DEFAULT_THUMB_W).clamp(MIN_THUMB_W, MAX_THUMB_W) } @@ -13,13 +52,133 @@ pub(super) fn thumbnail_height(width: f32) -> f32 { width * 9.0 / 16.0 + THUMB_CHIN_H } +pub(super) fn script_font(state: &ScriptUi) -> egui::FontId { + Tokens::ui(state.font_size.unwrap_or(SCRIPT_FONT_SIZE).clamp(10.0, 24.0)) +} + +pub(super) const ROW_NUMBER_INSET: f32 = 6.0; +pub(super) const SCENE_TRAILING_GAP: f32 = 5.0; + +pub(super) fn scene_font() -> egui::FontId { + Tokens::ui(11.0) +} + +#[derive(Clone)] +struct SceneWidth { + document: std::sync::Weak, + pixel_scale: f32, + width: f32, +} + +fn widest_scene(ui: &egui::Ui, doc: &Arc) -> f32 { + let key = egui::Id::unique("lined-script.canvas.scene-width"); + let document = Arc::downgrade(doc); + let pixel_scale = ui.ctx().pixels_per_point(); + if let Some(cached) = ui.data(|data| data.get_temp::(key)) + && cached.document.ptr_eq(&document) + && cached.pixel_scale == pixel_scale + { + return cached.width; + } + let width = ui.fonts_mut(|fonts| { + doc.lines + .iter() + .filter_map(|line| line.scene.as_deref()) + .map(|scene| fonts.layout_no_wrap(scene.trim().to_owned(), scene_font(), egui::Color32::WHITE).size().x.ceil()) + .fold(0.0, f32::max) + }); + ui.data_mut(|data| data.insert_temp(key, SceneWidth { document, pixel_scale, width })); + width +} + +const LABEL_GUTTER: f32 = 54.0; +const MAX_DEFAULT_WRAP_MARGIN: f32 = 424.0; +const DEFAULT_SETUP_ORIGIN: f32 = 614.0; + +pub(super) struct Margins { + pub scene_start: f32, + pub left: f32, + pub right: f32, + pub setup_origin: f32, + pub left_range: egui::Rangef, + pub right_range: egui::Rangef, +} + +impl Margins { + pub fn new(app: &FilmcraftApp, ui: &egui::Ui, width: f32) -> Self { + let state = &app.ui.script; + let doc = super::document(app); + let mut scene_start = ROW_NUMBER_INSET; + if state.show_line_numbers.unwrap_or(true) + && let Some(doc) = doc + { + let digits = doc.lines.len().max(1).ilog10() + 1; + let digit_width = ui.fonts_mut(|fonts| ('0'..='9').map(|c| fonts.glyph_width(&Tokens::ui(10.0), c)).fold(0.0, f32::max)); + scene_start += (digits as f32 * digit_width).ceil() + 5.0; + } + // Fit production scene identifiers while reserving at least four fifths of the panel for the script and takes. + let scene_width = doc.map_or(0.0, |doc| widest_scene(ui, doc)).min(width * 0.2).min(160.0); + let min_left = LABEL_GUTTER.max(scene_start + scene_width + SCENE_TRAILING_GAP + 2.0); + let max_right = (width - 85.0).max(100.0); + let right_range = egui::Rangef::new(180.0_f32.max(min_left + 48.0).min(max_right), max_right); + // Leave room for the first setup even when the canvas is narrower than the default layout. + let setup_origin = DEFAULT_SETUP_ORIGIN.min((width - thumbnail_width(state) - 8.0).max(0.0)); + let default_right = (width * 0.70).min(MAX_DEFAULT_WRAP_MARGIN); + let right = right_range.clamp(state.text_column_width.unwrap_or(default_right)); + let max_left = (right - 48.0).max(42.0); + let left_range = egui::Rangef::new(min_left.min(max_left), max_left); + let left = left_range.clamp(state.text_inset.unwrap_or(super::DEFAULT_TEXT_INSET)); + Self { scene_start, left, right, setup_origin, left_range, right_range } + } +} + +/// Return the text origin and wrap width in panel coordinates. Reserve space for text +/// before indenting narrow columns. A row without a role keeps its source indentation. +pub(super) fn row_column(element: Option, left: f32, right: f32, space: f32) -> (f32, f32) { + let available = (right - left).max(1.0); + let step = (10.0 * space).min((available - 48.0).max(0.0) / 2.0); + if element == Some(ScriptElement::Character) { + // All cues share a center twenty spaces into the dialogue column. A narrow + // ruler brings it inward, and long names can use space back to the left ruler. + let center = step + (20.0 * space).min((available - step) * 0.5); + let half_width = center.min(available - center); + return (left + center - half_width, 2.0 * half_width); + } + let offset = match element { + Some(ScriptElement::Parenthetical) => 1.5 * step, + Some(ScriptElement::Dialogue) => step, + _ => 0.0, + }; + (left + offset, (available - offset).max(48.0)) +} + +pub(super) fn row_alignment(element: Option) -> Align2 { + match element { + Some(ScriptElement::Character) => Align2::CENTER_TOP, + Some(ScriptElement::Transition) => Align2::RIGHT_TOP, + _ => Align2::LEFT_TOP, + } +} + +pub(super) fn row_galley(ui: &egui::Ui, line: &ScriptLine, font: egui::FontId, color: egui::Color32, width: f32) -> Arc { + let alignment = row_alignment(line.element); + if alignment != Align2::LEFT_TOP { + let mut job = egui::text::LayoutJob::simple(line.text.clone(), font, color, width); + job.halign = alignment.x(); + ui.painter().layout_job(job) + } else { + ui.painter().layout(line.text.clone(), font, color, width) + } +} + /// Measured once per document identity and view settings; a 4 MiB script may have 50,000 rows, so only /// visible rows are painted while their cached prefix heights keep the candles in exact alignment. pub(super) fn row_layout(app: &mut FilmcraftApp, ui: &egui::Ui, doc: &Arc, left_w: f32, text_inset: f32) { let width = left_w.round().max(1.0) as u32; let inset = text_inset.round().max(1.0) as u32; - let script_font_size = app.ui.script.font_size.unwrap_or(SCRIPT_FONT_SIZE).clamp(10.0, 24.0); - let font_size = script_font_size.to_bits(); + let font = script_font(&app.ui.script); + let font_size = font.size.to_bits(); + let row_spacing = app.ui.script.row_spacing(); let thumb_w = thumbnail_width(&app.ui.script); let thumb_width = thumb_w.round() as u32; if app.ui.script.layout_item == app.ui.script.item @@ -27,35 +186,64 @@ pub(super) fn row_layout(app: &mut FilmcraftApp, ui: &egui::Ui, doc: &Arc