FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
M3.12: Premiere default keyboard parity
Brandon Thomas3d14099425c1
diff --git a/ROADMAP.md b/ROADMAP.mdindex e87a65814..6f4d58113 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -60,7 +60,7 @@ Status: ✅ done · 🟡 in progress · ⬜ not started. Estimates are remaining| M0 | Skeleton + visual shell | ✅ | Workspace, 20 crates, dock/workspaces, Premiere 26 look, native menus, control channel, MCP, xtask gates (layers, wasm) | — | — || M1 | Media I/O | ✅ | MP4/MOV demux+mux, WAV, stills, MJPEG, symphonia audio (MP3/FLAC/ALAC/Vorbis), GOP seek + frame cache, import | Media Browser polish | 2 || M2 | H.264 decoder | ✅ | Own decoder, bit-exact on 37+ streams, 500–600 fps 1080p | — | — |-| M3 | Editing core | 🟡 | Edit algebra (insert/overwrite/razor/lift/extract/ripple/roll/slip/slide/rate-stretch/nest/paste), tools, markers, trim mode + Trim Monitor + dynamic J/K/L trimming, Keyboard Shortcuts editor with FilmCraft/Premiere/FCP/Avid presets; Edit/Clip/File menu commands (Label colours and Select Label Group, Paste/Remove Attributes, Select All Matching, Remove Unused, Consolidate Duplicates, Sequence From Clip, Bin From Selection, Offline File, Close Project, Make/Edit Subclip, Modify Audio Channels/Timecode, Frame Hold Options/Add Frame Hold/Insert Frame Hold Segment, Time Interpolation with frame blending, Fit/Fill frame, Breakout to Mono, Extract Audio, Replace With Clip; M3.11: Scene Edit Detection (pure-Rust cut detection, background job), Normalize Mix Track, Simplify Sequence, Transcribe Sequence, Find/Find Next and search bins, Automate to Sequence, Edit Original, Edit Offline, Source Settings, Update Metadata (XMP), Generate Audio Waveform, Project Settings General/Scratch Disks, Get Media File Properties, Save as Template, Selection as FilmCraft Project, Avid Log Exchange export, Flash Cue markers, Dynamic Audio Waveforms, Reveal Log Files, System Compatibility Report); multicam (Create Multi-Camera Source Sequence, Multi-Camera view with live switching on 1–9, angle switching, Enable/Flatten, Edit Cameras) and sync (Synchronize, Merge Clips; In/Out/timecode/marker/audio — GCC-PHAT, sample-accurate) | Multicam paging >16 angles and grid thumbnails, optical flow (renders as frame blending), ~200 Premiere default shortcuts whose commands don't exist yet | 6–10 |+| M3 | Editing core | 🟡 | Edit algebra (insert/overwrite/razor/lift/extract/ripple/roll/slip/slide/rate-stretch/nest/paste), tools, markers, trim mode + Trim Monitor + dynamic J/K/L trimming, Keyboard Shortcuts editor with FilmCraft/Premiere/FCP/Avid presets; Edit/Clip/File menu commands (Label colours and Select Label Group, Paste/Remove Attributes, Select All Matching, Remove Unused, Consolidate Duplicates, Sequence From Clip, Bin From Selection, Offline File, Close Project, Make/Edit Subclip, Modify Audio Channels/Timecode, Frame Hold Options/Add Frame Hold/Insert Frame Hold Segment, Time Interpolation with frame blending, Fit/Fill frame, Breakout to Mono, Extract Audio, Replace With Clip; M3.11: Scene Edit Detection (pure-Rust cut detection, background job), Normalize Mix Track, Simplify Sequence, Transcribe Sequence, Find/Find Next and search bins, Automate to Sequence, Edit Original, Edit Offline, Source Settings, Update Metadata (XMP), Generate Audio Waveform, Project Settings General/Scratch Disks, Get Media File Properties, Save as Template, Selection as FilmCraft Project, Avid Log Exchange export, Flash Cue markers, Dynamic Audio Waveforms, Reveal Log Files, System Compatibility Report); M3.12 keyboard parity: Premiere's default keyboard (~115 keyboard-only commands: edit-point navigation on targeted/any track, select clip at playhead/next/previous, extend edit to playhead, nudge/slip/slide selection, target and source-patch toggles, clip volume ±1 dB/many, frame maximize/full screen/panel cycling, monitor zoom, track heights, Project and Text panel keyboard navigation, text size/leading/alignment, Export Frame, poster frames; see docs/keyboard.md); multicam (Create Multi-Camera Source Sequence, Multi-Camera view with live switching on 1–9, angle switching, Enable/Flatten, Edit Cameras) and sync (Synchronize, Merge Clips; In/Out/timecode/marker/audio — GCC-PHAT, sample-accurate) | Multicam paging >16 angles and grid thumbnails, optical flow (renders as frame blending), 39 Premiere default shortcuts skipped with reasons in docs/keyboard.md (Productions, AI/cloud tools, work area bar, Production/Search panels) | 6–10 || M4 | Playback | 🟡 | Audio-clock master, prefetch with cancellation, J/K/L, correct dropped-frame stats, playback resolution, render bar + content-hashed render previews, App Nap opt-out; 1080p H.264 and 3 stacked 1080p streams play with 0 dropped frames | 4K under load, 8K, frame-threaded AV1 decode, reduced-resolution decode for multicam grids | 6–10 || M5 | Effects, keyframes, GPU | 🟡 | ~60 CPU effects, 30 transitions, keyframes + value/velocity graphs, wgpu compositor, effect + opacity masks (ellipse/polygon/pen, feather, expansion, modes; CPU/WGSL parity), mask tracking (Lucas–Kanade + RANSAC), adjustment layers, effect presets (built-in + user, JSON import/export) | Full ~150-effect catalogue, WGSL parity for all effects and masks in the live GPU path, Warp Stabilizer, Morph Cut | 20–30 || M6 | Export | ✅ | Own H.264 encoder (High/Main/Baseline, B-frames, VBR/CBR/2-pass) → MP4 or QuickTime + own AAC; ProRes, DNxHR, MJPEG, PNG/TIFF/BMP sequences (Premiere-style numbering), GIF, WAV, AIFF; background jobs; M6.5: Export mode parity (frame size / rate / scaling / pixel aspect, profile / level, CBR / VBR 1- and 2-pass, keyframe distance, audio codec / rate / channels / bitrate / sample size, multiplexer, burn-in or sidecar captions, image / name / timecode overlays, video limiter, loudness normalization with true-peak limiter, metadata, ranges, estimated size, summary), 24 built-in presets + user presets with favourites and import/export (Preset Manager), export queue (reorder, cancel, retry, several sequences / ranges), Quick Export; `export.*` commands and `filmcraft-cli export --preset` | Interlaced encoding, 5.1 audio, smart render, publishing destinations | 6–8 |diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 26b652c3f..f0916d2de 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -1441,20 +1441,9 @@ fn build() -> Vec<CommandSpec> {let n = s.prefs.playback.step_many_frames as i64;s.execute("playhead.step", json!({"frames": -n}))}),- cmd!("playhead.nextEdit", "Go to Next Edit Point", [], Some("Down"), "{}", has_seq, |s, _| {- let t = s.playhead();- if let Some(e) = s.active_sequence().and_then(|q| q.edit_points().into_iter().find(|e| *e > t)) {- s.set_playhead(e);- }- Ok(Value::Null)- }),- cmd!("playhead.prevEdit", "Go to Previous Edit Point", [], Some("Up"), "{}", has_seq, |s, _| {- let t = s.playhead();- if let Some(e) = s.active_sequence().and_then(|q| q.edit_points().into_iter().rev().find(|e| *e < t)) {- s.set_playhead(e);- }- Ok(Value::Null)- }),+ // Up / Down: edit points on the targeted tracks (Shift+Up / Shift+Down: any track)+ cmd!("playhead.nextEdit", "Go to Next Edit Point", [], Some("Down"), "{}", has_seq, |s, _| crate::keyboard::go_to_edit(s, true, false)),+ cmd!("playhead.prevEdit", "Go to Previous Edit Point", [], Some("Up"), "{}", has_seq, |s, _| crate::keyboard::go_to_edit(s, false, false)),cmd!("playhead.start", "Go to Sequence Start", [], Some("Home"), "{}", has_seq, |s, _| {s.set_playhead(Tick::ZERO);Ok(Value::Null)@@ -2133,6 +2122,7 @@ fn build() -> Vec<CommandSpec> {v.extend(crate::transcript::commands());v.extend(crate::panels::commands());v.extend(crate::scopes::commands());+ v.extend(crate::keyboard::commands());// Edit ▸ Label ▸ <colour>, Paste Attributes, subclips, Video / Audio Options, Replace With Clip…// and their menu ordercrate::clip_ops::apply_layout(&mut v);diff --git a/crates/engine/src/keyboard.rs b/crates/engine/src/keyboard.rsnew file mode 100644index 000000000..d6af66dc3--- /dev/null+++ b/crates/engine/src/keyboard.rs@@ -0,0 +1,741 @@+//! Keyboard-only editing commands from Premiere's default keyboard (M3.12): commands that have a+//! default shortcut in Premiere but no menu item, so they exist only to be pressed.+//!+//! | Id | Premiere command | Default key (scope) |+//! |---|---|---|+//! | `playhead.nextEditAnyTrack` / `playhead.prevEditAnyTrack` | Go to Next / Previous Edit Point on Any Track | Shift+Down / Shift+Up |+//! | `playhead.selectedClipStart` / `playhead.selectedClipEnd` | Go to Selected Clip Start / End | Shift+Home / Shift+End |+//! | `sequence.revealNested` | Reveal Nested Sequence | Cmd+Alt+F |+//! | `timeline.selectClipAtPlayhead` | Select Clip at Playhead | D |+//! | `timeline.selectNextClip` / `timeline.selectPrevClip` | Select Next / Previous Clip | Cmd+Down / Cmd+Up |+//! | `trim.extendPreviousEdit` / `trim.extendNextEdit` | Extend Previous / Next Edit To Playhead | Shift+Q / Shift+W |+//! | `timeline.nudgeLeft` … `timeline.nudgeRight5` | Nudge Clip Selection Left / Right One / Five Frames | Cmd+Left, Cmd+Right, Cmd+Shift+Left, Cmd+Shift+Right (Timeline) |+//! | `timeline.nudgeUp` / `timeline.nudgeDown` | Nudge Clip Selection Up / Down | Alt+Up / Alt+Down (Timeline) |+//! | `timeline.slipLeft` … `timeline.slipRight5` | Slip Clip Selection Left / Right One / Five Frames | Cmd+Alt+Left … Cmd+Alt+Shift+Right (Timeline) |+//! | `timeline.slideLeft` … `timeline.slideRight5` | Slide Clip Selection Left / Right One / Five Frames | Alt+, … Alt+Shift+. (Timeline) |+//! | `timeline.toggleAllVideoTargets` / `timeline.toggleAllAudioTargets` | Toggle All Video / Audio Targets | Cmd+0 / Cmd+9 |+//! | `timeline.toggleAllSourceVideo` / `timeline.toggleAllSourceAudio` | Toggle All Source Video / Audio | Cmd+Alt+0 / Cmd+Alt+9 |+//! | `timeline.toggleTargetV1` … `timeline.toggleTargetA8` | Toggle Target Video 1–8 / Audio 1–8 | |+//! | `timeline.moveVideoTargetsUp` … `timeline.moveAudioTargetsDown` | Move All Video / Audio Targets Up / Down | |+//! | `timeline.toggleMuteTargetedAudio` / `timeline.toggleSoloTargetedAudio` | Toggle Mute / Solo for All Targeted Audio Tracks | |+//! | `timeline.toggleOutputTargetedVideo` | Toggle Track Output for All Targeted Video Tracks | |+//! | `clip.volumeUp` / `clip.volumeDown` | Increase / Decrease Clip Volume (1 dB) | ] / [ |+//! | `clip.volumeUpMany` / `clip.volumeDownMany` | Increase / Decrease Clip Volume Many (Settings ▸ Audio ▸ Large Volume Adjustment) | Shift+] / Shift+[ |+//! | `clip.nudgeVolumeUp1` … `clip.nudgeVolumeDown3` | Nudge Volume ±1 dB / ±3 dB | |+//! | `audio.toggleScrubbing` | Toggle Audio During Scrubbing | Shift+S |+//! | `graphics.fontSizeUp` … `graphics.fontSizeDown5` | Increase / Decrease Font Size by One / Five Units | Cmd+Alt+Right … Cmd+Alt+Shift+Left |+//! | `graphics.leadingUp` … `graphics.leadingDown5` | Increase / Decrease Leading by One / Five Units | Alt+Up … Alt+Shift+Down |+//! | `graphics.alignTextLeft` / `…Center` / `…Right` | Left / Center / Right align text | Cmd+Shift+L / C / R |+//! | `graphics.nudgeLeft` … `graphics.nudgeDown5` | Nudge Selected Object by one / five | Cmd+arrows, Cmd+Shift+arrows (Program, Properties) |+//! | `file.exportFrame` | Export Frame | Shift+E |+//! | `clip.setPosterFrame` / `clip.clearPosterFrame` | Set / Clear Poster Frame | Cmd+P / Alt+P |+//!+//! Navigation and targeting are editor state (not undoable, as in Premiere); everything that+//! changes the project is one undo step.++use filmcraft_edit as edit;+use filmcraft_geom::Vec2;+use filmcraft_project::{ClipId, ItemKind, ParamValue, Sequence, TrackId, TrackKind};+use filmcraft_time::Tick;+use serde_json::{Value, json};++use crate::commands::{CommandSpec, always, bad, has_selection, has_seq, item_p, str_p, time_p, with_links};+use crate::{EngineError, Result, Session};++type Run = fn(&mut Session, &Value) -> Result<Value>;+type Enabled = fn(&Session) -> std::result::Result<(), String>;++fn spec(id: &'static str, label: &'static str, shortcut: Option<&'static str>, params: &'static str, enabled: Enabled, run: Run) -> CommandSpec {+ CommandSpec { id, label, menu: &[], shortcut, params, enabled, run, journal: true }+}++/// Metadata key holding an item's poster frame (media ticks).+pub const POSTER_FRAME_KEY: &str = "Poster Frame";++/// An item's poster frame (Set Poster Frame), if one is set.+pub fn poster_frame(item: &filmcraft_project::ProjectItem) -> Option<Tick> {+ item.metadata.get(POSTER_FRAME_KEY).and_then(|v| v.parse::<i64>().ok()).map(Tick)+}++// ------------------------------------------------------------------ navigation++/// Edit points on the given tracks (all tracks when `tracks` is None), sorted and unique.+fn edits_on(seq: &Sequence, tracks: Option<&[TrackId]>) -> Vec<Tick> {+ let mut v: Vec<Tick> =+ seq.all_tracks().filter(|t| tracks.is_none_or(|ts| ts.contains(&t.id))).flat_map(|t| t.items.iter().flat_map(|i| [i.start, i.end()])).collect();+ v.sort_unstable();+ v.dedup();+ v+}++/// Go to the next / previous edit point: on the targeted tracks (`any` = false; all tracks when+/// none is targeted) or on any track.+pub fn go_to_edit(s: &mut Session, next: bool, any: bool) -> Result<Value> {+ let t = s.playhead();+ let tg = s.targeting().targeted;+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let only = (!any && !tg.is_empty()).then_some(tg.as_slice());+ let edits = edits_on(seq, only);+ let e = if next { edits.into_iter().find(|e| *e > t) } else { edits.into_iter().rev().find(|e| *e < t) };+ if let Some(e) = e {+ s.set_playhead(e);+ }+ Ok(json!({"time": s.playhead().0}))+}++fn selected_span(s: &Session) -> Option<(Tick, Tick)> {+ let seq = s.active_sequence()?;+ let items: Vec<_> = s.state.selection.iter().filter_map(|c| seq.find_item(*c).map(|(_, i)| i)).collect();+ let a = items.iter().map(|i| i.start).min()?;+ let b = items.iter().map(|i| i.end()).max()?;+ Some((a, b))+}++fn go_to_selected(s: &mut Session, end: bool) -> Result<Value> {+ let (a, b) = selected_span(s).ok_or_else(|| EngineError::Other("no clips selected".into()))?;+ // Premiere parks on the clip's last frame for End (the frame before the Out edge)+ let t = if end { b - s.sequence_rate().frame_duration() } else { a };+ s.set_playhead(t.max(a));+ Ok(json!({"time": s.playhead().0}))+}++/// Reveal Nested Sequence: open the nested sequence of the selected clip (or the topmost nested+/// clip under the playhead on a targeted track) with its playhead on the matching frame.+fn reveal_nested(s: &mut Session) -> Result<Value> {+ let ph = s.playhead();+ let tg = s.targeting().targeted;+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let is_nest = |it: &filmcraft_project::TrackItem| s.project.sequence(it.item).is_some();+ let pick = s+ .state+ .selection+ .iter()+ .filter_map(|c| seq.find_item(*c).map(|(_, i)| i))+ .find(|i| is_nest(i))+ .or_else(|| {+ seq.video_tracks.iter().rev().chain(seq.audio_tracks.iter()).filter(|t| tg.contains(&t.id)).filter_map(|t| t.item_at(ph)).find(|i| is_nest(i))+ })+ .ok_or_else(|| EngineError::Other("select a nested sequence clip".into()))?;+ let (nested, t) = (pick.item, pick.source_time_at(ph.clamp(pick.start, pick.end() - Tick(1))));+ s.execute("sequence.open", json!({"item": nested.0}))?;+ s.set_playhead(t);+ Ok(json!({"sequence": nested.0, "time": s.playhead().0}))+}++// ------------------------------------------------------------------ selection++fn select_clip_at_playhead(s: &mut Session) -> Result<Value> {+ let t = s.playhead();+ let tg = s.targeting().targeted;+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let ids: Vec<ClipId> = seq.all_tracks().filter(|tr| tg.contains(&tr.id)).filter_map(|tr| tr.item_at(t).map(|i| i.id)).collect();+ s.state.selection = with_links(s, &ids);+ s.state.edit_points.clear();+ s.state.caption_selection.clear();+ Ok(json!({"selection": s.state.selection.iter().map(|c| c.0).collect::<Vec<_>>()}))+}++/// Select Next / Previous Clip: the clip after (before) the selection on each selected clip's+/// track; with nothing selected, the clips at the playhead on the targeted tracks.+fn select_step(s: &mut Session, next: bool) -> Result<Value> {+ if s.state.selection.is_empty() {+ return select_clip_at_playhead(s);+ }+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ // one anchor per track: the last (first) selected item+ let mut picks: Vec<ClipId> = Vec::new();+ for tr in seq.all_tracks() {+ let sel: Vec<usize> = tr.items.iter().enumerate().filter(|(_, i)| s.state.selection.contains(&i.id)).map(|(k, _)| k).collect();+ let Some(&anchor) = (if next { sel.last() } else { sel.first() }) else { continue };+ let k = if next { Some(anchor + 1) } else { anchor.checked_sub(1) };+ if let Some(it) = k.and_then(|k| tr.items.get(k)) {+ picks.push(it.id);+ }+ }+ // linked partners already follow their own track's step; keep the old selection when at the end+ if picks.is_empty() {+ return Ok(json!({"selection": s.state.selection.iter().map(|c| c.0).collect::<Vec<_>>()}));+ }+ s.state.selection = with_links(s, &picks);+ Ok(json!({"selection": s.state.selection.iter().map(|c| c.0).collect::<Vec<_>>()}))+}++// ------------------------------------------------------------------ trimming++/// Extend Previous / Next Edit To Playhead: on each targeted, unlocked track, move the nearest edit+/// point before (after) the playhead to the playhead. A cut between two clips rolls; an edge+/// next to a gap is trimmed (no ripple).+fn extend_edit(s: &mut Session, next: bool) -> Result<Value> {+ let ph = s.playhead();+ let tg = s.targeting().targeted;+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let mut ops: Vec<(Option<ClipId>, Option<ClipId>, Tick)> = Vec::new();+ for tr in seq.all_tracks().filter(|t| tg.contains(&t.id) && !t.locked) {+ let edges = tr.items.iter().flat_map(|i| [i.start, i.end()]);+ let e = if next { edges.filter(|e| *e > ph).min() } else { edges.filter(|e| *e < ph).max() };+ let Some(e) = e else { continue };+ let left = tr.items.iter().find(|i| i.end() == e).map(|i| i.id);+ let right = tr.items.iter().find(|i| i.start == e).map(|i| i.id);+ ops.push((left, right, ph - e));+ }+ if ops.is_empty() {+ return Err(EngineError::Other("no edit point on the targeted tracks".into()));+ }+ let label = if next { "Extend Next Edit To Playhead" } else { "Extend Previous Edit To Playhead" };+ s.edit_sequence(label, |q, ctx, _| {+ for (l, r, d) in &ops {+ match (l, r) {+ (Some(l), Some(r)) => {+ edit::roll(q, *l, *r, *d, ctx)?;+ }+ (Some(l), None) => {+ edit::trim(q, *l, edit::Edge::Out, edit::TrimMode::Regular, *d, ctx)?;+ }+ (None, Some(r)) => {+ edit::trim(q, *r, edit::Edge::In, edit::TrimMode::Regular, *d, ctx)?;+ }+ (None, None) => {}+ }+ }+ Ok(())+ })?;+ Ok(json!({"edits": ops.len()}))+}++/// Nudge the selection (with linked partners) by `frames` along the timeline (overwrite).+fn nudge_time(s: &mut Session, frames: i64) -> Result<Value> {+ let d = s.sequence_rate().tick_of(frames);+ let clips = with_links(s, &s.state.selection.clone());+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let items: Vec<(ClipId, TrackId, Tick)> = clips.iter().filter_map(|c| seq.find_item(*c).map(|(t, i)| (*c, t, i.start))).collect();+ let min_start = items.iter().map(|m| m.2).min().unwrap_or_default();+ // never past the sequence start+ let d = d.max(-min_start);+ if d == Tick::ZERO {+ return Ok(json!({"delta": 0}));+ }+ let moves: Vec<(ClipId, TrackId, Tick)> = items.into_iter().map(|(c, t, st)| (c, t, st + d)).collect();+ s.edit_sequence("Nudge", |q, ctx, _| Ok(edit::move_items(q, &moves, false, ctx)?))?;+ Ok(json!({"delta": d.0}))+}++/// Nudge the selected clips one track up (`up`) or down, as the timeline shows them: video up is+/// V(n+1), audio up is A(n-1).+fn nudge_track(s: &mut Session, up: bool) -> Result<Value> {+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let mut moves = Vec::new();+ for c in &s.state.selection {+ let Some((tid, it)) = seq.find_item(*c) else { continue };+ let Some(tr) = seq.track(tid) else { continue };+ let list = seq.tracks(tr.kind);+ let idx = list.iter().position(|t| t.id == tid).unwrap_or(0) as i64;+ let step = match (tr.kind, up) {+ (TrackKind::Video, true) | (TrackKind::Audio, false) => 1,+ _ => -1,+ };+ let dest = usize::try_from(idx + step).ok().and_then(|i| list.get(i)).ok_or_else(|| EngineError::Other("no track to move to".into()))?;+ moves.push((*c, dest.id, it.start));+ }+ if moves.is_empty() {+ return Err(EngineError::Other("no clips selected".into()));+ }+ s.edit_sequence("Nudge", |q, ctx, _| Ok(edit::move_items(q, &moves, false, ctx)?))?;+ Ok(json!({"moved": moves.len()}))+}++fn slip_selection(s: &mut Session, frames: i64) -> Result<Value> {+ let rate = s.sequence_rate();+ let clips = with_links(s, &s.state.selection.clone());+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ // media delta per clip (source frames run at the clip's speed)+ let deltas: Vec<(ClipId, Tick)> = clips+ .iter()+ .filter_map(|c| seq.find_item(*c).map(|(_, i)| (*c, Tick((rate.tick_of(frames).0 as f64 * i.speed.abs().max(1e-9)).round() as i64))))+ .collect();+ s.edit_sequence("Slip", |q, ctx, _| {+ for (c, d) in &deltas {+ edit::slip(q, *c, *d, ctx)?;+ }+ Ok(())+ })?;+ Ok(Value::Null)+}++fn slide_selection(s: &mut Session, frames: i64) -> Result<Value> {+ let d = s.sequence_rate().tick_of(frames);+ let clips = with_links(s, &s.state.selection.clone());+ s.edit_sequence("Slide", |q, ctx, _| {+ for c in &clips {+ edit::slide(q, *c, d, ctx)?;+ }+ Ok(())+ })?;+ Ok(Value::Null)+}++// ------------------------------------------------------------------ targeting++fn set_targeting(s: &mut Session, tg: crate::Targeting) -> Result<Value> {+ let seq = s.state.active_sequence.ok_or(EngineError::NoSequence)?;+ let out = json!({+ "targeted": tg.targeted.iter().map(|t| t.0).collect::<Vec<_>>(),+ "videoDest": tg.video_dest.map(|t| t.0),+ "audioDest": tg.audio_dest.map(|t| t.0),+ });+ s.state.targeting.insert(seq, tg);+ Ok(out)+}++fn track_ids(s: &Session, kind: TrackKind) -> Vec<TrackId> {+ s.active_sequence().map(|q| q.tracks(kind).iter().map(|t| t.id).collect()).unwrap_or_default()+}++fn toggle_all_targets(s: &mut Session, kind: TrackKind) -> Result<Value> {+ let ids = track_ids(s, kind);+ let mut tg = s.targeting();+ if ids.iter().all(|t| tg.targeted.contains(t)) {+ tg.targeted.retain(|t| !ids.contains(t));+ } else {+ for t in ids {+ if !tg.targeted.contains(&t) {+ tg.targeted.push(t);+ }+ }+ }+ set_targeting(s, tg)+}++fn toggle_all_source(s: &mut Session, kind: TrackKind) -> Result<Value> {+ let first = track_ids(s, kind).first().copied();+ let mut tg = s.targeting();+ let slot = if kind == TrackKind::Video { &mut tg.video_dest } else { &mut tg.audio_dest };+ *slot = if slot.is_some() { None } else { first };+ set_targeting(s, tg)+}++fn toggle_target(s: &mut Session, kind: TrackKind, n: usize) -> Result<Value> {+ let t = *track_ids(s, kind)+ .get(n - 1)+ .ok_or_else(|| EngineError::Other(format!("there is no track {}{n}", if kind == TrackKind::Video { "V" } else { "A" })))?;+ let mut tg = s.targeting();+ if let Some(i) = tg.targeted.iter().position(|x| *x == t) {+ tg.targeted.remove(i);+ } else {+ tg.targeted.push(t);+ }+ set_targeting(s, tg)+}++/// Move All Video / Audio Targets Up / Down: shift every targeted track of `kind` by one.+fn move_targets(s: &mut Session, kind: TrackKind, up: bool) -> Result<Value> {+ let ids = track_ids(s, kind);+ let mut tg = s.targeting();+ let idx: Vec<usize> = ids.iter().enumerate().filter(|(_, t)| tg.targeted.contains(t)).map(|(i, _)| i).collect();+ // visually up: video n+1, audio n-1+ let step: i64 = if (kind == TrackKind::Video) == up { 1 } else { -1 };+ if idx.iter().any(|i| *i as i64 + step < 0 || *i as i64 + step >= ids.len() as i64) {+ return Err(EngineError::Other("the targets are already at the edge".into()));+ }+ tg.targeted.retain(|t| !ids.contains(t));+ tg.targeted.extend(idx.iter().map(|i| ids[(*i as i64 + step) as usize]));+ set_targeting(s, tg)+}++fn toggle_targeted_tracks(s: &mut Session, kind: TrackKind, what: &'static str) -> Result<Value> {+ let tg = s.targeting().targeted;+ let ids: Vec<TrackId> = track_ids(s, kind).into_iter().filter(|t| tg.contains(t)).collect();+ if ids.is_empty() {+ return Err(EngineError::Other("no targeted tracks".into()));+ }+ let label = match what {+ "mute" => "Toggle Mute",+ "solo" => "Toggle Solo",+ _ => "Toggle Track Output",+ };+ s.edit_sequence(label, |q, _, _| {+ // all on → all off, else all on+ let get = |t: &filmcraft_project::Track| match what {+ "mute" => t.muted,+ "solo" => t.solo,+ _ => !t.enabled,+ };+ let all = ids.iter().filter_map(|i| q.track(*i)).all(get);+ for i in &ids {+ if let Some(t) = q.track_mut(*i) {+ match what {+ "mute" => t.muted = !all,+ "solo" => t.solo = !all,+ _ => t.enabled = all,+ }+ }+ }+ Ok(())+ })?;+ Ok(Value::Null)+}++// ------------------------------------------------------------------ audio++const VOLUME_MIN_DB: f64 = -287.5;+const VOLUME_MAX_DB: f64 = 15.0;++/// Change the Volume level of the selected audio clips by `db` (keyframed levels shift as a whole).+pub fn adjust_clip_volume(s: &mut Session, db: f64) -> Result<Value> {+ let clips = with_links(s, &s.state.selection.clone());+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let audio: Vec<ClipId> =+ clips.into_iter().filter(|c| seq.find_item(*c).and_then(|(t, _)| seq.track(t)).is_some_and(|t| t.kind == TrackKind::Audio)).collect();+ if audio.is_empty() {+ return Err(EngineError::Other("select audio clips".into()));+ }+ let shift = |v: &ParamValue| match v {+ ParamValue::Float(x) => ParamValue::Float((x + db).clamp(VOLUME_MIN_DB, VOLUME_MAX_DB)),+ o => o.clone(),+ };+ let label = if db > 0.0 { "Increase Clip Volume" } else { "Decrease Clip Volume" };+ s.edit_sequence(label, |q, _, _| {+ for c in &audio {+ let Some((_, it)) = q.find_item_mut(*c) else { continue };+ let Some(p) = it.effect_mut("volume").and_then(|e| e.param_mut("level")) else { continue };+ p.value = shift(&p.value);+ for k in &mut p.keyframes {+ k.value = shift(&k.value);+ }+ }+ Ok(())+ })?;+ let levels: Vec<Value> = s+ .active_sequence()+ .map(|q| {+ audio+ .iter()+ .filter_map(|c| q.find_item(*c))+ .filter_map(|(_, it)| it.effect("volume").and_then(|e| e.params.get("level")).and_then(|p| p.value.as_f64()))+ .map(|v| json!(v))+ .collect()+ })+ .unwrap_or_default();+ Ok(json!({"levels": levels}))+}++// ------------------------------------------------------------------ graphics++fn text_layer_targets(s: &Session) -> Result<(ClipId, Vec<usize>)> {+ let clip = crate::graphics::target_clip(s, &Value::Null).ok_or_else(|| EngineError::Other("select a graphic clip".into()))?;+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let (_, it) = seq.find_item(clip).ok_or_else(|| EngineError::Other("no such clip".into()))?;+ let idx = filmcraft_project::graphic::layer_indices(&it.effects);+ if idx.is_empty() {+ return Err(EngineError::Other("the graphic has no layers".into()));+ }+ let chosen: Vec<usize> = if s.state.graphic_layers.is_empty() {+ vec![*idx.last().unwrap_or(&0)]+ } else {+ s.state.graphic_layers.iter().filter_map(|l| idx.get(*l).copied()).collect()+ };+ Ok((clip, chosen))+}++/// Apply `f` to parameter `param` of the targeted graphic layers at the playhead (keyframe-aware).+fn edit_layers(s: &mut Session, label: &str, param: &'static str, text_only: bool, f: impl Fn(&ParamValue) -> Option<ParamValue>) -> Result<Value> {+ let (clip, layers) = text_layer_targets(s)?;+ let tl = s.playhead();+ let n = s.edit_sequence(label, |q, _, _| {+ let (_, it) = q.find_item_mut(clip).ok_or(filmcraft_edit::EditError::NoItem(clip))?;+ let mt = it.source_time_at(tl.clamp(it.start, it.end() - Tick(1)));+ let mut n = 0;+ for ei in &layers {+ let Some(e) = it.effects.get_mut(*ei) else { continue };+ if text_only && !e.params.contains_key("text") {+ continue;+ }+ let Some(p) = e.params.get_mut(param) else { continue };+ if let Some(v) = f(&p.value_at(mt)) {+ p.set_at(mt, v);+ n += 1;+ }+ }+ if n == 0 {+ return Err(EngineError::Other(if text_only { "select a text layer".into() } else { "nothing to change".into() }));+ }+ Ok(n)+ })?;+ Ok(json!({"layers": n}))+}++fn font_size(s: &mut Session, d: f64) -> Result<Value> {+ edit_layers(s, "Font Size", "size", true, |v| match v {+ ParamValue::Float(x) => Some(ParamValue::Float((x + d).clamp(1.0, 2000.0))),+ _ => None,+ })+}++fn leading(s: &mut Session, d: f64) -> Result<Value> {+ edit_layers(s, "Leading", "leading", true, |v| match v {+ ParamValue::Float(x) => Some(ParamValue::Float((x + d).clamp(-5000.0, 5000.0))),+ _ => None,+ })+}++fn align_text(s: &mut Session, choice: u32) -> Result<Value> {+ edit_layers(s, "Text Alignment", "align", true, move |_| Some(ParamValue::Choice(choice)))+}++/// Nudge Selected Object: graphic layers when a graphic is targeted, else the Motion position of+/// the selected video clips.+fn nudge_object(s: &mut Session, dx: f64, dy: f64) -> Result<Value> {+ let shift = move |v: &ParamValue| match v {+ ParamValue::Vec2(p) => Some(ParamValue::Vec2(Vec2::new(p.x + dx, p.y + dy))),+ _ => None,+ };+ if crate::graphics::target_clip(s, &Value::Null).is_some()+ && s.state.selection.iter().all(|c| s.active_sequence().is_some_and(|q| crate::graphics::is_graphic(s, q, *c)))+ {+ return edit_layers(s, "Nudge", "position", false, shift);+ }+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;+ let clips: Vec<ClipId> =+ s.state.selection.iter().copied().filter(|c| seq.find_item(*c).and_then(|(t, _)| seq.track(t)).is_some_and(|t| t.kind == TrackKind::Video)).collect();+ if clips.is_empty() {+ return Err(EngineError::Other("select a video clip or a graphic".into()));+ }+ let tl = s.playhead();+ s.edit_sequence("Nudge", |q, _, _| {+ for c in &clips {+ let Some((_, it)) = q.find_item_mut(*c) else { continue };+ let mt = it.source_time_at(tl.clamp(it.start, it.end() - Tick(1)));+ if let Some(p) = it.effect_mut("motion").and_then(|e| e.param_mut("position"))+ && let Some(v) = shift(&p.value_at(mt))+ {+ p.set_at(mt, v);+ }+ }+ Ok(())+ })?;+ Ok(json!({"clips": clips.len()}))+}++fn has_graphic_or_selection(s: &Session) -> std::result::Result<(), String> {+ has_seq(s)?;+ if crate::graphics::target_clip(s, &Value::Null).is_some() || !s.state.selection.is_empty() { Ok(()) } else { Err("select a clip or a graphic".into()) }+}+fn has_graphic(s: &Session) -> std::result::Result<(), String> {+ has_seq(s)?;+ crate::graphics::target_clip(s, &Value::Null).map(|_| ()).ok_or_else(|| "select a graphic clip".into())+}++// ------------------------------------------------------------------ export frame, poster frame++fn sanitize(name: &str) -> String {+ name.chars().map(|c| if matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') { '_' } else { c }).collect()+}++/// Export Frame: render the Program monitor frame at the playhead to a still image.+fn export_frame(s: &mut Session, p: &Value) -> Result<Value> {+ let fmt = str_p(p, "format").unwrap_or("png").to_ascii_lowercase();+ let format = match fmt.as_str() {+ "png" => filmcraft_export::Format::PngSequence,+ "tif" | "tiff" => filmcraft_export::Format::TiffSequence,+ "bmp" => filmcraft_export::Format::BmpSequence,+ _ => return Err(bad("file.exportFrame", "format must be png, tiff or bmp")),+ };+ let ext = if fmt == "tif" { "tiff" } else { fmt.as_str() };+ let seq_name = s.state.active_sequence.and_then(|i| s.project.item(i)).map(|i| i.name.clone()).unwrap_or_else(|| "Sequence".into());+ let path = match str_p(p, "path") {+ Some(path) => path.to_string(),+ None => {+ let dir = s.path.as_deref().and_then(|p| std::path::Path::new(p).parent()).map(|d| d.to_string_lossy().to_string()).unwrap_or_default();+ let base = sanitize(&seq_name);+ let mut n = 1;+ loop {+ let name = format!("{base}.Still{n:03}.{ext}");+ let cand = if dir.is_empty() { name } else { format!("{dir}/{name}") };+ if s.services.file_size(&cand).is_err() || n > 9999 {+ break cand;+ }+ n += 1;+ }+ }+ };+ let img = s.render_program(1.0).ok_or(EngineError::NoSequence)?;+ let (w, h) = (img.w as u32, img.h as u32);+ let bytes = filmcraft_export::encode_still(format, img.to_rgba8(), w, h).map_err(|e| EngineError::Other(e.to_string()))?;+ s.services.write_file(&path, &bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;+ let mut out = json!({"path": path, "width": w, "height": h});+ if p.get("import").and_then(Value::as_bool).unwrap_or(false) {+ out["import"] = s.execute("file.import", json!({"paths": [path]}))?;+ }+ s.toast(format!("Exported frame to {path}"));+ Ok(out)+}++/// The item Set / Clear Poster Frame acts on, and the frame: `item` + time, else the Source+/// monitor clip at its playhead, else the first Project panel selection (its current poster).+fn poster_target(s: &Session, p: &Value) -> Option<(filmcraft_project::ItemId, Tick)> {+ if let Some(i) = item_p(p, "item") {+ return Some((i, time_p(s, p, "").unwrap_or_default()));+ }+ let sel = s.state.project_selection.first().copied();+ match (s.state.source_item, sel) {+ (Some(src), None) => Some((src, s.state.source_playhead)),+ (Some(src), Some(sel)) if src == sel => Some((src, s.state.source_playhead)),+ (_, Some(sel)) => Some((sel, time_p(s, p, "").unwrap_or_default())),+ (None, None) => None,+ }+}++fn set_poster(s: &mut Session, p: &Value, clear: bool) -> Result<Value> {+ let (item, t) = poster_target(s, p).ok_or_else(|| EngineError::Other("open a clip in the Source monitor or select one in the Project panel".into()))?;+ let it = s.project.item(item).ok_or_else(|| bad("clip.setPosterFrame", "no such item"))?;+ if matches!(it.kind, ItemKind::AdjustmentLayer { .. }) {+ return Err(EngineError::Other("adjustment layers have no poster frame".into()));+ }+ let snapped = it.frame_rate().snap(t);+ s.edit(if clear { "Clear Poster Frame" } else { "Set Poster Frame" }, |pr, _| {+ let it = pr.item_mut(item).ok_or_else(|| bad("clip.setPosterFrame", "no such item"))?;+ if clear {+ it.metadata.remove(POSTER_FRAME_KEY);+ } else {+ it.metadata.insert(POSTER_FRAME_KEY.into(), snapped.0.to_string());+ }+ Ok(())+ })?;+ Ok(json!({"item": item.0, "posterFrame": (!clear).then_some(snapped.0)}))+}++fn has_poster_target(s: &Session) -> std::result::Result<(), String> {+ if s.state.source_item.is_some() || !s.state.project_selection.is_empty() {+ Ok(())+ } else {+ Err("open a clip in the Source monitor or select one in the Project panel".into())+ }+}++// ------------------------------------------------------------------ registry++pub fn commands() -> Vec<CommandSpec> {+ use TrackKind::{Audio, Video};+ let mut v = vec![+ // ---- navigation+ spec("playhead.nextEditAnyTrack", "Go to Next Edit Point on Any Track", Some("Shift+Down"), "{}", has_seq, |s, _| go_to_edit(s, true, true)),+ spec("playhead.prevEditAnyTrack", "Go to Previous Edit Point on Any Track", Some("Shift+Up"), "{}", has_seq, |s, _| go_to_edit(s, false, true)),+ spec("playhead.selectedClipStart", "Go to Selected Clip Start", Some("Shift+Home"), "{}", has_selection, |s, _| go_to_selected(s, false)),+ spec("playhead.selectedClipEnd", "Go to Selected Clip End", Some("Shift+End"), "{}", has_selection, |s, _| go_to_selected(s, true)),+ spec("sequence.revealNested", "Reveal Nested Sequence", Some("Cmd+Alt+F"), "{}", has_seq, |s, _| reveal_nested(s)),+ // ---- selection+ spec("timeline.selectClipAtPlayhead", "Select Clip at Playhead", Some("D"), "{}", has_seq, |s, _| select_clip_at_playhead(s)),+ spec("timeline.selectNextClip", "Select Next Clip", Some("Cmd+Down"), "{}", has_seq, |s, _| select_step(s, true)),+ spec("timeline.selectPrevClip", "Select Previous Clip", Some("Cmd+Up"), "{}", has_seq, |s, _| select_step(s, false)),+ // ---- trimming+ spec("trim.extendPreviousEdit", "Extend Previous Edit To Playhead", Some("Shift+Q"), "{}", has_seq, |s, _| extend_edit(s, false)),+ spec("trim.extendNextEdit", "Extend Next Edit To Playhead", Some("Shift+W"), "{}", has_seq, |s, _| extend_edit(s, true)),+ spec("timeline.nudgeLeft", "Nudge Clip Selection Left One Frame", None, "{}", has_selection, |s, _| nudge_time(s, -1)),+ spec("timeline.nudgeRight", "Nudge Clip Selection Right One Frame", None, "{}", has_selection, |s, _| nudge_time(s, 1)),+ spec("timeline.nudgeLeft5", "Nudge Clip Selection Left Five Frames", None, "{}", has_selection, |s, _| nudge_time(s, -5)),+ spec("timeline.nudgeRight5", "Nudge Clip Selection Right Five Frames", None, "{}", has_selection, |s, _| nudge_time(s, 5)),+ spec("timeline.nudgeUp", "Nudge Clip Selection Up", None, "{}", has_selection, |s, _| nudge_track(s, true)),+ spec("timeline.nudgeDown", "Nudge Clip Selection Down", None, "{}", has_selection, |s, _| nudge_track(s, false)),+ spec("timeline.slipLeft", "Slip Clip Selection Left One Frame", None, "{}", has_selection, |s, _| slip_selection(s, 1)),+ spec("timeline.slipRight", "Slip Clip Selection Right One Frame", None, "{}", has_selection, |s, _| slip_selection(s, -1)),+ spec("timeline.slipLeft5", "Slip Clip Selection Left Five Frames", None, "{}", has_selection, |s, _| slip_selection(s, 5)),+ spec("timeline.slipRight5", "Slip Clip Selection Right Five Frames", None, "{}", has_selection, |s, _| slip_selection(s, -5)),+ spec("timeline.slideLeft", "Slide Clip Selection Left One Frame", None, "{}", has_selection, |s, _| slide_selection(s, -1)),+ spec("timeline.slideRight", "Slide Clip Selection Right One Frame", None, "{}", has_selection, |s, _| slide_selection(s, 1)),+ spec("timeline.slideLeft5", "Slide Clip Selection Left Five Frames", None, "{}", has_selection, |s, _| slide_selection(s, -5)),+ spec("timeline.slideRight5", "Slide Clip Selection Right Five Frames", None, "{}", has_selection, |s, _| slide_selection(s, 5)),+ // ---- targeting+ spec("timeline.toggleAllVideoTargets", "Toggle All Video Targets", Some("Cmd+0"), "{}", has_seq, |s, _| toggle_all_targets(s, Video)),+ spec("timeline.toggleAllAudioTargets", "Toggle All Audio Targets", Some("Cmd+9"), "{}", has_seq, |s, _| toggle_all_targets(s, Audio)),+ spec("timeline.toggleAllSourceVideo", "Toggle All Source Video", Some("Cmd+Alt+0"), "{}", has_seq, |s, _| toggle_all_source(s, Video)),+ spec("timeline.toggleAllSourceAudio", "Toggle All Source Audio", Some("Cmd+Alt+9"), "{}", has_seq, |s, _| toggle_all_source(s, Audio)),+ spec("timeline.moveVideoTargetsUp", "Move All Video Targets Up", None, "{}", has_seq, |s, _| move_targets(s, Video, true)),+ spec("timeline.moveVideoTargetsDown", "Move All Video Targets Down", None, "{}", has_seq, |s, _| move_targets(s, Video, false)),+ spec("timeline.moveAudioTargetsUp", "Move All Audio Targets Up", None, "{}", has_seq, |s, _| move_targets(s, Audio, true)),+ spec("timeline.moveAudioTargetsDown", "Move All Audio Targets Down", None, "{}", has_seq, |s, _| move_targets(s, Audio, false)),+ spec("timeline.toggleMuteTargetedAudio", "Toggle Mute for All Targeted Audio Tracks", None, "{}", has_seq, |s, _| {+ toggle_targeted_tracks(s, Audio, "mute")+ }),+ spec("timeline.toggleSoloTargetedAudio", "Toggle Solo for All Targeted Audio Tracks", None, "{}", has_seq, |s, _| {+ toggle_targeted_tracks(s, Audio, "solo")+ }),+ spec("timeline.toggleOutputTargetedVideo", "Toggle Track Output for All Targeted Video Tracks", None, "{}", has_seq, |s, _| {+ toggle_targeted_tracks(s, Video, "output")+ }),+ // ---- audio+ spec("clip.volumeUp", "Increase Clip Volume", Some("]"), "{}", has_selection, |s, _| adjust_clip_volume(s, 1.0)),+ spec("clip.volumeDown", "Decrease Clip Volume", Some("["), "{}", has_selection, |s, _| adjust_clip_volume(s, -1.0)),+ spec("clip.volumeUpMany", "Increase Clip Volume Many", Some("Shift+]"), "{}", has_selection, |s, _| {+ let d = s.prefs.audio.large_volume_adjustment;+ adjust_clip_volume(s, d)+ }),+ spec("clip.volumeDownMany", "Decrease Clip Volume Many", Some("Shift+["), "{}", has_selection, |s, _| {+ let d = s.prefs.audio.large_volume_adjustment;+ adjust_clip_volume(s, -d)+ }),+ spec("clip.nudgeVolumeUp1", "Nudge Volume +1dB", None, "{}", has_selection, |s, _| adjust_clip_volume(s, 1.0)),+ spec("clip.nudgeVolumeUp3", "Nudge Volume +3dB", None, "{}", has_selection, |s, _| adjust_clip_volume(s, 3.0)),+ spec("clip.nudgeVolumeDown1", "Nudge Volume -1dB", None, "{}", has_selection, |s, _| adjust_clip_volume(s, -1.0)),+ spec("clip.nudgeVolumeDown3", "Nudge Volume -3dB", None, "{}", has_selection, |s, _| adjust_clip_volume(s, -3.0)),+ spec("audio.toggleScrubbing", "Toggle Audio During Scrubbing", Some("Shift+S"), "{}", always, |s, _| {+ let on = !s.prefs.audio.scrub_audio;+ s.execute("prefs.set", json!({"key": "audio.scrubAudio", "value": on}))?;+ s.toast(if on { "Audio during scrubbing on" } else { "Audio during scrubbing off" });+ Ok(json!({"scrubAudio": on}))+ }),+ // ---- graphics and titles+ spec("graphics.fontSizeUp", "Increase Font Size by One Unit", Some("Cmd+Alt+Right"), "{}", has_graphic, |s, _| font_size(s, 1.0)),+ spec("graphics.fontSizeDown", "Decrease Font Size by One Unit", Some("Cmd+Alt+Left"), "{}", has_graphic, |s, _| font_size(s, -1.0)),+ spec("graphics.fontSizeUp5", "Increase Font Size by Five Units", Some("Cmd+Alt+Shift+Right"), "{}", has_graphic, |s, _| font_size(s, 5.0)),+ spec("graphics.fontSizeDown5", "Decrease Font Size by Five Units", Some("Cmd+Alt+Shift+Left"), "{}", has_graphic, |s, _| font_size(s, -5.0)),+ spec("graphics.leadingUp", "Increase Leading by One Unit", Some("Alt+Up"), "{}", has_graphic, |s, _| leading(s, 1.0)),+ spec("graphics.leadingDown", "Decrease Leading by One Unit", Some("Alt+Down"), "{}", has_graphic, |s, _| leading(s, -1.0)),+ spec("graphics.leadingUp5", "Increase Leading by Five Units", Some("Alt+Shift+Up"), "{}", has_graphic, |s, _| leading(s, 5.0)),+ spec("graphics.leadingDown5", "Decrease Leading by Five Units", Some("Alt+Shift+Down"), "{}", has_graphic, |s, _| leading(s, -5.0)),+ spec("graphics.alignTextLeft", "Left align text", Some("Cmd+Shift+L"), "{}", has_graphic, |s, _| align_text(s, 0)),+ spec("graphics.alignTextCenter", "Center align text", Some("Cmd+Shift+C"), "{}", has_graphic, |s, _| align_text(s, 1)),+ spec("graphics.alignTextRight", "Right align text", Some("Cmd+Shift+R"), "{}", has_graphic, |s, _| align_text(s, 2)),+ spec("graphics.nudgeLeft", "Nudge Selected Object to left by one", None, "{}", has_graphic_or_selection, |s, _| nudge_object(s, -1.0, 0.0)),+ spec("graphics.nudgeRight", "Nudge Selected Object to right by one", None, "{}", has_graphic_or_selection, |s, _| nudge_object(s, 1.0, 0.0)),+ spec("graphics.nudgeUp", "Nudge Selected Object up by one", None, "{}", has_graphic_or_selection, |s, _| nudge_object(s, 0.0, -1.0)),+ spec("graphics.nudgeDown", "Nudge Selected Object down by one", None, "{}", has_graphic_or_selection, |s, _| nudge_object(s, 0.0, 1.0)),+ spec("graphics.nudgeLeft5", "Nudge Selected Object to left by five", None, "{}", has_graphic_or_selection, |s, _| nudge_object(s, -5.0, 0.0)),+ spec("graphics.nudgeRight5", "Nudge Selected Object to right by five", None, "{}", has_graphic_or_selection, |s, _| nudge_object(s, 5.0, 0.0)),+ spec("graphics.nudgeUp5", "Nudge Selected Object up by five", None, "{}", has_graphic_or_selection, |s, _| nudge_object(s, 0.0, -5.0)),+ spec("graphics.nudgeDown5", "Nudge Selected Object down by five", None, "{}", has_graphic_or_selection, |s, _| nudge_object(s, 0.0, 5.0)),+ // ---- export frame, poster frame+ // Shift+E is Clip > Enable in FilmCraft Default; the Premiere preset moves it here+ spec("file.exportFrame", "Export Frame", None, r#"{"path":str?,"format":"png|tiff|bmp"?,"import":bool?}"#, has_seq, export_frame),+ spec("clip.setPosterFrame", "Set Poster Frame", Some("Cmd+P"), r#"{"item":id?,"time":ticks?}"#, has_poster_target, |s, p| set_poster(s, p, false)),+ spec("clip.clearPosterFrame", "Clear Poster Frame", Some("Alt+P"), r#"{"item":id?}"#, has_poster_target, |s, p| set_poster(s, p, true)),+ ];+ v.extend(target_toggles());+ v+}++/// Toggle Target Video 1–8 / Audio 1–8.+fn target_toggles() -> Vec<CommandSpec> {+ macro_rules! tt {+ ($id:literal, $label:literal, $kind:expr, $n:literal) => {+ spec($id, $label, None, "{}", has_seq, |s, _| toggle_target(s, $kind, $n))+ };+ }+ use TrackKind::{Audio, Video};+ vec![+ tt!("timeline.toggleTargetV1", "Toggle Target Video 1", Video, 1),+ tt!("timeline.toggleTargetV2", "Toggle Target Video 2", Video, 2),+ tt!("timeline.toggleTargetV3", "Toggle Target Video 3", Video, 3),+ tt!("timeline.toggleTargetV4", "Toggle Target Video 4", Video, 4),+ tt!("timeline.toggleTargetV5", "Toggle Target Video 5", Video, 5),+ tt!("timeline.toggleTargetV6", "Toggle Target Video 6", Video, 6),+ tt!("timeline.toggleTargetV7", "Toggle Target Video 7", Video, 7),+ tt!("timeline.toggleTargetV8", "Toggle Target Video 8", Video, 8),+ tt!("timeline.toggleTargetA1", "Toggle Target Audio 1", Audio, 1),+ tt!("timeline.toggleTargetA2", "Toggle Target Audio 2", Audio, 2),+ tt!("timeline.toggleTargetA3", "Toggle Target Audio 3", Audio, 3),+ tt!("timeline.toggleTargetA4", "Toggle Target Audio 4", Audio, 4),+ tt!("timeline.toggleTargetA5", "Toggle Target Audio 5", Audio, 5),+ tt!("timeline.toggleTargetA6", "Toggle Target Audio 6", Audio, 6),+ tt!("timeline.toggleTargetA7", "Toggle Target Audio 7", Audio, 7),+ tt!("timeline.toggleTargetA8", "Toggle Target Audio 8", Audio, 8),+ ]+}diff --git a/crates/engine/src/keyboard_tests.rs b/crates/engine/src/keyboard_tests.rsnew file mode 100644index 000000000..b23a9809d--- /dev/null+++ b/crates/engine/src/keyboard_tests.rs@@ -0,0 +1,378 @@+//! Keyboard parity commands (M3.12): the shortcut tables, navigation, selection, trimming,+//! nudging, targeting, clip volume, text layers, poster and export frames.++use super::*;+use crate::shortcut_presets as presets;+use crate::shortcuts::Chord;+use filmcraft_project::ParamValue;+use serde_json::json;++fn demo() -> Session {+ let mut s = Session::default();+ s.execute("file.openDemoProject", json!({})).unwrap();+ s+}++/// (id, start, end) of the items on a track.+fn items(s: &Session, kind: TrackKind, idx: usize) -> Vec<(u64, Tick, Tick)> {+ s.active_sequence().unwrap().tracks(kind)[idx].items.iter().map(|i| (i.id.0, i.start, i.end())).collect()+}++fn clip(s: &Session, id: u64) -> filmcraft_project::TrackItem {+ s.active_sequence().unwrap().find_item(ClipId(id)).unwrap().1.clone()+}++fn track_of(s: &Session, id: u64) -> TrackId {+ s.active_sequence().unwrap().find_item(ClipId(id)).unwrap().0+}++/// Target only V1.+fn target_v1(s: &mut Session) {+ let tg = s.targeting();+ let v1 = s.active_sequence().unwrap().video_tracks[0].id;+ for t in tg.targeted {+ s.execute("timeline.setTargeting", json!({"track": t.0, "targeted": t == v1})).unwrap();+ }+ s.execute("timeline.setTargeting", json!({"track": v1.0, "targeted": true})).unwrap();+}++#[test]+fn shortcut_tables_have_no_key_used_twice_in_one_scope() {+ let tables: [(&str, Vec<presets::Entry>); 4] = [+ ("Premiere", presets::premiere()),+ ("FilmCraft panels", presets::FILMCRAFT_PANEL.iter().chain(presets::PREMIERE_PANEL).copied().collect()),+ ("Final Cut", presets::FINAL_CUT.to_vec()),+ ("Avid", presets::AVID.to_vec()),+ ];+ for (name, table) in tables {+ let mut seen: std::collections::BTreeMap<(String, String), &str> = Default::default();+ for (id, keys, panel) in table {+ let chord = Chord::parse(keys).unwrap_or_else(|e| panic!("{name}: `{keys}` for {id}: {e}")).canonical();+ if let Some(other) = seen.insert((panel.to_string(), chord.clone()), id) {+ panic!("{name}: {chord} in scope `{panel}` is bound to both {other} and {id}");+ }+ }+ }+ // the FilmCraft Default set (registry defaults + panel tables + the Premiere audit) has no+ // same-context conflicts for the new commands either+ let s = Session::default();+ let new_ids: Vec<&str> = keyboard::commands().iter().map(|c| c.id).collect();+ for (ctx, key, ids) in s.shortcuts.conflicts(crate::shortcuts::Platform::Mac) {+ assert!(!ids.iter().any(|i| new_ids.contains(&i.as_str())), "conflict on {key} ({ctx}): {ids:?}");+ }+}++#[test]+fn premiere_engine_entries_exist() {+ // UI-owned ids (tools, transport, panels…) are checked by the ui-egui keyboard test+ let ui_prefixes =+ ["tool.", "playback.", "window.", "view.", "app.", "help.", "mode.", "multicam.", "projectPanel.", "textPanel.", "panel.", "mediaBrowser."];+ let ui_ids = ["timeline.expandAllTracks", "timeline.minimizeAllTracks", "graphics.beginTextEditing"];+ for (id, _, _) in presets::premiere() {+ if id.starts_with("timeline.") && (id.contains("Height") || id.contains("Screen")) || ui_ids.contains(&id) {+ continue;+ }+ if ui_prefixes.iter().any(|p| id.starts_with(p)) && commands::find(id).is_none() {+ continue;+ }+ assert!(commands::find(id).is_some(), "Premiere table names unknown engine command `{id}`");+ }+}++#[test]+fn edit_point_navigation_follows_targets_or_any_track() {+ let mut s = demo();+ target_v1(&mut s);+ let v1 = items(&s, TrackKind::Video, 0);+ let mut v1_edges: Vec<Tick> = v1.iter().flat_map(|c| [c.1, c.2]).collect();+ v1_edges.dedup();+ let all = s.active_sequence().unwrap().edit_points();+ s.set_playhead(Tick::ZERO);+ // Down walks V1's edit points only+ for e in v1_edges.iter().skip(1) {+ s.execute("playhead.nextEdit", json!({})).unwrap();+ assert_eq!(s.playhead(), *e);+ }+ // Shift+Up walks every track's edit points backwards+ let mut expect: Vec<Tick> = all.iter().copied().filter(|t| *t < s.playhead()).collect();+ expect.reverse();+ for e in expect.iter().take(3) {+ s.execute("playhead.prevEditAnyTrack", json!({})).unwrap();+ assert_eq!(s.playhead(), *e);+ }+ s.set_playhead(Tick::ZERO);+ s.execute("playhead.nextEditAnyTrack", json!({})).unwrap();+ assert_eq!(s.playhead(), all[1]);+}++#[test]+fn select_clip_at_playhead_next_previous_and_go_to_selected_clip() {+ let mut s = demo();+ target_v1(&mut s);+ let v1 = items(&s, TrackKind::Video, 0);+ let rate = s.sequence_rate();+ s.set_playhead(v1[1].1 + rate.tick_of(3));+ // D: the clip under the playhead on V1 (and its linked audio)+ let r = s.execute("timeline.selectClipAtPlayhead", json!({})).unwrap();+ assert!(s.state.selection.contains(&ClipId(v1[1].0)), "{r}");+ assert!(!s.state.selection.is_empty());+ // Cmd+Down / Cmd+Up step along the track+ s.execute("timeline.selectNextClip", json!({})).unwrap();+ assert!(s.state.selection.contains(&ClipId(v1[2].0)));+ assert!(!s.state.selection.contains(&ClipId(v1[1].0)));+ s.execute("timeline.selectPrevClip", json!({})).unwrap();+ s.execute("timeline.selectPrevClip", json!({})).unwrap();+ assert!(s.state.selection.contains(&ClipId(v1[0].0)));+ // Shift+Home / Shift+End+ s.execute("timeline.select", json!({"clips": [v1[1].0]})).unwrap();+ s.execute("playhead.selectedClipStart", json!({})).unwrap();+ assert_eq!(s.playhead(), v1[1].1);+ s.execute("playhead.selectedClipEnd", json!({})).unwrap();+ assert_eq!(s.playhead(), v1[1].2 - rate.frame_duration(), "parks on the clip's last frame");+ // nothing selected: disabled with a reason+ s.execute("edit.deselectAll", json!({})).unwrap();+ assert!(s.execute("playhead.selectedClipStart", json!({})).is_err());+}++#[test]+fn extend_previous_and_next_edit_roll_cuts_to_the_playhead() {+ let mut s = demo();+ target_v1(&mut s);+ let rate = s.sequence_rate();+ let v1 = items(&s, TrackKind::Video, 0);+ let dur0 = s.active_sequence().unwrap().duration();+ let undo0 = s.history.undo.len();+ // Shift+Q: the cut before the playhead rolls to it+ let ph = v1[1].1 + rate.tick_of(10);+ s.set_playhead(ph);+ s.execute("trim.extendPreviousEdit", json!({})).unwrap();+ assert_eq!(clip(&s, v1[0].0).end(), ph);+ assert_eq!(clip(&s, v1[1].0).start, ph);+ assert_eq!(s.active_sequence().unwrap().duration(), dur0, "a roll keeps the duration");+ assert_eq!(s.history.undo.len(), undo0 + 1);+ assert_eq!(s.history.undo.last().unwrap().0, "Extend Previous Edit To Playhead");+ s.undo();+ assert_eq!(clip(&s, v1[0].0).end(), v1[0].2);+ // Shift+W: the cut after the playhead rolls back to it+ let ph = v1[1].2 - rate.tick_of(4);+ s.set_playhead(ph);+ s.execute("trim.extendNextEdit", json!({})).unwrap();+ assert_eq!(clip(&s, v1[1].0).end(), ph);+ assert_eq!(clip(&s, v1[2].0).start, ph);+}++#[test]+fn nudge_slip_and_slide_the_selection_with_undo() {+ let mut s = demo();+ let rate = s.sequence_rate();+ let v1 = items(&s, TrackKind::Video, 0);+ let last = *v1.last().unwrap();+ s.execute("timeline.select", json!({"clips": [last.0]})).unwrap();+ let sel: Vec<(ClipId, Tick)> = s.state.selection.iter().map(|c| (*c, clip(&s, c.0).start)).collect();+ assert!(sel.len() > 1, "the linked audio is selected too");+ // Cmd+Right: one frame later, linked audio too+ s.execute("timeline.nudgeRight", json!({})).unwrap();+ for (c, st) in &sel {+ assert_eq!(clip(&s, c.0).start, *st + rate.tick_of(1));+ }+ assert_eq!(s.history.undo.last().unwrap().0, "Nudge");+ s.execute("timeline.nudgeLeft5", json!({})).unwrap();+ assert_eq!(clip(&s, last.0).start, last.1 - rate.tick_of(4));+ s.undo();+ s.undo();+ assert_eq!(clip(&s, last.0).start, last.1);+ // Alt+Up / Alt+Down: to the track above (V1 -> V2) and back+ let v1_id = track_of(&s, last.0);+ s.state.selection = vec![ClipId(last.0)];+ s.execute("timeline.nudgeUp", json!({})).unwrap();+ assert_eq!(track_of(&s, last.0), s.active_sequence().unwrap().video_tracks[1].id);+ assert_eq!(clip(&s, last.0).start, last.1, "a vertical nudge keeps the time");+ s.execute("timeline.nudgeDown", json!({})).unwrap();+ assert_eq!(track_of(&s, last.0), v1_id);+ assert!(s.execute("timeline.nudgeDown", json!({})).is_err(), "there is no track below V1");+ // slip: the source In moves, the clip stays+ let mid = v1[1];+ s.execute("timeline.select", json!({"clips": [mid.0]})).unwrap();+ let in0 = clip(&s, mid.0).source_in;+ s.execute("timeline.slipLeft5", json!({})).unwrap();+ assert_eq!(clip(&s, mid.0).source_in, in0 + rate.tick_of(5));+ assert_eq!(clip(&s, mid.0).start, mid.1);+ // slide: the clip moves, its neighbours absorb it+ s.execute("timeline.slideRight", json!({})).unwrap();+ assert_eq!(clip(&s, mid.0).start, mid.1 + rate.tick_of(1));+ assert_eq!(clip(&s, v1[0].0).end(), mid.1 + rate.tick_of(1));+ assert_eq!(s.history.undo.last().unwrap().0, "Slide");+}++#[test]+fn targeting_toggles() {+ let mut s = demo();+ let seq = s.active_sequence().unwrap().clone();+ let vids: Vec<TrackId> = seq.video_tracks.iter().map(|t| t.id).collect();+ let auds: Vec<TrackId> = seq.audio_tracks.iter().map(|t| t.id).collect();+ // Cmd+0: all video targeted → none+ s.execute("timeline.toggleAllVideoTargets", json!({})).unwrap();+ assert!(vids.iter().all(|t| !s.targeting().targeted.contains(t)));+ assert!(auds.iter().all(|t| s.targeting().targeted.contains(t)), "audio untouched");+ s.execute("timeline.toggleAllVideoTargets", json!({})).unwrap();+ assert!(vids.iter().all(|t| s.targeting().targeted.contains(t)));+ // Cmd+9+ s.execute("timeline.toggleAllAudioTargets", json!({})).unwrap();+ assert!(auds.iter().all(|t| !s.targeting().targeted.contains(t)));+ // Toggle Target Audio 2+ s.execute("timeline.toggleTargetA2", json!({})).unwrap();+ assert_eq!(s.targeting().targeted.iter().filter(|t| auds.contains(t)).collect::<Vec<_>>(), vec![&auds[1]]);+ assert!(s.execute("timeline.toggleTargetA8", json!({})).is_err(), "no A8 in the demo");+ // Move All Audio Targets Up: A2 → A1 (the track above)+ s.execute("timeline.moveAudioTargetsUp", json!({})).unwrap();+ assert_eq!(s.targeting().targeted.iter().filter(|t| auds.contains(t)).collect::<Vec<_>>(), vec![&auds[0]]);+ assert!(s.execute("timeline.moveAudioTargetsUp", json!({})).is_err(), "already at the top");+ // Cmd+Alt+0 / Cmd+Alt+9: source patching off and back on (to V1 / A1)+ s.execute("timeline.toggleAllSourceVideo", json!({})).unwrap();+ assert_eq!(s.targeting().video_dest, None);+ s.execute("timeline.toggleAllSourceVideo", json!({})).unwrap();+ assert_eq!(s.targeting().video_dest, Some(vids[0]));+ s.execute("timeline.toggleAllSourceAudio", json!({})).unwrap();+ assert_eq!(s.targeting().audio_dest, None);+ // mute targeted audio tracks: undoable+ s.execute("timeline.toggleMuteTargetedAudio", json!({})).unwrap();+ assert!(s.active_sequence().unwrap().audio_tracks[0].muted);+ assert!(!s.active_sequence().unwrap().audio_tracks[1].muted);+ s.undo();+ assert!(!s.active_sequence().unwrap().audio_tracks[0].muted);+ s.execute("timeline.toggleOutputTargetedVideo", json!({})).unwrap();+ assert!(s.active_sequence().unwrap().video_tracks.iter().all(|t| !t.enabled));+ s.execute("timeline.toggleOutputTargetedVideo", json!({})).unwrap();+ assert!(s.active_sequence().unwrap().video_tracks.iter().all(|t| t.enabled));+}++fn level(s: &Session, id: u64) -> f64 {+ clip(s, id).effect("volume").unwrap().params["level"].value.as_f64().unwrap()+}++#[test]+fn clip_volume_keys_and_scrub_toggle() {+ let mut s = demo();+ let a1 = items(&s, TrackKind::Audio, 0);+ let c = a1[0].0;+ let l0 = level(&s, c);+ s.execute("timeline.select", json!({"clips": [c]})).unwrap();+ s.execute("clip.volumeUp", json!({})).unwrap();+ assert_eq!(level(&s, c), l0 + 1.0);+ s.execute("clip.volumeDownMany", json!({})).unwrap();+ assert_eq!(level(&s, c), l0 + 1.0 - s.prefs.audio.large_volume_adjustment);+ s.undo();+ s.undo();+ assert_eq!(level(&s, c), l0);+ // a video clip's linked audio follows it+ let v = items(&s, TrackKind::Video, 0)[0].0;+ s.execute("timeline.select", json!({"clips": [v]})).unwrap();+ s.execute("clip.volumeUp", json!({})).unwrap();+ assert_eq!(level(&s, c), l0 + 1.0);+ // Shift+S+ let on = s.prefs.audio.scrub_audio;+ let r = s.execute("audio.toggleScrubbing", json!({})).unwrap();+ assert_eq!(r["scrubAudio"], json!(!on));+ assert_eq!(s.prefs.audio.scrub_audio, !on);+}++#[test]+fn text_layer_keys_change_size_leading_alignment_and_position() {+ let mut s = demo();+ s.set_playhead(Tick::ZERO);+ let r = s.execute("graphics.newText", json!({"text": "Hello"})).unwrap();+ let c = r["clip"].as_u64().unwrap();+ s.execute("timeline.select", json!({"clips": [c]})).unwrap();+ let layer = |s: &Session| {+ let it = clip(s, c);+ let idx = filmcraft_project::graphic::layer_indices(&it.effects);+ it.effects[*idx.last().unwrap()].clone()+ };+ let f = |s: &Session, p: &str| layer(s).params[p].value.as_f64().unwrap_or(f64::NAN);+ let size0 = f(&s, "size");+ s.execute("graphics.fontSizeUp", json!({})).unwrap();+ s.execute("graphics.fontSizeUp5", json!({})).unwrap();+ assert_eq!(f(&s, "size"), size0 + 6.0);+ s.execute("graphics.leadingDown", json!({})).unwrap();+ assert_eq!(f(&s, "leading"), -1.0);+ s.execute("graphics.alignTextRight", json!({})).unwrap();+ assert_eq!(layer(&s).params["align"].value, ParamValue::Choice(2));+ let pos = |s: &Session| match layer(s).params["position"].value {+ ParamValue::Vec2(v) => (v.x, v.y),+ _ => panic!("position"),+ };+ let p0 = pos(&s);+ s.execute("graphics.nudgeRight5", json!({})).unwrap();+ s.execute("graphics.nudgeUp", json!({})).unwrap();+ assert_eq!(pos(&s), (p0.0 + 5.0, p0.1 - 1.0));+ // all undoable+ for _ in 0..6 {+ s.undo();+ }+ assert_eq!(f(&s, "size"), size0);+ assert_eq!(pos(&s), p0);+}++#[test]+fn nudge_object_moves_motion_position_of_video_clips() {+ let mut s = demo();+ let v = items(&s, TrackKind::Video, 0)[0];+ s.state.selection = vec![ClipId(v.0)];+ let pos = |s: &Session| match clip(s, v.0).effect("motion").unwrap().params["position"].value {+ ParamValue::Vec2(p) => (p.x, p.y),+ _ => panic!("position"),+ };+ let p0 = pos(&s);+ s.execute("graphics.nudgeLeft", json!({})).unwrap();+ s.execute("graphics.nudgeDown5", json!({})).unwrap();+ assert_eq!(pos(&s), (p0.0 - 1.0, p0.1 + 5.0));+}++#[test]+fn poster_frame_and_export_frame() {+ let mut s = demo();+ let v = items(&s, TrackKind::Video, 0)[0];+ let item = clip(&s, v.0).item;+ s.execute("source.open", json!({"item": item.0})).unwrap();+ s.execute("source.setPlayhead", json!({"frame": 12})).unwrap();+ let r = s.execute("clip.setPosterFrame", json!({})).unwrap();+ let rate = s.project.item(item).unwrap().frame_rate();+ assert_eq!(r["posterFrame"], json!(rate.tick_of(12).0));+ assert_eq!(keyboard::poster_frame(s.project.item(item).unwrap()), Some(rate.tick_of(12)));+ s.execute("clip.clearPosterFrame", json!({})).unwrap();+ assert_eq!(keyboard::poster_frame(s.project.item(item).unwrap()), None);+ s.undo();+ assert!(keyboard::poster_frame(s.project.item(item).unwrap()).is_some());++ // Shift+E writes the Program frame+ let dir = std::env::temp_dir().join(format!("fc-export-frame-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("frame.png");+ let r = s.execute("file.exportFrame", json!({"path": path.to_string_lossy()})).unwrap();+ let bytes = std::fs::read(&path).unwrap();+ assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");+ let seq = s.active_sequence().unwrap();+ assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (seq.settings.width as u64, seq.settings.height as u64));+ // with Import, the still lands in the project+ let n = s.project.items.len();+ s.execute("file.exportFrame", json!({"path": dir.join("frame2.tiff").to_string_lossy(), "format": "tiff", "import": true})).unwrap();+ assert_eq!(s.project.items.len(), n + 1);+ let _ = std::fs::remove_dir_all(&dir);+}++#[test]+fn reveal_nested_sequence_opens_it_at_the_matching_frame() {+ let mut s = demo();+ let outer = s.state.active_sequence.unwrap();+ let v = items(&s, TrackKind::Video, 0)[1];+ s.execute("timeline.select", json!({"clips": [v.0]})).unwrap();+ s.execute("clip.nest", json!({"name": "Nest"})).unwrap();+ let nest_clip = s.active_sequence().unwrap().video_tracks[0].items.iter().find(|i| s.project.sequence(i.item).is_some()).unwrap().clone();+ let rate = s.sequence_rate();+ s.set_playhead(nest_clip.start + rate.tick_of(7));+ s.state.selection = vec![nest_clip.id];+ let r = s.execute("sequence.revealNested", json!({})).unwrap();+ assert_eq!(s.state.active_sequence, Some(nest_clip.item));+ assert_ne!(s.state.active_sequence, Some(outer));+ assert_eq!(s.playhead(), nest_clip.source_in + rate.tick_of(7), "{r}");+}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 368ebd80a..e936408be 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -18,6 +18,7 @@ pub mod essential_sound;pub mod export_tools;pub mod graphics;pub mod interchange;+pub mod keyboard;pub mod masks;pub mod media_pool;pub mod mixer;@@ -812,6 +813,8 @@ mod file_tests;#[cfg(test)]mod image_sequence_tests;#[cfg(test)]+mod keyboard_tests;+#[cfg(test)]mod masks_tests;#[cfg(test)]mod media_test_util;diff --git a/crates/engine/src/shortcut_presets.rs b/crates/engine/src/shortcut_presets.rsindex f769ccf12..38f5a234a 100644--- a/crates/engine/src/shortcut_presets.rs+++ b/crates/engine/src/shortcut_presets.rs@@ -179,13 +179,182 @@ pub const PREMIERE: &[Entry] = &[("trim.backwardMany", "Alt+Shift+Left", ""),("trim.forward", "Alt+Right", ""),("trim.forwardMany", "Alt+Shift+Right", ""),+ // Keyboard parity (M3.12): commands that only have a key+ ("file.close", "Cmd+W", ""),+ ("file.closeProject", "Cmd+Shift+W", ""),+ ("file.importFromMediaBrowser", "Cmd+Alt+I", ""),+ ("export.queue.add", "Alt+Shift+M", ""),+ ("file.mediaProperties", "Cmd+Shift+H", ""),+ ("edit.pasteAttributes", "Cmd+Alt+V", ""),+ ("edit.find", "Cmd+F", ""),+ ("edit.editOriginal", "Cmd+E", ""),+ ("clip.makeSubclip", "Cmd+U", ""),+ ("clip.audioChannels", "Shift+G", ""),+ ("graphics.newText", "Cmd+T", ""),+ ("graphics.newRectangle", "Cmd+Alt+R", ""),+ ("graphics.newEllipse", "Cmd+Alt+E", ""),+ ("graphics.bringToFront", "Cmd+Shift+]", ""),+ ("graphics.bringForward", "Cmd+]", ""),+ ("graphics.sendBackward", "Cmd+[", ""),+ ("graphics.sendToBack", "Cmd+Shift+[", ""),+ ("graphics.selectNextLayer", "Cmd+Alt+]", ""),+ ("graphics.selectPreviousLayer", "Cmd+Alt+[", ""),+ ("graphics.beginTextEditing", "Cmd+Alt+'", ""),+ ("graphics.alignTextLeft", "Cmd+Shift+L", ""),+ ("graphics.alignTextCenter", "Cmd+Shift+C", ""),+ ("graphics.alignTextRight", "Cmd+Shift+R", ""),+ ("graphics.fontSizeUp", "Cmd+Alt+Right", ""),+ ("graphics.fontSizeDown", "Cmd+Alt+Left", ""),+ ("graphics.fontSizeUp5", "Cmd+Alt+Shift+Right", ""),+ ("graphics.fontSizeDown5", "Cmd+Alt+Shift+Left", ""),+ ("graphics.leadingUp", "Alt+Up", ""),+ ("graphics.leadingDown", "Alt+Down", ""),+ ("graphics.leadingUp5", "Alt+Shift+Up", ""),+ ("graphics.leadingDown5", "Alt+Shift+Down", ""),+ ("help.filmcraftHelp", "F1", ""),+ ("app.quit", "Cmd+Q", ""),+ ("clip.setPosterFrame", "Cmd+P", ""),+ ("clip.clearPosterFrame", "Alt+P", ""),+ ("clip.volumeUp", "]", ""),+ ("clip.volumeDown", "[", ""),+ ("clip.volumeUpMany", "Shift+]", ""),+ ("clip.volumeDownMany", "Shift+[", ""),+ ("timeline.expandAllTracks", "Shift+=", ""),+ ("timeline.minimizeAllTracks", "Shift+-", ""),+ ("file.exportFrame", "Shift+E", ""),+ ("trim.extendPreviousEdit", "Shift+Q", ""),+ ("trim.extendNextEdit", "Shift+W", ""),+ ("playhead.nextEditAnyTrack", "Shift+Down", ""),+ ("playhead.prevEditAnyTrack", "Shift+Up", ""),+ ("playhead.selectedClipStart", "Shift+Home", ""),+ ("playhead.selectedClipEnd", "Shift+End", ""),+ ("window.maximizeFrame", "Shift+`", ""),+ ("window.maximizeFrameUnderCursor", "`", ""),+ ("window.toggleFullScreen", "Ctrl+`", ""),+ ("window.openSearch", "Cmd+Shift+F", ""),+ ("panel.selectFindBox", "Shift+F", ""),+ ("playback.inToOutPreroll", "Shift+Space", ""),+ ("playback.toOut", "Ctrl+Space", ""),+ ("sequence.revealNested", "Cmd+Alt+F", ""),+ ("timeline.selectClipAtPlayhead", "D", ""),+ ("timeline.selectNextClip", "Cmd+Down", ""),+ ("timeline.selectPrevClip", "Cmd+Up", ""),+ ("window.nextPanel", "Ctrl+Shift+.", ""),+ ("window.prevPanel", "Ctrl+Shift+,", ""),+ ("timeline.toggleAllAudioTargets", "Cmd+9", ""),+ ("timeline.toggleAllSourceAudio", "Cmd+Alt+9", ""),+ ("timeline.toggleAllSourceVideo", "Cmd+Alt+0", ""),+ ("timeline.toggleAllVideoTargets", "Cmd+0", ""),+ ("audio.toggleScrubbing", "Shift+S", ""),+ ("window.workspace.learning", "Alt+Shift+7", ""),+ ("window.workspace.review", "Alt+Shift+8", ""),+ ("window.workspace.allpanels", "Alt+Shift+9", ""),+ ("view.programZoom100", "Cmd+Shift+1", ""),+ ("view.programZoomFit", "Cmd+Shift+0", ""),+ ("view.sourceZoom100", "Cmd+Alt+Shift+1", ""),+ ("view.sourceZoomFit", "Cmd+Alt+Shift+0", ""),// Panels+ ("file.newBinFromSelection", "Shift+B", "Project"),+ ("edit.paste", "Cmd+V", "Timeline"),+ ("edit.pasteInsert", "Cmd+Shift+V", "Timeline"),("project.delete", "Backspace", "Project"),("source.open", "Shift+O", "Project"),("edit.undo", "Left", "History"),("edit.redo", "Right", "History"),];+/// Premiere's panel-scoped default keys for the keyboard-only commands (M3.12). FilmCraft Default+/// uses them as they are, and they are part of the "Premiere Pro Compatible" preset ([`premiere`]).+pub const PREMIERE_PANEL: &[Entry] = &[+ ("timeline.nudgeLeft", "Cmd+Left", "Timeline"),+ ("timeline.nudgeRight", "Cmd+Right", "Timeline"),+ ("timeline.nudgeLeft5", "Cmd+Shift+Left", "Timeline"),+ ("timeline.nudgeRight5", "Cmd+Shift+Right", "Timeline"),+ ("timeline.nudgeUp", "Alt+Up", "Timeline"),+ ("timeline.nudgeDown", "Alt+Down", "Timeline"),+ ("timeline.slipLeft", "Cmd+Alt+Left", "Timeline"),+ ("timeline.slipRight", "Cmd+Alt+Right", "Timeline"),+ ("timeline.slipLeft5", "Cmd+Alt+Shift+Left", "Timeline"),+ ("timeline.slipRight5", "Cmd+Alt+Shift+Right", "Timeline"),+ ("timeline.slideLeft", "Alt+,", "Timeline"),+ ("timeline.slideRight", "Alt+.", "Timeline"),+ ("timeline.slideLeft5", "Alt+Shift+,", "Timeline"),+ ("timeline.slideRight5", "Alt+Shift+.", "Timeline"),+ ("timeline.increaseVideoHeight", "Cmd+=", "Timeline"),+ ("timeline.decreaseVideoHeight", "Cmd+-", "Timeline"),+ ("timeline.increaseAudioHeight", "Alt+=", "Timeline"),+ ("timeline.decreaseAudioHeight", "Alt+-", "Timeline"),+ ("timeline.nextScreen", "PageDown", "Timeline"),+ ("timeline.prevScreen", "PageUp", "Timeline"),+ ("graphics.nudgeLeft", "Cmd+Left", "Program"),+ ("graphics.nudgeRight", "Cmd+Right", "Program"),+ ("graphics.nudgeUp", "Cmd+Up", "Program"),+ ("graphics.nudgeDown", "Cmd+Down", "Program"),+ ("graphics.nudgeLeft5", "Cmd+Shift+Left", "Program"),+ ("graphics.nudgeRight5", "Cmd+Shift+Right", "Program"),+ ("graphics.nudgeUp5", "Cmd+Shift+Up", "Program"),+ ("graphics.nudgeDown5", "Cmd+Shift+Down", "Program"),+ ("graphics.nudgeLeft", "Cmd+Left", "Properties"),+ ("graphics.nudgeRight", "Cmd+Right", "Properties"),+ ("graphics.nudgeUp", "Cmd+Up", "Properties"),+ ("graphics.nudgeDown", "Cmd+Down", "Properties"),+ ("graphics.nudgeLeft5", "Cmd+Shift+Left", "Properties"),+ ("graphics.nudgeRight5", "Cmd+Shift+Right", "Properties"),+ ("graphics.nudgeUp5", "Cmd+Shift+Up", "Properties"),+ ("graphics.nudgeDown5", "Cmd+Shift+Down", "Properties"),+ ("edit.clear", "Backspace", "Properties"),+ ("view.showRulers", "Cmd+R", "Program"),+ ("view.showGuides", "Cmd+;", "Program"),+ ("view.snapInProgramMonitor", "Cmd+Shift+;", "Program"),+ ("view.lockGuides", "Cmd+Alt+Shift+R", "Program"),+ ("projectPanel.viewList", "Cmd+PageUp", "Project"),+ ("projectPanel.viewIcon", "Cmd+PageDown", "Project"),+ ("projectPanel.toggleView", "Shift+\\", "Project"),+ ("projectPanel.hoverScrub", "Shift+H", "Project"),+ ("projectPanel.thumbnailLarger", "Shift+]", "Project"),+ ("projectPanel.thumbnailLarger", "=", "Project"),+ ("projectPanel.thumbnailSmaller", "Shift+[", "Project"),+ ("projectPanel.thumbnailSmaller", "-", "Project"),+ ("projectPanel.moveUp", "Up", "Project"),+ ("projectPanel.moveDown", "Down", "Project"),+ ("projectPanel.moveLeft", "Left", "Project"),+ ("projectPanel.moveRight", "Right", "Project"),+ ("projectPanel.moveHome", "Home", "Project"),+ ("projectPanel.moveEnd", "End", "Project"),+ ("projectPanel.movePageUp", "PageUp", "Project"),+ ("projectPanel.movePageDown", "PageDown", "Project"),+ ("projectPanel.extendUp", "Shift+Up", "Project"),+ ("projectPanel.extendDown", "Shift+Down", "Project"),+ ("projectPanel.extendLeft", "Shift+Left", "Project"),+ ("projectPanel.extendRight", "Shift+Right", "Project"),+ ("textPanel.prevWord", "Left", "Text"),+ ("textPanel.nextWord", "Right", "Text"),+ ("textPanel.selectPrevWord", "Shift+Left", "Text"),+ ("textPanel.selectNextWord", "Shift+Right", "Text"),+ ("textPanel.prevLine", "Up", "Text"),+ ("textPanel.nextLine", "Down", "Text"),+ ("textPanel.selectPrevLine", "Shift+Up", "Text"),+ ("textPanel.selectNextLine", "Shift+Down", "Text"),+ ("textPanel.segmentStart", "Home", "Text"),+ ("textPanel.segmentEnd", "End", "Text"),+ ("textPanel.selectToSegmentStart", "Shift+Home", "Text"),+ ("textPanel.selectToSegmentEnd", "Cmd+Shift+Down", "Text"),+ ("textPanel.delete", "Alt+Backspace", "Text"),+ ("textPanel.rippleDelete", "Backspace", "Text"),+ ("textPanel.showProgramTranscript", "Shift+X", "Text"),+ ("captions.merge", "Alt+M", "Text"),+ ("captions.split", "Alt+S", "Text"),+ ("playback.loop", "Cmd+L", "Audio Track Mixer"),+ ("playback.toggle", "Space", "Metadata"),+ ("playback.loop", "Cmd+L", "Metadata"),+ ("mediaBrowser.openInSource", "Shift+O", "Media Browser"),+];++/// The whole "Premiere Pro Compatible" table: [`PREMIERE`] plus [`PREMIERE_PANEL`].+pub fn premiere() -> Vec<Entry> {+ PREMIERE.iter().chain(PREMIERE_PANEL).copied().collect()+}+/// Final Cut Pro's default keys for the equivalent FilmCraft commands.pub const FINAL_CUT: &[Entry] = &[("tool.selection", "A", ""),diff --git a/crates/engine/src/shortcuts.rs b/crates/engine/src/shortcuts.rsindex ac76902fb..301f2ea4c 100644--- a/crates/engine/src/shortcuts.rs+++ b/crates/engine/src/shortcuts.rs@@ -47,6 +47,7 @@ pub const PANELS: &[&str] = &["History","Markers","Media Browser",+ "Metadata","Audio Track Mixer","Audio Clip Mixer","Essential Graphics",@@ -552,7 +553,7 @@ impl Shortcuts {out.push(Binding::new(&c.id, k, p.as_deref()));}}- for (c, k, p) in presets::FILMCRAFT_PANEL {+ for (c, k, p) in presets::FILMCRAFT_PANEL.iter().chain(presets::PREMIERE_PANEL) {if self.known(c) {out.push(Binding::new(c, k, panel_opt(p)));}@@ -582,14 +583,14 @@ impl Shortcuts {pub fn builtin(&self, name: &str) -> Option<Vec<Binding>> {let mut b = self.base_defaults();b.extend(self.audit());- let table: &[Entry] = match name {- DEFAULT_PRESET => &[],- PREMIERE_PRESET => presets::PREMIERE,- FCP_PRESET => presets::FINAL_CUT,- AVID_PRESET => presets::AVID,+ let table: Vec<Entry> = match name {+ DEFAULT_PRESET => Vec::new(),+ PREMIERE_PRESET => presets::premiere(),+ FCP_PRESET => presets::FINAL_CUT.to_vec(),+ AVID_PRESET => presets::AVID.to_vec(),_ => return None,};- self.apply_table(&mut b, table);+ self.apply_table(&mut b, &table);Some(b)}diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rsindex b7bb9ea67..180916af4 100644--- a/crates/export/src/lib.rs+++ b/crates/export/src/lib.rs@@ -951,8 +951,8 @@ impl Write for SharedBuf {}}-/// Encode one still of an image sequence.-fn encode_still(format: Format, rgba: Vec<u8>, w: u32, h: u32) -> Result<Vec<u8>> {+/// Encode one still of an image sequence (also Export Frame).+pub fn encode_still(format: Format, rgba: Vec<u8>, w: u32, h: u32) -> Result<Vec<u8>> {let enc = |e: image::ImageError| ExportError::Encode(e.to_string());let mut out = std::io::Cursor::new(Vec::new());match format {diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 3c05e27c2..d603e23c2 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -122,6 +122,8 @@ pub struct Playback {pub preroll_ready: bool,/// The window was hidden (occluded/minimized) since the monitor last refreshed.pub hidden: bool,+ /// Forward playback stops here (Play In to Out, Play from Playhead to Out Point).+ pub stop_at: Option<Tick>,}/// How long `ui.screenshot` waits for the window to present the frame.@@ -421,6 +423,7 @@ impl FilmcraftApp {pub fn stop(&mut self) {self.playback.playing = false;+ self.playback.stop_at = None;self.playback.preroll = None;self.playback.meter.finish();self.frames.stop_prefetch();@@ -525,7 +528,10 @@ impl FilmcraftApp {} else {(Tick::ZERO, dur)};- if t >= hi && self.playback.speed > 0.0 {+ if let Some(end) = self.playback.stop_at.filter(|e| t >= *e && self.playback.speed > 0.0 && !self.playback.looping) {+ self.session.set_playhead(end);+ self.stop();+ } else if t >= hi && self.playback.speed > 0.0 {if self.playback.looping {self.session.set_playhead(lo);self.play(self.playback.speed);@@ -1006,14 +1012,21 @@ impl FilmcraftApp {fn dock_area(&mut self, ui: &mut egui::Ui, body: egui::Rect) {let t = self.tokens;- let mut dock = std::mem::replace(&mut self.ui.dock, dock::DockNode::Tabs { panels: vec![], active: 0 });+ // Maximize or Restore Frame (` / Shift+`): the maximized panel fills the dock area.+ let maximized = self.ui.keys.maximized.filter(|p| self.ui.dock.contains(*p));+ let mut dock = match maximized {+ Some(p) => dock::DockNode::Tabs { panels: vec![p], active: 0 },+ None => std::mem::replace(&mut self.ui.dock, dock::DockNode::Tabs { panels: vec![], active: 0 }),+ };let mut groups = Vec::new();dock::layout(ui, &mut dock, body, &t, "", &mut groups, &mut self.auto);let mut actions = Vec::new();for g in &groups {actions.extend(dock::draw_group_chrome(ui, g, self.ui.focused, &t, &mut self.auto));}- self.ui.dock = dock;+ if maximized.is_none() {+ self.ui.dock = dock;+ }for g in &groups {let Some(p) = g.panels.get(g.active).copied() else { continue };self.auto.add(&format!("panel.{}", p.id()), g.content, p.title());diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex cc3ccb2a9..6852c0670 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -29,7 +29,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[uic!("playback.slowForward", "Shuttle Slow Right", [], None),uic!("playback.slowReverse", "Shuttle Slow Left", [], None),uic!("playback.playAround", "Play Around", [], None),- uic!("playback.inToOut", "Play In to Out", [], Some("Shift+Space")),+ uic!("playback.inToOut", "Play In to Out", [], Some("Alt+K")),uic!("playback.loop", "Loop", [], None),uic!("view.zoomIn", "Zoom In", ["View"], Some("=")),uic!("view.zoomOut", "Zoom Out", ["View"], Some("-")),@@ -164,6 +164,9 @@ pub fn invoke(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: Valapp.ui.tool = tool;return Ok(json!({"tool": tool}));}+ if let Some(r) = crate::panels::keyboard::route(app, ctx, id, ¶ms) {+ return r;+ }if let Some(r) = crate::panels::trim_monitor::route_transport(app, ctx, id) {return r;}@@ -221,10 +224,13 @@ pub fn invoke(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: Valreturn Ok(Value::Null);}"playback.inToOut" => {- if let Some(i) = app.session.active_sequence().and_then(|q| q.mark_in) {+ let seq = app.session.active_sequence();+ let out = seq.and_then(|q| q.mark_out.map(|o| o + q.settings.frame_rate.frame_duration()));+ if let Some(i) = seq.and_then(|q| q.mark_in) {app.session.set_playhead(i);}app.play(1.0);+ app.playback.stop_at = out;return Ok(Value::Null);}"playback.loop" => {@@ -382,7 +388,7 @@ pub fn menu_items_for(session: &filmcraft_engine::Session) -> Vec<MenuItem> {checked: None,});}- for c in UI_COMMANDS {+ for c in UI_COMMANDS.iter().chain(crate::panels::keyboard::COMMANDS) {if c.menu.is_empty() {continue;}@@ -479,7 +485,8 @@ fn shifted_key(k: egui::Key) -> Option<egui::Key> {/// rebound and resolved alongside engine commands (the `shortcuts.` commands).pub fn external_commands() -> Vec<filmcraft_engine::shortcuts::CommandInfo> {use filmcraft_engine::shortcuts::CommandInfo;- let mut v: Vec<CommandInfo> = UI_COMMANDS.iter().map(|c| CommandInfo::new(c.id, c.label, c.menu, c.shortcut)).collect();+ 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), p.title(), &["Window"], p.window_shortcut()));}diff --git a/crates/ui-egui/src/panels/keyboard.rs b/crates/ui-egui/src/panels/keyboard.rsnew file mode 100644index 000000000..f1156c898--- /dev/null+++ b/crates/ui-egui/src/panels/keyboard.rs@@ -0,0 +1,520 @@+//! Keyboard-only UI commands from Premiere's default keyboard (M3.12): frame maximize / full+//! screen, panel cycling, monitor zoom, track heights, Project panel and Text panel keyboard+//! navigation, play-to-Out variants. The project-changing keyboard commands are engine commands+//! (`filmcraft_engine::keyboard`); these only change what the UI shows.+//!+//! | Id | Premiere command | Default key (scope) |+//! |---|---|---|+//! | `window.maximizeFrame` / `window.maximizeFrameUnderCursor` | Maximize or Restore Active Frame / Frame Under Cursor | Shift+` / ` |+//! | `window.toggleFullScreen` | Toggle Full Screen | Ctrl+` |+//! | `window.nextPanel` / `window.prevPanel` | Select Next / Previous Panel | Ctrl+Shift+. / Ctrl+Shift+, |+//! | `window.toggleMonitorFocus` | Toggle Source/Program Monitor Focus | |+//! | `window.openSearch` / `panel.selectFindBox` | Open Search / Select Find Box | Cmd+Shift+F / Shift+F |+//! | `view.programZoom100` / `view.programZoomFit` | Zoom Program Monitor to 100% / Fit | Cmd+Shift+1 / Cmd+Shift+0 |+//! | `view.sourceZoom100` / `view.sourceZoomFit` | Zoom Source Monitor to 100% / Fit | Cmd+Alt+Shift+1 / Cmd+Alt+Shift+0 |+//! | `playback.inToOutPreroll` / `playback.toOut` | Play In to Out with Preroll/Postroll / Play from Playhead to Out Point | Shift+Space / Ctrl+Space |+//! | `timeline.expandAllTracks` / `timeline.minimizeAllTracks` | Expand / Minimize All Tracks | Shift+= / Shift+- |+//! | `timeline.increaseVideoHeight` … `timeline.decreaseAudioHeight` | Increase / Decrease Video / Audio Tracks Height | Cmd+= / Cmd+- / Alt+= / Alt+- (Timeline) |+//! | `timeline.nextScreen` / `timeline.prevScreen` | Show Next / Previous Screen | PageDown / PageUp (Timeline) |+//! | `projectPanel.*` | Project panel: List / Icon / Toggle View, Hover Scrub, thumbnail size, Move / Extend Selection | (Project) |+//! | `textPanel.*` | Text panel transcript: word / line / segment navigation and selection, Delete, Ripple Delete, Show Program Transcript | (Text) |+//! | `graphics.beginTextEditing` | Begin Text Editing for a Graphic Layer | Cmd+Alt+' |+//! | `help.filmcraftHelp` | Help (Premiere Help…) | F1 |+//! | `app.quit` | Quit | Cmd+Q |++use serde::{Deserialize, Serialize};+use serde_json::{Value, json};++use crate::FilmcraftApp;+use crate::dock::PanelKind;+use crate::menus::UiCommand;+use crate::state::ProjectView;++/// Keyboard-only view state.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct KeysState {+ /// The maximized frame (Maximize or Restore Frame); None = the normal layout.+ pub maximized: Option<PanelKind>,+ /// Project panel ▸ Hover Scrub (icon view thumbnails follow the pointer).+ pub hover_scrub: bool,+ /// Track heights before Expand / Minimize All Tracks (pressing again restores them).+ pub saved_heights: Option<[f32; 2]>,+ /// Icon view columns in the last frame (Move Selection Up / Down step).+ pub icon_columns: usize,+}++impl Default for KeysState {+ fn default() -> Self {+ Self { maximized: None, hover_scrub: true, saved_heights: None, icon_columns: 1 }+ }+}++macro_rules! uic {+ ($id:literal, $label:literal, [$($m:literal),*], $sc:expr) => {+ UiCommand { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc }+ };+}++/// Frontend commands added for keyboard parity. Panel-scoped keys are in the shortcut tables+/// (`FILMCRAFT_PANEL`), so they have no application-wide default here.+pub const COMMANDS: &[UiCommand] = &[+ uic!("window.maximizeFrame", "Maximize or Restore Active Frame", [], Some("Shift+`")),+ uic!("window.maximizeFrameUnderCursor", "Maximize or Restore Frame Under Cursor", [], Some("`")),+ uic!("window.toggleFullScreen", "Toggle Full Screen", [], Some("Ctrl+`")),+ uic!("window.nextPanel", "Select Next Panel", [], Some("Ctrl+Shift+.")),+ uic!("window.prevPanel", "Select Previous Panel", [], Some("Ctrl+Shift+,")),+ uic!("window.toggleMonitorFocus", "Toggle Source/Program Monitor Focus", [], None),+ uic!("window.openSearch", "Open Search", [], Some("Cmd+Shift+F")),+ uic!("panel.selectFindBox", "Select Find Box", [], Some("Shift+F")),+ uic!("window.workspace.learning", "Learning", ["Window", "Workspaces"], Some("Alt+Shift+7")),+ uic!("window.workspace.review", "Review", ["Window", "Workspaces"], Some("Alt+Shift+8")),+ uic!("view.programZoom100", "Zoom Program Monitor to 100%", [], Some("Cmd+Shift+1")),+ uic!("view.programZoomFit", "Zoom Program Monitor to Fit", [], Some("Cmd+Shift+0")),+ uic!("view.sourceZoom100", "Zoom Source Monitor to 100%", [], Some("Cmd+Alt+Shift+1")),+ uic!("view.sourceZoomFit", "Zoom Source Monitor to Fit", [], Some("Cmd+Alt+Shift+0")),+ uic!("playback.inToOutPreroll", "Play In to Out with Preroll/Postroll", [], Some("Shift+Space")),+ uic!("playback.toOut", "Play from Playhead to Out Point", [], Some("Ctrl+Space")),+ uic!("timeline.expandAllTracks", "Expand All Tracks", [], Some("Shift+=")),+ uic!("timeline.minimizeAllTracks", "Minimize All Tracks", [], Some("Shift+-")),+ uic!("timeline.increaseVideoHeight", "Increase Video Tracks Height", [], None),+ uic!("timeline.decreaseVideoHeight", "Decrease Video Tracks Height", [], None),+ uic!("timeline.increaseAudioHeight", "Increase Audio Tracks Height", [], None),+ uic!("timeline.decreaseAudioHeight", "Decrease Audio Tracks Height", [], None),+ uic!("timeline.nextScreen", "Show Next Screen", [], None),+ uic!("timeline.prevScreen", "Show Previous Screen", [], None),+ uic!("projectPanel.viewList", "List", [], None),+ uic!("projectPanel.viewIcon", "Icon", [], None),+ uic!("projectPanel.toggleView", "Toggle View", [], None),+ uic!("projectPanel.hoverScrub", "Hover Scrub", [], None),+ uic!("projectPanel.thumbnailLarger", "Thumbnail Size Next", [], None),+ uic!("projectPanel.thumbnailSmaller", "Thumbnail Size Previous", [], None),+ uic!("projectPanel.moveUp", "Move Selection Up", [], None),+ uic!("projectPanel.moveDown", "Move Selection Down", [], None),+ uic!("projectPanel.moveLeft", "Move Selection Left", [], None),+ uic!("projectPanel.moveRight", "Move Selection Right", [], None),+ uic!("projectPanel.moveHome", "Move Selection Home", [], None),+ uic!("projectPanel.moveEnd", "Move Selection End", [], None),+ uic!("projectPanel.movePageUp", "Move Selection Page Up", [], None),+ uic!("projectPanel.movePageDown", "Move Selection Page Down", [], None),+ uic!("projectPanel.extendUp", "Extend Selection Up", [], None),+ uic!("projectPanel.extendDown", "Extend Selection Down", [], None),+ uic!("projectPanel.extendLeft", "Extend Selection Left", [], None),+ uic!("projectPanel.extendRight", "Extend Selection Right", [], None),+ uic!("textPanel.prevWord", "Navigate to Previous Word", [], None),+ uic!("textPanel.nextWord", "Navigate to Next Word", [], None),+ uic!("textPanel.selectPrevWord", "Select to Previous Word", [], None),+ uic!("textPanel.selectNextWord", "Select to Next Word", [], None),+ uic!("textPanel.prevLine", "Navigate to Previous Line", [], None),+ uic!("textPanel.nextLine", "Navigate to Next Line", [], None),+ uic!("textPanel.selectPrevLine", "Select to Previous Line", [], None),+ uic!("textPanel.selectNextLine", "Select to Next Line", [], None),+ uic!("textPanel.segmentStart", "Navigate to Start of Segment", [], None),+ uic!("textPanel.segmentEnd", "Navigate to End of Segment", [], None),+ uic!("textPanel.selectToSegmentStart", "Select to Segment Start", [], None),+ uic!("textPanel.selectToSegmentEnd", "Select to Segment End", [], None),+ uic!("textPanel.delete", "Delete", [], None),+ uic!("textPanel.rippleDelete", "Ripple Delete", [], None),+ uic!("textPanel.showProgramTranscript", "Show Program Transcript", [], None),+ uic!("mediaBrowser.openInSource", "Open In Source Monitor", [], None),+ uic!("graphics.beginTextEditing", "Begin Text Editing for a Graphic Layer", [], Some("Cmd+Alt+'")),+ uic!("help.filmcraftHelp", "FilmCraft Help…", ["Help"], Some("F1")),+ uic!("app.quit", "Quit FilmCraft", [], Some("Cmd+Q")),+];++/// FilmCraft's documentation (Help ▸ FilmCraft Help…, F1).+pub const HELP_URL: &str = "https://github.com/storytold/filmcraft/tree/main/docs";++const HEIGHT_STEP: f32 = 12.0;+const MIN_TRACK_H: f32 = 24.0;+const MAX_TRACK_H: f32 = 240.0;++/// Run a keyboard UI command; None when `id` is not one of them.+pub fn route(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option<Result<Value, String>> {+ if !COMMANDS.iter().any(|c| c.id == id) {+ return None;+ }+ let r = match id {+ "window.maximizeFrame" => Ok(toggle_maximize(app, app.ui.focused)),+ "window.maximizeFrameUnderCursor" => {+ let p =+ params.get("panel").and_then(Value::as_str).and_then(PanelKind::from_name).or_else(|| panel_under_pointer(app, ctx)).unwrap_or(app.ui.focused);+ Ok(toggle_maximize(app, p))+ }+ "window.toggleFullScreen" => {+ let fs = !ctx.input(|i| i.viewport().fullscreen.unwrap_or(false));+ ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(fs));+ Ok(json!({"fullScreen": fs}))+ }+ "window.nextPanel" | "window.prevPanel" => Ok(cycle_panel(app, id == "window.nextPanel")),+ "window.toggleMonitorFocus" => {+ let p = if app.ui.focused == PanelKind::Program { PanelKind::Source } else { PanelKind::Program };+ app.show_panel(p);+ Ok(json!({"focused": p.title()}))+ }+ "window.openSearch" => {+ app.show_panel(PanelKind::Project);+ Ok(focus_find_box(app, ctx))+ }+ "panel.selectFindBox" => Ok(focus_find_box(app, ctx)),+ "window.workspace.learning" | "window.workspace.review" => {+ let name = if id.ends_with("learning") { "Learning" } else { "Review" };+ app.set_workspace(name);+ Ok(json!({"workspace": name}))+ }+ "view.programZoom100" | "view.programZoomFit" | "view.sourceZoom100" | "view.sourceZoomFit" => {+ let v = if id.starts_with("view.program") { &mut app.ui.program } else { &mut app.ui.source };+ v.zoom = id.ends_with("100").then_some(1.0);+ v.pan = [0.0, 0.0];+ Ok(json!({"zoom": v.zoom}))+ }+ "playback.inToOutPreroll" => play_range(app, true),+ "playback.toOut" => play_range(app, false),+ "timeline.expandAllTracks" | "timeline.minimizeAllTracks" => Ok(all_heights(app, id == "timeline.expandAllTracks")),+ "timeline.increaseVideoHeight" | "timeline.decreaseVideoHeight" | "timeline.increaseAudioHeight" | "timeline.decreaseAudioHeight" => {+ let d = if id.contains("increase") { HEIGHT_STEP } else { -HEIGHT_STEP };+ let tv = &mut app.ui.timeline;+ let h = if id.contains("Video") { &mut tv.video_track_h } else { &mut tv.audio_track_h };+ *h = (*h + d).clamp(MIN_TRACK_H, MAX_TRACK_H);+ Ok(json!({"videoTrackHeight": tv.video_track_h, "audioTrackHeight": tv.audio_track_h}))+ }+ "timeline.nextScreen" | "timeline.prevScreen" => {+ let tv = &mut app.ui.timeline;+ let w = (app.last_timeline_width.max(200.0) - tv.header_w) as f64;+ let page = w / tv.pps.max(1e-6);+ let d = if id == "timeline.nextScreen" { page } else { -page };+ tv.target_scroll = (tv.target_scroll + d).max(0.0);+ Ok(json!({"scroll": tv.target_scroll}))+ }+ "graphics.beginTextEditing" => begin_text_editing(app),+ "mediaBrowser.openInSource" => open_browser_file(app),+ "help.filmcraftHelp" => {+ crate::links::open(ctx, HELP_URL);+ Ok(json!({"url": HELP_URL}))+ }+ "app.quit" => {+ ctx.send_viewport_cmd(egui::ViewportCommand::Close);+ Ok(Value::Null)+ }+ _ if id.starts_with("projectPanel.") => project_panel(app, &id["projectPanel.".len()..]),+ _ if id.starts_with("textPanel.") => text_panel(app, &id["textPanel.".len()..]),+ _ => return None,+ };+ if let Err(e) = &r {+ app.ui.status = e.clone();+ }+ Some(r)+}++// ------------------------------------------------------------------ frames and panels++fn toggle_maximize(app: &mut FilmcraftApp, p: PanelKind) -> Value {+ app.ui.keys.maximized = if app.ui.keys.maximized.is_some() { None } else { Some(p) };+ if let Some(p) = app.ui.keys.maximized {+ app.ui.dock.activate(p);+ app.ui.focused = p;+ }+ json!({"maximized": app.ui.keys.maximized.map(|p| p.title())})+}++/// The visible panel under the pointer (from last frame's automation rects).+fn panel_under_pointer(app: &FilmcraftApp, ctx: &egui::Context) -> Option<PanelKind> {+ let pos = ctx.input(|i| i.pointer.latest_pos())?;+ app.auto.query("panel.").into_iter().find_map(|e| {+ let r = egui::Rect::from_min_size(egui::pos2(e.rect[0], e.rect[1]), egui::vec2(e.rect[2], e.rect[3]));+ r.contains(pos).then(|| PanelKind::from_name(&e.id["panel.".len()..])).flatten()+ })+}++/// Visible panels in layout order (the active tab of each frame).+fn visible_panels(app: &FilmcraftApp) -> Vec<PanelKind> {+ let mut all = Vec::new();+ app.ui.dock.panels(&mut all);+ all.into_iter().filter(|p| app.ui.dock.is_visible(*p) && !p.compact()).collect()+}++fn cycle_panel(app: &mut FilmcraftApp, next: bool) -> Value {+ let v = visible_panels(app);+ if v.is_empty() {+ return Value::Null;+ }+ 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()})+}++/// Ask the focused panel's search field for keyboard focus (`widgets::search_field` takes it).+fn focus_find_box(app: &mut FilmcraftApp, ctx: &egui::Context) -> Value {+ let p = app.ui.focused;+ 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::new(FOCUS_SEARCH), rect.unwrap_or(egui::Rect::EVERYTHING)));+ json!({"panel": p.title()})+}++/// egui temp-data key: the panel rect whose search field should take focus.+pub const FOCUS_SEARCH: &str = "fc-focus-search";++/// Called by search fields: take focus when Select Find Box targets the panel they sit in.+pub fn take_search_focus(ui: &egui::Ui, field: egui::Rect, resp: &egui::Response) {+ let id = egui::Id::new(FOCUS_SEARCH);+ let Some(panel) = ui.ctx().data(|d| d.get_temp::<egui::Rect>(id)) else { return };+ if panel.contains(field.center()) {+ resp.request_focus();+ ui.ctx().data_mut(|d| d.remove::<egui::Rect>(id));+ }+}++// ------------------------------------------------------------------ playback and timeline++fn play_range(app: &mut FilmcraftApp, preroll: bool) -> Result<Value, String> {+ let seq = app.session.active_sequence().ok_or("no sequence is open")?;+ let fd = seq.settings.frame_rate.frame_duration();+ let end = seq.mark_out.map(|o| o + fd).unwrap_or(seq.duration());+ let start = if preroll {+ let i = seq.mark_in.unwrap_or(filmcraft_time::Tick::ZERO);+ let pre = filmcraft_time::Tick::from_seconds_f64(app.session.prefs.playback.preroll_seconds);+ (i - pre).max(filmcraft_time::Tick::ZERO)+ } else {+ app.session.playhead()+ };+ let stop = if preroll { end + filmcraft_time::Tick::from_seconds_f64(app.session.prefs.playback.postroll_seconds) } else { end };+ app.session.set_playhead(start);+ app.play(1.0);+ app.playback.stop_at = Some(stop);+ Ok(json!({"from": start.0, "to": stop.0}))+}++fn all_heights(app: &mut FilmcraftApp, expand: bool) -> Value {+ let tv = &mut app.ui.timeline;+ let target = if expand { 120.0 } else { MIN_TRACK_H };+ let at_target = tv.video_track_h == target && tv.audio_track_h == target;+ match (at_target, app.ui.keys.saved_heights) {+ // pressing again restores the heights from before+ (true, Some([v, a])) => {+ tv.video_track_h = v;+ tv.audio_track_h = a;+ app.ui.keys.saved_heights = None;+ }+ _ => {+ app.ui.keys.saved_heights = Some([tv.video_track_h, tv.audio_track_h]);+ tv.video_track_h = target;+ tv.audio_track_h = target;+ }+ }+ json!({"videoTrackHeight": tv.video_track_h, "audioTrackHeight": tv.audio_track_h})+}++fn begin_text_editing(app: &mut FilmcraftApp) -> Result<Value, String> {+ let list = app.session.execute("graphics.list", json!({})).map_err(|e| e.to_string())?;+ let layers = list["layers"].as_array().cloned().unwrap_or_default();+ let is_text = |l: &Value| l["kind"] == json!("text");+ let pick = app+ .session+ .state+ .graphic_layers+ .first()+ .and_then(|i| layers.iter().find(|l| l["layer"].as_u64() == Some(*i as u64) && is_text(l)))+ .or_else(|| layers.iter().rev().find(|l| is_text(l)))+ .ok_or("the graphic has no text layer")?;+ let (clip, layer) = (list["clip"].as_u64().unwrap_or(0), pick["layer"].as_u64().unwrap_or(0) as usize);+ let len = pick["text"].as_str().map_or(0, str::len);+ app.session.execute("graphics.selectLayer", json!({"clip": clip, "layers": [layer]})).map_err(|e| e.to_string())?;+ // like Premiere, the whole text is selected so typing replaces it+ app.ui.gfx_edit = Some(crate::state::GfxEdit { clip, layer, caret: len, anchor: 0 });+ app.show_panel(PanelKind::Program);+ Ok(json!({"clip": clip, "layer": layer}))+}++/// Media Browser ▸ Open In Source Monitor: the selected file (imported first: the Source monitor+/// shows project items).+fn open_browser_file(app: &mut FilmcraftApp) -> Result<Value, String> {+ let path = app.ui.extras.media_browser_selection.first().cloned().ok_or("select a file in the Media Browser")?;+ let existing = app+ .session+ .project+ .items+ .values()+ .find(|i| i.as_media().is_some_and(|m| matches!(&m.media, filmcraft_project::MediaRef::File { path: p } if *p == path)))+ .map(|i| i.id);+ let item = match existing {+ Some(i) => i,+ None => {+ let r = app.session.execute("file.import", json!({"paths": [path]})).map_err(|e| e.to_string())?;+ let id =+ r["items"].as_array().and_then(|a| a.first()).and_then(Value::as_u64).or_else(|| r["item"].as_u64()).ok_or("the file could not be imported")?;+ filmcraft_project::ItemId(id)+ }+ };+ app.session.execute("source.open", json!({"item": item.0})).map_err(|e| e.to_string())?;+ app.show_panel(PanelKind::Source);+ Ok(json!({"item": item.0}))+}++// ------------------------------------------------------------------ Project panel++/// Items as the Project panel lists them (expanded bins only in list view).+fn panel_items(app: &FilmcraftApp) -> Vec<filmcraft_project::ItemId> {+ fn walk(app: &FilmcraftApp, bin: &filmcraft_project::Bin, list: bool, out: &mut Vec<filmcraft_project::ItemId>) {+ for e in &bin.children {+ match e {+ filmcraft_project::BinEntry::Item(i) => out.push(*i),+ filmcraft_project::BinEntry::Bin(b) => {+ if !list || app.ui.expanded_bins.contains(&b.id.0) || !app.ui.project_search.is_empty() {+ walk(app, b, list, out);+ }+ }+ }+ }+ }+ let mut v = Vec::new();+ walk(app, &app.session.project.root, app.ui.project_view == ProjectView::List, &mut v);+ let filter = app.ui.project_search.to_ascii_lowercase();+ v.retain(|i| {+ app.session.project.item(*i).is_some_and(|it| {+ !matches!(it.kind, filmcraft_project::ItemKind::Graphic { .. }) && (filter.is_empty() || it.name.to_ascii_lowercase().contains(&filter))+ })+ });+ v+}++fn project_panel(app: &mut FilmcraftApp, op: &str) -> Result<Value, String> {+ match op {+ "viewList" | "viewIcon" | "toggleView" => {+ app.ui.project_view = match op {+ "viewList" => ProjectView::List,+ "viewIcon" => ProjectView::Icon,+ _ if app.ui.project_view == ProjectView::List => ProjectView::Icon,+ _ => ProjectView::List,+ };+ return Ok(json!({"view": app.ui.project_view}));+ }+ "hoverScrub" => {+ app.ui.keys.hover_scrub = !app.ui.keys.hover_scrub;+ return Ok(json!({"hoverScrub": app.ui.keys.hover_scrub}));+ }+ "thumbnailLarger" | "thumbnailSmaller" => {+ let f = if op == "thumbnailLarger" { 1.25 } else { 0.8 };+ app.ui.icon_size = (app.ui.icon_size * f).clamp(64.0, 400.0);+ return Ok(json!({"iconSize": app.ui.icon_size}));+ }+ _ => {}+ }+ let items = panel_items(app);+ if items.is_empty() {+ return Ok(json!({"items": []}));+ }+ let sel = app.session.state.project_selection.clone();+ let last = sel.last().and_then(|s| items.iter().position(|i| i == s));+ let icon = app.ui.project_view != ProjectView::List;+ let cols = if icon { app.ui.keys.icon_columns.max(1) as i64 } else { 1 };+ let page = 10i64;+ let n = items.len() as i64;+ let (step, extend): (Option<i64>, bool) = match op {+ "moveUp" => (Some(-cols), false),+ "moveDown" => (Some(cols), false),+ "moveLeft" => (Some(if icon { -1 } else { 0 }), false),+ "moveRight" => (Some(if icon { 1 } else { 0 }), false),+ "movePageUp" => (Some(-page * cols), false),+ "movePageDown" => (Some(page * cols), false),+ "extendUp" => (Some(-cols), true),+ "extendDown" => (Some(cols), true),+ "extendLeft" => (Some(if icon { -1 } else { 0 }), true),+ "extendRight" => (Some(if icon { 1 } else { 0 }), true),+ "moveHome" | "moveEnd" => (None, false),+ _ => return Err(format!("unknown Project panel command `{op}`")),+ };+ let target = match (step, last) {+ (None, _) => {+ if op == "moveHome" {+ 0+ } else {+ n - 1+ }+ }+ (Some(d), Some(i)) => (i as i64 + d).clamp(0, n - 1),+ (Some(d), None) => {+ if d < 0 {+ n - 1+ } else {+ 0+ }+ }+ } as usize;+ let mut new_sel: Vec<filmcraft_project::ItemId> = if extend {+ let anchor = sel.first().and_then(|s| items.iter().position(|i| i == s)).unwrap_or(target);+ let (a, b) = (anchor.min(target), anchor.max(target));+ let mut v: Vec<_> = items[a..=b].to_vec();+ // keep the anchor first and the moving end last+ if target < anchor {+ v.reverse();+ }+ v+ } else {+ vec![items[target]]+ };+ new_sel.dedup();+ let ids: Vec<u64> = new_sel.iter().map(|i| i.0).collect();+ app.session.execute("project.select", json!({"items": ids})).map_err(|e| e.to_string())?;+ Ok(json!({"items": ids}))+}++// ------------------------------------------------------------------ Text panel (transcript)++fn text_panel(app: &mut FilmcraftApp, op: &str) -> Result<Value, String> {+ if op == "showProgramTranscript" {+ app.show_panel(PanelKind::Text);+ app.ui.text_tab = "Transcript".into();+ return Ok(json!({"tab": "Transcript"}));+ }+ if app.ui.text_tab != "Transcript" {+ // the Captions tab: Delete / Ripple Delete act on the selected captions+ return match op {+ "delete" => app.session.execute("edit.clear", json!({})).map_err(|e| e.to_string()),+ "rippleDelete" => app.session.execute("edit.rippleDelete", json!({})).map_err(|e| e.to_string()),+ _ => Ok(Value::Null),+ };+ }+ let words = filmcraft_engine::transcript::sequence_words(&app.session);+ if words.is_empty() {+ return Err("the sequence has no transcript".into());+ }+ let n = words.len();+ let paras = filmcraft_edit::transcript::paragraphs(&words, filmcraft_time::Tick::from_seconds_f64(1.5));+ let para_of = |i: usize| paras.iter().position(|p| p.contains(&i)).unwrap_or(0);+ let (anchor, cur) = app.ui.transcript_sel.unwrap_or_else(|| {+ let i = filmcraft_edit::transcript::word_at(&words, app.session.playhead()).unwrap_or(0);+ (i, i)+ });+ let line = |i: usize, d: i64| -> usize {+ let p = para_of(i) as i64 + d;+ if p < 0 { 0 } else { paras.get(p as usize).map_or(n - 1, |r| r.start) }+ };+ let (to, extend) = match op {+ "prevWord" => (cur.saturating_sub(1), false),+ "nextWord" => ((cur + 1).min(n - 1), false),+ "selectPrevWord" => (cur.saturating_sub(1), true),+ "selectNextWord" => ((cur + 1).min(n - 1), true),+ "prevLine" => (line(cur, -1), false),+ "nextLine" => (line(cur, 1), false),+ "selectPrevLine" => (line(cur, -1), true),+ "selectNextLine" => (line(cur, 1), true),+ "segmentStart" => (paras[para_of(cur)].start, false),+ "segmentEnd" => (paras[para_of(cur)].end - 1, false),+ "selectToSegmentStart" => (paras[para_of(cur)].start, true),+ "selectToSegmentEnd" => (paras[para_of(cur)].end - 1, true),+ "delete" | "rippleDelete" => {+ let Some((a, b)) = app.ui.transcript_sel else { return Err("select text in the transcript".into()) };+ let cmd = if op == "delete" { "transcript.lift" } else { "transcript.extract" };+ let r = app.session.execute(cmd, json!({"from": a.min(b), "to": a.max(b)})).map_err(|e| e.to_string())?;+ app.ui.transcript_sel = None;+ return Ok(r);+ }+ _ => return Err(format!("unknown Text panel command `{op}`")),+ };+ app.ui.transcript_sel = Some(if extend { (anchor, to) } else { (to, to) });+ // the playhead follows the caret+ app.session.set_playhead(words[to].start);+ Ok(json!({"selection": [anchor.min(to), anchor.max(to)], "word": to}))+}diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rsindex 436948440..c6322e239 100644--- a/crates/ui-egui/src/panels/mod.rs+++ b/crates/ui-egui/src/panels/mod.rs@@ -13,6 +13,7 @@ pub mod export_mode;pub mod file_dialogs;pub mod graphics;pub mod import_mode;+pub mod keyboard;pub mod lumetri;pub mod masks;pub mod media_dialogs;diff --git a/crates/ui-egui/src/panels/project.rs b/crates/ui-egui/src/panels/project.rsindex 884992db0..0d0bc3920 100644--- a/crates/ui-egui/src/panels/project.rs+++ b/crates/ui-egui/src/panels/project.rs@@ -410,6 +410,7 @@ fn icon_view(app: &mut FilmcraftApp, ui: &mut egui::Ui, root: &Bin, filter: &strlet th_h = size * 9.0 / 16.0;let cell = vec2(size + 12.0, th_h + 34.0);let per_row = ((ui.available_width() - 8.0) / cell.x).floor().max(1.0) as usize;+ app.ui.keys.icon_columns = per_row;let ctx = ui.ctx().clone();for chunk in ids.iter().filter(|i| matches(app, **i, filter)).copied().collect::<Vec<_>>().chunks(per_row) {let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), cell.y), Sense::hover());@@ -418,14 +419,16 @@ fn icon_view(app: &mut FilmcraftApp, ui: &mut egui::Ui, root: &Bin, filter: &strlet r = Rect::from_min_size(pos2(row.min.x + 6.0 + k as f32 * cell.x, row.min.y + 4.0), vec2(size, th_h));let resp = ui.interact(r.expand(2.0), egui::Id::new(("icon", id.0)), Sense::click_and_drag());ui.painter().rect_filled(r, 3.0, Color32::from_rgb(12, 12, 12));- let hover_t = if resp.hovered() {+ let hover_t = if resp.hovered() && app.ui.keys.hover_scrub {// hover scrub: pointer x picks the timectx.pointer_hover_pos().map(|p| ((p.x - r.min.x) / r.width()).clamp(0.0, 1.0) as f64).unwrap_or(0.3)} else {0.3};let dur = it.duration();- let tt = filmcraft_time::Tick((dur.0 as f64 * hover_t) as i64);+ // Set Poster Frame (Cmd+P) picks the resting thumbnail+ let poster = filmcraft_engine::keyboard::poster_frame(&it).filter(|_| !(resp.hovered() && app.ui.keys.hover_scrub));+ let tt = poster.unwrap_or(filmcraft_time::Tick((dur.0 as f64 * hover_t) as i64));let q = filmcraft_time::Tick((tt.0 / (filmcraft_time::TICKS_PER_SECOND / 4)) * (filmcraft_time::TICKS_PER_SECOND / 4));if let Some((tex, sz)) = app.thumbnail(&ctx, *id, q, (size as u32).clamp(96, 320)) {let fitted = crate::panels::monitor::fit(r, sz.x, sz.y);diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex 74cd20c19..5b1136e76 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -445,6 +445,10 @@ pub struct UiState {/// `panels::panel_state`.#[serde(default)]pub panels: crate::panels::panel_state::PanelsState,+ /// Keyboard-only view state (maximized frame, Project panel hover scrub). See+ /// `panels::keyboard`.+ #[serde(default)]+ pub keys: crate::panels::keyboard::KeysState,}/// An open Edit / Clip / File menu dialog: the engine command it runs on OK and the parameters@@ -724,6 +728,7 @@ impl Default for UiState {clip_dialog: None,extras: Default::default(),panels: Default::default(),+ keys: Default::default(),}}}diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rsindex cf0b5369c..26b5fe677 100644--- a/crates/ui-egui/src/widgets.rs+++ b/crates/ui-egui/src/widgets.rs@@ -124,7 +124,10 @@ pub fn search_field(ui: &mut Ui, text: &mut String, hint: &str, width: f32, t: &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));let mut child = ui.new_child(egui::UiBuilder::new().max_rect(inner));- child.add(egui::TextEdit::singleline(text).hint_text(hint).frame(egui::Frame::NONE).desired_width(inner.width()).font(Tokens::ui(12.0)))+ let resp = child.add(egui::TextEdit::singleline(text).hint_text(hint).frame(egui::Frame::NONE).desired_width(inner.width()).font(Tokens::ui(12.0)));+ // Select Find Box (Shift+F) / Open Search (Cmd+Shift+F)+ crate::panels::keyboard::take_search_focus(ui, rect, &resp);+ resp}/// Premiere-style dropdown text ("Fit ▾").diff --git a/crates/ui-egui/tests/keyboard_ui.rs b/crates/ui-egui/tests/keyboard_ui.rsnew file mode 100644index 000000000..d96486830--- /dev/null+++ b/crates/ui-egui/tests/keyboard_ui.rs@@ -0,0 +1,178 @@+//! Keyboard parity (M3.12): every Premiere-table entry names a real command, the active key sets+//! have no conflicts in the new commands, and a few of the new keys pressed headlessly.++use std::sync::mpsc::{Sender, channel};++use egui_kittest::Harness;+use filmcraft_engine::Session;+use filmcraft_engine::shortcut_presets as presets;+use filmcraft_engine::shortcuts::{PREMIERE_PRESET, Platform};+use filmcraft_ui_egui::FilmcraftApp;+use filmcraft_ui_egui::control::ControlRequest;+use serde_json::{Value, json};++struct Driver {+ harness: Harness<'static, FilmcraftApp>,+ tx: Sender<ControlRequest>,+}++impl Driver {+ fn new() -> Self {+ let mut s = Session::default();+ s.execute("file.openDemoProject", json!({})).unwrap();+ let (tx, rx) = channel();+ let mut app = FilmcraftApp::new(s).with_control(rx);+ app.hooks.open_path = Some(Box::new(|_, _| Ok(())));+ let harness = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_max_steps(10_000).build_eframe(move |_cc| app);+ let mut d = Driver { harness, tx };+ d.frames(4);+ d+ }++ fn frames(&mut self, n: usize) {+ for _ in 0..n {+ let ctx = self.harness.ctx.clone();+ let mut raw = std::mem::take(self.harness.input_mut());+ eframe::App::raw_input_hook(self.harness.state_mut(), &ctx, &mut raw);+ *self.harness.input_mut() = raw;+ self.harness.step();+ }+ }++ fn ok(&mut self, method: &str, params: Value) -> Value {+ let (req, reply) = ControlRequest::new(method, params.clone());+ self.tx.send(req).unwrap();+ for _ in 0..600 {+ self.frames(1);+ if let Ok(v) = reply.try_recv() {+ assert_eq!(v["ok"], json!(true), "{method} {params} failed: {v}");+ return v["result"].clone();+ }+ }+ panic!("no reply to {method} {params}");+ }++ fn exec(&mut self, command: &str, params: Value) -> Value {+ self.ok("engine.execute", json!({"command": command, "params": params}))+ }++ fn key(&mut self, key: &str) {+ self.ok("ui.key", json!({"key": key}));+ self.frames(3);+ }++ fn focus(&mut self, panel: &str) {+ self.ok("ui.set", json!({"focused": panel}));+ self.frames(2);+ }++ fn app(&self) -> &FilmcraftApp {+ self.harness.state()+ }+}++/// Ids added for keyboard parity (engine + UI).+fn new_ids() -> Vec<String> {+ let mut v: Vec<String> = filmcraft_engine::keyboard::commands().iter().map(|c| c.id.to_string()).collect();+ v.extend(filmcraft_ui_egui::panels::keyboard::COMMANDS.iter().map(|c| c.id.to_string()));+ v+}++#[test]+fn premiere_table_has_no_dangling_ids_or_new_conflicts() {+ let ui: Vec<String> = filmcraft_ui_egui::menus::external_commands().into_iter().map(|c| c.id).collect();+ for (id, keys, panel) in presets::premiere() {+ assert!(filmcraft_engine::find_command(id).is_some() || ui.iter().any(|u| u == id), "Premiere table: `{id}` ({keys} {panel}) is not a command");+ }+ for (id, _, _) in presets::FILMCRAFT_PANEL.iter().chain(presets::PREMIERE_PANEL) {+ assert!(filmcraft_engine::find_command(id).is_some() || ui.iter().any(|u| u == id), "panel table: `{id}` is not a command");+ }+ let mut s = Session::default();+ s.shortcuts.register_external(filmcraft_ui_egui::menus::external_commands());+ let new = new_ids();+ for preset in [None, Some(PREMIERE_PRESET)] {+ if let Some(p) = preset {+ s.shortcuts.load_preset(p).unwrap();+ }+ for (ctx, key, ids) in s.shortcuts.conflicts(Platform::Mac) {+ assert!(!ids.iter().any(|i| new.contains(i)), "{preset:?}: {key} in {ctx} is bound to {ids:?}");+ }+ }+ // the Premiere preset binds every new command that Premiere has a key for+ for id in ["timeline.selectClipAtPlayhead", "file.exportFrame", "window.maximizeFrame", "timeline.nudgeRight", "clip.volumeUp"] {+ assert!(!s.shortcuts.for_command(id).is_empty(), "{id} has no key in the Premiere preset");+ }+}++#[test]+fn new_keys_work_in_the_app() {+ let mut d = Driver::new();+ let seq = d.exec("sequence.inspect", json!({}));+ let v1 = seq["video"][0]["items"].as_array().unwrap().clone();+ let second = &v1[1];+ let (clip, start) = (second["clip"].as_u64().unwrap(), second["start"].as_i64().unwrap());+ d.exec("playhead.set", json!({"time": start + 1_000_000_000}));++ // D selects the clip at the playhead+ d.focus("Timeline");+ d.key("D");+ assert!(d.app().session.state.selection.iter().any(|c| c.0 == clip), "D selects the clip under the playhead");++ // Cmd+Right (Timeline panel): nudge one frame right; undoable+ d.key("Cmd+Right");+ let rate = d.app().session.sequence_rate();+ let now = d.exec("sequence.inspect", json!({}))["video"][0]["items"]+ .as_array()+ .unwrap()+ .iter()+ .find(|i| i["clip"].as_u64() == Some(clip))+ .map(|i| i["start"].as_i64().unwrap())+ .unwrap();+ assert_eq!(now, start + rate.tick_of(1).0);+ d.key("Cmd+Z");++ // Cmd+0 toggles all video targets+ let n0 = d.app().session.targeting().targeted.len();+ d.key("Cmd+0");+ assert!(d.app().session.targeting().targeted.len() < n0);+ d.key("Cmd+0");+ assert_eq!(d.app().session.targeting().targeted.len(), n0);++ // Shift+` maximizes the focused frame, again restores it+ d.key("Shift+`");+ assert_eq!(d.app().ui.keys.maximized, Some(filmcraft_ui_egui::dock::PanelKind::Timeline));+ let r = d.ok("ui.elements", json!({"prefix": "panel."}));+ let frames: Vec<&Value> = r.as_array().unwrap().iter().filter(|e| e["id"].as_str().is_some_and(|i| !i["panel.".len()..].contains('.'))).collect();+ assert_eq!(frames.len(), 1, "only the maximized panel is laid out: {r}");+ d.key("Shift+`");+ assert_eq!(d.app().ui.keys.maximized, None);++ // Shift+= expands all tracks, pressing again restores+ let h0 = d.app().ui.timeline.video_track_h;+ d.key("Shift+=");+ assert!(d.app().ui.timeline.video_track_h > h0);+ d.key("Shift+=");+ assert_eq!(d.app().ui.timeline.video_track_h, h0);++ // Ctrl+Shift+. cycles panel focus+ d.key("Ctrl+Shift+.");+ assert_ne!(d.app().ui.focused, filmcraft_ui_egui::dock::PanelKind::Timeline);++ // Project panel: Down moves the selection; Shift+\ toggles the view+ d.focus("Project");+ d.exec("project.select", json!({"items": []}));+ d.key("Down");+ assert_eq!(d.app().session.state.project_selection.len(), 1);+ let first = d.app().session.state.project_selection[0];+ d.key("Down");+ assert_ne!(d.app().session.state.project_selection[0], first);+ let view0 = d.app().ui.project_view;+ d.key("Shift+\\");+ assert_ne!(d.app().ui.project_view, view0);++ // Cmd+Shift+1 zooms the Program monitor to 100%+ d.key("Cmd+Shift+1");+ assert_eq!(d.app().ui.program.zoom, Some(1.0));+ d.key("Cmd+Shift+0");+ assert_eq!(d.app().ui.program.zoom, None);+}diff --git a/docs/keyboard.md b/docs/keyboard.mdnew file mode 100644index 000000000..46809decc--- /dev/null+++ b/docs/keyboard.md@@ -0,0 +1,64 @@+# Keyboard parity with Premiere Pro++FilmCraft's **Premiere Pro Compatible** shortcut preset (Edit ▸ Keyboard Shortcuts…) follows+Premiere's default keyboard (macOS). The table lives in `crates/engine/src/shortcut_presets.rs`:+`PREMIERE` (application-wide keys and a few panel keys) and `PREMIERE_PANEL` (panel-scoped keys+that FilmCraft Default uses as well). `presets::premiere()` is the whole preset.++Every entry names a FilmCraft command id. Engine commands run through `Session::execute`; UI+commands (frames, panels, monitor zoom, Project and Text panel navigation) run through+`menus::invoke`. Both are reachable by id from the CLI (`filmcraft-cli exec <id>`), the control+channel (`engine.execute` / `ui.menu.invoke`) and MCP (`command_run`).++Tests: `crates/engine/src/keyboard_tests.rs` (no key used twice in one scope; behaviour of the+keyboard commands, with undo) and `crates/ui-egui/tests/keyboard_ui.rs` (no dangling ids in the+tables, no conflicts in FilmCraft Default or the Premiere preset, keys pressed in the headless app).++## Keyboard-only commands (M3.12)++Premiere has these as keys only (most are not in a menu). Modules: `filmcraft_engine::keyboard`+(engine) and `filmcraft_ui_egui::panels::keyboard` (UI); their module docs list each id.++| Group | Commands | Keys |+|---|---|---|+| Navigation | Go to Next/Previous Edit Point (targeted tracks), …on Any Track, Go to Selected Clip Start/End, Reveal Nested Sequence | Down/Up, Shift+Down/Up, Shift+Home/End, Cmd+Alt+F |+| Selection | Select Clip at Playhead, Select Next/Previous Clip, Select Find Box, Open Search | D, Cmd+Down/Up, Shift+F, Cmd+Shift+F |+| Trimming | Extend Previous/Next Edit To Playhead; Nudge Clip Selection Left/Right One/Five Frames, Up/Down; Slip and Slide Clip Selection Left/Right One/Five Frames | Shift+Q/W; Cmd+(Shift+)Left/Right, Alt+Up/Down; Cmd+Alt+(Shift+)Left/Right; Alt+(Shift+), / . (Timeline) |+| Targeting | Toggle All Video/Audio Targets, Toggle All Source Video/Audio; Toggle Target Video/Audio 1–8, Move All Video/Audio Targets Up/Down, Toggle Mute/Solo for targeted audio, Toggle Track Output for targeted video (unbound, as in Premiere) | Cmd+0/9, Cmd+Alt+0/9 |+| Tracks | Expand/Minimize All Tracks (again restores), Increase/Decrease Video/Audio Tracks Height, Show Next/Previous Screen | Shift+= / Shift+-, Cmd+= / Cmd+- / Alt+= / Alt+-, PageDown/PageUp (Timeline) |+| Monitors | Zoom Program/Source Monitor to 100%/Fit, Toggle Full Screen, Play In to Out with Preroll/Postroll, Play from Playhead to Out Point, Export Frame, Set/Clear Poster Frame | Cmd+Shift+1/0, Cmd+Alt+Shift+1/0, Ctrl+`, Shift+Space, Ctrl+Space, Shift+E, Cmd+P / Alt+P |+| Panels | Maximize or Restore Active Frame / Frame Under Cursor, Select Next/Previous Panel, Toggle Source/Program Monitor Focus, Workspaces 7–9 | Shift+`, `, Ctrl+Shift+. / ,, Alt+Shift+7/8/9 |+| Audio | Increase/Decrease Clip Volume (1 dB) and …Many (Settings ▸ Audio ▸ Large Volume Adjustment), Nudge Volume ±1/±3 dB, Toggle Audio During Scrubbing | ] / [, Shift+] / Shift+[, Shift+S |+| Graphics | Increase/Decrease Font Size and Leading by One/Five Units, Left/Center/Right align text, Begin Text Editing, Nudge Selected Object by one/five (graphic layers, else Motion position) | Cmd+Alt+(Shift+)Left/Right, Alt+(Shift+)Up/Down, Cmd+Shift+L/C/R, Cmd+Alt+', Cmd+(Shift+)arrows (Program, Properties) |+| Project panel | List/Icon/Toggle View, Hover Scrub, Thumbnail Size Next/Previous (and = / -), Move/Extend Selection | Cmd+PageUp/PageDown, Shift+\, Shift+H, Shift+] / Shift+[, arrows, Home/End, PageUp/PageDown |+| 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 |+| 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+Project, Import from Media Browser, Get Media File Properties, Paste Attributes, Find, Edit+Original, Make Subclip, Audio Channels, the Graphics New Layer / Arrange / Select Layer commands,+Program monitor Show Rulers / Show Guides / Snap / Lock Guides, New Bin From Selection, Paste and+Paste Insert in the Timeline, the Audio Track Mixer Loop).++FilmCraft Default keeps its own keys where they differ (Shift+E is Clip ▸ Enable there, so Export+Frame has no default key; the Premiere preset moves Shift+E to Export Frame and Enable to ⇧⌘E).++## Skipped Premiere default shortcuts++| Premiere command (key, scope) | Reason |+|---|---|+| Generative Media Tool (⇧V) | Adobe Firefly cloud generation; not part of FilmCraft. |+| Add to object / Subtract from object (⌘= / ⌘-) | Refine an AI object mask (Object Mask tool); FilmCraft has no AI object masks. |+| Change Draw Mode (⌥⌘L) | Premiere's shape draw modes for the Pen/shape tools; FilmCraft's shape tools have no draw modes. |+| Production panel: New Project, New Folder, Close Project, Make a Copy, Move Selection Home/End/Page Up/Page Down, Move To Trash, Open Project, Zoom In/Out (12 keys) | Productions (shared multi-project folders) are not implemented; there is no Production panel. |+| Search panel: Open in Source Monitor (⇧O) | No separate Search panel; Open Search (⇧⌘F) focuses the Project panel search. |+| Audio Track Mixer: Show/Hide Tracks… (⌥⌘T), Meter Input(s) Only (⌃⇧I) | The mixer has no track visibility dialog and no input metering (no hardware input recording). |+| Effect Controls: Remove Selected Effect (Delete), Loop During Audio-Only Playback (⌘L) | Effect Controls has no effect selection state and no audio-only playback mode; effects are removed from their context menu or `effects.remove`. |+| Effects panel: New Custom Bin (⌘/), Delete Custom Item (Delete) | The Effects panel has no custom bins (effect presets live in the Presets bin). |+| History panel: Delete (Delete) | History states cannot be selected and deleted individually. |+| Media Browser: Select Directory List / Select Media List (⇧← / ⇧→) | The Media Browser is a single list without separate directory and media panes. |+| Project panel: Delete Selection with Options (⌘Delete) | Needs the "delete instances in sequences" dialog; plain Clear (Backspace) deletes. |+| Project panel: Next/Previous Column Field, Next/Previous Row Field (Tab, ⇧Tab, Return, ⇧Return) | The list view has no inline-editable metadata cells. |+| Text panel: Edit Segment (Return) | No inline transcript text editing (corrections go through `transcript.set`). |+| Text panel: Follow Active Monitor (⇧C), Show Source Transcript (⇧Z) | Only sequence transcripts exist; source clips have no transcript view. |+| Timeline: Set Work Area Bar In/Out Point (⌥[ / ⌥]) | FilmCraft has no work area bar (Premiere hides it by default; renders use In/Out). |