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>
This commit is contained in:
Whatever Industries
2026-12-01 01:55:58 -08:00
committed by GitHub
parent e19d4961c6
commit f2c4a49a35
45 changed files with 4359 additions and 1149 deletions
+1
View File
@@ -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 |
+3
View File
@@ -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,
+2 -2
View File
@@ -3305,7 +3305,7 @@ fn build() -> Vec<CommandSpec> {
.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<Value> {
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)
+8
View File
@@ -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<ItemId>,
/// 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<ItemId> = Vec::new();
for id in view.open_sequences {
if self.project.sequence(id).is_some() && !open.contains(&id) {
+123 -24
View File
@@ -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<Value> {
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<Value> {
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<Value> {
} 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<Value> {
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<Value> {
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<Value> {
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<Value> {
Ok(json!({"time":time}))
}
fn set_tree_outline_color(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
let cmd = "script.moveThumbnail";
let item = item(p, cmd)?;
@@ -508,7 +553,8 @@ fn insert_line(s: &mut Session, p: &Value) -> Result<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<CommandSpec> {
@@ -1044,6 +1102,7 @@ pub fn commands() -> Vec<CommandSpec> {
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<CommandSpec> {
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::<Vec<_>>(), ["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;
+1
View File
@@ -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),
+3
View File
@@ -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(),
+3 -2
View File
@@ -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);
+44 -1
View File
@@ -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<ScriptElement>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scene: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub page: Option<String>,
@@ -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,
+23 -1
View File
@@ -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<Option<ItemId>>,
pub active: Option<ItemId>,
}
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<ItemId>,
#[serde(default)]
+8 -10
View File
@@ -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.
+18 -4
View File
@@ -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<FrameServer>) -> 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());
+7 -2
View File
@@ -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
+13 -3
View File
@@ -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<filmcraft_project::Project>,
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() {
+3
View File
@@ -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;
+132 -77
View File
@@ -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<PanelKind>, b: Node<PanelKind>) -> Node<Panel
Node::split(Axis::Y, size, a, b)
}
pub const WORKSPACES: [&str; 11] =
["Editing", "Assembly", "Color", "Effects", "Audio", "Captions and Graphics", "Vertical", "Script", "Learning", "Review", "All Panels"];
/// Display label for a panel or shortcut context.
pub fn display_name(name: &str) -> &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<String> {
/// The workspace called `query` (any case, spaces optional).
pub fn find(prefs: &WorkspacePrefs, query: &str) -> Option<String> {
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<PanelKind> {
),
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<egui::Galley>,
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<egui::Response> {
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::<usize>(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<f32> {
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::<f32>() + 12.0
sequence_widths(ui, seqs).iter().map(|w| w + DocumentTab::GAP).sum::<f32>() + 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::<f32>() + 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::<f32>() + 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::<f32>(wheel_id));
}
let mut x = strip.min.x + 12.0;
let mut seq_rects: Vec<(u64, Rect)> = Vec::new();
let mut dragged: Option<u64> = 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::<usize>(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::<bool>(list_id)).unwrap_or(false);
+4 -2
View File
@@ -250,9 +250,11 @@ fn tl_literals(text: &str) -> Vec<String> {
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<String> {
#[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)"]);
}
+10
View File
@@ -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,
+14 -2
View File
@@ -12,11 +12,12 @@ pub(crate) struct Dropdown<'a> {
width: Option<f32>,
height: Option<f32>,
truncate: bool,
corners: Option<egui::CornerRadius>,
}
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<R>(mut self, ui: &mut Ui, body: impl FnOnce(&mut Ui) -> R) -> InnerResponse<Option<R>> {
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();
+1
View File
@@ -211,6 +211,7 @@ struct NativeTimelineDrop {
pub struct FilmcraftApp {
pub session: Session,
pub(crate) script_practice: Option<panels::script::Practice>,
pub ui: UiState,
pub tokens: Tokens,
pub frames: Arc<FrameServer>,
+2
View File
@@ -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";
+49 -38
View File
@@ -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<Value, String> {
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, &params) {
return crate::panels::export_mode::preview_command(app, command, &params);
}
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, &params);
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, &params) {
return r;
@@ -1088,6 +1093,7 @@ pub fn menu_items(app: &FilmcraftApp) -> Vec<MenuItem> {
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<MenuItem> {
"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<MenuItem> {
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<filmcraft_engine::shortcuts::CommandInfo> {
let mut v: Vec<CommandInfo> =
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");
+6 -2
View File
@@ -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();
+4 -4
View File
@@ -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.
+2 -2
View File
@@ -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"));
+2 -2
View File
@@ -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();
}
+304 -161
View File
@@ -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<u8> = 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<u64>,
tabs: Vec<tabs::ScriptTab>,
#[serde(skip)]
practicing: bool,
#[serde(skip)]
project: Option<Arc<()>>,
#[serde(skip)]
@@ -53,15 +69,23 @@ pub struct ScriptUi {
pub selected_slate: Option<u64>,
pub selected_take: Option<u64>,
pub selected_mark: Option<u64>,
#[serde(skip)]
screening: Option<playback::Screening>,
/// Thumbnail selection is distinct from its display take for delete routing.
pub selected_thumbnail: Option<u64>,
#[serde(skip)]
drag_take_number: Option<u64>,
#[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<u64>,
#[serde(skip)]
pub selected_section_slates: Vec<u64>,
#[serde(skip)]
pub section_clipboard: Option<Value>,
@@ -69,7 +93,8 @@ pub struct ScriptUi {
lasso_start: Option<egui::Pos2>,
#[serde(skip)]
lasso_end: Option<egui::Pos2>,
pub paint_color: ScriptColor,
pub paint_color: Option<ScriptColor>,
pub edit_mode: bool,
pub edit_line: Option<u64>,
pub edit_text: String,
#[serde(skip)]
@@ -107,9 +132,15 @@ pub struct ScriptUi {
pub text_column_width: Option<f32>,
pub text_inset: Option<f32>,
pub font_size: Option<f32>,
pub row_spacing: Option<u8>,
pub thumbnail_width: Option<f32>,
pub candle_width: Option<f32>,
pub candle_distance: Option<u8>,
pub show_row_colors: Option<bool>,
pub show_line_numbers: Option<bool>,
pub hide_page_numbers: bool,
pub show_page_controls: bool,
pub keep_thumbnails_visible: bool,
pub search: String,
#[serde(skip)]
search_results: Vec<u64>,
@@ -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<u64>,
/// 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<f32>,
#[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<Value, String> {
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<Value, Str
return Err("select a line within the candle".into());
}
let source = take.source.ok_or("reattach this candle's source first")?;
let selected_mark = app.ui.script.selected_mark.filter(|id| take.marks.iter().any(|mark| mark.id.0 == *id && mark.line == line.id));
let pass = active_screening(app);
// A running pass owns the Source playhead; marking another candle would take that frame or swap the clip.
if pass.is_some_and(|pass| pass.take() != take.id.0) {
return Err(tl!("Stop the running take before marking another candle.").into());
}
let recording = pass.is_some_and(|pass| pass.records(take.id.0));
let selected_mark = if recording {
take.marks.iter().find(|mark| mark.line == line.id).map(|mark| mark.id.0)
} else {
app.ui.script.selected_mark.filter(|id| take.marks.iter().any(|mark| mark.id.0 == *id && mark.line == line.id))
};
let take_id = take.id.0;
let line_id = line.id.0;
if app.session.state.source_item != Some(source) {
app.session.execute("source.open", json!({"item":source.0,"focus":false})).map_err(|error| error.to_string())?;
if !recording {
playback::open_take_source(app, source)?;
}
let time = app.session.state.source_playhead.0;
let time = practice::visible_source(app).session.state.source_playhead.0;
let (command, params) = if let Some(mark) = selected_mark {
("script.setMarkTime", json!({"item":item,"take":take_id,"mark":mark,"sourceTime":time}))
} else {
("script.addMark", json!({"item":item,"take":take_id,"line":line_id,"sourceTime":time}))
};
app.session.execute(command, params).map_err(|error| error.to_string())
execute(app, command, params)
}
pub(crate) fn delete_selection(app: &mut FilmcraftApp) -> Result<Value, String> {
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<Value, String>
} 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<Value, String> {
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<Value
}
}
}
app.session
.execute("script.setTakeStyle", json!({"item":item,"take":take.id.0,"offscreenLines":updated.iter().map(|id|id.0).collect::<Vec<_>>()}))
.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::<Vec<_>>()}))
}
pub(crate) fn apply_candle_color(app: &mut FilmcraftApp) -> Result<Value, String> {
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<Value, String> {
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<bool>) -> Result<Value, String> {
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<Value, String> {
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<Value, String> {
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<String> {
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<Value, String> {
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<Val
if text.is_empty() {
return Ok(Value::Null);
}
if copied_plain_text(app).as_deref() == Some(text) && app.ui.script.item.is_some() {
if copied_plain_text(app).as_deref() == Some(text) && document(app).is_some() {
return copy_paste_section(app, false);
}
let result = if let Some(item) = app.ui.script.item {
let doc = app.session.project.item(ItemId(item)).and_then(|item| item.as_script()).ok_or("open a script first")?;
let result = if let Some(doc) = document(app) {
require_text_editing(app)?;
let item = app.ui.script.item;
let after = selected_range(doc, app.ui.script.selected_lines).map(|(_, last)| doc.lines[last].id.0);
app.session.execute("script.pasteText", json!({"item":item,"text":text,"afterLine":after})).map_err(|e| e.to_string())?
execute(app, "script.pasteText", json!({"item":item,"text":text,"afterLine":after}))?
} else {
let result = app
.session
.execute("script.importText", json!({"name":tl!("Untitled Script"),"text":text.replace("\r\n", "\n").replace('\r', "\n")}))
.map_err(|e| e.to_string())?;
app.ui.script.open_document(result["item"].as_u64());
let result = execute(app, "script.importText", json!({"name":tl!("Untitled Script"),"text":text.replace("\r\n", "\n").replace('\r', "\n")}))?;
activate_tab(app, result["item"].as_u64());
result
};
app.ui.script.clear_object_selection();
@@ -349,11 +475,14 @@ pub(crate) fn finish_edit_on_click_away(app: &mut FilmcraftApp, ctx: &egui::Cont
let Some(id) = id else { return };
let Some(response) = ctx.read_response(id) else { return };
let outside = ctx.input(|input| input.pointer.primary_pressed() && input.pointer.interact_pos().is_some_and(|pos| !response.interact_rect.contains(pos)));
if !outside {
return;
if outside && finish_script_fields(app) {
ctx.memory_mut(|memory| memory.surrender_focus(id));
}
let params = app.ui.script.item.and_then(|item| {
let doc = app.session.project.item(ItemId(item))?.as_script()?;
}
fn finish_script_fields(app: &mut FilmcraftApp) -> 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<Value, String> {
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<Value> {
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>) {
}
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<Action>) {
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>) {
}
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>) {
}
}
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<Action>) {
{
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<Action>) {
}
// 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<Action>) {
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<Value, Stri
return Err("This clip is not linked to a script".into());
}
if matches.len() == 1 {
select_source_match(&mut app.ui.script, &matches[0]);
select_source_match(app, &matches[0]);
} else {
app.ui.script.find_source = Some(source.0);
}
@@ -759,8 +872,9 @@ fn source_matches(app: &FilmcraftApp, source: ItemId) -> Vec<SourceMatch> {
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<Item =
doc.lines.get(range.0..=range.1).unwrap_or_default().iter().map(|line| line.id)
}
fn truncate(text: &str, max_chars: usize) -> 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());
File diff suppressed because it is too large Load Diff
+202 -14
View File
@@ -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<ScriptDocument>,
pixel_scale: f32,
width: f32,
}
fn widest_scene(ui: &egui::Ui, doc: &Arc<ScriptDocument>) -> 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::<SceneWidth>(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<ScriptElement>, 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<ScriptElement>) -> 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<egui::Galley> {
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<ScriptDocument>, 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<Script
&& app.ui.script.layout_width == width
&& app.ui.script.layout_inset == inset
&& app.ui.script.layout_font_size == font_size
&& app.ui.script.layout_row_spacing == row_spacing
&& app.ui.script.layout_thumbnail_width == thumb_width
&& app.ui.script.row_tops.len() == doc.lines.len().saturating_add(1)
{
return;
}
let mut tops = Vec::with_capacity(doc.lines.len().saturating_add(1));
let leading_blank = doc.lines.iter().take(5).take_while(|line| line.text.is_empty()).count();
let clearance = thumbnail_height(thumb_w) + TAKE_HEADER_H + 10.0;
let top_space = if leading_blank >= 3 { (clearance - leading_blank as f32 * MIN_ROW_H).max(8.0) } else { clearance };
tops.push(top_space);
let mut total = top_space;
let font = Tokens::ui(script_font_size);
// A thumbnail is drawn above its anchor. Reserve extra space only if the
// actual rows above that anchor are too short to contain it.
let mut anchors = std::collections::HashSet::new();
for slate in doc.slates.iter().filter(|slate| !slate.takes.is_empty()) {
if let Some(line) = slate.thumbnail_line {
anchors.insert(line);
} else {
anchors.extend(slate.takes.iter().map(|take| take.start_line));
}
}
// With no setup rows, keep the same header lane as setups move between lines.
// A script that starts with editable space can use that space for its thumbnails.
let has_setup_rows = doc.lines.first().is_some_and(|line| line.text.is_empty());
let spacing = f32::from(row_spacing);
let mut total = 0.0;
let mut first_anchor = (!has_setup_rows && !anchors.is_empty()).then_some(0.0);
tops.push(total);
let space = ui.fonts_mut(|fonts| fonts.glyph_width(&font, ' '));
app.ui.script.layout_space_width = space;
let visual_line_height = ui.painter().layout_no_wrap("Mg".to_owned(), font.clone(), app.tokens.text).size().y;
let max_height = (visual_line_height * MAX_VISUAL_LINES + 4.0).max(MIN_ROW_H);
// Preserve the default leading, and let it contract alongside smaller type.
let min_row = visual_line_height.max(DEFAULT_LINE_H * (font.size / SCRIPT_FONT_SIZE).min(1.0)) + spacing;
app.ui.script.single_row_height = min_row;
let max_height = (visual_line_height * MAX_VISUAL_LINES + spacing).max(min_row);
for line in &doc.lines {
let text_w = (left_w - text_inset).max(48.0);
if first_anchor.is_none() && anchors.contains(&line.id) {
first_anchor = Some(total);
}
let (_, text_w) = row_column(line.element, text_inset, left_w, space);
// Measure the rendered font instead of assigning a fixed row height.
// The cap also scales with the font, preserving up to 12 visible lines.
let galley = ui.painter().layout(line.text.clone(), font.clone(), app.tokens.text, text_w);
let height = (galley.size().y + 4.0).clamp(MIN_ROW_H, max_height);
let galley = row_galley(ui, line, font.clone(), app.tokens.text, text_w);
let height = (galley.size().y + spacing).clamp(min_row, max_height);
total += height;
tops.push(total);
}
if let Some(anchor_y) = first_anchor {
let extra = thumbnail_height(thumb_w) + TAKE_HEADER_H + 10.0 - anchor_y;
if extra > 0.0 {
for top in &mut tops {
*top += extra;
}
}
}
app.ui.script.row_tops = tops;
app.ui.script.layout_item = app.ui.script.item;
app.ui.script.layout_doc = Some(Arc::clone(doc));
app.ui.script.layout_width = width;
app.ui.script.layout_inset = inset;
app.ui.script.layout_font_size = font_size;
app.ui.script.layout_row_spacing = row_spacing;
app.ui.script.layout_thumbnail_width = thumb_width;
}
@@ -0,0 +1,79 @@
//! Playing a selected candle and timing its rows against the visible Source monitor.
use super::{FilmcraftApp, ItemId, PanelKind, Value, document, execute, json, practice, recovery, take_by_id};
use crate::menus::invoke_command;
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Screening {
take: u64,
source: ItemId,
run: u64,
pub(super) recording: bool,
}
impl Screening {
pub(super) fn take(self) -> u64 {
self.take
}
pub(super) fn records(self, take: u64) -> bool {
self.recording && self.take == take
}
}
pub(crate) fn active_screening(app: &FilmcraftApp) -> Option<Screening> {
let pass = app.ui.script.screening?;
let monitor = practice::visible_source(app);
let playback = &monitor.source_playback;
if !playback.clock.playing || playback.run_id != pass.run || monitor.session.state.source_item != Some(pass.source) {
return None;
}
// The pass owns the transport until it stops, even after another candle is selected.
let take = take_by_id(document(app)?, Some(pass.take))?;
(take.source == Some(pass.source)).then_some(pass)
}
pub(crate) fn toggle_screening(app: &mut FilmcraftApp, ctx: &egui::Context, recording: bool) -> Result<Value, String> {
let selected = app.ui.script.selected_take;
if active_screening(app).is_some_and(|pass| selected != Some(pass.take)) {
// Play or Record on a different candle hands the pass over to that take.
invoke_command(app, ctx, "source.playback.stop", json!({}))?;
app.ui.script.screening = None;
}
if let Some(pass) = active_screening(app) {
if pass.recording == recording {
invoke_command(app, ctx, "source.playback.stop", json!({}))?;
app.ui.script.screening = None;
} else {
app.ui.script.screening = Some(Screening { recording, ..pass });
}
} else {
let take = document(app).and_then(|doc| take_by_id(doc, app.ui.script.selected_take)).ok_or(tl!("Select a candle first."))?;
let source = take.source.filter(|_| !recovery::needs_rebind(app, take)).ok_or(tl!("Reconnect the candle’s source first."))?;
let take = take.id.0;
open_take_source(app, source)?;
app.show_panel(PanelKind::Source);
// Keep the candle reachable even if Source shares its tab group.
app.show_panel(PanelKind::Script);
// Help plays Source in a private session, so its transport cannot stop the live Program.
if practice::example_visible(app) && app.transport_running() {
app.stop();
}
invoke_command(app, ctx, "source.playback.play", json!({}))?;
let run = practice::visible_source(app).source_playback.run_id;
app.ui.script.screening = Some(Screening { take, source, run, recording });
}
Ok(json!({"playing":app.ui.script.screening.is_some(), "recording":app.ui.script.screening.is_some_and(|pass| pass.recording)}))
}
/// Preserve the current source frame when the candle is already cued.
pub(super) fn open_take_source(app: &mut FilmcraftApp, source: ItemId) -> Result<(), String> {
if practice::examples(app, source).is_some() {
return practice::open_example(app, source, None, false);
}
practice::close_example(app);
if app.session.state.source_item != Some(source) {
execute(app, "source.open", json!({"item":source.0, "focus":false}))?;
}
Ok(())
}
@@ -0,0 +1,524 @@
//! Editable Help screenplay, kept in a private editing session for the current visit.
use super::{Arc, FilmcraftApp, ItemId, ItemKind, ScriptDocument, Value, guide_steps, json};
use filmcraft_engine::Session;
use filmcraft_media::{DemoScene, Generator, generators::GeneratorSource};
use filmcraft_project::MediaRef;
use filmcraft_project::{BinEntry, Label, Project, ScriptElement, ScriptLine, ScriptLineId};
use filmcraft_time::Tick;
use std::sync::Weak;
const DIALOGUE_COLUMNS: usize = 35;
/// The private session has the regular engine undo stack and no autosave or file path.
pub(crate) struct Practice {
session: Session,
item: ItemId,
sources: Weak<Project>,
examples: Arc<Project>,
example_slates: Vec<u64>,
preview: Option<Box<FilmcraftApp>>,
}
impl Practice {
fn new(live: &Session) -> Result<Self, String> {
let (doc, passages) = help_document()?;
let mut session = Session::new(live.services.clone());
session.media = live.media.clone();
let mut examples = Project::new(tl!("Help"));
// Private preview IDs sit outside the range of any valid saved project.
let mut example_sources = Vec::new();
for (index, scene) in DemoScene::ALL.into_iter().enumerate() {
examples.next_id = Project::MAX_NEXT_ID + 1 + index as u64;
let existing = live.project.items.values().find(|item| {
item.as_media().is_some_and(|clip| !clip.offline && clip.info.video.is_some() && clip.media == MediaRef::Generator(Generator::Demo(scene)))
});
let source = if let Some(item) = existing {
Arc::make_mut(&mut session.project).items.insert(item.id, item.clone());
item.id
} else {
filmcraft_engine::demo::add_generator(&mut examples, &session.media, GeneratorSource::demo(scene), scene.file_name(), Label::Iris, None)
};
example_sources.push((scene, source));
}
// Opening Help only needs its example sources. Copy the other project items on the first practice operation.
let project = Arc::make_mut(&mut session.project);
project.next_id = live.project.next_id;
project.items.extend(examples.items.clone());
let item = project.add_item(tl!("Help"), Label::Blue, ItemKind::Script(Arc::new(doc)), None);
let mut example_slates = Vec::new();
let mut sources = example_sources.into_iter();
let final_exchange = passages.last().ok_or(tl!("Help script unavailable"))?;
for (index, exchange) in passages.iter().enumerate() {
let mut slate = None;
// Compare two readings of the introduction, then give each numbered step its own setup.
for (scene, source) in sources.by_ref().take(if index == 0 { 2 } else { 1 }) {
exchange.stage(&mut session, item, scene, source, &mut slate, final_exchange)?;
}
if let Some(id) = slate {
example_slates.push(id);
}
}
session.history.clear();
Ok(Self { session, item, sources: Weak::new(), examples: Arc::new(examples), example_slates, preview: None })
}
fn doc(&self) -> Option<&Arc<ScriptDocument>> {
match &self.session.project.item(self.item)?.kind {
ItemKind::Script(doc) => Some(doc),
_ => None,
}
}
fn install(session: &mut Session, live: &Session, examples: &Project, doc: Arc<ScriptDocument>) -> ItemId {
// Keep the current sources available to ordinary take, cue, and relink commands.
// Help is the only script in this snapshot, including for batch rebind.
let mut project = Project::new(tl!("Help"));
project.next_id = live.project.next_id;
for item in live.project.items.values().filter(|item| item.as_script().is_none()) {
project.root.children.push(BinEntry::Item(item.id));
project.items.insert(item.id, item.clone());
}
project.items.extend(examples.items.iter().map(|(id, item)| (*id, item.clone())));
let item = project.add_item(tl!("Help"), Label::Blue, ItemKind::Script(doc), None);
session.project = Arc::new(project);
item
}
}
/// Author each speech as individually markable screenplay lines. Resizing and
/// changing the viewer font can soft-wrap these lines without moving their marks.
fn speech(rows: &mut Vec<(ScriptElement, String)>, character: &str, dialogue: &str) -> std::ops::RangeInclusive<usize> {
rows.push((ScriptElement::Action, String::new()));
rows.push((ScriptElement::Character, character.to_owned()));
let first = rows.len();
let mut line = String::new();
let mut columns = 0;
for word in dialogue.split_whitespace() {
let length = word.chars().count();
if !line.is_empty() && columns + 1 + length > DIALOGUE_COLUMNS {
rows.push((ScriptElement::Dialogue, std::mem::take(&mut line)));
columns = 0;
}
if !line.is_empty() {
line.push(' ');
columns += 1;
}
line.push_str(word);
columns += length;
}
rows.push((ScriptElement::Dialogue, line));
first..=rows.len() - 1
}
struct HelpExchange {
question: ScriptLineId,
question_end: ScriptLineId,
reply: ScriptLineId,
end: ScriptLineId,
}
impl HelpExchange {
fn stage(
&self,
session: &mut Session,
item: ItemId,
scene: DemoScene,
source: ItemId,
slate: &mut Option<u64>,
final_exchange: &HelpExchange,
) -> Result<(), String> {
let resets = match scene {
DemoScene::Dunes => 2,
DemoScene::Plasma => 3,
_ => 1,
};
let view = filmcraft_engine::clip_ops::source_view(session, source).ok_or(tl!("Example clip unavailable"))?;
let frames = view.rate.frame_at(view.end - view.start);
for reset in 0..resets {
let question_only = scene == DemoScene::Dunes && reset == 0;
let end = if question_only {
self.question_end
} else if scene == DemoScene::Forest {
final_exchange.end
} else {
self.end
};
let added = session
.execute("script.addTake", json!({"item":item.0,"source":source.0,"slate":*slate,"startLine":self.question.0,"endLine":end.0}))
.map_err(|e| e.to_string())?;
*slate = added["slate"].as_u64();
// Treat each reset as a separate reading within the same source clip.
let first_frame = frames * reset / resets;
let reply_frame = first_frame + frames / (3 * resets);
let mut marks = vec![(self.question, first_frame)];
if !question_only {
marks.push((self.reply, reply_frame));
}
if scene == DemoScene::Forest {
marks.extend([(final_exchange.question, frames * 2 / 3), (final_exchange.reply, frames * 5 / 6)]);
}
for (line, frame) in marks {
let time = view.start + view.rate.tick_of(frame);
session.execute("script.addMark", json!({"item":item.0,"take":added["take"],"line":line.0,"sourceTime":time.0})).map_err(|e| e.to_string())?;
}
}
Ok(())
}
}
fn help_document() -> Result<(ScriptDocument, Vec<HelpExchange>), String> {
let mut rows = vec![(ScriptElement::Action, String::new()); ScriptDocument::LEADING_SETUP_ROWS];
rows.push((ScriptElement::SceneHeading, tl!("INT. CUTTING ROOM - DAY").to_owned()));
let question = speech(&mut rows, tl!("USER"), tl!("What’s a lined script for?"));
let answer = speech(
&mut rows,
tl!("HELP"),
tl!(
"In scripted film and TV, editors use it to see which takes cover each line and compare readings of the same dialogue. These clips are examples. Usually you’d see actors delivering these lines."
),
);
let mut passages = vec![[*question.start(), *question.end(), *answer.start(), *answer.end()]];
for (index, (_, _, question, answer)) in guide_steps().into_iter().enumerate() {
let question = speech(&mut rows, tl!("USER"), question);
let answer = speech(&mut rows, tl!("HELP"), &tlf!("Step #{number}: {answer}", number = index + 1, answer));
passages.push([*question.start(), *question.end(), *answer.start(), *answer.end()]);
}
rows.push((ScriptElement::Action, String::new()));
let mut doc = ScriptDocument::new();
for (element, text) in rows {
let id = ScriptLineId(doc.alloc_id()?);
let scene = (element == ScriptElement::SceneHeading).then(|| "1".to_owned());
doc.lines.push(ScriptLine { id, text, element: Some(element), scene, page: None });
}
doc.validate()?;
let coverage = passages
.into_iter()
.map(|indices| {
let [question, question_end, reply, end] = indices.map(|i| doc.lines[i].id);
HelpExchange { question, question_end, reply, end }
})
.collect();
Ok((doc, coverage))
}
pub(super) fn open(app: &mut FilmcraftApp) {
close_example(app);
match Practice::new(&app.session) {
Ok(help) => {
app.ui.script.ensure_tab(None);
app.ui.script.reset_document(None);
app.script_practice = Some(help);
app.ui.script.practicing = true;
app.ui.script.scroll_to_line = document(app).and_then(|doc| doc.lines.first()).map(|line| line.id.0);
}
Err(error) => app.ui.status = error,
}
}
pub(super) fn document(app: &FilmcraftApp) -> Option<&Arc<ScriptDocument>> {
if let Some(id) = app.ui.script.item {
match &app.session.project.item(ItemId(id))?.kind {
ItemKind::Script(doc) => Some(doc),
_ => None,
}
} else {
practice(app)?.doc()
}
}
fn practice(app: &FilmcraftApp) -> Option<&Practice> {
app.script_practice.as_ref().filter(|_| app.ui.script.practicing)
}
/// Stagger the staged thumbnails so the next one leaves the preceding candle visible.
pub(super) fn example_lane(app: &FilmcraftApp, slate: u64) -> Option<usize> {
practice(app)?.example_slates.iter().position(|&id| id == slate).map(|index| index % 2)
}
pub(super) fn revision(app: &FilmcraftApp) -> u64 {
practice(app).map_or(app.session.revision, |help| help.session.revision)
}
pub(crate) fn history_enabled(app: &FilmcraftApp, id: &str) -> Option<bool> {
let help = practice(app)?;
match id {
"edit.undo" => Some(help.session.history.can_undo()),
"edit.redo" => Some(help.session.history.can_redo()),
_ => None,
}
}
pub(crate) fn execute(app: &mut FilmcraftApp, id: &str, mut params: Value) -> Result<Value, String> {
let history = matches!(id, "edit.undo" | "edit.redo");
let practice_edit = id.starts_with("script.") && params.get("item").is_some_and(Value::is_null);
if !app.ui.script.practicing || !(history || practice_edit) {
return app.session.execute(id, params).map_err(|e| e.to_string());
}
let help = app.script_practice.as_mut().ok_or(tl!("Open Help first"))?;
if history {
let result = help.session.execute(id, params).map_err(|e| e.to_string())?;
// Undo may restore an earlier snapshot, with different source items and IDs.
help.item = help.session.project.items.values().find(|item| item.as_script().is_some()).ok_or(tl!("Help script unavailable"))?.id;
help.sources = Weak::new();
return Ok(result);
}
if !Weak::ptr_eq(&help.sources, &Arc::downgrade(&app.session.project)) {
let doc = help.doc().cloned().ok_or(tl!("Help script unavailable"))?;
help.item = Practice::install(&mut help.session, &app.session, &help.examples, doc);
help.sources = Arc::downgrade(&app.session.project);
}
help.session.prefs.timeline = app.session.prefs.timeline.clone();
help.session.prefs.playback.lined_script_preroll_seconds = app.session.prefs.playback.lined_script_preroll_seconds;
params["item"] = json!(help.item.0);
let focus = params["focus"].as_bool().unwrap_or(true);
let result = help.session.execute(id, params).map_err(|e| e.to_string())?;
if matches!(id, "script.cueLine" | "script.cueMark") {
if let Some(source) = help.session.state.source_item.filter(|id| help.examples.item(*id).is_some()) {
let time = help.session.state.source_playhead;
open_example(app, source, Some(time), focus)?;
return Ok(result);
}
close_example(app);
app.session.execute("source.open", json!({"item":result["item"], "focus":focus})).map_err(|e| e.to_string())?;
app.session.execute("source.setPlayhead", json!({"time":result["time"]})).map_err(|e| e.to_string())?;
}
Ok(result)
}
/// An example that isn't in the user's bins uses a private Source monitor. Its
/// ordinary playback, marks and transport can never edit or save the user's project.
pub(super) fn examples(app: &FilmcraftApp, source: ItemId) -> Option<Arc<Project>> {
let project = &practice(app)?.examples;
project.item(source).map(|_| project.clone())
}
pub(super) fn source_session(app: &FilmcraftApp, source: ItemId) -> &Session {
practice(app).filter(|help| help.examples.item(source).is_some()).map_or(&app.session, |help| &help.session)
}
pub(super) fn visible_source(app: &FilmcraftApp) -> &FilmcraftApp {
visible_example(app).unwrap_or(app)
}
pub(crate) fn example_visible(app: &FilmcraftApp) -> bool {
visible_example(app).is_some()
}
fn visible_example(app: &FilmcraftApp) -> Option<&FilmcraftApp> {
app.script_practice
.as_ref()
.and_then(|help| help.preview.as_deref())
.filter(|preview| Arc::ptr_eq(&preview.session.project_instance, &app.session.project_instance))
}
pub(crate) fn example_monitor(app: &mut FilmcraftApp) -> Option<&mut FilmcraftApp> {
app.script_practice.as_mut()?.preview.as_deref_mut()
}
pub(crate) fn with_example_monitor<R>(app: &mut FilmcraftApp, show: impl FnOnce(&mut FilmcraftApp) -> R) -> Option<R> {
if app.script_practice.as_ref()?.preview.as_ref().is_some_and(|monitor| !Arc::ptr_eq(&monitor.session.project_instance, &app.session.project_instance)) {
close_example(app);
}
let monitor = app.script_practice.as_mut()?.preview.as_deref_mut()?;
monitor.tokens = app.tokens;
monitor.ui.language = app.ui.language;
std::mem::swap(&mut monitor.audio, &mut app.audio);
std::mem::swap(&mut monitor.auto, &mut app.auto);
let result = show(monitor);
std::mem::swap(&mut monitor.auto, &mut app.auto);
std::mem::swap(&mut monitor.audio, &mut app.audio);
Some(result)
}
pub(crate) fn close_example(app: &mut FilmcraftApp) {
if let Some(mut monitor) = app.script_practice.as_mut().and_then(|help| help.preview.take()) {
std::mem::swap(&mut monitor.audio, &mut app.audio);
monitor.stop_source();
std::mem::swap(&mut monitor.audio, &mut app.audio);
}
}
pub(super) fn open_example(app: &mut FilmcraftApp, source: ItemId, time: Option<Tick>, focus: bool) -> Result<(), String> {
app.stop_source();
let help = app.script_practice.as_mut().ok_or(tl!("Open Help first"))?;
let monitor = help.preview.get_or_insert_with(|| {
let mut session = Session::new(app.session.services.clone());
session.project = help.examples.clone();
session.project_instance = app.session.project_instance.clone();
session.media = app.session.media.clone();
session.prefs = app.session.prefs.clone();
let mut monitor = Box::new(FilmcraftApp::with_frames(session, app.frames.clone()));
monitor.ui.focused = crate::dock::PanelKind::Source;
monitor
});
if time.is_some() || monitor.session.state.source_item != Some(source) {
std::mem::swap(&mut monitor.audio, &mut app.audio);
monitor.stop_source();
std::mem::swap(&mut monitor.audio, &mut app.audio);
monitor.session.execute("source.open", json!({"item": source.0})).map_err(|e| e.to_string())?;
if let Some(time) = time {
monitor.session.execute("source.setPlayhead", json!({"time":time.0})).map_err(|e| e.to_string())?;
}
drop(monitor.session.drain_events());
}
let previous = app.ui.focused;
app.show_panel(crate::dock::PanelKind::Source);
if !focus {
app.ui.focused = previous;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn each_help_exchange_has_example_coverage_and_marks_on_both_speakers() {
let help = Practice::new(&Session::default()).unwrap();
let doc = help.doc().unwrap();
let mut covered = std::collections::HashSet::new();
let mut sources = std::collections::HashSet::new();
assert_eq!(doc.slates.len(), guide_steps().len() + 1);
let last_dialogue = doc.lines.iter().rev().find(|line| line.element == Some(ScriptElement::Dialogue)).unwrap().id;
for setup in &doc.slates {
for take in &setup.takes {
sources.insert(take.source.unwrap());
let (start, end) = doc.line_range(take.start_line, take.end_line).unwrap();
let passage = &doc.lines[start..=end];
covered.extend(passage.iter().map(|line| line.id));
let speech_starts = std::iter::once(take.start_line)
.chain(passage.windows(2).filter(|pair| pair[0].element == Some(ScriptElement::Character)).map(|pair| pair[1].id));
assert!(take.marks.iter().map(|mark| mark.line).eq(speech_starts));
assert!(take.marks.windows(2).all(|pair| pair[0].source_time < pair[1].source_time));
}
}
assert_eq!(sources.len(), DemoScene::ALL.len());
let setup = |scene: DemoScene| doc.slates.iter().find(|setup| setup.name == scene.file_name()).unwrap();
let dunes = &setup(DemoScene::Dunes).takes;
assert_eq!(dunes.len(), 2);
assert_eq!(dunes[0].source, dunes[1].source);
assert_eq!(dunes[0].start_line, dunes[1].start_line);
let (_, first_end) = doc.line_range(dunes[0].start_line, dunes[0].end_line).unwrap();
assert_eq!(doc.lines[first_end].element, Some(ScriptElement::Dialogue));
assert!(doc.lines[first_end + 1].text.is_empty());
assert_eq!(dunes[0].marks.len(), 1);
assert_eq!(dunes[1].marks.len(), 2);
assert_eq!(setup(DemoScene::Forest).takes[0].end_line, last_dialogue);
let neon = &setup(DemoScene::Plasma).takes;
assert_eq!(neon.len(), 3);
assert!(neon.windows(2).all(|pair| pair[0].source == pair[1].source && pair[0].marks[1].source_time < pair[1].marks[0].source_time));
assert!(doc.lines.iter().filter(|line| line.element == Some(ScriptElement::Dialogue)).all(|line| covered.contains(&line.id)));
}
#[test]
fn help_mark_respects_changes_to_the_playback_preference() {
let mut app = FilmcraftApp::new(Session::default());
open(&mut app);
let original = document(&app).unwrap().clone();
let take = &original.slates[0].takes[0];
let mark = &take.marks[1];
let params = json!({"item":null,"take":take.id,"mark":mark.id});
let lead_in = execute(&mut app, "script.cueMark", params.clone()).unwrap();
app.session.execute("prefs.set", json!({"key":"playback.linedScriptPrerollSeconds","value":0.0})).unwrap();
let exact = execute(&mut app, "script.cueMark", params).unwrap();
assert_eq!(exact["time"], mark.source_time.0);
assert!(lead_in["time"].as_i64().unwrap() < mark.source_time.0);
assert_eq!(example_monitor(&mut app).unwrap().session.state.source_playhead, mark.source_time);
assert_eq!(document(&app).unwrap(), &original);
}
#[test]
fn example_transport_respects_explicit_targets_and_protects_the_sequence() {
use crate::{dock::PanelKind, menus::invoke_command};
let mut session = Session::default();
session.execute("file.newSequence", json!({"name":"Program","fps":24})).unwrap();
let mut app = FilmcraftApp::new(session);
let ctx = egui::Context::default();
open(&mut app);
let source = document(&app).unwrap().slates[0].takes[0].source.unwrap();
open_example(&mut app, source, None, false).unwrap();
app.ui.focused = PanelKind::Timeline;
let live_time = app.session.state.source_playhead;
invoke_command(&mut app, &ctx, "source.setPlayhead", json!({"seconds":1})).unwrap();
assert!(example_monitor(&mut app).unwrap().session.state.source_playhead > Tick::ZERO);
assert_eq!(app.session.state.source_playhead, live_time);
app.ui.focused = PanelKind::Source;
let before = app.session.active_sequence().unwrap().markers.len();
invoke_command(&mut app, &ctx, "markers.add", json!({"target":"program","seconds":1})).unwrap();
assert_eq!(app.session.active_sequence().unwrap().markers.len(), before + 1);
let project = app.session.project.clone();
for command in ["source.insert", "source.overwrite"] {
assert_eq!(invoke_command(&mut app, &ctx, command, json!({})).unwrap_err(), tl!("Open a project clip in Source to insert or overwrite."));
assert!(Arc::ptr_eq(&project, &app.session.project));
}
}
#[test]
fn recording_help_uses_its_private_source_and_disarms_after_transport_restarts() {
let mut app = FilmcraftApp::new(Session::default());
app.session.execute("file.newSequence", json!({})).unwrap();
open(&mut app);
let project = app.session.project.clone();
let doc = document(&app).unwrap().clone();
let take = &doc.slates[0].takes[0];
let mark = &take.marks[0];
app.ui.script.selected_take = Some(take.id.0);
app.ui.script.selected_lines = Some((mark.line.0, mark.line.0));
let ctx = egui::Context::default();
open_example(&mut app, take.source.unwrap(), Some(Tick::from_seconds_f64(1.0)), false).unwrap();
let time = visible_source(&app).session.state.source_playhead;
app.play(1.0);
assert!(app.playback.playing);
super::super::toggle_screening(&mut app, &ctx, true).unwrap();
assert!(!app.playback.playing, "starting a Help pass stops Program");
assert_eq!(visible_source(&app).session.state.source_playhead, time);
super::super::add_mark_at_selection(&mut app).unwrap();
assert_eq!(document(&app).unwrap().take(take.id).unwrap().marks[0].source_time, time);
assert!(visible_source(&app).source_playback.clock.playing);
let preview = example_monitor(&mut app).unwrap();
preview.stop_source();
preview.play_source().unwrap();
assert!(super::super::active_screening(&app).is_none());
assert!(app.session.state.source_item.is_none());
assert!(Arc::ptr_eq(&app.session.project, &project));
}
#[test]
fn sample_takes_cue_and_mark_in_an_empty_project_without_becoming_project_media() {
let mut app = FilmcraftApp::new(Session::default());
let live = app.session.project.clone();
open(&mut app);
let doc = document(&app).unwrap().clone();
let slate = doc.slates.first().expect("opening setup");
let [first, second] = slate.takes.as_slice() else { panic!("expected two example takes") };
assert_ne!(first.source, second.source);
assert_eq!(first.start_line, second.start_line);
assert_eq!(first.end_line, second.end_line);
assert_eq!(doc.lines[doc.line_index(first.start_line).unwrap()].element, Some(ScriptElement::Dialogue));
assert!(!history_enabled(&app, "edit.undo").unwrap());
for take in &slate.takes {
execute(&mut app, "script.cueLine", json!({"item":null,"take":take.id.0,"line":take.start_line.0})).unwrap();
let monitor = example_monitor(&mut app).unwrap();
assert_eq!(monitor.session.state.source_item, take.source);
assert!(monitor.session.source(take.source.unwrap()).is_some());
monitor.session.execute("source.setPlayhead", json!({"seconds":2})).unwrap();
let time = monitor.session.state.source_playhead;
let [question, answer] = take.marks.as_slice() else { panic!("expected both dialogue cues") };
assert_eq!(question.line, take.start_line);
assert!(doc.lines[doc.line_index(answer.line).unwrap()].text.starts_with("In scripted film"));
assert!(answer.source_time > question.source_time);
app.ui.script.selected_mark = Some(question.id.0);
app.ui.script.selected_take = Some(take.id.0);
app.ui.script.selected_lines = Some((take.start_line.0, take.start_line.0));
crate::panels::script::add_mark_at_selection(&mut app).unwrap();
assert_eq!(document(&app).unwrap().take(take.id).unwrap().marks[0].source_time, time);
}
open(&mut app);
assert_eq!(document(&app).unwrap().slates, doc.slates);
assert!(Arc::ptr_eq(&live, &app.session.project));
assert!(app.session.state.source_item.is_none());
}
}
+6 -2
View File
@@ -3,7 +3,7 @@
use super::{Action, FilmcraftApp, ItemId, ItemKind, ScriptTake};
fn source_missing(app: &FilmcraftApp, source: ItemId) -> bool {
let Some(item) = app.session.project.item(source) else { return true };
let Some(item) = app.session.project.item(source) else { return super::practice::examples(app, source).is_none() };
match &item.kind {
ItemKind::Media(_) | ItemKind::Subclip { .. } => app
.session
@@ -36,7 +36,11 @@ pub(super) fn source_menu(app: &mut FilmcraftApp, ui: &mut egui::Ui, take: &Scri
let response = ui
.add_enabled(source.is_some(), egui::Button::new(tl!("Rebind to Selected Project Clip")))
.on_disabled_hover_text(tl!("Select one available media clip, subclip, or multicamera source in Project first."))
.on_hover_text(tl!("Reconnect every matching candle in all scripts. Matching footage keeps its marks; other replacements require review."));
.on_hover_text(if app.ui.script.practicing {
tl!("Reconnect matching practice candles. Changes reset when you leave Help.")
} else {
tl!("Reconnect every matching candle in all scripts. Matching footage keeps its marks; other replacements require review.")
});
app.auto.add(&format!("script.take.{}.rebindSelected", take.id.0), response.rect, "Rebind to Selected Project Clip");
if response.clicked()
&& let Some(source) = source
+42 -7
View File
@@ -6,40 +6,75 @@ use super::{ScriptDocument, ScriptLine, ScriptTake, ScriptUi};
impl ScriptUi {
/// A new project can reuse the same item IDs. Its edits and take links need a fresh owner.
pub(crate) fn sync_project(&mut self, project: &Arc<()>) {
pub(crate) fn sync_project(&mut self, project: &Arc<()>, view: &filmcraft_project::ScriptTabsView) {
if let Some(previous) = &self.project {
if Arc::ptr_eq(previous, project) {
return;
}
self.open_document(None);
self.tabs.clear();
self.reset_document(None);
self.section_clipboard = None;
}
if !view.open.is_empty() {
self.tabs = view.open.iter().map(|id| super::tabs::ScriptTab { item: id.map(|id| id.0), ..Default::default() }).collect();
self.item = view.active.map(|id| id.0);
}
self.project = Some(project.clone());
}
/// IDs belong to one script. Retain view preferences and the cross-script clipboard,
/// but never carry an edit, drag or replacement confirmation into another document.
pub(crate) fn open_document(&mut self, item: Option<u64>) {
if self.item == item {
self.ensure_tab(item);
if self.item == item && !self.practicing {
return;
}
let previous = std::mem::take(self);
self.reset_document(item);
}
pub(super) fn reset_document(&mut self, item: Option<u64>) {
let mut previous = std::mem::take(self);
if let Some(tab) = previous.tabs.iter_mut().find(|tab| tab.item.is_some() && tab.item == previous.item) {
tab.selected_lines = previous.selected_lines;
tab.take_scroll = previous.take_scroll;
}
let tab = previous.tabs.iter().find(|tab| item.is_some() && tab.item == item);
*self = Self {
item,
selected_lines: tab.and_then(|tab| tab.selected_lines),
take_scroll: tab.map_or(0.0, |tab| tab.take_scroll),
tabs: previous.tabs,
project: previous.project,
paint_color: previous.paint_color,
edit_mode: previous.edit_mode,
section_clipboard: previous.section_clipboard,
text_column_width: previous.text_column_width,
text_inset: previous.text_inset,
font_size: previous.font_size,
row_spacing: previous.row_spacing,
thumbnail_width: previous.thumbnail_width,
candle_width: previous.candle_width,
candle_distance: previous.candle_distance,
keep_thumbnails_visible: previous.keep_thumbnails_visible,
show_row_colors: previous.show_row_colors,
show_line_numbers: previous.show_line_numbers,
hide_page_numbers: previous.hide_page_numbers,
show_page_controls: previous.show_page_controls,
search: previous.search,
..Self::default()
};
}
pub(crate) fn is_practicing(&self) -> bool {
self.practicing
}
pub(crate) fn leave_practice(&mut self) {
if self.practicing {
self.reset_document(None);
}
}
pub(super) fn clear_object_selection(&mut self) {
self.selected_mark = None;
self.selected_take = None;
@@ -89,14 +124,14 @@ mod tests {
let first = Arc::new(());
let second = Arc::new(());
let mut state = ScriptUi::default();
state.sync_project(&first);
state.sync_project(&first, &Default::default());
state.open_document(Some(1));
state.selected_take = Some(2);
state.section_clipboard = Some(serde_json::json!({"lines":[],"slates":[]}));
state.sync_project(&first);
state.sync_project(&first, &Default::default());
assert_eq!(state.selected_take, Some(2));
assert!(state.section_clipboard.is_some());
state.sync_project(&second);
state.sync_project(&second, &Default::default());
state.open_document(Some(1));
assert_eq!(state.selected_take, None);
assert!(state.section_clipboard.is_none());
+187
View File
@@ -0,0 +1,187 @@
//! Open document views. The internal Help tab has no Project item ID.
use super::{FilmcraftApp, ItemId, Rect, ScriptUi, practice};
use crate::dock::{DocumentTab, document_tab_drag};
use egui::{Key, Sense, vec2};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub(super) struct ScriptTab {
pub(super) item: Option<u64>,
pub(super) selected_lines: Option<(u64, u64)>,
pub(super) take_scroll: f32,
}
impl ScriptUi {
pub(super) fn ensure_tab(&mut self, item: Option<u64>) {
if !self.tabs.iter().any(|tab| tab.item == item) {
self.tabs.push(ScriptTab { item, ..Default::default() });
}
}
}
pub(crate) fn activate(app: &mut FilmcraftApp, item: Option<u64>) {
if item.is_some() {
app.ui.script.open_document(item);
} else if !app.ui.script.practicing {
practice::open(app);
}
remember_tabs(app);
}
fn remember_tabs(app: &mut FilmcraftApp) {
let state = &app.ui.script;
let view = &mut app.session.state.script_tabs;
view.open.clear();
view.open.extend(state.tabs.iter().map(|tab| tab.item.map(ItemId)));
view.active = state.item.map(ItemId);
}
pub(super) fn reconcile(app: &mut FilmcraftApp) {
let project = &app.session.project;
let exists = |id| project.item(ItemId(id)).is_some_and(|item| item.as_script().is_some());
let state = &mut app.ui.script;
let previous_count = state.tabs.len();
state.tabs.retain(|tab| tab.item.is_none_or(exists));
if state.item.is_some_and(exists) {
// Older saved views only have the active item's ID.
state.ensure_tab(state.item);
if state.tabs.len() != previous_count {
remember_tabs(app);
}
} else if !state.practicing {
let next = if state.item.is_none() && state.tabs.iter().any(|tab| tab.item.is_none()) { None } else { state.tabs.last().and_then(|tab| tab.item) };
activate(app, next);
} else if state.tabs.len() != previous_count {
remember_tabs(app);
}
}
fn close(app: &mut FilmcraftApp, item: Option<u64>) {
let state = &mut app.ui.script;
let Some(index) = state.tabs.iter().position(|tab| tab.item == item) else { return };
state.tabs.remove(index);
if state.item == item {
let next = state.tabs.get(index).or_else(|| state.tabs.last()).and_then(|tab| tab.item);
activate(app, next);
}
}
pub(super) fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, strip: Rect) {
let t = app.tokens;
let active = app.ui.script.item;
let can_close_help = app.ui.script.tabs.len() > 1;
let mut switch = None;
let mut closing = None;
let mut reorder = None;
let title = tl!("Open scripts");
let mut strip_ui =
ui.new_child(egui::UiBuilder::new().id_salt("script.tabs").max_rect(strip).accessibility_role(egui::Role::TabList).accessibility_label(title));
app.auto.add("script.tabs", strip, title);
let selection_id = strip_ui.scope_id().with("active");
let selection = (active, app.ui.script.tabs.iter().position(|tab| tab.item == active));
let changed = strip_ui.data_mut(|data| {
let previous = data.get_temp(selection_id);
data.insert_temp(selection_id, selection);
previous != Some(selection)
});
strip_ui.painter().rect_filled(strip, 0.0, t.tab_bg);
egui::ScrollArea::horizontal().id_salt("open").animated(false).max_height(strip.height()).auto_shrink([false, false]).show(&mut strip_ui, |ui| {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 0.0;
ui.add_space(DocumentTab::STRIP_INSET);
let mut tab_responses = Vec::with_capacity(app.ui.script.tabs.len());
for (index, tab) in app.ui.script.tabs.iter().enumerate() {
let item = tab.item;
let name = item.and_then(|id| app.session.project.item(ItemId(id))).map_or(tl!("Help"), |it| it.name.as_str());
let key = item.map_or_else(|| "help".into(), |id| id.to_string());
let selected = item == active;
let closable = item.is_some() || can_close_help;
let tab = DocumentTab::new(ui.painter(), name, selected, closable);
let width = tab.width().min(strip.width().clamp(40.0, 240.0));
let truncated = tab.width() > width;
let (_, rect) = ui.allocate_space(vec2(width, strip.height()));
let response = ui.interact(rect, egui::Id::unique(("script.tab", item)), Sense::click_and_drag());
app.auto.add_response(&format!("script.tab.{key}"), &response, name);
let painter = ui.painter().clone();
if let Some(close) = tab.show(ui, &painter, &response, response.id.with("close"), &t) {
let label = tlf!("Close {name}", name = name);
close.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, close.enabled(), &label));
app.auto.add_response(&format!("script.tab.{key}.close"), &close, &label);
if close.clicked() {
closing = Some(item);
}
close.on_hover_text(label);
}
if closable && response.middle_clicked() {
closing = Some(item);
}
if response.dragged_by(egui::PointerButton::Primary)
&& let Some(pos) = response.interact_pointer_pos()
&& strip.y_range().contains(pos.y)
{
// Reveal neighbours past the edge of the horizontal scroll area.
let edge = ui.spacing().interact_size.y.min(strip.width() / 2.0);
let speed = (strip.left() + edge - pos.x).clamp(0.0, edge) - (pos.x - strip.right() + edge).clamp(0.0, edge);
if speed != 0.0 {
ui.scroll_with_delta(vec2(speed * 12.0 * ui.input(|i| i.stable_dt.min(0.1)), 0.0));
}
}
if response.clicked() || response.drag_started_by(egui::PointerButton::Primary) {
switch = Some(item);
}
if response.has_focus() {
ui.memory_mut(|m| m.set_focus_lock_filter(response.id, egui::EventFilter { horizontal_arrows: true, ..Default::default() }));
let shift = ui.input(|i| i.modifiers.shift);
let modifiers = if shift { egui::Modifiers::SHIFT } else { egui::Modifiers::NONE };
let next = ui.input_mut(|i| {
if i.consume_key(modifiers, Key::ArrowRight) {
Some(index + 1)
} else if i.consume_key(modifiers, Key::ArrowLeft) {
index.checked_sub(1)
} else {
None
}
});
if let Some(next) = next.filter(|&next| next < app.ui.script.tabs.len()) {
if shift {
reorder = Some((index, next));
switch = Some(item);
} else {
switch = Some(app.ui.script.tabs[next].item);
}
}
}
if truncated {
response.clone().on_hover_text(name);
}
if selected && changed {
ui.scroll_to_rect(rect, None);
}
tab_responses.push(response);
ui.add_space(DocumentTab::GAP);
}
reorder = reorder.or_else(|| document_tab_drag(&tab_responses, 0));
});
});
if (closing == Some(active) || switch.is_some_and(|item| item != active)) && !super::finish_script_fields(app) {
return;
}
if let Some((from, to)) = reorder {
let tabs = &mut app.ui.script.tabs;
let tab = tabs.remove(from);
tabs.insert(to.min(tabs.len()), tab);
remember_tabs(app);
ui.ctx().request_repaint();
}
if let Some(item) = closing {
close(app, item);
switch = Some(app.ui.script.item);
}
if let Some(item) = switch {
activate(app, item);
ui.memory_mut(|m| {
m.move_focus(egui::FocusDirection::None);
m.request_focus(egui::Id::unique(("script.tab", item)));
});
}
}
+594 -278
View File
@@ -1,244 +1,282 @@
//! Script toolbar, settings, and keyboard coverage controls.
//! Lined Script toolbar, settings, and keyboard coverage controls.
use super::{
Action, Arc, DEFAULT_TEXT_INSET, FilmcraftApp, ItemId, MAX_THUMB_W, MIN_THUMB_W, PanelKind, Rect, SCRIPT_FONT_SIZE, ScriptColor, ScriptDocument, Stroke,
current_line, guide_contents, json, pos2, script_color, select_line, select_source_match, selected_take_lines, source_matches, take_by_id, thumbnail_width,
vec2,
Action, Arc, FilmcraftApp, ItemId, MAX_THUMB_W, MIN_THUMB_W, PanelKind, Rect, ScriptColor, ScriptDocument, Stroke, current_line, guide_contents, json,
pos2, script_color, select_line, select_source_match, selected_take_lines, source_matches, take_by_id, thumbnail_width, vec2,
};
pub(super) fn header(
app: &mut FilmcraftApp,
ui: &mut egui::Ui,
rect: Rect,
scripts: &[(ItemId, String)],
doc: Option<&Arc<ScriptDocument>>,
actions: &mut Vec<Action>,
) -> f32 {
const BUTTON: f32 = 24.0;
const SEARCH_MIN: f32 = 96.0;
const SEARCH_PREFERRED: f32 = 140.0;
enum CenterControl {
Jump { scene: bool, caption_width: f32 },
Search,
SearchCount,
Edit,
Annotations,
Transport,
FindSource(u64),
}
pub(super) fn header(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, actions: &mut Vec<Action>) -> f32 {
let active = super::document(app).cloned();
let doc = active.as_deref();
let t = app.tokens;
let help_rect = Rect::from_min_size(pos2((rect.right() - 37.0).max(rect.left()), rect.top() + 4.0), vec2(29.0, ui.spacing().interact_size.y.max(23.0)));
let mut help_ui = ui.new_child(egui::UiBuilder::new().max_rect(help_rect).layout(egui::Layout::right_to_left(egui::Align::Center)));
let help = help_ui.add(egui::Button::new("?").min_size(vec2(29.0, 23.0))).on_hover_text(tl!("Script help"));
app.auto.add("script.help", help.rect, "Script help");
let help_width = (ui.ctx().content_rect().width() - 32.0).clamp(1.0, 640.0);
let help_height = (ui.ctx().content_rect().height() - 120.0).max(1.0);
egui::Popup::menu(&help).width(help_width).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {
ui.set_width(help_width);
egui::ScrollArea::vertical().id_salt("script.help.scroll").max_height(help_height).show(ui, |ui| {
guide_contents(app, ui, "script.help.guide");
});
let gap = ui.spacing().item_spacing.x;
let inner = rect.shrink2(vec2(8.0, 0.0));
let width = inner.width().max(1.0);
let top = rect.top() + 4.0;
let import_label = tl!("Import");
let blank_label = tl!("Blank");
let [import_width, blank_width] = pair_widths(ui, [import_label, blank_label], &t);
let files_width = import_width + blank_width;
let left = Rect::from_min_size(pos2(inner.left(), top), vec2(files_width, BUTTON));
let mut files = toolbar_cell(ui, "files", left);
group(&mut files, files_width, |ui| {
let import = ui.add(segment(import_label, import_width, true, false)).on_hover_text(tl!("Plain text .txt supported."));
app.auto.add_response("script.import", &import, import_label);
if import.clicked() {
actions.push(Action::Import);
}
let blank = ui.add(segment(blank_label, blank_width, false, true));
app.auto.add_response("script.new", &blank, blank_label);
if blank.clicked() {
actions.push(Action::Create);
}
});
let mut top = ui.new_child(egui::UiBuilder::new().max_rect(Rect::from_min_max(rect.min + vec2(8.0, 4.0), rect.max - vec2(45.0, 0.0))));
let controls = top.horizontal_wrapped(|ui| {
let name =
app.ui.script.item.and_then(|id| scripts.iter().find(|entry| entry.0.0 == id).map(|entry| entry.1.as_str())).unwrap_or(tl!("Choose a script"));
let document = crate::legacy_dropdown::Dropdown::from_id_salt("script.document").selected_text(name).width(180.0).show_ui(ui, |ui| {
for (id, name) in scripts {
let response = ui.selectable_label(app.ui.script.item == Some(id.0), name);
app.auto.add(&format!("script.document.{}", id.0), response.rect, name);
if response.clicked() {
app.ui.script.open_document(Some(id.0));
let row_height = BUTTON.max(ui.spacing().interact_size.y);
let stride = row_height + ui.spacing().item_spacing.y;
let edges_fit = files_width + gap + 2.0 * BUTTON <= width;
let right_y = if edges_fit { top } else { top + stride };
let right = Rect::from_min_size(pos2(inner.right() - 2.0 * BUTTON, right_y), vec2(2.0 * BUTTON, BUTTON));
settings_and_help(app, ui, right, rect.width());
let mut controls = Vec::new();
if let Some(doc) = active.as_ref() {
let captions = pair_widths(ui, [tl!("Sc:"), tl!("Pg:")], &t);
let chrome = ui.spacing().icon_width + ui.spacing().icon_spacing + 2.0 * ui.spacing().button_padding.x.min(4.0);
for ((scene, caption_width), label) in [true, false].into_iter().zip(captions).zip(jump_label_widths(ui, doc)) {
if scene || app.ui.script.show_page_controls {
controls.push((CenterControl::Jump { scene, caption_width }, (caption_width + (label + chrome).ceil() + BUTTON).min(width)));
}
}
}
controls.push((CenterControl::Search, (SEARCH_MIN + 2.0 * BUTTON).min(width)));
if doc.is_some() && !app.ui.script.search.is_empty() {
let text = search_count(app);
let measured = ui.painter().layout_no_wrap(text, egui::TextStyle::Body.resolve(ui.style()), t.text).size().x;
controls.push((CenterControl::SearchCount, measured.ceil().min(width)));
}
controls.extend([(CenterControl::Edit, BUTTON), (CenterControl::Transport, 2.0 * BUTTON), (CenterControl::Annotations, 3.0 * BUTTON)]);
if let Some(source) = app.ui.script.find_source {
controls.push((CenterControl::FindSource(source), 190.0_f32.min(width)));
}
// Reserve equal clearance on both sides of the first row. Subsequent rows use the whole panel.
let mut room = (width - 2.0 * (files_width.max(right.width()) + gap)).max(0.0);
let mut y = right_y;
let mut remaining = controls.as_slice();
while !remaining.is_empty() {
let mut used = 0.0;
let mut count = 0;
for (_, w) in remaining {
let next = if count == 0 { *w } else { used + gap + w };
if next > room && (count > 0 || room < width) {
break;
}
used = next;
count += 1;
}
// Pack whole controls at their minimum widths, then give spare room back to Search.
let row = &remaining[..count];
let search_extra =
if row.iter().any(|(control, _)| matches!(control, CenterControl::Search)) { (room - used).clamp(0.0, SEARCH_PREFERRED - SEARCH_MIN) } else { 0.0 };
let mut x = rect.center().x - (used + search_extra) * 0.5;
for (control, w) in row {
let w = if matches!(control, CenterControl::Search) { w + search_extra } else { *w };
let bounds = Rect::from_min_size(pos2(x, y), vec2(w, row_height));
let mut cell = toolbar_cell(ui, control.id(), bounds);
match control {
CenterControl::Jump { scene, caption_width } => {
if let Some(doc) = doc {
jump_field(app, &mut cell, doc, *scene, *caption_width, (w - caption_width - BUTTON).max(1.0));
}
}
CenterControl::Search => search_controls(app, &mut cell, active.as_ref()),
CenterControl::SearchCount => {
let label = cell.label(search_count(app));
app.auto.add("script.search.count", label.rect, "Search result count");
}
CenterControl::Edit => edit_button(app, &mut cell),
CenterControl::Annotations => annotation_buttons(app, &mut cell, doc, actions),
CenterControl::Transport => transport_buttons(app, &mut cell, doc),
CenterControl::FindSource(source) => find_source(app, &mut cell, *source),
}
});
app.auto.add("script.document", document.response.rect, "Choose a script");
let settings = ui.menu_button("⚙", |ui| {
ui.label(tl!("Script settings"));
let mut font_size = app.ui.script.font_size.unwrap_or(SCRIPT_FONT_SIZE);
let size = ui.add(egui::Slider::new(&mut font_size, 10.0..=24.0).text(tl!("Text size")));
app.auto.add("script.settings.textSize", size.rect, "Script text size");
if size.changed() {
app.ui.script.font_size = Some(font_size);
}
let mut thumb_w = thumbnail_width(&app.ui.script);
let thumb_size = ui.add(egui::Slider::new(&mut thumb_w, MIN_THUMB_W..=MAX_THUMB_W).text(tl!("Thumbnail size")).suffix(" px"));
app.auto.add("script.settings.thumbnailSize", thumb_size.rect, "Thumbnail width; picture keeps a 16:9 aspect ratio");
if thumb_size.changed() {
app.ui.script.thumbnail_width = Some(thumb_w.round());
}
let mut left_margin = app.ui.script.text_inset.unwrap_or(DEFAULT_TEXT_INSET);
let margin = ui.add(egui::DragValue::new(&mut left_margin).range(54.0..=600.0).suffix(" px").prefix(format!("{} ", tl!("Left margin"))));
app.auto.add("script.settings.leftMargin", margin.rect, "Script left margin");
if margin.changed() {
app.ui.script.text_inset = Some(left_margin);
}
let mut wrap_margin = app.ui.script.text_column_width.unwrap_or((rect.width() * 0.49).max(180.0));
let wrap = ui.add(egui::DragValue::new(&mut wrap_margin).range(180.0..=1600.0).suffix(" px").prefix(format!("{} ", tl!("Wrap margin"))));
app.auto.add("script.settings.wrapMargin", wrap.rect, "Script wrap margin");
if wrap.changed() {
app.ui.script.text_column_width = Some(wrap_margin);
}
let mut row_colors = app.ui.script.show_row_colors.unwrap_or(true);
let stripes = ui.checkbox(&mut row_colors, tl!("Show row colors"));
app.auto.add("script.settings.rowColors", stripes.rect, "Show row colors");
if stripes.changed() {
app.ui.script.show_row_colors = Some(row_colors);
}
let mut line_numbers = app.ui.script.show_line_numbers.unwrap_or(true);
let numbers = ui.checkbox(&mut line_numbers, tl!("Show line numbers"));
app.auto.add("script.settings.lineNumbers", numbers.rect, "Show line numbers");
if numbers.changed() {
app.ui.script.show_line_numbers = Some(line_numbers);
}
});
app.auto.add("script.settings", settings.response.rect, "Script settings");
for (key, text, action) in [("new", tl!("New"), Action::Create), ("import", tl!("Import Text…"), Action::Import)] {
let response = ui.button(text);
let response = if key == "import" { response.on_hover_text(tl!("Plain text .txt supported.")) } else { response };
app.auto.add(&format!("script.{key}"), response.rect, text);
x += w + gap;
}
remaining = &remaining[count..];
if !remaining.is_empty() {
y += stride;
room = width;
}
}
let bottom = (y + row_height + 8.0).min(rect.bottom());
app.auto.add("script.toolbar", Rect::from_min_max(rect.min, pos2(rect.right(), bottom)), "Lined Script toolbar");
ui.painter().line_segment([pos2(rect.min.x, bottom - 1.0), pos2(rect.max.x, bottom - 1.0)], Stroke::new(1.0, t.separator));
bottom
}
impl CenterControl {
fn id(&self) -> &'static str {
match self {
Self::Jump { scene: true, .. } => "scene",
Self::Jump { scene: false, .. } => "page",
Self::Search => "search",
Self::SearchCount => "count",
Self::Edit => "edit",
Self::Annotations => "annotations",
Self::Transport => "transport",
Self::FindSource(_) => "source",
}
}
}
fn toolbar_cell(ui: &mut egui::Ui, id: &str, bounds: Rect) -> egui::Ui {
ui.new_child(egui::UiBuilder::new().id_salt(("script.toolbar", id)).max_rect(bounds).layout(egui::Layout::left_to_right(egui::Align::Center)))
}
fn edit_button(app: &mut FilmcraftApp, ui: &mut egui::Ui) {
use craft_ui::primitives::{IconSpec, paint_icon};
let label = tl!("Edit");
let enabled = app.ui.script.edit_mode;
let edit = ui.add(segment("", BUTTON, true, true).selected(enabled)).on_hover_text(tl!("Edit screenplay text and headings"));
edit.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, enabled, label));
let env = craft_ui::runtime::env::Env::of(ui);
let icon = IconSpec::svg(craft_behavior::IconId::new("pencil"));
paint_icon(ui.painter(), &env.tokens, env.view().direction(), Rect::from_center_size(edit.rect.center(), vec2(15.0, 15.0)), &icon);
app.auto.add_response("script.editMode", &edit, label);
if edit.clicked() && (!enabled || app.ui.script.edit_line.is_none() || super::finish_script_fields(app)) {
app.ui.script.edit_mode = !enabled;
}
}
fn find_source(app: &mut FilmcraftApp, ui: &mut egui::Ui, source: u64) {
let matches = source_matches(app, ItemId(source));
let chooser = crate::legacy_dropdown::Dropdown::from_id_salt("script.findSource")
.selected_text(tlf!("Choose linked take ({count})", count = matches.len()))
.width(ui.max_rect().width())
.truncate();
chooser.show_ui(ui, |ui| {
for entry in matches {
let response = ui.selectable_label(false, &entry.label);
app.auto.add(&format!("script.findSource.{}.{}", entry.item.0, entry.take), response.rect, &entry.label);
if response.clicked() {
actions.push(action);
}
}
let paint = ui
.add(egui::Button::new(" ").min_size(vec2(29.0, 23.0)))
.on_hover_text(tl!("Set selected candle rows to the current color; right-click for palette"));
app.auto.add("script.color.apply", paint.rect, "Set candle row color");
let sample = script_color(app, app.ui.script.paint_color);
let icon = paint.rect.shrink2(vec2(7.0, 4.0));
ui.painter().rect_filled(icon, 1.0, sample);
ui.painter().rect_stroke(icon, 1.0, Stroke::new(1.0, t.text_dim), egui::StrokeKind::Inside);
let corner = paint.rect.right_bottom() - vec2(3.0, 3.0);
ui.painter().add(egui::Shape::convex_polygon(vec![corner - vec2(6.0, 0.0), corner - vec2(0.0, 6.0), corner], t.text_dim, Stroke::NONE));
paint.clone().context_menu(|ui| {
ui.label(tl!("Candle color"));
for colors in ScriptColor::ALL.chunks(9) {
ui.horizontal(|ui| {
for &color in colors {
let response = ui
.add(egui::Button::new(" ").fill(script_color(app, color)).min_size(vec2(24.0, 21.0)))
.on_hover_text(crate::i18n::t(color.name()));
app.auto.add(&format!("script.color.{}", color.name().to_lowercase()), response.rect, color.name());
if response.clicked() {
app.ui.script.paint_color = color;
ui.close();
}
}
});
}
});
if paint.clicked()
&& let Some(doc) = doc
&& let Some(take) = take_by_id(doc, app.ui.script.selected_take)
{
let ids = selected_take_lines(doc, &app.ui.script, take);
if !ids.is_empty() {
let mut updated = take.line_colors.clone();
updated.retain(|entry| !ids.contains(&entry.line));
for line in ids {
if app.ui.script.paint_color != take.color {
updated.push(filmcraft_project::ScriptLineColor { line, color: app.ui.script.paint_color });
}
}
actions.push(Action::Command(
"script.setTakeStyle",
json!({"item": app.ui.script.item, "take": take.id.0,
"lineColors": updated.iter().map(|entry| json!({"line":entry.line.0,"color":entry.color.name()})).collect::<Vec<_>>()}),
));
}
}
if let Some(doc) = doc {
for (key, label, focus, tooltip) in
[("scene.add", "S#", 1, tl!("Add or edit Scene on the selected line")), ("page.add", "P#", 2, tl!("Add or edit Page on the selected line"))]
{
let response = ui.add_enabled(current_line(doc, &app.ui.script).is_some(), egui::Button::new(label)).on_hover_text(tooltip);
app.auto.add(&format!("script.{key}"), response.rect, tooltip);
if response.clicked()
&& let Some(line) = current_line(doc, &app.ui.script)
{
app.ui.script.label_line = Some(line.id.0);
app.ui.script.scroll_to_line = Some(line.id.0);
app.ui.script.label_focus = Some(focus);
if focus == 1 {
app.ui.script.scene_text = line.scene.clone().unwrap_or_default();
app.ui.script.edit_scene = Some(line.id.0);
app.ui.script.edit_page = None;
} else {
app.ui.script.page_text = line.page.clone().unwrap_or_default();
app.ui.script.edit_page = Some(line.id.0);
app.ui.script.edit_scene = None;
}
}
}
for (key, caption, scene) in [("scene", "Sc:", true), ("page", "Pg:", false)] {
// Labels are navigation points: repeated numbers belong to
// distinct script rows and must remain separate options.
let values: Vec<_> = doc
.lines
.iter()
.filter_map(|line| {
let value = if scene { line.scene.as_deref() } else { line.page.as_deref() }?.trim();
(!value.is_empty()).then_some((value, line))
})
.collect();
let selected_line = current_line(doc, &app.ui.script).and_then(|line| doc.line_index(line.id)).and_then(|index| {
doc.lines[..=index]
.iter()
.rev()
.find(|line| (if scene { line.scene.as_deref() } else { line.page.as_deref() }).is_some_and(|value| !value.trim().is_empty()))
});
let selected = selected_line.and_then(|line| if scene { line.scene.as_deref() } else { line.page.as_deref() });
let label_width = ui.painter().layout_no_wrap(caption.to_owned(), egui::TextStyle::Body.resolve(ui.style()), t.text).size().x;
let group_size = vec2(label_width + ui.spacing().item_spacing.x + 60.0, ui.spacing().interact_size.y);
ui.allocate_ui_with_layout(group_size, egui::Layout::left_to_right(egui::Align::Center), |ui| {
ui.label(caption);
let combo = crate::legacy_dropdown::Dropdown::from_id_salt(format!("script.{key}.combo"))
.selected_text(selected.unwrap_or("—"))
.width(44.0)
.show_ui(ui, |ui| {
for (value, line) in &values {
let response = ui.selectable_label(selected_line.is_some_and(|selected| selected.id == line.id), *value);
app.auto.add(&format!("script.{key}.option.{}", line.id.0), response.rect, value);
if response.clicked() {
select_line(&mut app.ui.script, line, false);
app.ui.script.scroll_to_line = Some(line.id.0);
}
}
});
app.auto.add(&format!("script.{key}.combo"), combo.response.rect, &tlf!("Jump to {caption} label", caption));
});
}
if let (Some(line), Some(take)) = (current_line(doc, &app.ui.script), take_by_id(doc, app.ui.script.selected_take)) {
let in_candle = doc
.line_range(take.start_line, take.end_line)
.is_some_and(|(start, end)| doc.line_index(line.id).is_some_and(|current| (start..=end).contains(&current)));
let can_mark = take.source.is_some() && in_candle;
let mark = ui
.add_enabled(can_mark, egui::Button::new(" ").min_size(vec2(29.0, 23.0)))
.on_hover_text(tl!("Add a mark at the Source playhead; cues the selected candle's source if needed"));
app.auto.add("script.mark.add", mark.rect, "Mark this line at the Source playhead");
let center = mark.rect.center();
let icon_color = if can_mark { t.text } else { t.text_dim };
ui.painter().add(egui::Shape::convex_polygon(
vec![center + vec2(0.0, -5.5), center + vec2(5.5, 0.0), center + vec2(0.0, 5.5), center + vec2(-5.5, 0.0)],
icon_color,
Stroke::NONE,
));
if mark.clicked() {
actions.push(Action::AddMarkAtSelection);
}
let ids = selected_take_lines(doc, &app.ui.script, take);
let all_offscreen = !ids.is_empty() && ids.iter().all(|id| take.offscreen_lines.contains(id));
let offscreen = ui
.add_enabled(!ids.is_empty(), egui::Button::new(" ").min_size(vec2(29.0, 23.0)).selected(all_offscreen))
.on_hover_text(tl!("Mark or clear the selected candle rows as off-screen"));
app.auto.add("script.offscreen.toggle", offscreen.rect, "Toggle off-screen passage");
let center = offscreen.rect.center();
ui.painter().add(egui::Shape::line(
vec![center + vec2(0.0, -6.0), center + vec2(-3.0, -3.0), center + vec2(3.0, 0.0), center + vec2(-3.0, 3.0), center + vec2(0.0, 6.0)],
Stroke::new(2.5, if ids.is_empty() { t.text_dim } else { t.text }),
));
if offscreen.clicked() {
actions.push(Action::ToggleOffscreenSelection);
}
select_source_match(app, &entry);
app.ui.script.find_source = None;
}
}
});
let search_top = controls.response.rect.bottom() + 5.0;
let mut search = ui.new_child(egui::UiBuilder::new().max_rect(Rect::from_min_max(pos2(rect.left() + 8.0, search_top), rect.max - vec2(8.0, 0.0))));
let search = search.horizontal_wrapped(|ui| {
ui.label(tl!("Find in Script"));
let response = ui.add(egui::TextEdit::singleline(&mut app.ui.script.search).hint_text(tl!("Search text")).desired_width(140.0));
app.auto.add_response("script.search", &response, "Find in Script");
}
fn pair_widths(ui: &egui::Ui, labels: [&str; 2], t: &crate::theme::Tokens) -> [f32; 2] {
let button_font = egui::TextStyle::Button.resolve(ui.style());
labels.map(|label| {
let text_width = ui.painter().layout_no_wrap(label.to_owned(), button_font.clone(), t.text).size().x;
(text_width + 2.0 * ui.spacing().button_padding.x).ceil()
})
}
fn assign_label_button(app: &mut FilmcraftApp, ui: &mut egui::Ui, doc: &ScriptDocument, scene: bool) {
let row = current_line(doc, &app.ui.script);
let has_label = row.and_then(|line| jump_label(line, scene)).is_some();
let (id, tooltip) = match (scene, has_label) {
(true, false) => ("script.scene.add", tl!("Assign scene number to selected row")),
(true, true) => ("script.scene.add", tl!("Edit scene number")),
(false, false) => ("script.page.add", tl!("Assign page number to selected row")),
(false, true) => ("script.page.add", tl!("Edit page number")),
};
let hint = if row.is_some() {
tooltip
} else if scene {
tl!("Select a row to add a scene number in the left margin.")
} else {
tl!("Select a row to add a page number in the right margin.")
};
let add = ui.add_enabled(row.is_some(), segment("+", BUTTON, false, true)).on_hover_text(hint).on_disabled_hover_text(hint);
let name = format!("+ {hint}");
add.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, add.enabled(), &name));
app.auto.add_response(id, &add, &name);
if add.clicked()
&& let Some(line) = row
{
app.ui.script.label_line = Some(line.id.0);
app.ui.script.scroll_to_line = Some(line.id.0);
if scene {
app.ui.script.label_focus = Some(1);
app.ui.script.scene_text = line.scene.clone().unwrap_or_default();
app.ui.script.edit_scene = Some(line.id.0);
app.ui.script.edit_page = None;
} else {
app.ui.script.label_focus = Some(2);
app.ui.script.page_text = line.page.clone().unwrap_or_default();
app.ui.script.edit_page = Some(line.id.0);
app.ui.script.edit_scene = None;
}
}
}
fn jump_field(app: &mut FilmcraftApp, ui: &mut egui::Ui, doc: &ScriptDocument, scene: bool, caption_width: f32, field_width: f32) {
let (key, caption) = if scene { ("scene", tl!("Sc:")) } else { ("page", tl!("Pg:")) };
let t = app.tokens;
let field_padding = ui.spacing().button_padding.x.min(4.0);
let font = egui::TextStyle::Button.resolve(ui.style());
group(ui, caption_width + field_width + BUTTON, |ui| {
let name = if scene { tl!("Sc: Jump to scene") } else { tl!("Pg: Jump to page") };
let (rect, label) = ui.allocate_exact_size(vec2(caption_width, 24.0), egui::Sense::hover());
ui.painter().rect(rect, segment_corners(true, false), t.panel_bg, Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside);
ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, caption, font, t.text_dim);
label.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, caption));
app.auto.add_response(&format!("script.{key}.caption"), &label, caption);
let current = current_line(doc, &app.ui.script)
.and_then(|line| doc.line_index(line.id))
.and_then(|index| doc.lines[..=index].iter().rev().find(|line| jump_label(line, scene).is_some()));
let selected = current.and_then(|line| jump_label(line, scene)).unwrap_or("—");
ui.spacing_mut().button_padding.x = field_padding;
let combo = crate::legacy_dropdown::Dropdown::from_id_salt(format!("script.{key}.combo"))
.selected_text(selected)
.width(field_width)
.joined(segment_corners(false, false))
.show_ui(ui, |ui| {
// Repeated labels point to distinct rows and stay in screenplay order.
for (value, line) in doc.lines.iter().filter_map(|line| Some((jump_label(line, scene)?, line))) {
let response = ui.selectable_label(current.is_some_and(|selected| selected.id == line.id), value);
app.auto.add(&format!("script.{key}.option.{}", line.id.0), response.rect, value);
if response.clicked() {
select_line(&mut app.ui.script, line, false);
app.ui.script.scroll_to_line = Some(line.id.0);
}
}
});
let field = combo.response.on_hover_text(name);
app.auto.add_response(&format!("script.{key}.combo"), &field, name);
assign_label_button(app, ui, doc, scene);
});
}
fn search_count(app: &FilmcraftApp) -> String {
let count = app.ui.script.search_results.len();
if count == 0 { tl!("No matches").to_owned() } else { tlf!("{current} of {count}", current = app.ui.script.search_result_index + 1, count = count) }
}
fn search_controls(app: &mut FilmcraftApp, ui: &mut egui::Ui, doc: Option<&Arc<ScriptDocument>>) {
let t = app.tokens;
let field_width = (ui.max_rect().width() - 2.0 * BUTTON).max(48.0);
group(ui, field_width + 2.0 * BUTTON, |ui| {
let hint = tl!("Search script");
let response = crate::widgets::search_field_sized(ui, &mut app.ui.script.search, hint, vec2(field_width, 24.0), segment_corners(true, false), &t);
app.auto.add_response("script.search", &response, hint);
if let Some(doc) = doc {
let query_changed =
response.changed() || app.ui.script.search_cache_query != app.ui.script.search || app.ui.script.search_cache_item != app.ui.script.item;
@@ -266,60 +304,338 @@ pub(super) fn header(
app.ui.script.search_result_index = app.ui.script.search_result_index.min(app.ui.script.search_results.len().saturating_sub(1));
}
}
let count = app.ui.script.search_results.len();
if !app.ui.script.search.is_empty() {
let previous = ui.add_enabled(count > 0, egui::Button::new("‹")).on_hover_text(tl!("Previous match (Shift+Enter)"));
app.auto.add("script.search.previous", previous.rect, "Previous search match");
let next = ui.add_enabled(count > 0, egui::Button::new("›")).on_hover_text(tl!("Next match (Enter)"));
app.auto.add("script.search.next", next.rect, "Next search match");
let enter = response.has_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter));
if count > 0 && (previous.clicked() || next.clicked() || enter) {
let backwards = previous.clicked() || enter && ui.input(|input| input.modifiers.shift);
let index = &mut app.ui.script.search_result_index;
*index = if backwards { (*index + count - 1) % count } else { (*index + 1) % count };
let id = app.ui.script.search_results[*index];
if let Some(line) = doc.lines.iter().find(|line| line.id.0 == id) {
select_line(&mut app.ui.script, line, false);
app.ui.script.scroll_to_line = Some(id);
}
}
let status = if count == 0 {
tl!("No matches").to_owned()
} else {
tlf!("{current} of {count}", current = app.ui.script.search_result_index + 1, count)
};
let label = ui.label(status);
app.auto.add("script.search.count", label.rect, "Search result count");
}
let count = doc.map_or(0, |_| app.ui.script.search_results.len());
let mut step = None;
for (backwards, glyph, key, label) in
[(true, "‹", "script.search.previous", tl!("Previous match (Shift+Enter)")), (false, "›", "script.search.next", tl!("Next match (Enter)"))]
{
let button = ui.add_enabled(count > 0, segment(glyph, 24.0, false, !backwards)).on_hover_text(label);
button.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, button.enabled(), format!("{glyph} {label}")));
app.auto.add_response(key, &button, label);
if button.clicked() {
step = Some(backwards);
}
}
if let Some(source) = app.ui.script.find_source {
let matches = source_matches(app, ItemId(source));
let chooser = crate::legacy_dropdown::Dropdown::from_id_salt("script.findSource")
.selected_text(tlf!("Choose linked take ({count})", count = matches.len()))
.width(190.0);
chooser.show_ui(ui, |ui| {
for entry in matches {
let response = ui.selectable_label(false, &entry.label);
app.auto.add(&format!("script.findSource.{}.{}", entry.item.0, entry.take), response.rect, &entry.label);
if response.clicked() {
select_source_match(&mut app.ui.script, &entry);
app.ui.script.find_source = None;
}
if let Some(doc) = doc.filter(|_| !app.ui.script.search.is_empty()) {
if (response.has_focus() || response.lost_focus()) && ui.input(|input| input.key_pressed(egui::Key::Enter)) {
step = Some(ui.input(|input| input.modifiers.shift));
response.request_focus();
}
if let Some(backwards) = step.filter(|_| count > 0) {
let index = &mut app.ui.script.search_result_index;
*index = if backwards { (*index + count - 1) % count } else { (*index + 1) % count };
let id = app.ui.script.search_results[*index];
if let Some(line) = doc.lines.iter().find(|line| line.id.0 == id) {
select_line(&mut app.ui.script, line, false);
app.ui.script.scroll_to_line = Some(id);
}
});
}
if let Some(line) = doc.and_then(|doc| current_line(doc, &app.ui.script)) {
ui.label(tlf!(
"Line {current} of {total}",
current = doc.map_or(0, |d| d.lines.iter().position(|candidate| candidate.id == line.id).map_or(0, |index| index + 1)),
total = doc.map_or(0, |d| d.lines.len())
));
}
}
});
}
fn jump_label(line: &filmcraft_project::ScriptLine, scene: bool) -> Option<&str> {
(if scene { line.scene.as_deref() } else { line.page.as_deref() }).map(str::trim).filter(|label| !label.is_empty())
}
#[derive(Clone)]
struct JumpWidths {
document: std::sync::Weak<ScriptDocument>,
font: egui::FontId,
pixels_per_point: f32,
labels: [f32; 2],
}
/// The menus list only the active script's labels, including temporary edits in Help.
fn jump_label_widths(ui: &egui::Ui, doc: &Arc<ScriptDocument>) -> [f32; 2] {
let cache_id = ui.scope_id().with("script.jumpWidths");
let document = Arc::downgrade(doc);
let font = egui::TextStyle::Body.resolve(ui.style());
let pixels_per_point = ui.pixels_per_point();
if let Some(cache) = ui.data(|data| data.get_temp::<JumpWidths>(cache_id))
&& cache.document.ptr_eq(&document)
&& cache.font == font
&& cache.pixels_per_point == pixels_per_point
{
return cache.labels;
}
let mut values = [std::collections::HashSet::from(["—"]), std::collections::HashSet::from(["—"])];
for row in &doc.lines {
for (labels, scene) in values.iter_mut().zip([true, false]) {
if let Some(value) = jump_label(row, scene) {
labels.insert(value);
}
}
}
let labels = ui.fonts_mut(|fonts| {
values.map(|values| {
values.into_iter().map(|value| fonts.layout_no_wrap(value.to_owned(), font.clone(), egui::Color32::WHITE).size().x).fold(0.0, f32::max)
})
});
ui.data_mut(|data| data.insert_temp(cache_id, JumpWidths { document, font, pixels_per_point, labels }));
labels
}
/// Pin the joined settings and help buttons to the top-right of the toolbar.
fn settings_and_help(app: &mut FilmcraftApp, ui: &mut egui::Ui, bounds: Rect, panel_width: f32) {
let t = app.tokens;
let width = BUTTON;
let mut tools = toolbar_cell(ui, "settingsAndHelp", bounds);
group(&mut tools, 2.0 * width, |ui| {
let settings_label = tl!("Lined Script Display Settings");
let button = segment("", width, true, false);
let (settings, _) = egui::containers::menu::MenuButton::from_button(button).ui(ui, |ui| {
ui.label(settings_label);
let mut font_size = super::layout::script_font(&app.ui.script).size;
let size = ui.add(egui::Slider::new(&mut font_size, 10.0..=24.0).text(tl!("Text size")).suffix(" pt"));
app.auto.add("script.settings.textSize", size.rect, "Lined Script text size");
if size.changed() {
app.ui.script.font_size = Some(font_size);
}
let mut spacing = app.ui.script.row_spacing();
let label = tl!("Row spacing");
let rows = ui.add(egui::Slider::new(&mut spacing, 0..=super::MAX_ROW_SPACING).text(label).suffix(" pt"));
app.auto.add_response("script.settings.rowSpacing", &rows, label);
if rows.changed() {
app.ui.script.row_spacing = Some(spacing);
}
let mut thumb_w = thumbnail_width(&app.ui.script);
let thumb_size = ui.add(egui::Slider::new(&mut thumb_w, MIN_THUMB_W..=MAX_THUMB_W).text(tl!("Thumbnail size")).suffix(" pt"));
app.auto.add("script.settings.thumbnailSize", thumb_size.rect, "Thumbnail width; picture keeps a 16:9 aspect ratio");
if thumb_size.changed() {
app.ui.script.thumbnail_width = Some(thumb_w.round());
}
let mut candle_width = app.ui.script.candle_stroke_width();
let label = tl!("Candle width");
let candle_size = ui.add(egui::Slider::new(&mut candle_width, super::MIN_CANDLE_W..=super::MAX_CANDLE_W).step_by(1.0).text(label).suffix(" pt"));
app.auto.add_response("script.settings.candleWidth", &candle_size, label);
if candle_size.changed() {
app.ui.script.candle_width = Some(candle_width);
}
let mut distance = app.ui.script.candle_distance();
let label = tl!("Candle distance");
let response = ui
.add(egui::Slider::new(&mut distance, super::CANDLE_DISTANCE).text(label).suffix(" pt"))
.on_hover_text(tl!("Space between the outer edges of script marks on adjacent takes."));
app.auto.add_response("script.settings.candleDistance", &response, label);
if response.changed() {
app.ui.script.candle_distance = Some(distance);
}
let mut preroll = app.session.prefs.playback.lined_script_preroll_seconds;
let label = tl!("Pre-Roll Playback");
let lead = ui
.add(egui::Slider::new(&mut preroll, 0.0..=5.0).step_by(0.1).fixed_decimals(1).text(label).suffix(" s"))
.on_hover_text(tl!("Cue Source this many seconds before a script mark or candle row."));
app.auto.add_response("script.settings.preroll", &lead, label);
if lead.changed() {
super::command(app, "prefs.set", json!({"key":"playback.linedScriptPrerollSeconds","value":preroll}));
}
let margins = super::layout::Margins::new(app, ui, panel_width);
let mut left_margin = margins.left;
let margin = ui.add(
egui::DragValue::new(&mut left_margin)
.range(margins.left_range.min..=margins.left_range.max)
.suffix(" pt")
.prefix(format!("{} ", tl!("Left margin"))),
);
app.auto.add("script.settings.leftMargin", margin.rect, "Lined Script left margin");
if margin.changed() {
app.ui.script.text_inset = Some(left_margin);
}
let mut wrap_margin = margins.right;
let wrap = ui.add(
egui::DragValue::new(&mut wrap_margin)
.range(margins.right_range.min..=margins.right_range.max)
.suffix(" pt")
.prefix(format!("{} ", tl!("Wrap margin"))),
);
app.auto.add("script.settings.wrapMargin", wrap.rect, "Lined Script wrap margin");
if wrap.changed() {
app.ui.script.text_column_width = Some(wrap_margin);
}
let label = tl!("Keep setup thumbnails visible while scrolling");
let pin = ui.checkbox(&mut app.ui.script.keep_thumbnails_visible, label);
app.auto.add_response("script.settings.keepThumbnailsVisible", &pin, label);
let mut row_colors = app.ui.script.show_row_colors.unwrap_or(true);
let stripes = ui.checkbox(&mut row_colors, tl!("Show row colors"));
app.auto.add("script.settings.rowColors", stripes.rect, "Show row colors");
if stripes.changed() {
app.ui.script.show_row_colors = Some(row_colors);
}
let mut line_numbers = app.ui.script.show_line_numbers.unwrap_or(true);
let numbers = ui.checkbox(&mut line_numbers, tl!("Show line numbers"));
app.auto.add("script.settings.lineNumbers", numbers.rect, "Show line numbers");
if numbers.changed() {
app.ui.script.show_line_numbers = Some(line_numbers);
}
let label = tl!("Show page controls");
let controls = ui.checkbox(&mut app.ui.script.show_page_controls, label);
app.auto.add_response("script.settings.showPageControls", &controls, label);
let name = tl!("Hide page numbers in the right margin");
let pages = ui.checkbox(&mut app.ui.script.hide_page_numbers, name);
app.auto.add_response("script.settings.hidePageNumbers", &pages, name);
});
let settings = settings.on_hover_text(settings_label);
let icon_rect = Rect::from_center_size(settings.rect.center(), vec2(14.0, 14.0));
crate::icons::paint(ui.painter(), icon_rect, crate::icons::Icon::Wrench, t.text_dim);
app.auto.add_response("script.settings", &settings, settings_label);
let help_label = tl!("Lined Script help");
let help = ui.add(segment("?", width, false, true)).on_hover_text(help_label);
help.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, help.enabled(), format!("? {help_label}")));
app.auto.add_response("script.help", &help, help_label);
let help_width = (ui.ctx().content_rect().width() - 32.0).clamp(1.0, 640.0);
let help_height = (ui.ctx().content_rect().height() - 120.0).max(1.0);
egui::Popup::menu(&help).width(help_width).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {
ui.set_width(help_width);
egui::ScrollArea::vertical().id_salt("script.help.scroll").max_height(help_height).show(ui, |ui| {
let name = tl!("Show Help script");
let show = ui.button(name);
app.auto.add_response("script.help.showScript", &show, name);
if show.clicked() {
super::tabs::activate(app, None);
ui.close();
}
guide_contents(app, ui, "script.help.guide");
});
});
});
}
fn segment_corners(left: bool, right: bool) -> egui::CornerRadius {
let l = if left { 3 } else { 0 };
let r = if right { 3 } else { 0 };
egui::CornerRadius { nw: l, sw: l, ne: r, se: r }
}
fn segment(label: &str, width: f32, left: bool, right: bool) -> egui::Button<'_> {
egui::Button::new(label).min_size(vec2(width, 24.0)).corner_radius(segment_corners(left, right))
}
fn group(ui: &mut egui::Ui, total_width: f32, contents: impl FnOnce(&mut egui::Ui)) {
ui.allocate_ui_with_layout(vec2(total_width, 24.0), egui::Layout::left_to_right(egui::Align::Center), |ui| {
ui.spacing_mut().item_spacing.x = 0.0;
contents(ui);
});
}
fn transport_buttons(app: &mut FilmcraftApp, ui: &mut egui::Ui, doc: Option<&ScriptDocument>) {
let take = doc.and_then(|doc| take_by_id(doc, app.ui.script.selected_take));
let enabled = take.is_some_and(|take| !super::recovery::needs_rebind(app, take));
let hint = if take.is_some() { tl!("Reconnect the candle’s source first.") } else { tl!("Select a candle first.") };
// A pass for another candle keeps running; these buttons start the selected take.
let active = app.ui.script.screening.filter(|pass| take.is_some_and(|take| take.id.0 == pass.take()));
group(ui, 2.0 * BUTTON, |ui| {
for (record, id, name, tooltip) in [
(false, "script.playTake", tl!("Play take"), tl!("Play the selected take in Source.")),
(true, "script.recordMarks", tl!("Record script marks"), tl!("Play the take and click candle rows to time script marks.")),
] {
let on = active.is_some_and(|pass| pass.recording == record);
let response = ui
.add_enabled(enabled, segment("", BUTTON, !record, record).selected(on))
.on_hover_text(if on { tl!("Stop take playback") } else { tooltip })
.on_disabled_hover_text(hint);
response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, enabled, on, name));
app.auto.add_response(id, &response, name);
let center = response.rect.center();
let ink = if enabled { app.tokens.text } else { app.tokens.text_dim };
if on {
ui.painter().rect_filled(Rect::from_center_size(center, vec2(9.0, 9.0)), 1.0, ink);
} else if record {
ui.painter().circle_filled(center, 5.0, if enabled { app.tokens.danger } else { ink });
} else {
crate::icons::paint(ui.painter(), Rect::from_center_size(center, vec2(16.0, 16.0)), crate::icons::Icon::Play, ink);
}
if response.clicked()
&& let Err(error) = crate::menus::invoke_command(app, ui.ctx(), id, json!({}))
{
app.ui.status = error;
}
}
});
}
fn annotation_buttons(app: &mut FilmcraftApp, ui: &mut egui::Ui, doc: Option<&ScriptDocument>, actions: &mut Vec<Action>) {
let t = app.tokens;
let width = BUTTON;
group(ui, 3.0 * width, |ui| {
let button = |left, right| segment(" ", width, left, right).stroke(Stroke::new(1.0, t.separator));
let take = doc.and_then(|doc| take_by_id(doc, app.ui.script.selected_take));
let ids = doc.zip(take).map_or_else(Vec::new, |(doc, take)| selected_take_lines(doc, &app.ui.script, take));
let other_pass = app.ui.script.screening.is_some_and(|pass| take.is_some_and(|take| take.id.0 != pass.take()));
let can_mark = !other_pass
&& take.is_some_and(|take| take.source.is_some())
&& doc.and_then(|doc| current_line(doc, &app.ui.script)).is_some_and(|line| ids.contains(&line.id));
let label = tl!("Add script mark");
let mark_hint = if other_pass {
tl!("Stop the running take before marking another candle.")
} else if take.is_some_and(|take| take.source.is_none()) {
tl!("Drag the source clip from Project onto this candle to reconnect it.")
} else {
tl!("Click a candle on the row where you want to add a script mark.")
};
let mark = crate::widgets::accessible_name(ui.add_enabled(can_mark, button(true, false)), label)
.on_hover_text(tl!("Add a mark at the Source playhead; cues the selected candle's source if needed"))
.on_disabled_hover_text(mark_hint);
app.auto.add_response("script.mark.add", &mark, label);
let icon_color = if can_mark { t.text } else { t.text_dim };
crate::icons::paint_script_mark(ui.painter(), mark.rect.center(), 5.5, 1.5, icon_color);
if mark.clicked() {
actions.push(Action::AddMarkAtSelection);
}
let all_offscreen = !ids.is_empty() && take.is_some_and(|take| ids.iter().all(|id| take.offscreen_lines.contains(id)));
let label = tl!("Mark offscreen");
let offscreen = crate::widgets::accessible_name(ui.add_enabled(!ids.is_empty(), button(false, false).selected(all_offscreen)), label)
.on_hover_text(tl!("Mark or clear the selected candle rows as off-screen"))
.on_disabled_hover_text(tl!("Click a candle on the row to mark offscreen. Shift-click the same candle to select a range."));
app.auto.add_response("script.offscreen.toggle", &offscreen, label);
let center = offscreen.rect.center();
ui.painter().add(egui::Shape::line(
vec![center + vec2(0.0, -6.0), center + vec2(-3.0, -3.0), center + vec2(3.0, 0.0), center + vec2(-3.0, 3.0), center + vec2(0.0, 6.0)],
Stroke::new(2.5, if ids.is_empty() { t.text_dim } else { t.text }),
));
if offscreen.clicked() {
actions.push(Action::ToggleOffscreenSelection);
}
let paint_color = app.ui.script.paint_color.unwrap_or(super::DEFAULT_SWATCH);
let sample = script_color(app, paint_color);
let paint = ui
.add(button(false, true).fill(sample))
.on_hover_text(tl!("Set selected candle rows to the current color; right-click or press Shift+F10 for palette"));
app.auto.add_response("script.color.apply", &paint, &tlf!("Color candle: {color}", color = crate::i18n::t(paint_color.name())));
let corner = paint.rect.right_bottom() - vec2(3.0, 3.0);
ui.painter().add(egui::Shape::convex_polygon(
vec![corner - vec2(6.0, 0.0), corner - vec2(0.0, 6.0), corner],
if sample.intensity() > 0.5 { egui::Color32::BLACK } else { egui::Color32::WHITE },
Stroke::NONE,
));
let popup = egui::Popup::context_menu(&paint).at_position(paint.rect.left_bottom());
let popup = if paint.has_focus() && ui.input_mut(|i| i.consume_key(egui::Modifiers::SHIFT, egui::Key::F10)) {
popup.open_memory(egui::SetOpenCommand::Bool(true))
} else {
popup
};
popup.show(|ui| {
ui.label(tl!("Candle color"));
for colors in ScriptColor::ALL.chunks(9) {
ui.horizontal(|ui| {
for &color in colors {
let response = ui
.add(egui::Button::new(" ").fill(script_color(app, color)).min_size(vec2(24.0, 21.0)))
.on_hover_text(crate::i18n::t(color.name()));
app.auto.add_response(&format!("script.color.{}", color.name().to_lowercase()), &response, crate::i18n::t(color.name()));
if response.clicked() {
app.ui.script.paint_color = Some(color);
ui.close();
}
}
});
}
});
if paint.clicked() && !ids.is_empty() {
actions.push(Action::ApplyCandleColor);
}
});
let bottom = (search.response.rect.bottom().max(search_top + 25.0) + 8.0).min(rect.bottom());
app.auto.add("script.toolbar", Rect::from_min_max(rect.min, pos2(rect.right(), bottom)), "Script toolbar");
ui.painter().line_segment([pos2(rect.min.x, bottom - 1.0), pos2(rect.max.x, bottom - 1.0)], Stroke::new(1.0, t.separator));
bottom
}
/// The selected take's keyboard coverage commands stay active without a second toolbar row.
+11 -6
View File
@@ -296,12 +296,16 @@ fn header(app: &mut FilmcraftApp, ui: &mut egui::Ui, t: &Tokens) {
let cur = app.shortcut_editor.context.clone();
let r = crate::legacy_dropdown::Dropdown::from_id_salt("shortcuts-context")
.width(280.0)
.selected_text(crate::i18n::t(if cur.is_empty() { APPLICATION } else { &cur }))
.selected_text(crate::i18n::t(if cur.is_empty() { APPLICATION } else { crate::dock::display_name(&cur) }))
.show_ui(ui, |ui| {
for c in std::iter::once(APPLICATION).chain(PANELS.iter().copied()) {
let label = if c == APPLICATION { crate::i18n::t(c).to_string() } else { tlf!("{panel} Panel", panel = crate::i18n::t(c)) };
let r = ui.selectable_label(cur == c, label);
app.auto.add(&format!("shortcuts.context.{c}"), r.rect, c);
let label = if c == APPLICATION {
crate::i18n::t(c).to_string()
} else {
tlf!("{panel} Panel", panel = crate::i18n::t(crate::dock::display_name(c)))
};
let r = ui.selectable_label(cur == c, &label);
app.auto.add(&format!("shortcuts.context.{c}"), r.rect, &label);
if r.clicked() {
app.shortcut_editor.context = c.to_string();
}
@@ -849,7 +853,7 @@ fn command_list(app: &mut FilmcraftApp, ui: &mut egui::Ui, height: f32, t: &Toke
.map(|b| {
let d = b["display"].as_str().unwrap_or("").to_string();
match b["panel"].as_str() {
Some(pn) => format!("{d} ({pn})"),
Some(pn) => format!("{d} ({})", crate::i18n::t(crate::dock::display_name(pn))),
None => d,
}
})
@@ -894,6 +898,7 @@ fn matches_search(row: &serde_json::Value, query: &str) -> bool {
["id", "label", "category"].iter().any(|key| crate::i18n::matches_query(row.get(key).and_then(serde_json::Value::as_str).unwrap_or(""), query))
|| row.get("shortcuts").and_then(serde_json::Value::as_array).into_iter().flatten().any(|binding| {
["keys", "display", "panel"].iter().any(|key| crate::i18n::matches_query(binding.get(key).and_then(serde_json::Value::as_str).unwrap_or(""), query))
|| binding["panel"].as_str().is_some_and(|panel| crate::i18n::matches_query(crate::dock::display_name(panel), query))
})
}
@@ -926,7 +931,7 @@ fn key_detail(app: &mut FilmcraftApp, ui: &mut egui::Ui, height: f32, t: &Tokens
ui.painter().text(r.left_center() + vec2(8.0, 0.0), Align2::LEFT_CENTER, mods.unwrap_or_default(), Tokens::ui(12.5), t.text);
let cmd = b["command"].as_str().unwrap_or("");
let label = match b["panel"].as_str() {
Some(p) => format!("{} ({p})", label_of(app, cmd)),
Some(p) => format!("{} ({})", label_of(app, cmd), crate::i18n::t(crate::dock::display_name(p))),
None => label_of(app, cmd),
};
ui.painter().text(r.left_center() + vec2(110.0, 0.0), Align2::LEFT_CENTER, label, Tokens::ui(12.5), t.text);
+4 -3
View File
@@ -214,11 +214,12 @@ pub fn dialogs(app: &mut FilmcraftApp, ctx: &egui::Context) {
}
WorkspaceDialog::Edit { selected, name } => {
for (i, n) in names.iter().enumerate() {
let r = ui.selectable_label(selected.as_ref() == Some(n), crate::i18n::t(n));
push(&format!("workspaces.edit.row.{i}"), &r, n);
let label = crate::i18n::t(n);
let r = ui.selectable_label(selected.as_ref() == Some(n), label);
push(&format!("workspaces.edit.row.{i}"), &r, label);
if r.clicked() {
*selected = Some(n.clone());
*name = n.clone();
*name = if is_builtin(n) { label.to_owned() } else { n.clone() };
}
}
ui.separator();
+3
View File
@@ -13,6 +13,8 @@ use crate::{AUDIO_RETRY_S, AUDIO_STALL_S, FilmcraftApp, Playback, shuttle};
#[derive(Default)]
pub struct SourcePlayback {
pub clock: Playback,
/// Identifies a continuous run, including when the same source is stopped and restarted.
pub(crate) run_id: u64,
item: Option<ItemId>,
shown: Tick,
range_start: Option<Tick>,
@@ -98,6 +100,7 @@ impl FilmcraftApp {
self.session.execute("source.setPlayhead", json!({"time": time.0})).map_err(|e| e.to_string())?;
let time = self.session.state.source_playhead;
self.source_playback.range_start = start;
self.source_playback.run_id = self.source_playback.run_id.wrapping_add(1);
self.source_playback.item = Some(item);
self.source_playback.shown = time;
self.source_playback.clock = Playback { playing: true, speed, anchor_time: -1.0, anchor_tick: time, looping, stop_at: stop, ..Default::default() };
+8 -4
View File
@@ -470,10 +470,14 @@ pub fn icon_toggle(ui: &mut Ui, rect: Rect, icon: Icon, on: bool, t: &Tokens, id
/// Search field with a magnifier icon.
pub fn search_field(ui: &mut Ui, text: &mut String, hint: &str, width: f32, t: &Tokens) -> Response {
let h = 22.0;
let (rect, _) = ui.allocate_exact_size(vec2(width, h), Sense::hover());
ui.painter().rect_filled(rect, h / 2.0, t.field_bg);
ui.painter().rect_stroke(rect, h / 2.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
search_field_sized(ui, text, hint, vec2(width, 22.0), egui::CornerRadius::same(11), t)
}
/// Draw a search field with the dimensions and corners of the toolbar group that holds it.
pub(crate) fn search_field_sized(ui: &mut Ui, text: &mut String, hint: &str, size: egui::Vec2, corners: egui::CornerRadius, t: &Tokens) -> Response {
let (rect, _) = ui.allocate_exact_size(size, Sense::hover());
ui.painter().rect_filled(rect, corners, t.field_bg);
ui.painter().rect_stroke(rect, corners, Stroke::new(1.0, t.field_border), StrokeKind::Inside);
icons::paint(ui.painter(), Rect::from_center_size(pos2(rect.min.x + 12.0, rect.center().y), vec2(12.0, 12.0)), Icon::Search, t.text_dim);
let inner = Rect::from_min_max(pos2(rect.min.x + 22.0, rect.min.y + 2.0), pos2(rect.max.x - 8.0, rect.max.y - 2.0));
// centred across the field: a text edit aligns its text to the top unless told otherwise
File diff suppressed because it is too large Load Diff
+27 -1
View File
@@ -78,6 +78,33 @@ fn saved_file(data: &Path) -> Value {
serde_json::from_slice(&std::fs::read(data.join("workspaces.json")).expect("workspaces.json written")).unwrap()
}
#[test]
fn retired_script_template_reopens_the_last_layout_and_preserves_saved_workspaces() {
let data = data_dir("retired-script");
let mut d = Driver::launch(&data);
d.menu("window.panel.Script", json!({}));
d.app().remember_layout();
drop(d);
let mut prefs = saved_file(&data);
prefs["current"] = json!("Script");
prefs["last"]["name"] = json!("Script");
let path = data.join("workspaces.json");
std::fs::write(&path, serde_json::to_vec(&prefs).unwrap()).unwrap();
let mut migrated = Driver::launch(&data);
assert_eq!(migrated.workspace(), "Editing");
assert!(migrated.shows(PanelKind::Script));
assert!(!migrated.workspaces_menu().iter().any(|(name, _)| name == "Script" || name == "Lined Script"));
drop(migrated);
prefs["saved"] = json!([prefs["last"]]);
std::fs::write(path, serde_json::to_vec(&prefs).unwrap()).unwrap();
let mut custom = Driver::launch(&data);
assert_eq!(custom.workspace(), "Script");
assert!(custom.shows(PanelKind::Script));
assert!(custom.workspaces_menu().iter().any(|(name, checked)| name == "Script" && *checked));
}
fn built_in_keeps_saved_changes_and_restores(d: &mut Driver) {
// Save Changes to this Workspace on a built-in; it can't be deleted, only restored
d.ok("ui.set", json!({"workspace": "Assembly"}));
@@ -120,7 +147,6 @@ fn save_switch_reset_rename_delete_and_restart() {
"Editing",
"Effects",
"Learning",
"Lined Script",
"Review",
"Vertical",
"Reset to Saved Layout",
+1 -1
View File
@@ -39,7 +39,7 @@ Premiere has these as keys only (most are not in a menu). Modules: `filmcraft_en
| History panel | Delete (Delete Redoable Actions, which asks for OK first) | Backspace |
| Project panel | List/Icon/Toggle View, Hover Scrub, Thumbnail Size Next/Previous (and = / -), Move/Extend Selection, Mark In / Out of the hover-scrubbed clip | Cmd+PageUp/PageDown, Shift+\, Shift+H, Shift+] / Shift+[, arrows, Home/End, PageUp/PageDown, I / O |
| Text panel | Navigate/Select to Previous/Next Word and Line, Start/End of Segment, Delete (lift), Ripple Delete (extract), Show Program Transcript, Merge/Split Segments | arrows, Shift+arrows, Home/End, Shift+Home, Cmd+Shift+Down, Alt+Backspace, Backspace, Shift+X, Alt+M / Alt+S |
| Script panel | Clear selected mark, candle, or setup thumbnail (the whole setup); text fields keep normal editing | Backspace / Delete |
| Lined Script panel | Clear selected mark, candle, or setup thumbnail (the whole setup); text fields keep normal editing | Backspace / Delete |
| Other | Help (F1), Quit (Cmd+Q), Media Browser ▸ Open In Source Monitor (imports the file first), Send to Media Encoder (= Send to Export Queue, Alt+Shift+M), Metadata panel Play/Loop | |
Existing commands that only lacked their Premiere key were added to the table too (Close, Close
+67
View File
@@ -0,0 +1,67 @@
# Lined Script
A lined script shows which takes cover each line of dialogue or action. Use it to find an actor’s reading, compare it with another take, or see where a character is offscreen.
Open **Window → Lined Script**. The built-in **Help** tab is a practice script with FilmCraft’s sample footage. The opening exchange has two takes to compare. Each step has its own setup. Desert Dunes shows partial coverage. Its first candle covers USER’s question, and the second includes HELP’s reply. Misty Forest continues to the last line, with marks for both speakers in the final exchange. Neon Loop shows three resets from one source, each cued to a different point in the clip. Double-click a mark beside the opening dialogue, then press **Space** in Source to play. Try the same line on the other candle to compare takes. You can edit Help and add marks while you practice. Those edits reset when you leave the tab or reopen the project.
## Open and organize scripts
- Choose **Import** to open a UTF-8 plain-text screenplay. Each hard line break becomes a script row. Five empty rows above the text leave room for setup thumbnails. Long rows wrap when the panel narrows and keep their marks.
- Choose **Blank** to type or paste a script. Edit mode turns on and the caret starts on row 5, below four empty rows. With Edit on, press **F2** on a focused row to edit its text.
- Double-click a script in **Project** to open its tab. Drag tabs to reorder them. With a tab focused, use Left or Right to switch tabs and Shift+Left or Shift+Right to move the tab. Escape cancels a drag. FilmCraft remembers the tabs, their order and the active script when you save the project.
- Click the **×** beside the active tab’s name to close it. You can reopen the script from Project. Help returns when the last script closes, or you can choose **? → Show Help script** at any time.
## Add takes and read their numbers
Click the first row a take covers, then Shift-click the last. Drag a clip or group from **Project** onto those rows. A thumbnail identifies the setup. Beneath it, a numbered box identifies the take, and a vertical line called a *candle* spans its coverage. To add another take to the same setup, select its rows and drop the clip directly on the shared thumbnail. To start another setup, drop beside the thumbnail.
For setup 07B, enter 1, 2, and 3 in the **Take** column for the three clips so each candle’s box shows its take number. To fill in Take, select the source clip in **Project**, open **Window → Metadata**, and enter the number in **Clip → Take**. To see the column in Project **List** view, right-click a column heading, choose **Metadata Display…**, and enable **Take**.
Each candle reads Take from its linked Project item, including audio clips, subclips and multicamera groups. If two candles use the same clip or group, both show its logged take number. Each box displays the first two characters. Hover over it to read the full value. When Take is blank, the box shows the candle’s position in the setup.
Click a take number or candle to show that take in the shared thumbnail. With the take selected, press Left or Right to change the thumbnail frame. Hold the key to shuttle faster. Each take remembers its own frame. Double-click the thumbnail to cue that frame in Source.
Hold Cmd on macOS or Ctrl on Windows/Linux and drag a thumbnail to move its setup and candles together. Use the same modifier to drag a take number horizontally and reorder candles within the setup. You can also right-click the number and choose **Move Left** or **Move Right**.
## Mark a line and compare readings
1. Double-click the candle at the row you want to mark to open that take in **Source**. Find the frame where the line begins.
2. Click **Add script mark** (the split-circle button). Two half-circles appear beside the candle on that row.
3. Mark the same line on another take. Double-click either mark and press **Space** to hear that reading. A single click cues Source and keeps keyboard focus in Lined Script.
To mark as you watch, select a candle and use the joined **Play | Record** control. **Play** auditions the take in Source. **Record** plays it and lets you click the candle beside each line as you hear it. Each click saves the current Source frame. Clicking a marked row again updates its timing. You can switch between Play and Record mid-take. Click the active half again or press **Space** in Lined Script to stop. To see the picture while marking, dock Source beside Lined Script.
By default, Source cues **half a second before** the marked frame. Open the wrench, **Lined Script Display Settings**, and adjust **Pre-Roll Playback** from 0 to 5 seconds in 0.1-second steps. Choose 0 to cue the marked frame exactly. The lead-in stops at the linked source’s start. Double-clicking between marks cues an estimated position with the same lead-in. A candle without marks cues the start of the source.
Select candle rows and click **Mark offscreen** to toggle the zigzag for that passage. Click the **Color candle** swatch to color the selected rows. Right-click the swatch, or focus it and press Shift+F10, to pick a color. To use the current swatch by keyboard, assign **Apply Candle Color** in **Edit → Keyboard Shortcuts**.
To identify a whole setup by color, right-click its shared thumbnail and choose **Tree Outline Color**. This colors the thumbnail border, take-number boxes, connectors, candle outlines and end caps. Each candle keeps its fill and individual row colors. Choose **Theme Default** to restore the theme outline.
## Navigate and adjust the display
Use **Sc:** and **Pg:** to jump to a labeled row. To assign or edit a label, select the row and click the **+** next to the corresponding dropdown. Scene labels can include letters, such as `BB29`. **Search script** finds text across the active script. Use the attached arrows or press Enter and Shift+Enter to step through matches.
Open the **Lined Script Display Settings** wrench to change how the script reads.
| Control | Effect |
| --- | --- |
| Text size and Row spacing | Change the type size or adjust the extra space per row from 0 to 12 pt. Reduce row spacing to fit more lines at the same type size. |
| Left margin and Wrap margin | Set where text begins and wraps. You can also drag the two markers on the ruler. |
| Thumbnail size | Scale the setup picture while preserving its proportions. |
| Candle width | Adjust the candle stroke and the size of its half-circle marks. Wider marks automatically move neighboring take columns apart. |
| Candle distance | Set the gap between the outer edges of marks on adjacent takes in one setup. The default is **3 pt**, adjustable from **2 to 10 pt**. |
| Keep setup thumbnails visible while scrolling | Keep the thumbnail and take numbers in view as you scroll through a long candle. |
| Show row colors and Show line numbers | Toggle alternating row shading and the row numbers in the left gutter. |
| Show page controls and Hide page numbers in the right margin | Show the **Pg:** toolbar control or hide printed page labels independently. The toolbar control starts hidden. |
## Edit, copy and recover
Turn on **Edit** (the pencil) to change screenplay text or headings. Click a row to type. Pasting inside a row edits its text. Pasting on the canvas inserts new rows after the selection, or appends them when nothing is selected. Scene and page labels, takes, marks and candle colors can also be changed with Edit off.
To copy a passage with its takes, hold Option on macOS or Alt on Windows/Linux and drag across the rows and trees. Copy, switch to the destination tab, select the insertion row, turn on **Edit** and paste. The copied passage includes the intersecting coverage, marks, offscreen passages and row colors.
Shortening a candle hides annotations outside its coverage. Extend it again to reveal them. Deleting a script row removes its annotations. To remove a mark, candle or entire setup, select it and press Delete or Backspace. Select the thumbnail to delete the whole setup. **Edit → Undo** restores a deletion.
To delete a whole script, select it in **Project** and press Delete or choose **Clear** from its context menu. Use **Edit → Undo** to recover it while the deletion is in the project history. The built-in Help tab can be closed and reopened from **?**.
If a candle’s source goes offline or is deleted, drop the replacement clip on its candle or thumbnail, or choose **Rebind to Selected Project Clip**. FilmCraft uses source identity or a footage fingerprint to reconnect matching candles across scripts. Review the replacement if it changes the footage or excludes existing marks.
+7 -5
View File
@@ -24,10 +24,12 @@ writing them is `crates/format` (`filmcraft-format`); the engine's `file.*` comm
order, the active one, each sequence's zoom, scroll and track heights, and each sequence's
playhead (`filmcraft_project::ProjectView`). It is beside the project, not in it: it is not part of the
edit, never an undo step, and changing it does not mark the project as changed. Opening a
project restores it when the Timeline preference "Restore open sequences when opening projects"
is on. It is outside the schema version: older builds ignore it, ids that are not sequences and
numbers out of range are dropped or clamped (a playhead also snaps to a frame of its sequence), and a `view` that cannot be read is ignored (the
project opens on its first sequence, as it does without one or with no open sequence in it).
project restores its sequence view when the Timeline preference "Restore open sequences when opening projects"
is on. Lined Script independently restores its open tabs in order and its active tab. In
`script_tabs`, a null tab ID represents Help. Help edits live only in memory. Older builds
ignore unfamiliar view fields. On load, FilmCraft drops missing or mismatched tab IDs, clamps
view values to their supported ranges, and snaps each playhead to a frame of its sequence.
A project with an unreadable or missing view opens on its first sequence and the Help script.
- A coordinate of an effect's point parameter may be `null`. Point parameters use NaN for "auto"
(the frame centre, or the source centre for `anchor`), and JSON writes NaN as `null`; it reads back
as "auto". Placing a clip resolves these points at once. An interchange import resolves them
@@ -352,7 +354,7 @@ its original file preserves Script marks and candles. If a relink candidate cann
the same file and a linked Script take has marks, the command stops before changing any media.
The Link Media dialog asks for an explicit same-footage confirmation; command clients may pass
`confirmScriptSameFootage: true` after review. This preserves the marks; to use different footage,
replace the take in the Script window instead.
replace the take in the Lined Script window instead.
Link Media dialog automation ids: `linkMedia.row.<n>`,
`linkMedia.match.<fileName|extension|clipId|duration|mediaStart|metadata>`, `linkMedia.alignTimecode`,
-36
View File
@@ -1,36 +0,0 @@
# Script window settings inventory
Open **Window → Lined Script** to show the panel, or choose **Window → Workspaces → Lined Script** for the dedicated layout.
The Script toolbar has a gear menu for settings that are implemented today. This inventory tracks the other requested controls without presenting them as working features.
Toolbar controls wrap when the panel is narrow. Scene/Page captions stay with their menus, the **?** help button stays visible and aligned with the first row, and search sits below the wrapped controls. The **?** button opens the same getting-started guide shown before a script is created or imported.
Paste plain text with Cmd-V/Ctrl-V or Edit → Paste. With no script open, this creates a script. Otherwise it inserts after the selected row range, or appends when no rows are selected. Inside a row editor, paste replaces the character selection at the caret; each hard line break adds one logical row and shifts later rows down. Windows CRLF counts as one break. Existing row IDs, labels, candles and marks remain attached, and one Undo removes the paste while retaining text typed beforehand. Clicking outside the row editor, including another row's right margin, commits valid changes and closes the text box even if it has already lost keyboard focus. An unchanged blur adds no Undo step.
Shortening either candle endpoint changes only its visible coverage. Script marks, per-row colors, and off-screen passages on hidden lines remain stored with their original line IDs; marks also retain their IDs and exact source times. Expanding the candle reveals them again. Hidden marks have no canvas target and do not anchor visible-row cue interpolation. Deleting a logical line removes its annotations even when that line is hidden. No Script project schema change is needed.
Backspace or forward Delete removes the selected Script object: a mark, a candle, or a setup selected by its thumbnail. Deleting a thumbnail removes that entire setup with all its candles and marks. Deleting the last candle also removes its empty setup. Script text and Project media stay intact, and Undo restores the deleted objects. With no object selected these keys do nothing; in a text field they retain normal text-editing behavior.
Rows can be selected across the entire canvas width, beyond both text margins. Shift-click extends the selected range. Thumbnails, candles, and marks keep their own click actions; clicking elsewhere on a row clears those active objects and selects the row. Clicking below the rows clears the row selection.
Clips dragged from the Project panel can be dropped across the entire Script canvas width, including open space between take columns. Selected rows determine inclusive candle coverage regardless of the pointer row. New setups stay at the pointer's horizontal position, including when scrolled or when their thumbnails overlap another setup. A drop directly on an online thumbnail adds a candle to that setup, using selected rows or its last candle's coverage; selected-row drops outside the thumbnail create a separate setup. Without selected rows, the hovered line determines a new setup's coverage and a drop below the last line uses the last line.
Offline or deleted-source candles and thumbnails accept recovery drops before new-setup creation. Their menus also offer **Rebind to Selected Project Clip**. Recovery reconnects matching candles across scripts using the original Project source ID or retained footage fingerprint, never a filename match, in one Undo step. Matching footage preserves marks and styling; incompatible footage or a source span excluding existing marks requires review before a whole-batch replacement can clear marks. Without a retained source ID or fingerprint, only the targeted candle can be identified safely. Ordinary candle rebinding without a row selection retains its review safeguards.
| Control | FilmCraft state |
| --- | --- |
| Font and size | Text-size control in the gear menu; font-family choice pending. |
| Left margin, text width | Gear controls and draggable ruler markers. |
| Word Wrap | Always on; toggle pending. |
| Take Coloring | Set Color toolbar button and per-row candle colors; a separate default-color setting pending. |
| Pre-Roll | Pending; custom Script play/record remains deferred. |
| Show Frames | Pending. |
| Show All Takes | All takes are shown; filtering toggle pending. |
| Show Line Number | Gear toggle. |
| Interpolate Position | Double-clicking a candle cues Source at its start when unmarked, or interpolates between surrounding script marks by row. Continuous playback behavior remains pending. |
| Hold Slates Onscreen | Pending; requires scroll behavior design. |
| Script Window Background / White Background | Uses FilmCraft theme; white override pending. |
| Show Row Colors | Gear toggle. |
Possible context actions include Play, Delete, Find in Project, Add Script Mark, Apply/Clear Color to Range, Set Font, Script Settings, Show Script in Project, and Hide Sidebar. FilmCraft currently exposes mark, color-range, and Find in Project actions through its Script and Project controls. The other context actions are not implemented by this inventory.