Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

M4.7: View menu and monitor view options: Paused Resolution, 1/16, High Quality Playback, Display Mode (alpha/RGB channels, comparison, multi-camera, source audio waveform, video+waveform split), Magnification with panning, rulers, guides (drag from rulers, lock, clear, Add Guide, templates in preferences), Snap in Program Monitor

Brandon Thomas9947fee3595b
diff --git a/crates/engine/src/autosave.rs b/crates/engine/src/autosave.rs
index 6c1327ccb..c129da86c 100644
--- a/crates/engine/src/autosave.rs
+++ b/crates/engine/src/autosave.rs
@@ -106,6 +106,30 @@ pub struct Preferences {
pub trim: TrimPrefs,
pub media: MediaPrefs,
pub essential_sound: EssentialSoundPrefs,
+ pub guides: GuidePrefs,
+}
+
+/// View ▸ Guide Templates: guide sets saved from the Program Monitor.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct GuidePrefs {
+ pub templates: Vec<GuideTemplate>,
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct GuideTemplate {
+ pub name: String,
+ pub guides: Vec<Guide>,
+}
+
+/// A monitor guide: a vertical line at x = `position` or a horizontal line at y = `position`
+/// (frame pixels).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct Guide {
+ pub vertical: bool,
+ pub position: f64,
}
/// Preferences ▸ Media.
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 17bc54903..b26647ba9 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -158,6 +158,21 @@ pub fn handle(app: &mut FilmcraftApp, ctx: &egui::Context, req: &ControlRequest)
if let Some(v) = p.get("safeMargins").and_then(Value::as_bool) {
app.ui.program.safe_margins = v;
}
+ // Monitor view state (serde fields of `MonitorView`), merged into the current state.
+ for k in ["program", "source"] {
+ let Some(patch) = p.get(k).and_then(Value::as_object) else { continue };
+ let mv = if k == "program" { &mut app.ui.program } else { &mut app.ui.source };
+ let mut cur = serde_json::to_value(&*mv).unwrap_or_default();
+ if let Some(o) = cur.as_object_mut() {
+ for (f, v) in patch {
+ o.insert(f.clone(), v.clone());
+ }
+ }
+ match serde_json::from_value(cur) {
+ Ok(m) => *mv = m,
+ Err(e) => return err(format!("`{k}`: {e}")),
+ }
+ }
ok(Value::Null)
}
"ui.panel.show" | "ui.panel.close" => {
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 8b2c24388..13a63bb43 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -489,6 +489,30 @@ impl FilmcraftApp {
id
}
+ /// Like [`Self::texture_for`], uploading `map(img)` (computed only when the key changed).
+ pub fn texture_for_mapped(
+ &mut self,
+ ctx: &egui::Context,
+ name: &str,
+ key: FrameKey,
+ img: &frames::Rgba,
+ map: impl FnOnce(&frames::Rgba) -> frames::Rgba,
+ ) -> egui::TextureId {
+ if let Some((k, tex)) = self.textures.get_mut(name) {
+ if *k != key {
+ let m = map(img);
+ tex.set(egui::ColorImage::from_rgba_unmultiplied([m.w, m.h], &m.px), TextureOptions::LINEAR);
+ *k = key;
+ }
+ return tex.id();
+ }
+ let m = map(img);
+ let tex = ctx.load_texture(name, egui::ColorImage::from_rgba_unmultiplied([m.w, m.h], &m.px), TextureOptions::LINEAR);
+ let id = tex.id();
+ self.textures.insert(name.to_string(), (key, tex));
+ id
+ }
+
pub fn texture_existing(&self, name: &str) -> Option<(egui::TextureId, egui::Vec2)> {
self.textures.get(name).map(|(_, t)| (t.id(), t.size_vec2()))
}
@@ -573,6 +597,12 @@ impl FilmcraftApp {
let Some(path) = self.hooks.pick_open_project.as_mut().and_then(|f| f()) else { return Ok(Value::Null) };
self.session.execute("file.open", json!({"path": path})).map_err(|e| e.to_string())
}
+ "graphics.newFromFile" => {
+ let exts: Vec<&str> = filmcraft_media::STILL_EXTENSIONS.iter().chain(filmcraft_media::VIDEO_EXTENSIONS).copied().collect();
+ let paths = self.hooks.pick_files.as_mut().map(|f| f(&exts)).unwrap_or_default();
+ let Some(path) = paths.into_iter().next() else { return Ok(Value::Null) };
+ self.session.execute("graphics.newFromFile", json!({"path": path})).map_err(|e| e.to_string())
+ }
"captions.import" => {
let paths = self.hooks.pick_files.as_mut().map(|f| f(&["srt", "vtt", "scc"])).unwrap_or_default();
let Some(path) = paths.into_iter().next() else { return Ok(Value::Null) };
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 490d8c6fb..bd1af41a3 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -6,7 +6,7 @@ use serde_json::{Value, json};
use crate::FilmcraftApp;
use crate::dock::PanelKind;
-use crate::state::{Mode, PlaybackRes, Tool};
+use crate::state::{Mode, Tool};
pub struct UiCommand {
pub id: &'static str,
@@ -38,7 +38,45 @@ pub const UI_COMMANDS: &[UiCommand] = &[
uic!("view.playbackRes.half", "1/2", ["View", "Playback Resolution"], None),
uic!("view.playbackRes.quarter", "1/4", ["View", "Playback Resolution"], None),
uic!("view.playbackRes.eighth", "1/8", ["View", "Playback Resolution"], None),
- uic!("view.safeMargins", "Safe Margins", ["View"], None),
+ uic!("view.playbackRes.sixteenth", "1/16", ["View", "Playback Resolution"], None),
+ uic!("view.pausedRes.full", "Full", ["View", "Paused Resolution"], None),
+ uic!("view.pausedRes.half", "1/2", ["View", "Paused Resolution"], None),
+ uic!("view.pausedRes.quarter", "1/4", ["View", "Paused Resolution"], None),
+ uic!("view.pausedRes.eighth", "1/8", ["View", "Paused Resolution"], None),
+ uic!("view.pausedRes.sixteenth", "1/16", ["View", "Paused Resolution"], None),
+ uic!("view.highQualityPlayback", "High Quality Playback", ["View"], None),
+ uic!("view.display.composite", "Composite Video", ["View", "Display Mode"], None),
+ uic!("view.display.alpha", "Alpha", ["View", "Display Mode"], None),
+ uic!("view.display.red", "Red", ["View", "Display Mode"], None),
+ uic!("view.display.green", "Green", ["View", "Display Mode"], None),
+ uic!("view.display.blue", "Blue", ["View", "Display Mode"], None),
+ uic!("view.display.multicam", "Multi-Camera", ["View", "Display Mode"], None),
+ uic!("view.display.audioWaveform", "Audio Waveform", ["View", "Display Mode"], None),
+ uic!("view.display.comparison", "Comparison View", ["View", "Display Mode"], None),
+ uic!("view.display.videoAndWaveform", "Video and Audio Waveform Split", ["View", "Display Mode"], None),
+ uic!("view.magnification.fit", "Fit", ["View", "Magnification"], None),
+ uic!("view.magnification.10", "10%", ["View", "Magnification"], None),
+ uic!("view.magnification.25", "25%", ["View", "Magnification"], None),
+ uic!("view.magnification.50", "50%", ["View", "Magnification"], None),
+ uic!("view.magnification.75", "75%", ["View", "Magnification"], None),
+ uic!("view.magnification.100", "100%", ["View", "Magnification"], None),
+ uic!("view.magnification.150", "150%", ["View", "Magnification"], None),
+ uic!("view.magnification.200", "200%", ["View", "Magnification"], None),
+ uic!("view.magnification.400", "400%", ["View", "Magnification"], None),
+ uic!("view.magnification.800", "800%", ["View", "Magnification"], None),
+ uic!("view.magnification.1600", "1600%", ["View", "Magnification"], None),
+ uic!("view.showRulers", "Show Rulers", ["View"], None),
+ uic!("view.showGuides", "Show Guides", ["View"], None),
+ uic!("view.lockGuides", "Lock Guides", ["View"], None),
+ uic!("view.addGuide", "Add Guide…", ["View"], None),
+ uic!("view.clearGuides", "Clear Guides", ["View"], None),
+ uic!("view.snapInProgramMonitor", "Snap in Program Monitor", ["View"], None),
+ uic!("view.safeMargins", "Safe Margins", ["View", "Guide Templates"], None),
+ uic!("view.guideTemplates.save", "Save Guides as Template…", ["View", "Guide Templates"], None),
+ uic!("view.guideTemplates.manage", "Manage Guides…", ["View", "Guide Templates"], None),
+ uic!("view.guideTemplates.apply", "Apply Guide Template", [], None),
+ uic!("view.guideTemplates.delete", "Delete Guide Template", [], None),
+ uic!("view.compare.setReference", "Set Comparison Reference", [], None),
uic!("multicam.toggleView", "Multi-Camera View", ["View"], Some("Shift+0")),
uic!("multicam.recordToggle", "Multi-Camera Record On/Off Toggle", [], Some("0")),
uic!("view.theme.dark", "Darkest", ["View", "Appearance"], None),
@@ -114,6 +152,12 @@ pub fn invoke(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: Val
}
return r;
}
+ if let Some(r) = crate::panels::monitor_view::route(app, id, &params) {
+ if let Err(e) = &r {
+ app.ui.status = e.clone();
+ }
+ return r;
+ }
match id {
"playback.slowForward" | "playback.slowReverse" => {
app.play(if id == "playback.slowForward" { 0.25 } else { -0.25 });
@@ -158,10 +202,6 @@ pub fn invoke(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: Val
app.ui.timeline.fit_pending = true;
return Ok(Value::Null);
}
- "view.safeMargins" => {
- app.ui.program.safe_margins = !app.ui.program.safe_margins;
- return Ok(Value::Null);
- }
"mode.import" => {
app.ui.mode = Mode::Import;
return Ok(Value::Null);
@@ -225,17 +265,6 @@ pub fn invoke(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: Val
}
_ => {}
}
- if let Some(r) = id.strip_prefix("view.playbackRes.") {
- let res = match r {
- "full" => PlaybackRes::Full,
- "half" => PlaybackRes::Half,
- "quarter" => PlaybackRes::Quarter,
- "eighth" => PlaybackRes::Eighth,
- _ => PlaybackRes::Sixteenth,
- };
- app.ui.program.res = res;
- return Ok(Value::Null);
- }
if let Some(th) = id.strip_prefix("view.theme.") {
let k = crate::theme::ThemeKind::from_name(th).ok_or("unknown theme")?;
app.set_theme(ctx, k);
@@ -248,6 +277,7 @@ pub fn invoke(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: Val
|| (id == "file.open" && params.get("path").is_none())
|| (id == "file.save" && params.get("path").is_none() && app.session.path.is_none())
|| (matches!(id, "captions.import" | "captions.export") && params.get("path").is_none())
+ || (id == "graphics.newFromFile" && params.get("path").is_none())
{
return app.file_dialog(id, &params);
}
@@ -266,12 +296,22 @@ pub struct MenuItem {
pub path: Vec<String>,
pub shortcut: Option<String>,
pub enabled: bool,
+ /// Checkmark state of toggle / radio items (None = not checkable).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub checked: Option<bool>,
}
pub const MENUS: [&str; 9] = ["File", "Edit", "Clip", "Sequence", "Markers", "Graphics and Titles", "View", "Window", "Help"];
pub fn menu_items(app: &FilmcraftApp) -> Vec<MenuItem> {
- menu_items_for(&app.session)
+ let mut v = menu_items_for(&app.session);
+ for it in &mut v {
+ if it.id.starts_with("view.") {
+ it.checked = crate::panels::monitor_view::checked(app, &it.id);
+ it.enabled &= crate::panels::monitor_view::enabled(app, &it.id);
+ }
+ }
+ v
}
/// Menu entries with their live shortcuts and enablement.
@@ -287,6 +327,7 @@ pub fn menu_items_for(session: &filmcraft_engine::Session) -> Vec<MenuItem> {
path: c.menu.iter().map(|s| s.to_string()).collect(),
shortcut: session.shortcuts.primary(c.id),
enabled: session.is_enabled(c.id),
+ checked: None,
});
}
for c in UI_COMMANDS {
@@ -299,6 +340,7 @@ pub fn menu_items_for(session: &filmcraft_engine::Session) -> Vec<MenuItem> {
path: c.menu.iter().map(|s| s.to_string()).collect(),
shortcut: session.shortcuts.primary(c.id),
enabled: true,
+ checked: None,
});
}
for p in PanelKind::ALL {
@@ -308,6 +350,7 @@ pub fn menu_items_for(session: &filmcraft_engine::Session) -> Vec<MenuItem> {
path: vec!["Window".into()],
shortcut: session.shortcuts.primary(&panel_command_id(p)),
enabled: true,
+ checked: None,
});
}
out
@@ -415,9 +458,19 @@ pub fn menu_bar(app: &mut FilmcraftApp, ui: &mut egui::Ui) {
}
fn menu_entry(ui: &mut egui::Ui, it: &MenuItem) -> bool {
- let mut b = egui::Button::new(&it.label);
+ // checkable items leave room for a checkmark drawn at the left
+ let label = if it.checked.is_some() { format!(" {}", it.label) } else { it.label.clone() };
+ let mut b = egui::Button::new(label);
if let Some(s) = &it.shortcut {
b = b.shortcut_text(shortcut_text(s));
}
- ui.add_enabled(it.enabled, b).clicked()
+ let r = ui.add_enabled(it.enabled, b);
+ if it.checked == Some(true) {
+ let c = r.rect.left_center() + egui::vec2(10.0, 0.0);
+ let col = ui.visuals().text_color();
+ let st = egui::Stroke::new(1.5, col);
+ ui.painter().line_segment([c + egui::vec2(-4.0, 0.0), c + egui::vec2(-1.0, 3.0)], st);
+ ui.painter().line_segment([c + egui::vec2(-1.0, 3.0), c + egui::vec2(4.5, -3.5)], st);
+ }
+ r.clicked()
}
diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs
index dc18d4ace..d8d43d421 100644
--- a/crates/ui-egui/src/panels/dialogs.rs
+++ b/crates/ui-egui/src/panels/dialogs.rs
@@ -8,6 +8,7 @@ pub fn show(app: &mut FilmcraftApp, ctx: &egui::Context) {
crate::panels::color_dialogs::show(app, ctx);
crate::panels::presets::save_dialog(app, ctx);
crate::panels::multicam::show_dialog(app, ctx);
+ crate::panels::monitor_view::dialogs(app, ctx);
let Some(d) = app.dialog else { return };
if let Some(still_open) = crate::panels::file_dialogs::show(app, ctx, d) {
if !still_open && app.dialog == Some(d) {
diff --git a/crates/ui-egui/src/panels/graphics.rs b/crates/ui-egui/src/panels/graphics.rs
index 14976a2f9..5f3a56d59 100644
--- a/crates/ui-egui/src/panels/graphics.rs
+++ b/crates/ui-egui/src/panels/graphics.rs
@@ -250,7 +250,8 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
// ---- presses
if graphics_tool && resp.drag_started() {
- let p = resp.interact_pointer_pos().unwrap_or(pic.center());
+ // where the button went down (a drag starts only after the pointer has moved a little)
+ let p = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos()).unwrap_or(pic.center());
let shift = ui.input(|i| i.modifiers.shift);
let in_edit = edit_view.is_some_and(|v| v.hit(p));
drag = None;
@@ -306,11 +307,19 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
if let Some(d) = drag {
let cur = resp.interact_pointer_pos().or(hover).unwrap_or(d.start);
let v = views.iter().find(|v| v.clip == d.clip && v.layer == d.layer);
+ // Snap in Program Monitor (hold ⌘/Ctrl to move freely)
+ let snap_off = match (d.kind, v) {
+ (DragKind::Move, Some(v)) if !ui.input(|i| i.modifiers.command) => {
+ crate::panels::monitor_view::snap_move(app, pic, frame, Rect::from_points(&v.quad()), cur - d.start)
+ }
+ _ => (cur - d.start, Vec::new()),
+ };
match d.kind {
DragKind::Move => {
if let Some(v) = v {
- let off = cur - d.start;
+ let off = snap_off.0;
painter.add(egui::Shape::closed_line(v.quad().iter().map(|q| *q + off).collect(), Stroke::new(1.0, Color32::WHITE)));
+ crate::panels::monitor_view::draw_snap_lines(&painter, pic, &snap_off.1);
}
}
DragKind::Scale => {
@@ -345,7 +354,8 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
DragKind::Move if moved => {
if let Some(v) = v {
let lin = Affine { e: 0.0, f: 0.0, ..v.canvas_to_screen };
- let delta = lin.inverse().map(|i| i.apply(Vec2::new((cur.x - d.start.x) as f64, (cur.y - d.start.y) as f64))).unwrap_or_default();
+ let off = snap_off.0;
+ let delta = lin.inverse().map(|i| i.apply(Vec2::new(off.x as f64, off.y as f64))).unwrap_or_default();
let p0 = v.spec.transform.position;
actions.push((
"graphics.set".into(),
diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs
index d552c3a9f..0bad2b559 100644
--- a/crates/ui-egui/src/panels/mod.rs
+++ b/crates/ui-egui/src/panels/mod.rs
@@ -17,6 +17,7 @@ pub mod meters;
pub mod misc;
pub mod mixer;
pub mod monitor;
+pub mod monitor_view;
pub mod multicam;
pub mod presets;
pub mod project;
diff --git a/crates/ui-egui/src/panels/monitor.rs b/crates/ui-egui/src/panels/monitor.rs
index ef5cb3c9d..2937992c5 100644
--- a/crates/ui-egui/src/panels/monitor.rs
+++ b/crates/ui-egui/src/panels/monitor.rs
@@ -13,7 +13,8 @@ use serde_json::json;
use crate::FilmcraftApp;
use crate::frames::{FrameKey, Target};
use crate::icons::{self, Icon};
-use crate::state::PlaybackRes;
+use crate::panels::monitor_view;
+use crate::state::{DisplayMode, PlaybackRes};
use crate::theme::Tokens;
#[derive(Clone, Copy, PartialEq)]
@@ -66,8 +67,10 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)
}
};
let prefix = if which == Which::Program { "program" } else { "source" };
+ let mv = monitor_view::view(app, which).clone();
+ let display = mv.display_mode().unwrap_or(DisplayMode::Composite);
// Multi-Camera view: the angle grid on the left, the program on the right
- let multicam = which == Which::Program && app.ui.program.multicam;
+ let multicam = which == Which::Program && mv.multicam;
let (grid_area, video_area) = if multicam {
let mid = video_area.center().x;
(Some(Rect::from_min_max(video_area.min, pos2(mid - 2.0, video_area.max.y))), Rect::from_min_max(pos2(mid + 2.0, video_area.min.y), video_area.max))
@@ -78,13 +81,64 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)
crate::panels::multicam::grid(app, ui, g);
}
ui.painter().rect_filled(video_area, 0.0, t.panel_bg);
- // ---- picture
let has_video = frame_size.0 > 0;
- let pic = if has_video { fit(video_area, frame_size.0 as f32, frame_size.1 as f32) } else { video_area };
- ui.painter().rect_filled(pic, 0.0, t.monitor_bg);
- let res = if which == Which::Program { app.ui.program.res } else { app.ui.source.res };
- if has_video {
- let ppp = ctx.pixels_per_point();
+ // Source waveform modes: Audio Waveform (or an audio-only clip) and the video/waveform split.
+ let source_item = if which == Which::Source { app.session.state.source_item } else { None };
+ let wave_only = source_item.is_some() && (!has_video || display == DisplayMode::AudioWaveform);
+ let (video_area, wave_area) = if wave_only {
+ (video_area, Some(video_area))
+ } else if source_item.is_some() && display == DisplayMode::VideoAndWaveform {
+ let split = video_area.min.y + video_area.height() * 0.62;
+ (Rect::from_min_max(video_area.min, pos2(video_area.max.x, split - 2.0)), Some(Rect::from_min_max(pos2(video_area.min.x, split + 2.0), video_area.max)))
+ } else {
+ (video_area, None)
+ };
+ if let (Some(wa), Some(item)) = (wave_area, source_item) {
+ monitor_view::waveform(app, ui, wa, item, time, duration, mark_in, mark_out);
+ }
+ let show_picture = has_video && !wave_only;
+ // Rulers along the top and left of the picture area.
+ let rulers = show_picture && mv.show_rulers;
+ let (ruler_rects, video_area) = if rulers {
+ let r = monitor_view::RULER;
+ (
+ Some((
+ Rect::from_min_max(pos2(video_area.min.x + r, video_area.min.y), pos2(video_area.max.x, video_area.min.y + r)),
+ Rect::from_min_max(pos2(video_area.min.x, video_area.min.y + r), pos2(video_area.min.x + r, video_area.max.y)),
+ )),
+ Rect::from_min_max(video_area.min + vec2(r, r), video_area.max),
+ )
+ } else {
+ (None, video_area)
+ };
+ let picture_area = video_area;
+ // Comparison View: the reference frame on the left, the current frame on the right.
+ let compare = which == Which::Program && show_picture && display == DisplayMode::Comparison;
+ let (ref_area, video_area) = if compare {
+ let mid = video_area.center().x;
+ let bar_h = 22.0;
+ (
+ Some(Rect::from_min_max(video_area.min, pos2(mid - 2.0, video_area.max.y - bar_h))),
+ Rect::from_min_max(pos2(mid + 2.0, video_area.min.y), pos2(video_area.max.x, video_area.max.y - bar_h)),
+ )
+ } else {
+ (None, video_area)
+ };
+ // ---- picture
+ let ppp = ctx.pixels_per_point();
+ let pic = if compare {
+ fit(video_area, frame_size.0 as f32, frame_size.1 as f32)
+ } else if show_picture {
+ monitor_view::picture_rect(video_area, frame_size.0 as f32, frame_size.1 as f32, &mv, ppp)
+ } else {
+ video_area
+ };
+ let saved_clip = ui.clip_rect();
+ ui.set_clip_rect(saved_clip.intersect(if mv.zoom.is_some() && !compare { video_area } else { picture_area.expand(12.0) }));
+ if show_picture {
+ ui.painter().rect_filled(pic, 0.0, t.monitor_bg);
+ let playing = which == Which::Program && app.playback.playing;
+ let res = mv.effective_res(playing);
let screen_scale = (pic.width() * ppp / frame_size.0 as f32).min(1.0);
let scale = quantize_scale(res.scale().min(screen_scale.max(1.0 / 32.0)));
let frame = rate.frame_at(time);
@@ -93,14 +147,15 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)
_ => app.session.revision,
};
let size_key = (scale * 1000.0) as u32;
- let use_gpu = which == Which::Program && app.gpu.is_some();
+ let channel = display.is_channel();
+ let use_gpu = which == Which::Program && app.gpu.is_some() && !channel;
+ let cpu_target = target;
let target = match (use_gpu, target) {
(true, Target::Sequence(s)) => Target::SequencePlan(s),
(_, t) => t,
};
let key = FrameKey { target, frame, size: size_key, revision: rev };
let project = app.session.project.clone();
- let playing = which == Which::Program && app.playback.playing;
if playing {
let preroll = app.playback.preroll.is_some();
app.frames.schedule_playback(key, rate, scale, &project, app.playback.speed, preroll);
@@ -110,7 +165,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)
} else {
app.frames.request(key, rate.tick_of(frame), scale, &project, 0);
}
- let tex_name = format!("monitor-{prefix}");
+ let tex_name = if channel { format!("monitor-{prefix}-{display:?}") } else { format!("monitor-{prefix}") };
let (shown, exact) = if use_gpu {
let exact = app.frames.get_plan(&key).map(|p| (key, p));
let is_exact = exact.is_some();
@@ -119,14 +174,8 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)
None => app.gpu.as_ref().and_then(|g| g.texture),
};
(tex, is_exact)
- } else if let Some(img) = app.frames.get(&key) {
- (Some(app.texture_for(&ctx, &tex_name, key, &img)), true)
} else {
- let tex = match app.frames.nearest(target, frame, size_key, rev, 6) {
- Some(img) => Some(app.texture_for(&ctx, &tex_name, FrameKey { frame: frame - 1, ..key }, &img)),
- None => app.texture_existing(&tex_name).map(|(id, _)| id),
- };
- (tex, false)
+ cpu_texture(app, &ctx, &tex_name, key, display)
};
if playing {
if std::mem::take(&mut app.playback.hidden) {
@@ -138,7 +187,20 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)
if let Some(tex) = shown {
ui.painter().image(tex, pic, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
}
- let mv = if which == Which::Program { &app.ui.program } else { &app.ui.source };
+ if let Some(ra) = ref_area {
+ // the reference frame (CPU path)
+ let rf = rate.frame_at(Tick(mv.compare_ref.unwrap_or(time.0)));
+ let rkey = FrameKey { target: cpu_target, frame: rf, size: size_key, revision: rev };
+ app.frames.request(rkey, rate.tick_of(rf), scale, &project, 1);
+ let rpic = fit(ra, frame_size.0 as f32, frame_size.1 as f32);
+ ui.painter().rect_filled(rpic, 0.0, t.monitor_bg);
+ if let (Some(tex), _) = cpu_texture(app, &ctx, &format!("monitor-{prefix}-ref"), rkey, DisplayMode::Composite) {
+ ui.painter().image(tex, rpic, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
+ }
+ app.auto.add("program.compare.reference", rpic, "reference frame");
+ let bar = Rect::from_min_max(pos2(ra.min.x, ra.max.y + 2.0), pos2(video_area.max.x, ra.max.y + 22.0));
+ monitor_view::compare_bar(app, ui, bar, rate, drop_frame);
+ }
if mv.safe_margins {
for (f, c) in [(0.9, Color32::from_white_alpha(120)), (0.8, Color32::from_white_alpha(90))] {
let r = Rect::from_center_size(pic.center(), pic.size() * f);
@@ -148,29 +210,40 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)
ui.painter().line_segment([c - vec2(8.0, 0.0), c + vec2(8.0, 0.0)], Stroke::new(1.0, Color32::from_white_alpha(120)));
ui.painter().line_segment([c - vec2(0.0, 8.0), c + vec2(0.0, 8.0)], Stroke::new(1.0, Color32::from_white_alpha(120)));
}
- } else if which == Which::Source {
- // audio-only source: draw a waveform placeholder
- ui.painter().text(pic.center(), Align2::CENTER_CENTER, format!("♪ {name}"), Tokens::ui(14.0), t.text_dim);
+ if display != DisplayMode::Composite && !compare {
+ let label = format!("{display:?}");
+ ui.painter().text(pos2(video_area.max.x - 8.0, video_area.min.y + 6.0), Align2::RIGHT_TOP, label, Tokens::ui(10.0), t.text_dim);
+ }
}
// Dropped-frame indicator (Program only)
if which == Which::Program && app.playback.playing {
let c = if app.playback.meter.counts().1 > 0 { t.render_yellow } else { t.render_green };
ui.painter().circle_filled(pos2(video_area.min.x + 10.0, video_area.min.y + 10.0), 4.0, c);
}
- // Click/drag in the picture: the Hand tool pans, otherwise focus.
+ // Click/drag in the picture: the Hand tool pans a magnified picture, otherwise focus.
let pic_resp = ui.interact(pic, egui::Id::new((prefix, "pic")), Sense::click());
- app.auto.add(&format!("{prefix}.picture"), pic, "picture");
- if which == Which::Program && has_video {
+ app.auto.add(&format!("{prefix}.picture"), pic.intersect(video_area), "picture");
+ if show_picture {
+ monitor_view::pan_input(app, ui, which, video_area, pic);
+ }
+ if which == Which::Program && show_picture {
crate::panels::graphics::monitor_overlay(app, ui, pic, frame_size);
crate::panels::masks::monitor_overlay(app, ui, pic, frame_size);
}
+ if show_picture {
+ monitor_view::guides(app, ui, which, video_area, pic, frame_size);
+ }
+ ui.set_clip_rect(saved_clip);
+ if let Some((top, left)) = ruler_rects {
+ monitor_view::rulers(app, ui, which, top, left, video_area, pic, frame_size);
+ }
if pic_resp.double_clicked() && which == Which::Source {
// (Premiere opens the clip's settings; we show info)
app.ui.status = name.clone();
}
// ---- controls row: timecode | zoom | res | wrench | duration
- let row1 = Rect::from_min_size(pos2(rect.min.x + 14.0, video_area.max.y + 2.0), vec2(rect.width() - 28.0, 26.0));
+ let row1 = Rect::from_min_size(pos2(rect.min.x + 14.0, rect.max.y - controls_h + 2.0), vec2(rect.width() - 28.0, 26.0));
let tc = format_time(time, rate, drop_frame, TimeDisplay::Timecode, 48000);
ui.painter().text(pos2(row1.min.x, row1.center().y), Align2::LEFT_CENTER, &tc, Tokens::semibold(15.0), t.hot_text);
app.auto.add(&format!("{prefix}.timecode"), Rect::from_min_size(row1.min, vec2(110.0, row1.height())), &tc);
@@ -184,22 +257,21 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)
ui.painter().text(pos2(row1.max.x, row1.center().y), Align2::RIGHT_CENTER, &dur_tc, Tokens::semibold(15.0), t.text_dim);
// zoom + resolution dropdowns centred-ish
let zr = Rect::from_min_size(pos2(row1.min.x + 116.0, row1.min.y), vec2(70.0, 24.0));
- let zoom_label = match if which == Which::Program { app.ui.program.zoom } else { app.ui.source.zoom } {
+ let zoom_label = match mv.zoom {
None => "Fit".to_string(),
- Some(z) => format!("{}%", (z * 100.0) as i32),
+ Some(z) => format!("{}%", (z * 100.0).round() as i32),
};
- crate::widgets::dropdown_text(ui, zr, &zoom_label, &t, egui::Id::new((prefix, "zoom")));
+ let zresp = crate::widgets::dropdown_text(ui, zr, &zoom_label, &t, egui::Id::new((prefix, "zoom")));
+ app.auto.add(&format!("{prefix}.zoom"), zr, "Select Zoom Level");
+ monitor_view::zoom_menu(app, &zresp, which);
+ let res = mv.res;
let rr = Rect::from_min_size(pos2(row1.max.x - 196.0, row1.min.y), vec2(62.0, 24.0));
let rresp = crate::widgets::dropdown_text(ui, rr, res.label(), &t, egui::Id::new((prefix, "res")));
app.auto.add(&format!("{prefix}.resolution"), rr, "Select Playback Resolution");
egui::Popup::menu(&rresp).show(|ui| {
for r in PlaybackRes::ALL {
if ui.selectable_label(r == res, r.label()).clicked() {
- if which == Which::Program {
- app.ui.program.res = r;
- } else {
- app.ui.source.res = r;
- }
+ monitor_view::view_mut(app, which).res = r;
}
}
});
@@ -208,13 +280,14 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)
icons::paint(ui.painter(), wr.shrink(4.0), Icon::Wrench, if wresp.hovered() { t.tab_text_active } else { t.icon });
app.auto.add(&format!("{prefix}.settings"), wr, "Settings");
egui::Popup::menu(&wresp).show(|ui| {
- let mv = if which == Which::Program { &mut app.ui.program } else { &mut app.ui.source };
+ ui.set_min_width(240.0);
+ monitor_view::wrench_items(app, ui, which);
+ let mv = monitor_view::view_mut(app, which);
ui.checkbox(&mut mv.safe_margins, "Safe Margins");
ui.checkbox(&mut mv.show_transport, "Show Transport Controls");
if which == Which::Program {
ui.separator();
ui.checkbox(&mut app.ui.show_scopes, "Lumetri Scopes");
- ui.checkbox(&mut app.ui.program.multicam, "Multi-Camera");
ui.checkbox(&mut app.playback.looping, "Loop");
ui.separator();
let mut follows = app.session.state.multicam_audio_follows_video;
@@ -224,7 +297,6 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)
ui.checkbox(&mut app.ui.multicam_record, "Multi-Camera Record");
}
});
-
// ---- mini timeline / scrub bar
let bar = Rect::from_min_size(pos2(rect.min.x + 14.0, row1.max.y + 2.0), vec2(rect.width() - 28.0, 22.0));
mini_timeline(app, ui, bar, which, time, duration, rate, mark_in, mark_out);
@@ -234,6 +306,22 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)
transport(app, ui, row3, which);
}
+/// A monitor texture from the CPU frame path: the exact frame, else the nearest cached one, with
+/// the display mode's channel mapping. Returns (texture, exact).
+fn cpu_texture(app: &mut FilmcraftApp, ctx: &egui::Context, name: &str, key: FrameKey, mode: DisplayMode) -> (Option<egui::TextureId>, bool) {
+ let upload = |app: &mut FilmcraftApp, k: FrameKey, img: &crate::frames::Rgba| {
+ if mode.is_channel() { app.texture_for_mapped(ctx, name, k, img, |i| monitor_view::channel_view(i, mode)) } else { app.texture_for(ctx, name, k, img) }
+ };
+ if let Some(img) = app.frames.get(&key) {
+ return (Some(upload(app, key, &img)), true);
+ }
+ let tex = match app.frames.nearest(key.target, key.frame, key.size, key.revision, 6) {
+ Some(img) => Some(upload(app, FrameKey { frame: key.frame - 1, ..key }, &img)),
+ None => app.texture_existing(name).map(|(id, _)| id),
+ };
+ (tex, false)
+}
+
pub fn quantize_scale(s: f32) -> f32 {
// Buckets keep the cache effective while resizing the panel.
let buckets = [1.0 / 32.0, 1.0 / 16.0, 1.0 / 8.0, 0.1875, 0.25, 0.375, 0.5, 0.75, 1.0];
diff --git a/crates/ui-egui/src/panels/monitor_view.rs b/crates/ui-egui/src/panels/monitor_view.rs
new file mode 100644
index 000000000..8b6ca8175
--- /dev/null
+++ b/crates/ui-egui/src/panels/monitor_view.rs
@@ -0,0 +1,890 @@
+//! Monitor view options (the View menu and the monitors' wrench menus): Playback / Paused
+//! Resolution, High Quality Playback, Display Mode (Composite Video, Alpha, Red, Green, Blue,
+//! Multi-Camera, Audio Waveform, Comparison View, Video and Audio Waveform Split), Magnification
+//! (Fit, 10%…1600%, scroll or Hand-tool panning), rulers, guides (dragged out of the rulers, Add
+//! Guide…, Clear Guides, Lock Guides, templates saved in the user preferences) and Snap in Program
+//! Monitor (graphic drags snap to guides, the frame edges and centre).
+//!
+//! Everything is [`MonitorView`] state (serde: `ui.inspect`, `ui.set {"program": {…}}`) changed
+//! through the `view.*` UI commands, which [`route`] handles for `menus::invoke`. Commands act on
+//! `params.monitor` ("program" / "source"), else on the focused monitor (Program by default).
+//!
+//! Automation ids: `<monitor>.zoom`, `<monitor>.zoom.<fit|10|…|1600>`,
+//! `<monitor>.settings.<command suffix>` (wrench menu, e.g. `program.settings.display.alpha`),
+//! `<monitor>.ruler.top`, `<monitor>.ruler.left`, `<monitor>.guide.<n>`,
+//! `program.compare.<prev|next|set>`, `source.waveform`, and in the dialogs `guides.add.*`,
+//! `guides.save.*`, `guides.manage.*`.
+
+use egui::{Align2, Color32, Rect, Sense, Stroke, Vec2, pos2, vec2};
+use filmcraft_project::ItemId;
+use filmcraft_time::{Tick, TimeDisplay, format_time};
+use serde_json::{Value, json};
+
+use crate::FilmcraftApp;
+use crate::dock::PanelKind;
+use crate::frames::Rgba;
+use crate::panels::monitor::Which;
+use crate::state::{DisplayMode, Guide, GuideDialog, MonitorView, PlaybackRes, Tool};
+use crate::theme::Tokens;
+
+/// Magnification levels (View ▸ Magnification and the monitor zoom menu).
+pub const ZOOMS: [(&str, f32); 10] =
+ [("10", 0.1), ("25", 0.25), ("50", 0.5), ("75", 0.75), ("100", 1.0), ("150", 1.5), ("200", 2.0), ("400", 4.0), ("800", 8.0), ("1600", 16.0)];
+/// Ruler thickness (points).
+pub const RULER: f32 = 16.0;
+const GUIDE_COLOR: Color32 = Color32::from_rgb(0x3d, 0xa5, 0xff);
+const SNAP_COLOR: Color32 = Color32::from_rgb(0xff, 0x4f, 0xd8);
+/// Snap distance (points).
+pub const SNAP_PX: f32 = 6.0;
+
+const RES_NAMES: [(&str, PlaybackRes); 5] = [
+ ("full", PlaybackRes::Full),
+ ("half", PlaybackRes::Half),
+ ("quarter", PlaybackRes::Quarter),
+ ("eighth", PlaybackRes::Eighth),
+ ("sixteenth", PlaybackRes::Sixteenth),
+];
+
+const DISPLAY_NAMES: [(&str, DisplayMode); 8] = [
+ ("composite", DisplayMode::Composite),
+ ("alpha", DisplayMode::Alpha),
+ ("red", DisplayMode::Red),
+ ("green", DisplayMode::Green),
+ ("blue", DisplayMode::Blue),
+ ("audioWaveform", DisplayMode::AudioWaveform),
+ ("comparison", DisplayMode::Comparison),
+ ("videoAndWaveform", DisplayMode::VideoAndWaveform),
+];
+
+pub fn prefix(w: Which) -> &'static str {
+ if w == Which::Program { "program" } else { "source" }
+}
+
+pub fn view(app: &FilmcraftApp, w: Which) -> &MonitorView {
+ if w == Which::Program { &app.ui.program } else { &app.ui.source }
+}
+
+pub fn view_mut(app: &mut FilmcraftApp, w: Which) -> &mut MonitorView {
+ if w == Which::Program { &mut app.ui.program } else { &mut app.ui.source }
+}
+
+/// The monitor a `view.*` command acts on: `params.monitor`, else the focused monitor.
+fn which_of(app: &FilmcraftApp, params: &Value) -> Which {
+ match params.get("monitor").and_then(Value::as_str) {
+ Some("source") => Which::Source,
+ Some("program") => Which::Program,
+ _ if app.ui.focused == PanelKind::Source => Which::Source,
+ _ => Which::Program,
+ }
+}
+
+fn toggled(cur: bool, params: &Value) -> bool {
+ params.get("enabled").and_then(Value::as_bool).unwrap_or(!cur)
+}
+
+/// Frame size of a monitor's picture (sequence or source item), if it shows video.
+fn frame_size(app: &FilmcraftApp, w: Which) -> Option<(u32, u32)> {
+ match w {
+ Which::Program => app.session.active_sequence().map(|q| (q.settings.width, q.settings.height)),
+ Which::Source => {
+ let pi = app.session.project.item(app.session.state.source_item?)?;
+ match &pi.kind {
+ filmcraft_project::ItemKind::Media(m) => m.info.video.as_ref().map(|v| (v.width, v.height)),
+ filmcraft_project::ItemKind::Sequence(s) => Some((s.settings.width, s.settings.height)),
+ _ => Some((1920, 1080)),
+ }
+ }
+ }
+}
+
+/// Handle a `view.*` command (None for other ids).
+pub fn route(app: &mut FilmcraftApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
+ let rest = id.strip_prefix("view.")?;
+ let w = which_of(app, params);
+ let pfx = prefix(w);
+ if let Some(r) = rest.strip_prefix("playbackRes.") {
+ let (_, res) = RES_NAMES.iter().find(|(n, _)| *n == r)?;
+ view_mut(app, w).res = *res;
+ return Some(Ok(json!({"monitor": pfx, "playbackRes": res.label()})));
+ }
+ if let Some(r) = rest.strip_prefix("pausedRes.") {
+ let (_, res) = RES_NAMES.iter().find(|(n, _)| *n == r)?;
+ view_mut(app, w).paused_res = *res;
+ return Some(Ok(json!({"monitor": pfx, "pausedRes": res.label()})));
+ }
+ if let Some(d) = rest.strip_prefix("display.") {
+ return Some(set_display(app, w, d));
+ }
+ if let Some(z) = rest.strip_prefix("magnification.") {
+ let zoom = if z == "fit" { None } else { Some(ZOOMS.iter().find(|(n, _)| *n == z)?.1) };
+ let v = view_mut(app, w);
+ v.zoom = zoom;
+ v.pan = [0.0, 0.0];
+ return Some(Ok(json!({"monitor": pfx, "zoom": zoom})));
+ }
+ let r = match rest {
+ "highQualityPlayback" => {
+ let v = view_mut(app, w);
+ v.high_quality = toggled(v.high_quality, params);
+ Ok(json!({"monitor": pfx, "highQuality": v.high_quality}))
+ }
+ "safeMargins" => {
+ let v = view_mut(app, w);
+ v.safe_margins = toggled(v.safe_margins, params);
+ Ok(json!({"monitor": pfx, "safeMargins": v.safe_margins}))
+ }
+ "showRulers" => {
+ let v = view_mut(app, w);
+ v.show_rulers = toggled(v.show_rulers, params);
+ Ok(json!({"monitor": pfx, "showRulers": v.show_rulers}))
+ }
+ "showGuides" => {
+ let v = view_mut(app, w);
+ v.show_guides = toggled(v.show_guides, params);
+ Ok(json!({"monitor": pfx, "showGuides": v.show_guides}))
+ }
+ "lockGuides" => {
+ let v = view_mut(app, w);
+ v.lock_guides = toggled(v.lock_guides, params);
+ Ok(json!({"monitor": pfx, "lockGuides": v.lock_guides}))
+ }
+ "snapInProgramMonitor" => {
+ let v = &mut app.ui.program;
+ v.snap = toggled(v.snap, params);
+ Ok(json!({"snap": v.snap}))
+ }
+ "clearGuides" => {
+ let v = view_mut(app, w);
+ let n = v.guides.len();
+ v.guides.clear();
+ Ok(json!({"monitor": pfx, "cleared": n}))
+ }
+ "addGuide" => match params.get("position").and_then(Value::as_f64) {
+ Some(pos) => {
+ let vertical = params.get("orientation").and_then(Value::as_str) != Some("horizontal");
+ let v = view_mut(app, w);
+ v.guides.push(Guide { vertical, position: pos });
+ v.show_guides = true;
+ Ok(json!({"monitor": pfx, "guides": v.guides.len()}))
+ }
+ None => {
+ let mid = frame_size(app, w).map_or(960.0, |f| (f.0 / 2) as f64);
+ app.ui.guide_dialog = Some(GuideDialog::Add { vertical: true, position: mid, source: w == Which::Source });
+ Ok(json!({"dialog": "addGuide"}))
+ }
+ },
+ "guideTemplates.save" => match params.get("name").and_then(Value::as_str) {
+ Some(name) => save_template(app, w, name),
+ None => {
+ if view(app, w).guides.is_empty() {
+ return Some(Err("there are no guides to save".into()));
+ }
+ app.ui.guide_dialog = Some(GuideDialog::SaveTemplate { name: "Guides".into(), source: w == Which::Source });
+ Ok(json!({"dialog": "saveGuides"}))
+ }
+ },
+ "guideTemplates.manage" => {
+ app.ui.guide_dialog = Some(GuideDialog::Manage { selected: None, source: w == Which::Source });
+ Ok(json!({"dialog": "manageGuides", "templates": app.session.prefs.guides.templates.iter().map(|t| t.name.clone()).collect::<Vec<_>>()}))
+ }
+ "guideTemplates.apply" => {
+ let name = params.get("name").and_then(Value::as_str).unwrap_or("");
+ match app.session.prefs.guides.templates.iter().find(|t| t.name == name) {
+ Some(t) => {
+ let g = t.guides.clone();
+ let v = view_mut(app, w);
+ v.guides = g;
+ v.show_guides = true;
+ Ok(json!({"monitor": pfx, "guides": v.guides.len()}))
+ }
+ None => Err(format!("no guide template `{name}`")),
+ }
+ }
+ "guideTemplates.delete" => {
+ let name = params.get("name").and_then(Value::as_str).unwrap_or("").to_string();
+ let mut next = app.session.prefs.clone();
+ let before = next.guides.templates.len();
+ next.guides.templates.retain(|t| t.name != name);
+ if next.guides.templates.len() == before {
+ Err(format!("no guide template `{name}`"))
+ } else {
+ app.session.set_prefs(next).map(|_| json!({"deleted": name})).map_err(|e| format!("saving preferences: {e}"))
+ }
+ }
+ "compare.setReference" => {
+ let t = params
+ .get("time")
+ .and_then(Value::as_i64)
+ .map(Tick)
+ .or_else(|| params.get("seconds").and_then(Value::as_f64).map(Tick::from_seconds_f64))
+ .unwrap_or_else(|| app.session.playhead());
+ app.ui.program.compare_ref = Some(t.0);
+ Ok(json!({"reference": t.0}))
+ }
+ _ => return None,
+ };
+ Some(r)
+}
+
+fn set_display(app: &mut FilmcraftApp, w: Which, d: &str) -> Result<Value, String> {
+ if d == "multicam" {
+ app.ui.program.multicam = true;
+ return Ok(json!({"monitor": "program", "display": "multicam"}));
+ }
+ let (_, mode) = DISPLAY_NAMES.iter().find(|(n, _)| *n == d).ok_or_else(|| format!("unknown display mode `{d}`"))?;
+ // Audio Waveform and the split view are Source Monitor modes, Comparison is a Program mode.
+ let w = match mode {
+ DisplayMode::AudioWaveform | DisplayMode::VideoAndWaveform => Which::Source,
+ DisplayMode::Comparison => Which::Program,
+ _ => w,
+ };
+ let ph = app.session.playhead();
+ let v = view_mut(app, w);
+ v.display = *mode;
+ if w == Which::Program {
+ v.multicam = false;
+ }
+ if *mode == DisplayMode::Comparison && v.compare_ref.is_none() {
+ v.compare_ref = Some(ph.0);
+ }
+ Ok(json!({"monitor": prefix(w), "display": d}))
+}
+
+fn save_template(app: &mut FilmcraftApp, w: Which, name: &str) -> Result<Value, String> {
+ let name = name.trim();
+ if name.is_empty() {
+ return Err("the template needs a name".into());
+ }
+ let guides = view(app, w).guides.clone();
+ let mut next = app.session.prefs.clone();
+ next.guides.templates.retain(|t| t.name != name);
+ next.guides.templates.push(filmcraft_engine::autosave::GuideTemplate { name: name.to_string(), guides });
+ app.session.set_prefs(next).map_err(|e| format!("saving preferences: {e}"))?;
+ Ok(json!({"saved": name}))
+}
+
+/// Menu checkmark state of a `view.*` command (None = not a toggle / radio item).
+pub fn checked(app: &FilmcraftApp, id: &str) -> Option<bool> {
+ let rest = id.strip_prefix("view.")?;
+ let w = which_of(app, &Value::Null);
+ let v = view(app, w);
+ if let Some(r) = rest.strip_prefix("playbackRes.") {
+ return RES_NAMES.iter().find(|(n, _)| *n == r).map(|(_, x)| *x == v.res);
+ }
+ if let Some(r) = rest.strip_prefix("pausedRes.") {
+ return RES_NAMES.iter().find(|(n, _)| *n == r).map(|(_, x)| *x == v.paused_res);
+ }
+ if let Some(d) = rest.strip_prefix("display.") {
+ if d == "multicam" {
+ return Some(app.ui.program.multicam);
+ }
+ let (_, mode) = DISPLAY_NAMES.iter().find(|(n, _)| *n == d)?;
+ let v = match mode {
+ DisplayMode::AudioWaveform | DisplayMode::VideoAndWaveform => &app.ui.source,
+ DisplayMode::Comparison => &app.ui.program,
+ _ => v,
+ };
+ return Some(v.display_mode() == Some(*mode));
+ }
+ if let Some(z) = rest.strip_prefix("magnification.") {
+ return Some(if z == "fit" { v.zoom.is_none() } else { ZOOMS.iter().find(|(n, _)| *n == z).is_some_and(|(_, f)| v.zoom == Some(*f)) });
+ }
+ match rest {
+ "highQualityPlayback" => Some(v.high_quality),
+ "safeMargins" => Some(v.safe_margins),
+ "showRulers" => Some(v.show_rulers),
+ "showGuides" => Some(v.show_guides),
+ "lockGuides" => Some(v.lock_guides),
+ "snapInProgramMonitor" => Some(app.ui.program.snap),
+ _ => None,
+ }
+}
+
+/// Menu enablement of a `view.*` command.
+pub fn enabled(app: &FilmcraftApp, id: &str) -> bool {
+ let v = view(app, which_of(app, &Value::Null));
+ match id {
+ "view.lockGuides" | "view.clearGuides" | "view.guideTemplates.save" => !v.guides.is_empty(),
+ _ => true,
+ }
+}
+
+/// A channel of a frame as greyscale (Alpha, Red, Green, Blue display modes); colour channels are
+/// shown premultiplied, so transparent areas are black.
+pub fn channel_view(img: &Rgba, mode: DisplayMode) -> Rgba {
+ let mut px = Vec::with_capacity(img.px.len());
+ for p in img.px.chunks_exact(4) {
+ let a = p[3] as u32;
+ let v = match mode {
+ DisplayMode::Alpha => p[3],
+ DisplayMode::Red => (p[0] as u32 * a / 255) as u8,
+ DisplayMode::Green => (p[1] as u32 * a / 255) as u8,
+ DisplayMode::Blue => (p[2] as u32 * a / 255) as u8,
+ _ => {
+ px.extend_from_slice(p);
+ continue;
+ }
+ };
+ px.extend_from_slice(&[v, v, v, 255]);
+ }
+ Rgba { w: img.w, h: img.h, px }
+}
+
+/// The on-screen picture rect: fitted, or magnified about the area centre plus the (clamped) pan.
+pub fn picture_rect(area: Rect, fw: f32, fh: f32, v: &MonitorView, ppp: f32) -> Rect {
+ match v.zoom {
+ None => crate::panels::monitor::fit(area, fw, fh),
+ Some(z) => {
+ let size = vec2(fw * z / ppp.max(0.1), fh * z / ppp.max(0.1));
+ let max = ((size - area.size()) / 2.0).max(Vec2::ZERO);
+ let pan = vec2(v.pan[0].clamp(-max.x, max.x), v.pan[1].clamp(-max.y, max.y));
+ Rect::from_center_size(area.center() + pan, size)
+ }
+ }
+}
+
+/// Pan a magnified picture: scroll over it, or drag with the Hand tool.
+pub fn pan_input(app: &mut FilmcraftApp, ui: &mut egui::Ui, w: Which, area: Rect, pic: Rect) {
+ if view(app, w).zoom.is_none() {
+ return;
+ }
+ let mut d = Vec2::ZERO;
+ if ui.rect_contains_pointer(area) {
+ d += ui.input(|i| i.smooth_scroll_delta);
+ }
+ if app.ui.tool == Tool::Hand {
+ let resp = ui.interact(area, egui::Id::new((prefix(w), "pan")), Sense::drag());
+ if resp.hovered() || resp.dragged() {
+ ui.ctx().set_cursor_icon(if resp.dragged() { egui::CursorIcon::Grabbing } else { egui::CursorIcon::Grab });
+ }
+ d += resp.drag_delta();
+ }
+ if d != Vec2::ZERO {
+ let max = ((pic.size() - area.size()) / 2.0).max(Vec2::ZERO);
+ let v = view_mut(app, w);
+ v.pan = [(v.pan[0] + d.x).clamp(-max.x, max.x), (v.pan[1] + d.y).clamp(-max.y, max.y)];
+ }
+}
+
+/// Snap one axis: the moving item's (start, centre, end) against `targets`; returns
+/// (delta, target) of the closest pair within `thr`.
+pub fn snap_axis(edges: [f32; 3], targets: &[f32], thr: f32) -> Option<(f32, f32)> {
+ let mut best: Option<(f32, f32)> = None;
+ for e in edges {
+ for &t in targets {
+ let d = t - e;
+ if d.abs() <= thr && best.is_none_or(|(b, _)| d.abs() < b.abs()) {
+ best = Some((d, t));
+ }
+ }
+ }
+ best
+}
+
+/// Snap in Program Monitor: adjust a drag offset so the moved box's edges or centre meet the
+/// frame edges / centre or a guide. Returns the offset and the lines snapped to (vertical?, coord).
+pub fn snap_move(app: &FilmcraftApp, pic: Rect, frame: (u32, u32), moving: Rect, off: Vec2) -> (Vec2, Vec<(bool, f32)>) {
+ let v = &app.ui.program;
+ if !v.snap {
+ return (off, Vec::new());
+ }
+ let (kx, ky) = (pic.width() / frame.0.max(1) as f32, pic.height() / frame.1.max(1) as f32);
+ let mut tx = vec![pic.min.x, pic.center().x, pic.max.x];
+ let mut ty = vec![pic.min.y, pic.center().y, pic.max.y];
+ if v.show_guides {
+ for g in &v.guides {
+ if g.vertical {
+ tx.push(pic.min.x + g.position as f32 * kx);
+ } else {
+ ty.push(pic.min.y + g.position as f32 * ky);
+ }
+ }
+ }
+ let m = moving.translate(off);
+ let mut off = off;
+ let mut lines = Vec::new();
+ if let Some((d, t)) = snap_axis([m.min.x, m.center().x, m.max.x], &tx, SNAP_PX) {
+ off.x += d;
+ lines.push((true, t));
+ }
+ if let Some((d, t)) = snap_axis([m.min.y, m.center().y, m.max.y], &ty, SNAP_PX) {
+ off.y += d;
+ lines.push((false, t));
+ }
+ (off, lines)
+}
+
+pub fn draw_snap_lines(p: &egui::Painter, pic: Rect, lines: &[(bool, f32)]) {
+ for &(vertical, c) in lines {
+ let seg = if vertical { [pos2(c, pic.min.y), pos2(c, pic.max.y)] } else { [pos2(pic.min.x, c), pos2(pic.max.x, c)] };
+ p.line_segment(seg, Stroke::new(1.0, SNAP_COLOR));
+ }
+}
+
+fn nice_step(px_per_unit: f32) -> f32 {
+ [1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0, 200.0, 500.0, 1000.0, 2000.0].into_iter().find(|s| s * px_per_unit >= 50.0).unwrap_or(5000.0)
+}
+
+#[derive(Clone, Copy)]
+struct NewGuide {
+ vertical: bool,
+}
+
+/// Rulers (frame pixels) along the top and left of the picture area; drag out of a ruler to add a
+/// guide (top ruler → horizontal guide, left ruler → vertical guide).
+#[allow(clippy::too_many_arguments)]
+pub fn rulers(app: &mut FilmcraftApp, ui: &mut egui::Ui, w: Which, top: Rect, left: Rect, area: Rect, pic: Rect, frame: (u32, u32)) {
+ let t = app.tokens;
+ let pfx = prefix(w);
+ let p = ui.painter().clone();
+ for r in [top, left, Rect::from_min_max(left.min - vec2(0.0, RULER), top.min + vec2(0.0, RULER))] {
+ p.rect_filled(r, 0.0, t.tl_ruler_bg);
+ }
+ let (kx, ky) = (pic.width() / frame.0.max(1) as f32, pic.height() / frame.1.max(1) as f32);
+ for (r, vertical, k, o) in [(top, false, kx, pic.min.x), (left, true, ky, pic.min.y)] {
+ let cp = p.with_clip_rect(r);
+ let step = nice_step(k);
+ let (lo, hi) = if vertical { (r.min.y, r.max.y) } else { (r.min.x, r.max.x) };
+ let first = ((lo - o) / k / step * 5.0).floor() as i64;
+ let last = ((hi - o) / k / step * 5.0).ceil() as i64;
+ for i in first..=last {
+ let v = i as f32 * step / 5.0;
+ let s = o + v * k;
+ let major = i % 5 == 0;
+ let len = if major { RULER * 0.6 } else { RULER * 0.25 };
+ if vertical {
+ cp.line_segment([pos2(r.max.x - len, s), pos2(r.max.x, s)], Stroke::new(1.0, t.tl_ruler_tick));
+ if major {
+ cp.text(pos2(r.min.x + 1.0, s + 2.0), Align2::LEFT_TOP, format!("{}", v as i64), Tokens::ui(8.0), t.tl_ruler_text);
+ }
+ } else {
+ cp.line_segment([pos2(s, r.max.y - len), pos2(s, r.max.y)], Stroke::new(1.0, t.tl_ruler_tick));
+ if major {
+ cp.text(pos2(s + 2.0, r.min.y + 1.0), Align2::LEFT_TOP, format!("{}", v as i64), Tokens::ui(8.0), t.tl_ruler_text);
+ }
+ }
+ }
+ }
+ let drag_id = egui::Id::new((pfx, "new-guide"));
+ for (r, name, vertical) in [(top, "top", false), (left, "left", true)] {
+ let resp = ui.interact(r, egui::Id::new((pfx, "ruler", name)), Sense::drag());
+ app.auto.add(&format!("{pfx}.ruler.{name}"), r, if vertical { "left ruler" } else { "top ruler" });
+ if resp.hovered() {
+ ui.ctx().set_cursor_icon(if vertical { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::ResizeVertical });
+ }
+ if resp.drag_started() {
+ ui.data_mut(|d| d.insert_temp(drag_id, NewGuide { vertical }));
+ }
+ let Some(ng) = ui.data(|d| d.get_temp::<NewGuide>(drag_id)).filter(|g| g.vertical == vertical) else { continue };
+ let Some(pos) = resp.interact_pointer_pos().or(ui.ctx().pointer_latest_pos()) else { continue };
+ if area.contains(pos) {
+ let seg = if ng.vertical { [pos2(pos.x, area.min.y), pos2(pos.x, area.max.y)] } else { [pos2(area.min.x, pos.y), pos2(area.max.x, pos.y)] };
+ ui.painter().with_clip_rect(area).line_segment(seg, Stroke::new(1.0, GUIDE_COLOR));
+ }
+ if resp.drag_stopped() {
+ ui.data_mut(|d| d.remove::<NewGuide>(drag_id));
+ if area.contains(pos) {
+ let position = if ng.vertical { ((pos.x - pic.min.x) / kx).round() } else { ((pos.y - pic.min.y) / ky).round() } as f64;
+ let v = view_mut(app, w);
+ v.guides.push(Guide { vertical: ng.vertical, position });
+ v.show_guides = true;
+ }
+ }
+ }
+}
+
+/// Draw the guides; drag an unlocked guide to move it, or back onto a ruler (out of the picture
+/// area) to remove it.
+pub fn guides(app: &mut FilmcraftApp, ui: &mut egui::Ui, w: Which, area: Rect, pic: Rect, frame: (u32, u32)) {
+ let v = view(app, w).clone();
+ if !v.show_guides || v.guides.is_empty() {
+ return;
+ }
+ let pfx = prefix(w);
+ let (kx, ky) = (pic.width() / frame.0.max(1) as f32, pic.height() / frame.1.max(1) as f32);
+ let p = ui.painter().with_clip_rect(area);
+ let mut remove = None;
+ for (i, g) in v.guides.iter().enumerate() {
+ let c = if g.vertical { pic.min.x + g.position as f32 * kx } else { pic.min.y + g.position as f32 * ky };
+ let (seg, hit) = if g.vertical {
+ ([pos2(c, area.min.y), pos2(c, area.max.y)], Rect::from_min_max(pos2(c - 3.0, area.min.y), pos2(c + 3.0, area.max.y)))
+ } else {
+ ([pos2(area.min.x, c), pos2(area.max.x, c)], Rect::from_min_max(pos2(area.min.x, c - 3.0), pos2(area.max.x, c + 3.0)))
+ };
+ p.line_segment(seg, Stroke::new(1.0, GUIDE_COLOR));
+ let hit = hit.intersect(area);
+ app.auto.add(&format!("{pfx}.guide.{i}"), hit, if g.vertical { "vertical guide" } else { "horizontal guide" });
+ if v.lock_guides {
+ continue;
+ }
+ let resp = ui.interact(hit, egui::Id::new((pfx, "guide", i)), Sense::drag());
+ if resp.hovered() || resp.dragged() {
+ ui.ctx().set_cursor_icon(if g.vertical { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::ResizeVertical });
+ }
+ if let Some(pos) = resp.interact_pointer_pos()
+ && (resp.dragged() || resp.drag_stopped())
+ {
+ if !area.contains(pos) {
+ // outside the picture area: dropping here removes the guide
+ if resp.drag_stopped() {
+ remove = Some(i);
+ }
+ } else {
+ let position = if g.vertical { ((pos.x - pic.min.x) / kx).round() } else { ((pos.y - pic.min.y) / ky).round() } as f64;
+ view_mut(app, w).guides[i].position = position;
+ }
+ }
+ }
+ if let Some(i) = remove {
+ view_mut(app, w).guides.remove(i);
+ }
+}
+
+/// The Source Monitor's audio waveform (Audio Waveform display mode, audio-only clips and the
+/// split view): click to move the source playhead.
+#[allow(clippy::too_many_arguments)]
+pub fn waveform(
+ app: &mut FilmcraftApp,
+ ui: &mut egui::Ui,
+ area: Rect,
+ item: ItemId,
+ time: Tick,
+ duration: Tick,
+ mark_in: Option<Tick>,
+ mark_out: Option<Tick>,
+) {
+ let t = app.tokens;
+ let p = ui.painter().with_clip_rect(area);
+ p.rect_filled(area, 0.0, t.monitor_bg);
+ let dur = duration.0.max(1) as f64;
+ let xof = |tk: Tick| area.min.x + ((tk.0 as f64 / dur) as f32).clamp(0.0, 1.0) * area.width();
+ if mark_in.is_some() || mark_out.is_some() {
+ let (a, b) = (xof(mark_in.unwrap_or(Tick::ZERO)), xof(mark_out.unwrap_or(duration)));
+ p.rect_filled(Rect::from_min_max(pos2(a, area.min.y), pos2(b, area.max.y)), 0.0, Color32::from_white_alpha(14));
+ }
+ let mid = area.center().y;
+ p.line_segment([pos2(area.min.x, mid), pos2(area.max.x, mid)], Stroke::new(1.0, Color32::from_white_alpha(30)));
+ match crate::panels::timeline::request_peaks(app, item) {
+ Some(peaks) if !peaks.is_empty() => {
+ let half = area.height() * 0.45;
+ let spp = 256.0 * TICKS_PER_SAMPLE_48K;
+ let mut mesh = egui::Mesh::default();
+ let col = Color32::from_rgb(0x4f, 0xc3, 0x7a);
+ for x in (area.min.x.floor() as i32)..(area.max.x.ceil() as i32) {
+ let f0 = (x as f32 - area.min.x) / area.width();
+ let f1 = (x as f32 + 1.0 - area.min.x) / area.width();
+ let s0 = (dur * f0 as f64 / spp) as usize;
+ let s1 = ((dur * f1 as f64 / spp) as usize).max(s0 + 1);
+ let (lo, hi) = peaks.iter().skip(s0).take(s1 - s0).fold((0f32, 0f32), |(l, h), (a, b)| (l.min(*a), h.max(*b)));
+ if hi - lo > 0.002 {
+ mesh.add_colored_rect(
+ Rect::from_min_max(pos2(x as f32, mid - hi.min(1.0) * half), pos2(x as f32 + 1.0, mid - lo.max(-1.0) * half + 1.0)),
+ col,
+ );
+ }
+ }
+ p.add(mesh);
+ }
+ Some(_) => {
+ p.text(area.center(), Align2::CENTER_CENTER, "(no audio)", Tokens::ui(12.0), t.text_dim);
+ }
+ None => {
+ p.text(area.center(), Align2::CENTER_CENTER, "Generating waveform…", Tokens::ui(12.0), t.text_dim);
+ ui.ctx().request_repaint_after(std::time::Duration::from_millis(100));
+ }
+ }
+ let x = xof(time);
+ p.line_segment([pos2(x, area.min.y), pos2(x, area.max.y)], Stroke::new(1.0, t.playhead));
+ let resp = ui.interact(area, egui::Id::new("source-waveform"), Sense::click_and_drag());
+ app.auto.add("source.waveform", area, "audio waveform");
+ if (resp.clicked() || resp.dragged())
+ && let Some(pos) = resp.interact_pointer_pos()
+ {
+ let f = ((pos.x - area.min.x) / area.width()).clamp(0.0, 1.0) as f64;
+ let _ = app.session.execute("source.setPlayhead", json!({"time": (f * dur) as i64}));
+ }
+}
+
+/// Ticks per 48 kHz sample (the waveform peaks are 256-sample min/max pairs at 48 kHz).
+const TICKS_PER_SAMPLE_48K: f64 = filmcraft_time::TICKS_PER_SECOND as f64 / 48_000.0;
+
+/// Comparison View: the reference side's label, timecode and step / set buttons.
+pub fn compare_bar(app: &mut FilmcraftApp, ui: &mut egui::Ui, bar: Rect, rate: filmcraft_time::FrameRate, drop_frame: bool) {
+ let t = app.tokens;
+ let rf = Tick(app.ui.program.compare_ref.unwrap_or(app.session.playhead().0));
+ let tc = format_time(rf, rate, drop_frame, TimeDisplay::Timecode, 48000);
+ ui.painter().text(pos2(bar.min.x + 4.0, bar.center().y), Align2::LEFT_CENTER, format!("Reference {tc}"), Tokens::ui(11.0), t.text_dim);
+ let mut x = bar.max.x;
+ for (key, label, tip) in
+ [("set", "Set", "Set the reference to the playhead"), ("next", "▶", "Reference: next frame"), ("prev", "◀", "Reference: previous frame")]
+ {
+ let r = Rect::from_min_max(pos2(x - 34.0, bar.min.y + 1.0), pos2(x - 2.0, bar.max.y - 1.0));
+ x -= 34.0;
+ let resp = ui.interact(r, egui::Id::new(("compare", key)), Sense::click()).on_hover_text(tip);
+ ui.painter().rect_filled(r, 3.0, if resp.hovered() { t.hover } else { t.field_bg });
+ ui.painter().text(r.center(), Align2::CENTER_CENTER, label, Tokens::ui(10.0), t.text);
+ app.auto.add(&format!("program.compare.{key}"), r, tip);
+ if resp.clicked() {
+ let nt = match key {
+ "set" => app.session.playhead(),
+ "next" => rf + rate.frame_duration(),
+ _ => (rf - rate.frame_duration()).max(Tick::ZERO),
+ };
+ app.ui.program.compare_ref = Some(nt.0);
+ }
+ }
+}
+
+type Picks = Vec<(String, Rect, String, bool)>;
+
+fn pick(ui: &mut egui::Ui, out: &mut Picks, key: &str, label: &str, on: bool) {
+ let r = ui.selectable_label(on, label);
+ out.push((key.to_string(), r.rect, label.to_string(), r.clicked()));
+}
+
+/// The view items of a monitor's wrench menu (display modes, resolutions, rulers, guides, snap).
+pub fn wrench_items(app: &mut FilmcraftApp, ui: &mut egui::Ui, w: Which) {
+ let v = view(app, w).clone();
+ let mode = v.display_mode();
+ let mut out: Picks = Vec::new();
+ pick(ui, &mut out, "display.composite", "Composite Video", mode == Some(DisplayMode::Composite));
+ ui.menu_button("RGBA Channels", |ui| {
+ for (k, l, m) in [
+ ("alpha", "Alpha", DisplayMode::Alpha),
+ ("red", "Red", DisplayMode::Red),
+ ("green", "Green", DisplayMode::Green),
+ ("blue", "Blue", DisplayMode::Blue),
+ ] {
+ pick(ui, &mut out, &format!("display.{k}"), l, mode == Some(m));
+ }
+ });
+ if w == Which::Program {
+ pick(ui, &mut out, "display.multicam", "Multi-Camera", v.multicam);
+ pick(ui, &mut out, "display.comparison", "Comparison View", mode == Some(DisplayMode::Comparison));
+ } else {
+ pick(ui, &mut out, "display.audioWaveform", "Audio Waveform", mode == Some(DisplayMode::AudioWaveform));
+ pick(ui, &mut out, "display.videoAndWaveform", "Video and Audio Waveform Split", mode == Some(DisplayMode::VideoAndWaveform));
+ }
+ ui.separator();
+ ui.menu_button("Playback Resolution", |ui| {
+ for (k, r) in RES_NAMES {
+ pick(ui, &mut out, &format!("playbackRes.{k}"), r.label(), v.res == r);
+ }
+ });
+ ui.menu_button("Paused Resolution", |ui| {
+ for (k, r) in RES_NAMES {
+ pick(ui, &mut out, &format!("pausedRes.{k}"), r.label(), v.paused_res == r);
+ }
+ });
+ pick(ui, &mut out, "highQualityPlayback", "High Quality Playback", v.high_quality);
+ ui.separator();
+ pick(ui, &mut out, "showRulers", "Show Rulers", v.show_rulers);
+ pick(ui, &mut out, "showGuides", "Show Guides", v.show_guides);
+ if !v.guides.is_empty() {
+ pick(ui, &mut out, "lockGuides", "Lock Guides", v.lock_guides);
+ pick(ui, &mut out, "clearGuides", "Clear Guides", false);
+ }
+ if w == Which::Program {
+ pick(ui, &mut out, "snapInProgramMonitor", "Snap in Program Monitor", v.snap);
+ }
+ ui.separator();
+ let pfx = prefix(w);
+ for (key, r, label, clicked) in out {
+ app.auto.add(&format!("{pfx}.settings.{key}"), r, &label);
+ if clicked && let Some(Err(e)) = route(app, &format!("view.{key}"), &json!({"monitor": pfx})) {
+ app.ui.status = e;
+ }
+ }
+}
+
+/// The magnification popup of a monitor's zoom dropdown.
+pub fn zoom_menu(app: &mut FilmcraftApp, resp: &egui::Response, w: Which) {
+ let zoom = view(app, w).zoom;
+ let mut out: Picks = Vec::new();
+ egui::Popup::menu(resp).show(|ui| {
+ ui.set_min_width(80.0);
+ pick(ui, &mut out, "fit", "Fit", zoom.is_none());
+ ui.separator();
+ for (k, z) in ZOOMS {
+ pick(ui, &mut out, k, &format!("{k}%"), zoom == Some(z));
+ }
+ });
+ let pfx = prefix(w);
+ for (key, r, label, clicked) in out {
+ app.auto.add(&format!("{pfx}.zoom.{key}"), r, &label);
+ if clicked {
+ let _ = route(app, &format!("view.magnification.{key}"), &json!({"monitor": pfx}));
+ }
+ }
+}
+
+type Elems = Vec<(String, Rect, String)>;
+
+fn push(e: &mut Elems, id: &str, r: &egui::Response, label: &str) {
+ e.push((id.to_string(), r.rect, label.to_string()));
+}
+
+/// Add Guide… / Save Guides as Template… / Manage Guides… dialogs.
+pub fn dialogs(app: &mut FilmcraftApp, ctx: &egui::Context) {
+ let Some(mut d) = app.ui.guide_dialog.clone() else { return };
+ let mut elems: Elems = Vec::new();
+ let mut close = ctx.input(|i| i.key_pressed(egui::Key::Escape));
+ let mut act: Option<(String, Value)> = None;
+ let templates: Vec<String> = app.session.prefs.guides.templates.iter().map(|t| t.name.clone()).collect();
+ let title = match &d {
+ GuideDialog::Add { .. } => "Add Guide",
+ GuideDialog::SaveTemplate { .. } => "Save Guides as Template",
+ GuideDialog::Manage { .. } => "Manage Guides",
+ };
+ egui::Window::new(title).collapsible(false).resizable(false).anchor(Align2::CENTER_CENTER, [0.0, 0.0]).show(ctx, |ui| match &mut d {
+ GuideDialog::Add { vertical, position, source } => {
+ let m = if *source { "source" } else { "program" };
+ ui.horizontal(|ui| {
+ ui.label("Orientation:");
+ let r = ui.radio(*vertical, "Vertical");
+ push(&mut elems, "guides.add.vertical", &r, "Vertical");
+ if r.clicked() {
+ *vertical = true;
+ }
+ let r = ui.radio(!*vertical, "Horizontal");
+ push(&mut elems, "guides.add.horizontal", &r, "Horizontal");
+ if r.clicked() {
+ *vertical = false;
+ }
+ });
+ ui.horizontal(|ui| {
+ ui.label("Position:");
+ let r = ui.add(egui::DragValue::new(position).speed(1.0).suffix(" px"));
+ push(&mut elems, "guides.add.position", &r, "Position");
+ });
+ ui.horizontal(|ui| {
+ let r = ui.button("Cancel");
+ push(&mut elems, "guides.add.cancel", &r, "Cancel");
+ close |= r.clicked();
+ let r = ui.button("OK");
+ push(&mut elems, "guides.add.ok", &r, "OK");
+ if r.clicked() {
+ act = Some((
+ "view.addGuide".into(),
+ json!({"monitor": m, "orientation": if *vertical { "vertical" } else { "horizontal" }, "position": *position}),
+ ));
+ }
+ });
+ }
+ GuideDialog::SaveTemplate { name, source } => {
+ let m = if *source { "source" } else { "program" };
+ ui.horizontal(|ui| {
+ ui.label("Name:");
+ let r = ui.text_edit_singleline(name);
+ push(&mut elems, "guides.save.name", &r, "Name");
+ });
+ ui.horizontal(|ui| {
+ let r = ui.button("Cancel");
+ push(&mut elems, "guides.save.cancel", &r, "Cancel");
+ close |= r.clicked();
+ let r = ui.button("OK");
+ push(&mut elems, "guides.save.ok", &r, "OK");
+ if r.clicked() {
+ act = Some(("view.guideTemplates.save".into(), json!({"monitor": m, "name": name.clone()})));
+ }
+ });
+ }
+ GuideDialog::Manage { selected, source } => {
+ let m = if *source { "source" } else { "program" };
+ if templates.is_empty() {
+ ui.label("No saved guide templates.");
+ }
+ for (i, n) in templates.iter().enumerate() {
+ let r = ui.selectable_label(*selected == Some(i), n);
+ push(&mut elems, &format!("guides.manage.row.{i}"), &r, n);
+ if r.clicked() {
+ *selected = Some(i);
+ }
+ }
+ ui.separator();
+ ui.horizontal(|ui| {
+ let sel = selected.and_then(|i| templates.get(i)).cloned();
+ let r = ui.add_enabled(sel.is_some(), egui::Button::new("Apply"));
+ push(&mut elems, "guides.manage.apply", &r, "Apply");
+ if r.clicked()
+ && let Some(n) = &sel
+ {
+ act = Some(("view.guideTemplates.apply".into(), json!({"monitor": m, "name": n})));
+ }
+ let r = ui.add_enabled(sel.is_some(), egui::Button::new("Delete"));
+ push(&mut elems, "guides.manage.delete", &r, "Delete");
+ if r.clicked()
+ && let Some(n) = &sel
+ {
+ act = Some(("view.guideTemplates.delete".into(), json!({"name": n})));
+ *selected = None;
+ }
+ let r = ui.button("Close");
+ push(&mut elems, "guides.manage.close", &r, "Close");
+ close |= r.clicked();
+ });
+ }
+ });
+ for (id, r, l) in elems {
+ app.auto.add(&id, r, &l);
+ }
+ let keep_open = matches!(d, GuideDialog::Manage { .. });
+ app.ui.guide_dialog = Some(d);
+ if let Some((id, p)) = act {
+ match route(app, &id, &p) {
+ Some(Err(e)) => app.ui.status = e,
+ _ => close |= !keep_open || id == "view.guideTemplates.apply",
+ }
+ }
+ if close {
+ app.ui.guide_dialog = None;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn snap_axis_picks_the_closest_target_within_reach() {
+ assert_eq!(snap_axis([10.0, 20.0, 30.0], &[0.0, 33.0, 100.0], 6.0), Some((3.0, 33.0)));
+ assert_eq!(snap_axis([10.0, 20.0, 30.0], &[50.0], 6.0), None);
+ assert_eq!(snap_axis([10.0, 20.0, 30.0], &[8.0, 21.0], 6.0), Some((1.0, 21.0)));
+ }
+
+ #[test]
+ fn channel_view_greyscales() {
+ let img = Rgba { w: 2, h: 1, px: vec![200, 100, 50, 255, 255, 255, 255, 0] };
+ assert_eq!(channel_view(&img, DisplayMode::Red).px, vec![200, 200, 200, 255, 0, 0, 0, 255]);
+ assert_eq!(channel_view(&img, DisplayMode::Green).px[..4], [100, 100, 100, 255]);
+ assert_eq!(channel_view(&img, DisplayMode::Alpha).px, vec![255, 255, 255, 255, 0, 0, 0, 255]);
+ }
+
+ #[test]
+ fn picture_rect_fits_or_magnifies_with_clamped_pan() {
+ let area = Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0));
+ let mut v = MonitorView::default();
+ let r = picture_rect(area, 1920.0, 1080.0, &v, 1.0);
+ assert!((r.width() - 400.0).abs() < 1e-3);
+ v.zoom = Some(1.0);
+ v.pan = [10_000.0, 0.0];
+ let r = picture_rect(area, 1920.0, 1080.0, &v, 2.0);
+ assert!((r.width() - 960.0).abs() < 1e-3, "100% = one frame pixel per physical pixel");
+ assert!((r.min.x - 0.0).abs() < 1e-3, "pan clamped so the picture's left edge stays at the area's");
+ v.zoom = Some(0.1);
+ let r = picture_rect(area, 1920.0, 1080.0, &v, 1.0);
+ assert!((r.center().x - 200.0).abs() < 1e-3, "a small picture stays centred");
+ }
+
+ #[test]
+ fn effective_resolution_follows_paused_and_high_quality() {
+ let mut v = MonitorView::default();
+ assert_eq!(v.effective_res(false), PlaybackRes::Full);
+ assert_eq!(v.effective_res(true), PlaybackRes::Half);
+ v.high_quality = true;
+ assert_eq!(v.effective_res(true), PlaybackRes::Full);
+ v.paused_res = PlaybackRes::Quarter;
+ assert_eq!(v.effective_res(true), PlaybackRes::Half);
+ assert_eq!(v.effective_res(false), PlaybackRes::Quarter);
+ }
+}
diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rs
index a695ffaa8..1b69de599 100644
--- a/crates/ui-egui/src/panels/timeline.rs
+++ b/crates/ui-egui/src/panels/timeline.rs
@@ -574,7 +574,7 @@ fn waveform_display_gain(source_peak: f32, clip_gain_db: f64) -> f32 {
filmcraft_render::audio::db_to_gain(clip_gain_db) * boost
}
-fn request_peaks(app: &mut FilmcraftApp, item: ItemId) -> Option<Arc<Vec<(f32, f32)>>> {
+pub(crate) fn request_peaks(app: &mut FilmcraftApp, item: ItemId) -> Option<Arc<Vec<(f32, f32)>>> {
if let Some(p) = app.tl.peaks.lock().unwrap_or_else(|e| e.into_inner()).get(&item) {
return Some(p.clone());
}
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index 3609f37c0..b441b6d91 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -213,24 +213,118 @@ impl Default for TimelineView {
}
}
+/// Monitor display mode (View ▸ Display Mode / the monitor's wrench menu). Multi-Camera is the
+/// separate `MonitorView::multicam` switch.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub enum DisplayMode {
+ #[default]
+ Composite,
+ Alpha,
+ Red,
+ Green,
+ Blue,
+ /// Source Monitor: the clip's audio waveform.
+ AudioWaveform,
+ /// Program Monitor: a reference frame beside the current frame.
+ Comparison,
+ /// Source Monitor: the picture above the audio waveform.
+ VideoAndWaveform,
+}
+
+impl DisplayMode {
+ /// Shows a single colour channel (or alpha) as greyscale.
+ pub fn is_channel(self) -> bool {
+ matches!(self, DisplayMode::Alpha | DisplayMode::Red | DisplayMode::Green | DisplayMode::Blue)
+ }
+}
+
+/// Monitor guide (frame pixels): `vertical` = a line at x = `position`.
+pub type Guide = filmcraft_engine::autosave::Guide;
+
#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(default)]
pub struct MonitorView {
+ /// Playback Resolution (used while playing).
pub res: PlaybackRes,
- /// Zoom: None = Fit.
+ /// Paused Resolution (used while stopped).
+ pub paused_res: PlaybackRes,
+ /// High Quality Playback: play at the paused resolution when it is higher.
+ pub high_quality: bool,
+ /// Magnification: None = Fit, else the zoom factor (1.0 = 100%: one frame pixel per screen pixel).
pub zoom: Option<f32>,
+ /// Pan offset of a magnified picture from the centre (points).
+ pub pan: [f32; 2],
pub safe_margins: bool,
pub show_transport: bool,
/// Program monitor display mode Multi-Camera (angle grid + program).
- #[serde(default)]
pub multicam: bool,
+ pub display: DisplayMode,
+ /// Comparison View: the reference frame's time (ticks); None = set on entry from the playhead.
+ pub compare_ref: Option<i64>,
+ pub show_rulers: bool,
+ pub show_guides: bool,
+ pub lock_guides: bool,
+ /// Snap in Program Monitor: graphic drags snap to guides, the frame edges and centre.
+ pub snap: bool,
+ pub guides: Vec<Guide>,
}
impl Default for MonitorView {
fn default() -> Self {
- Self { res: PlaybackRes::Half, zoom: None, safe_margins: false, show_transport: true, multicam: false }
+ Self {
+ res: PlaybackRes::Half,
+ paused_res: PlaybackRes::Full,
+ high_quality: false,
+ zoom: None,
+ pan: [0.0, 0.0],
+ safe_margins: false,
+ show_transport: true,
+ multicam: false,
+ display: DisplayMode::Composite,
+ compare_ref: None,
+ show_rulers: false,
+ show_guides: true,
+ lock_guides: false,
+ snap: true,
+ guides: Vec::new(),
+ }
+ }
+}
+
+impl MonitorView {
+ /// The resolution frames are rendered at: Playback Resolution while playing (or the higher
+ /// of it and Paused Resolution with High Quality Playback), Paused Resolution when stopped.
+ pub fn effective_res(&self, playing: bool) -> PlaybackRes {
+ if !playing || (self.high_quality && self.paused_res.scale() > self.res.scale()) { self.paused_res } else { self.res }
+ }
+ /// The display mode in effect (None = Multi-Camera).
+ pub fn display_mode(&self) -> Option<DisplayMode> {
+ (!self.multicam).then_some(self.display)
}
}
+/// Guide dialogs (View ▸ Add Guide…, Guide Templates ▸ Save Guides as Template… / Manage Guides…).
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub enum GuideDialog {
+ /// `source`: the dialog acts on the Source Monitor (else the Program Monitor).
+ Add {
+ vertical: bool,
+ position: f64,
+ #[serde(default)]
+ source: bool,
+ },
+ SaveTemplate {
+ name: String,
+ #[serde(default)]
+ source: bool,
+ },
+ Manage {
+ selected: Option<usize>,
+ #[serde(default)]
+ source: bool,
+ },
+}
+
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum ProjectView {
#[default]
@@ -325,6 +419,9 @@ pub struct UiState {
/// Multi-Camera Record On/Off (key 0): playing in the Multi-Camera view records cuts.
#[serde(default = "yes")]
pub multicam_record: bool,
+ /// Open guide dialog (Add Guide / Save Guides as Template / Manage Guides).
+ #[serde(default)]
+ pub guide_dialog: Option<GuideDialog>,
}
/// A pen mask in progress: vertices placed so far, in clip pixels (`[x, y, tangent x, tangent y]`).
@@ -567,6 +664,7 @@ impl Default for UiState {
save_preset: None,
sync_dialog: None,
multicam_record: true,
+ guide_dialog: None,
}
}
}
diff --git a/crates/ui-egui/tests/view_ui.rs b/crates/ui-egui/tests/view_ui.rs
new file mode 100644
index 000000000..1e063cf3c
--- /dev/null
+++ b/crates/ui-egui/tests/view_ui.rs
@@ -0,0 +1,315 @@
+//! View menu and monitor view options, driven headless through the control channel: playback /
+//! paused resolution, High Quality Playback, display modes (channels, comparison, multi-camera,
+//! source waveform), magnification and panning, rulers and guides (drag out of the ruler, move,
+//! lock, clear, Add Guide…, templates), Snap in Program Monitor, and the Graphics menu commands.
+//!
+//! With `FILMCRAFT_UI_SHOTS=<dir>` the test also renders the UI with wgpu and writes `view-*.png`.
+
+use std::sync::mpsc::{Sender, channel};
+
+use egui_kittest::Harness;
+use filmcraft_engine::Session;
+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>,
+ shots: Option<std::path::PathBuf>,
+}
+
+impl Driver {
+ fn demo() -> Self {
+ let mut session = Session::default();
+ session.execute("file.openDemoProject", json!({})).expect("demo project");
+ let (tx, rx) = channel();
+ let app = FilmcraftApp::new(session).with_control(rx);
+ let shots = std::env::var_os("FILMCRAFT_UI_SHOTS").map(std::path::PathBuf::from);
+ let mut b = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_max_steps(10_000);
+ if shots.is_some() {
+ b = b.wgpu().with_pixels_per_point(1.0);
+ }
+ let harness = b.build_eframe(move |_cc| app);
+ let mut d = Driver { harness, tx, shots };
+ 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 call(&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() {
+ return v;
+ }
+ }
+ panic!("no reply to {method} {params}");
+ }
+ fn ok(&mut self, method: &str, params: Value) -> Value {
+ let r = self.call(method, params.clone());
+ assert_eq!(r["ok"], true, "{method} {params}: {r}");
+ r["result"].clone()
+ }
+ fn exec(&mut self, command: &str, params: Value) -> Value {
+ self.ok("engine.execute", json!({"command": command, "params": params}))
+ }
+ fn menu(&mut self, id: &str) -> Value {
+ let r = self.ok("ui.menu.invoke", json!({"id": id}));
+ self.frames(2);
+ r
+ }
+ fn program(&mut self) -> Value {
+ self.ok("ui.inspect", json!({}))["ui"]["program"].clone()
+ }
+ fn rect(&mut self, id: &str) -> [f64; 4] {
+ self.try_rect(id).unwrap_or_else(|| panic!("no element {id}"))
+ }
+ fn try_rect(&mut self, id: &str) -> Option<[f64; 4]> {
+ let v = self.ok("ui.elements", json!({"prefix": id}));
+ let e = v.as_array().unwrap().iter().find(|e| e["id"] == id)?.clone();
+ let r: Vec<f64> = e["rect"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect();
+ Some([r[0], r[1], r[2], r[3]])
+ }
+ fn click(&mut self, id: &str) {
+ self.ok("ui.click", json!({"id": id}));
+ self.frames(2);
+ }
+ fn shot(&mut self, name: &str) {
+ let Some(dir) = self.shots.clone() else { return };
+ // give the frame workers time to deliver full-resolution frames
+ for _ in 0..8 {
+ self.frames(3);
+ std::thread::sleep(std::time::Duration::from_millis(150));
+ }
+ let img = self.harness.render().expect("wgpu render");
+ std::fs::create_dir_all(&dir).unwrap();
+ img.save(dir.join(format!("view-{name}.png"))).unwrap();
+ }
+}
+
+fn first_media_item(v: &Value) -> Option<u64> {
+ match v {
+ Value::Object(m) => {
+ if let Some(id) = m.get("item").and_then(Value::as_u64)
+ && m.get("type").and_then(Value::as_str).is_some_and(|t| t == "Movie")
+ {
+ return Some(id);
+ }
+ m.values().find_map(first_media_item)
+ }
+ Value::Array(a) => a.iter().find_map(first_media_item),
+ _ => None,
+ }
+}
+
+#[test]
+fn view_menu_resolutions_and_display_modes() {
+ let mut d = Driver::demo();
+ let menu = d.ok("ui.menu.list", json!({}));
+ let item = |id: &str| menu.as_array().unwrap().iter().find(|m| m["id"] == id).cloned().unwrap_or_else(|| panic!("no menu item {id}"));
+ assert_eq!(item("view.playbackRes.sixteenth")["path"], json!(["View", "Playback Resolution"]));
+ assert_eq!(item("view.pausedRes.full")["checked"], true, "Paused Resolution defaults to Full");
+ assert_eq!(item("view.display.composite")["checked"], true);
+ assert_eq!(item("view.magnification.1600")["label"], "1600%");
+ assert_eq!(item("view.clearGuides")["enabled"], false, "no guides yet");
+ assert_eq!(item("graphics.alignFrame.left")["path"], json!(["Graphics and Titles", "Align to Video Frame"]));
+
+ d.menu("view.playbackRes.sixteenth");
+ d.menu("view.pausedRes.quarter");
+ d.menu("view.highQualityPlayback");
+ let p = d.program();
+ assert_eq!((p["res"].as_str(), p["paused_res"].as_str(), p["high_quality"].as_bool()), (Some("Sixteenth"), Some("Quarter"), Some(true)));
+
+ // channels
+ d.menu("view.display.red");
+ assert_eq!(d.program()["display"], "Red");
+ d.shot("display-red");
+ d.menu("view.display.alpha");
+ assert_eq!(d.program()["display"], "Alpha");
+
+ // comparison view: reference frame at the playhead, stepped by the reference buttons
+ d.exec("playhead.set", json!({"seconds": 2}));
+ d.menu("view.display.comparison");
+ let p = d.program();
+ assert_eq!(p["display"], "Comparison");
+ let r0 = p["compare_ref"].as_i64().unwrap();
+ d.frames(3);
+ assert!(d.try_rect("program.compare.reference").is_some());
+ d.click("program.compare.next");
+ let r1 = d.program()["compare_ref"].as_i64().unwrap();
+ assert!(r1 > r0, "reference stepped forward: {r0} → {r1}");
+ d.exec("playhead.set", json!({"seconds": 4}));
+ d.shot("comparison");
+
+ // Multi-Camera links to the existing multi-camera view; Composite turns it off
+ d.menu("view.display.multicam");
+ assert_eq!(d.program()["multicam"], true);
+ d.menu("view.display.composite");
+ let p = d.program();
+ assert_eq!((p["multicam"].as_bool(), p["display"].as_str()), (Some(false), Some("Composite")));
+
+ // wrench menu items carry automation ids
+ d.click("program.settings");
+ assert!(d.try_rect("program.settings.highQualityPlayback").is_some(), "wrench menu lists High Quality Playback");
+ d.click("program.settings.highQualityPlayback");
+ assert_eq!(d.program()["high_quality"], false);
+
+ // source monitor: Audio Waveform display mode
+ let project = d.exec("project.inspect", json!({}));
+ let item = first_media_item(&project).expect("media item");
+ d.exec("source.open", json!({"item": item}));
+ d.menu("view.display.audioWaveform");
+ let s = d.ok("ui.inspect", json!({}))["ui"]["source"]["display"].clone();
+ assert_eq!(s, "AudioWaveform");
+ d.frames(3);
+ assert!(d.try_rect("source.waveform").is_some(), "waveform drawn in the source monitor");
+ d.shot("source-waveform");
+ d.menu("view.display.videoAndWaveform");
+ d.frames(2);
+ assert!(d.try_rect("source.waveform").is_some() && d.try_rect("source.picture").is_some());
+ // ui.set reaches the monitor state directly
+ d.ok("ui.set", json!({"source": {"display": "Composite", "show_rulers": true}}));
+ let s = d.ok("ui.inspect", json!({}))["ui"]["source"].clone();
+ assert_eq!((s["display"].as_str(), s["show_rulers"].as_bool()), (Some("Composite"), Some(true)));
+}
+
+#[test]
+fn magnification_pans_and_guides_from_rulers() {
+ let mut d = Driver::demo();
+ // zoom dropdown → 200%
+ d.click("program.zoom");
+ d.click("program.zoom.200");
+ assert_eq!(d.program()["zoom"], 2.0);
+ let pic = d.rect("program.picture");
+ // pan with the Hand tool
+ d.ok("ui.set", json!({"tool": "Hand"}));
+ let (cx, cy) = (pic[0] + pic[2] / 2.0, pic[1] + pic[3] / 2.0);
+ d.ok("ui.drag", json!({"from": {"x": cx, "y": cy}, "to": {"x": cx + 80.0, "y": cy + 30.0}, "steps": 6}));
+ d.frames(2);
+ let pan = d.program()["pan"].clone();
+ assert!(pan[0].as_f64().unwrap() > 20.0, "panned right: {pan}");
+ d.shot("magnified");
+ d.menu("view.magnification.fit");
+ let p = d.program();
+ assert!(p["zoom"].is_null() && p["pan"] == json!([0.0, 0.0]));
+ d.ok("ui.set", json!({"tool": "Selection"}));
+
+ // rulers, then drag a guide out of the left ruler (vertical guide)
+ d.menu("view.showRulers");
+ d.frames(2);
+ let left = d.rect("program.ruler.left");
+ let pic = d.rect("program.picture");
+ let x = pic[0] + pic[2] * 0.25;
+ d.ok("ui.drag", json!({"from": {"x": left[0] + left[2] / 2.0, "y": pic[1] + pic[3] / 2.0}, "to": {"x": x, "y": pic[1] + pic[3] / 2.0}, "steps": 6}));
+ d.frames(2);
+ let g = d.program()["guides"].clone();
+ assert_eq!(g.as_array().unwrap().len(), 1, "{g}");
+ assert_eq!(g[0]["vertical"], true);
+ let pos = g[0]["position"].as_f64().unwrap();
+ assert!((pos - 480.0).abs() < 8.0, "a quarter across a 1920 frame: {pos}");
+ // and a horizontal one from the top ruler
+ let top = d.rect("program.ruler.top");
+ d.ok(
+ "ui.drag",
+ json!({"from": {"x": pic[0] + pic[2] / 2.0, "y": top[1] + top[3] / 2.0}, "to": {"x": pic[0] + pic[2] / 2.0, "y": pic[1] + pic[3] * 0.5}, "steps": 6}),
+ );
+ d.frames(2);
+ assert_eq!(d.program()["guides"].as_array().unwrap().len(), 2);
+ // move the vertical guide
+ let gr = d.rect("program.guide.0");
+ let (gx, gy) = (gr[0] + gr[2] / 2.0, gr[1] + gr[3] * 0.2);
+ d.ok("ui.drag", json!({"from": {"x": gx, "y": gy}, "to": {"x": gx + 40.0, "y": gy}, "steps": 6}));
+ d.frames(2);
+ let moved = d.program()["guides"][0]["position"].as_f64().unwrap();
+ assert!(moved > pos + 50.0, "guide moved: {pos} → {moved}");
+ d.shot("rulers-guides");
+ // lock: dragging no longer moves it
+ d.menu("view.lockGuides");
+ let gr = d.rect("program.guide.0");
+ let (gx, gy) = (gr[0] + gr[2] / 2.0, gr[1] + gr[3] * 0.2);
+ d.ok("ui.drag", json!({"from": {"x": gx, "y": gy}, "to": {"x": gx + 40.0, "y": gy}, "steps": 6}));
+ d.frames(2);
+ assert_eq!(d.program()["guides"][0]["position"].as_f64().unwrap(), moved);
+ d.menu("view.lockGuides");
+
+ // templates live in the preferences
+ d.ok("ui.menu.invoke", json!({"id": "view.guideTemplates.save", "params": {"name": "Two lines"}}));
+ let prefs = d.exec("prefs.get", json!({"key": "guides.templates"}));
+ assert_eq!(prefs[0]["name"], "Two lines");
+ assert_eq!(prefs[0]["guides"].as_array().unwrap().len(), 2);
+ d.menu("view.clearGuides");
+ assert!(d.program()["guides"].as_array().unwrap().is_empty());
+ d.menu("view.guideTemplates.manage");
+ d.click("guides.manage.row.0");
+ d.click("guides.manage.apply");
+ assert_eq!(d.program()["guides"].as_array().unwrap().len(), 2, "template applied");
+ assert!(d.ok("ui.inspect", json!({}))["ui"]["guide_dialog"].is_null(), "dialog closed");
+
+ // Add Guide… dialog
+ d.menu("view.addGuide");
+ d.click("guides.add.horizontal");
+ d.click("guides.add.ok");
+ let g = d.program()["guides"].clone();
+ assert_eq!(g.as_array().unwrap().len(), 3);
+ assert_eq!(g[2]["vertical"], false);
+ // dragging a guide out of the picture removes it
+ let gr = d.rect("program.guide.0");
+ let left = d.rect("program.ruler.left");
+ d.ok("ui.drag", json!({"from": {"x": gr[0] + gr[2] / 2.0, "y": gr[1] + gr[3] * 0.2}, "to": {"x": left[0] + 4.0, "y": gr[1] + gr[3] * 0.2}, "steps": 6}));
+ d.frames(2);
+ assert_eq!(d.program()["guides"].as_array().unwrap().len(), 2, "guide dropped on the ruler is removed");
+}
+
+#[test]
+fn snap_in_program_monitor_and_graphics_menu() {
+ let mut d = Driver::demo();
+ d.exec("playhead.set", json!({"seconds": 2}));
+ let r = d.exec("graphics.newRectangle", json!({"position": [880, 300], "size": [200, 100]}));
+ let clip = r["clip"].as_u64().unwrap();
+ d.frames(4);
+ let drag_by = |d: &mut Driver, frame_dx: f64, extra: f64| {
+ let pic = d.rect("program.picture");
+ let k = pic[2] / 1920.0;
+ let lr = d.rect(&format!("program.layer.{clip}.0"));
+ let (x, y) = (lr[0] + lr[2] / 2.0, lr[1] + lr[3] / 2.0);
+ d.ok("ui.drag", json!({"from": {"x": x, "y": y}, "to": {"x": x + frame_dx * k + extra, "y": y}, "steps": 8}));
+ d.frames(2);
+ };
+ let pos_x = |d: &mut Driver| d.exec("graphics.list", json!({"clip": clip}))["layers"][0]["position"][0].as_f64().unwrap();
+ // centre 880 → near 960 (+3 screen px): snaps onto the frame centre
+ drag_by(&mut d, 80.0, 3.0);
+ assert!((pos_x(&mut d) - 960.0).abs() < 0.01, "snapped to the centre: {}", pos_x(&mut d));
+ // a guide at x = 1300: the right edge (centre + 100) snaps to it
+ d.ok("ui.menu.invoke", json!({"id": "view.addGuide", "params": {"orientation": "vertical", "position": 1300}}));
+ drag_by(&mut d, 240.0, -4.0);
+ assert!((pos_x(&mut d) - 1200.0).abs() < 0.01, "right edge on the guide: {}", pos_x(&mut d));
+ d.shot("snap");
+ // snapping off: the same drag lands off the guide
+ d.menu("view.snapInProgramMonitor");
+ assert_eq!(d.program()["snap"], false);
+ drag_by(&mut d, -240.0, 4.0);
+ assert!((pos_x(&mut d) - 960.0).abs() > 1.0, "free move: {}", pos_x(&mut d));
+
+ // Graphics menu: New Layer ▸ Ellipse, Align to Video Frame, Arrange
+ d.exec("graphics.newEllipse", json!({"clip": clip, "position": [400, 400], "size": [100, 100]}));
+ d.menu("graphics.alignFrame.left");
+ let l = d.exec("graphics.list", json!({"clip": clip}));
+ assert!(l["layers"][1]["quad"][0][0].as_f64().unwrap().abs() < 0.01, "ellipse on the left edge: {l}");
+ d.menu("graphics.sendToBack");
+ let l = d.exec("graphics.list", json!({"clip": clip}));
+ assert_eq!(l["layers"][0]["kind"], "Ellipse");
+ let menu = d.ok("ui.menu.list", json!({}));
+ let shortcut = menu.as_array().unwrap().iter().find(|m| m["id"] == "graphics.bringToFront").unwrap()["shortcut"].clone();
+ assert_eq!(shortcut, "Cmd+Shift+]");
+ d.shot("graphics-menu");
+}
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 3374a9e6c..0061b76bc 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -19,7 +19,7 @@ Methods (handlers in `crates/ui-egui/src/control.rs`):
| `engine.commands` / `ui.menu.list` | – | command registry / menu tree |
| `ui.inspect` | – | UI state (tool, workspace, dock, timeline view, playback, fps…) |
| `ui.elements` | `{prefix?}` | every on-screen interactive element: id, label, rect |
-| `ui.set` | `{tool, workspace, mode, theme, focused, playbackRes, timeline:{pps,scroll,fit}}` | |
+| `ui.set` | `{tool, workspace, mode, theme, focused, playbackRes, timeline:{pps,scroll,fit}, program:{…}, source:{…}}` | `program` / `source` merge fields into the monitor view state (`res`, `paused_res`, `high_quality`, `display`, `zoom`, `pan`, `show_rulers`, `show_guides`, `lock_guides`, `snap`, `guides`, `compare_ref`, …; see [monitors.md](monitors.md)) |
| `ui.panel.show` / `ui.panel.close` | `{panel}` | |
| `ui.click` / `ui.move` | `{id}` or `{x,y}`, `button`, `count`, `modifiers` | synthetic pointer input |
| `ui.drag` | `{from, to, steps, modifiers}` | press–move–release |
diff --git a/docs/monitors.md b/docs/monitors.md
new file mode 100644
index 000000000..4f79e6d7a
--- /dev/null
+++ b/docs/monitors.md
@@ -0,0 +1,32 @@
+# Monitor view options
+
+The View menu and each monitor's wrench menu set how the Source and Program monitors show their
+picture. It is all UI state (`MonitorView` in `crates/ui-egui/src/state.rs`, serde): agents read
+it with `ui.inspect` (`ui.program`, `ui.source`) and set it with `ui.set {"program": {…}}`, or run
+the `view.*` UI commands. Commands act on `params.monitor` (`"program"` / `"source"`), else on the
+focused monitor (Program by default). Code: `crates/ui-egui/src/panels/monitor_view.rs`.
+
+| Command | Menu | Effect |
+|---|---|---|
+| `view.playbackRes.<full\|half\|quarter\|eighth\|sixteenth>` | View ▸ Playback Resolution | render scale while playing |
+| `view.pausedRes.<…>` | View ▸ Paused Resolution | render scale while stopped (default Full) |
+| `view.highQualityPlayback` | View ▸ High Quality Playback | play at the paused resolution when it is higher |
+| `view.display.<composite\|alpha\|red\|green\|blue>` | View ▸ Display Mode | composite, or one channel as greyscale (colour channels premultiplied) |
+| `view.display.multicam` | Display Mode ▸ Multi-Camera | the Program's multi-camera view (`multicam.toggleView`) |
+| `view.display.audioWaveform`, `view.display.videoAndWaveform` | Display Mode ▸ Audio Waveform / Video and Audio Waveform Split | Source Monitor: the clip's waveform (click to move the source playhead); audio-only clips always show it |
+| `view.display.comparison` | Display Mode ▸ Comparison View | Program: the reference frame (left) beside the current frame; the reference starts at the playhead and is stepped or reset with the buttons under it, or `view.compare.setReference {time\|seconds}` |
+| `view.magnification.<fit\|10\|25\|50\|75\|100\|150\|200\|400\|800\|1600>` | View ▸ Magnification and the zoom dropdown | 100% = one frame pixel per screen pixel; scroll or drag with the Hand tool to pan |
+| `view.showRulers`, `view.showGuides`, `view.lockGuides`, `view.clearGuides` | View | toggles take `{"enabled": bool}` |
+| `view.addGuide` | View ▸ Add Guide… | dialog, or `{"orientation": "vertical\|horizontal", "position": px}` |
+| `view.snapInProgramMonitor` | View ▸ Snap in Program Monitor | graphic moves snap to the frame edges / centre and the guides (6 pt) |
+| `view.safeMargins` | Guide Templates ▸ Safe Margins | action- and title-safe boxes |
+| `view.guideTemplates.save`, `.manage`, `.apply`, `.delete` | Guide Templates ▸ Save Guides as Template… / Manage Guides… | templates are stored in the user preferences (`guides.templates`) |
+
+Guides are in frame pixels. Drag out of the top ruler for a horizontal guide or the left ruler for
+a vertical one; drag a guide to move it (unless locked) and drop it outside the picture to remove it.
+
+Automation ids: `<monitor>.zoom`, `<monitor>.zoom.<level>`, `<monitor>.settings.<command suffix>`
+(wrench menu items, e.g. `program.settings.display.alpha`), `<monitor>.ruler.top|left`,
+`<monitor>.guide.<n>`, `program.compare.reference|prev|next|set`, `source.waveform`, and in the
+dialogs `guides.add.vertical|horizontal|position|ok|cancel`, `guides.save.name|ok|cancel`,
+`guides.manage.row.<n>|apply|delete|close`.
diff --git a/docs/testing.md b/docs/testing.md
index 7da145075..3a6c49bf4 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -17,6 +17,7 @@ FILMCRAFT_REQUIRE_ORACLES=1 cargo test --workspace # CI: missing ffmpeg fails
| Property (`proptest`) | `time`, `bitstream`, `edit`, `isobmff/tests/roundtrip.rs`, `interchange/tests/*` | tick↔frame round trips for every rate, DF timecode, edit invariants (no overlaps, durations conserved), mux→demux round trips, interchange export→import |
| Synthetic streams | `h264/src/synth_tests.rs`, `hevc/src/synth_tests.rs` | hand-built bitstreams for features the reference encoders don't emit; expected output known exactly |
| Scripted UI | `crates/ui-egui/tests/scripted.rs` | headless app (egui_kittest) driven over the control channel: razor/undo, insert, apply effect, playback, click by automation id (§4) |
+| Monitor view / Graphics menu | `crates/ui-egui/tests/view_ui.rs`, `crates/engine/src/graphics_tests.rs` | View menu items and checkmarks, playback/paused resolution, channel / comparison / multi-camera / waveform display modes, magnification and Hand-tool panning, guides dragged from the rulers (move, lock, remove, Add Guide…, templates in the preferences), snapping a graphic to the frame centre and a guide; align to frame / as group / to selection, distribute (centres and gaps), arrange, select next/previous graphic and layer, reset parameters / duration, vertical text, New Layer from file (`FILMCRAFT_UI_SHOTS=<dir>` writes `view-*.png`) |
| Golden images | `crates/golden/tests/golden.rs` | CPU renders vs committed PNGs; GPU vs CPU on the same scenes (§3) |
| Engine / command | `crates/engine/src/tests.rs` | run commands on the demo project, assert the sequence, undo/redo, disabled cases |
| Render | `crates/render/src/tests.rs` | compositing, opacity, Motion, cross dissolve midpoint, ½-res vs full, GPU plan vs reference, audio mix, audio-effect continuity |