Skip to content

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

M12.5: Settings dialog with every Premiere category, wired to real behaviour

Brandon Thomasa69148d5e78e
diff --git a/apps/filmcraft/src/audio.rs b/apps/filmcraft/src/audio.rs
index a83a625c4..4e54897c4 100644
--- a/apps/filmcraft/src/audio.rs
+++ b/apps/filmcraft/src/audio.rs
@@ -1,15 +1,42 @@
-//! cpal audio output: the playback master clock.
+//! cpal audio output: the playback master clock. Settings ▸ Audio Hardware picks the host
+//! ("Device Class"), the output device, the I/O buffer size and the sample rate.
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
-use filmcraft_ui_egui::AudioOut;
+use filmcraft_engine::settings::AudioHardwarePrefs;
+use filmcraft_ui_egui::{AudioDevices, AudioOut};
pub struct CpalOut {
stream: Option<cpal::Stream>,
played: Arc<AtomicU64>,
rate: u32,
+ hw: AudioHardwarePrefs,
+ /// Sequence sample rate for "Attempt to force hardware to document sample rate".
+ document_rate: Option<u32>,
+}
+
+/// The host named in the settings (empty or unknown = the default host).
+fn host(name: &str) -> cpal::Host {
+ if !name.is_empty()
+ && let Some(id) = cpal::available_hosts().into_iter().find(|h| h.name() == name)
+ && let Ok(h) = cpal::host_from_id(id)
+ {
+ return h;
+ }
+ cpal::default_host()
+}
+
+/// The output device named in the settings (empty or missing = the host's default).
+fn output_device(h: &cpal::Host, name: &str) -> Option<cpal::Device> {
+ if !name.is_empty()
+ && let Ok(mut devs) = h.output_devices()
+ && let Some(d) = devs.find(|d| d.name().is_ok_and(|n| n == name))
+ {
+ return Some(d);
+ }
+ h.default_output_device()
}
impl CpalOut {
@@ -17,18 +44,39 @@ impl CpalOut {
let host = cpal::default_host();
let dev = host.default_output_device()?;
let cfg = dev.default_output_config().ok()?;
- Some(Self { stream: None, played: Arc::new(AtomicU64::new(0)), rate: cfg.sample_rate().0 })
+ Some(Self { stream: None, played: Arc::new(AtomicU64::new(0)), rate: cfg.sample_rate().0, hw: AudioHardwarePrefs::default(), document_rate: None })
+ }
+
+ /// The stream configuration the settings ask for, falling back to the device default.
+ fn config(&self, dev: &cpal::Device) -> Result<cpal::SupportedStreamConfig, String> {
+ let default = dev.default_output_config().map_err(|e| e.to_string())?;
+ let want = if self.hw.force_document_rate { self.document_rate.unwrap_or(self.hw.sample_rate) } else { self.hw.sample_rate };
+ let exact = dev.supported_output_configs().ok().and_then(|mut it| {
+ it.find(|c| {
+ c.sample_format() == cpal::SampleFormat::F32
+ && c.channels() == default.channels()
+ && (c.min_sample_rate().0..=c.max_sample_rate().0).contains(&want)
+ })
+ .and_then(|c| c.try_with_sample_rate(cpal::SampleRate(want)))
+ });
+ Ok(exact.unwrap_or(default))
}
}
impl AudioOut for CpalOut {
fn start(&mut self, mut fill: Box<dyn FnMut(&mut [f32], usize) + Send>) -> Result<u32, String> {
self.stop();
- let host = cpal::default_host();
- let dev = host.default_output_device().ok_or("no output device")?;
- let cfg = dev.default_output_config().map_err(|e| e.to_string())?;
+ let host = host(&self.hw.device_class);
+ let dev = output_device(&host, &self.hw.default_output).ok_or("no output device")?;
+ let cfg = self.config(&dev)?;
let channels = cfg.channels() as usize;
- let config: cpal::StreamConfig = cfg.clone().into();
+ let mut config: cpal::StreamConfig = cfg.clone().into();
+ if let cpal::SupportedBufferSize::Range { min, max } = cfg.buffer_size()
+ && (*min..=*max).contains(&self.hw.buffer_size)
+ {
+ config.buffer_size = cpal::BufferSize::Fixed(self.hw.buffer_size);
+ }
+ self.rate = cfg.sample_rate().0;
self.played.store(0, Ordering::SeqCst);
let played = self.played.clone();
let err = |e| eprintln!("filmcraft: audio stream error: {e}");
@@ -58,4 +106,22 @@ impl AudioOut for CpalOut {
fn played_frames(&self) -> Option<u64> {
self.stream.as_ref().map(|_| self.played.load(Ordering::SeqCst))
}
+ fn devices(&self) -> AudioDevices {
+ let h = host(&self.hw.device_class);
+ let outputs = h.output_devices().map(|d| d.filter_map(|x| x.name().ok()).collect()).unwrap_or_default();
+ let inputs = h.input_devices().map(|d| d.filter_map(|x| x.name().ok()).collect()).unwrap_or_default();
+ let output_channels = output_device(&h, &self.hw.default_output).and_then(|d| self.config(&d).ok()).map(|c| c.channels()).unwrap_or(0);
+ AudioDevices { hosts: cpal::available_hosts().iter().map(|h| h.name().to_string()).collect(), inputs, outputs, output_channels }
+ }
+ fn configure(&mut self, hw: &AudioHardwarePrefs, document_rate: Option<u32>) {
+ self.hw = hw.clone();
+ self.document_rate = document_rate;
+ // the rate playback mixes at must be known before `start`
+ let host = host(&self.hw.device_class);
+ if let Some(dev) = output_device(&host, &self.hw.default_output)
+ && let Ok(cfg) = self.config(&dev)
+ {
+ self.rate = cfg.sample_rate().0;
+ }
+ }
}
diff --git a/apps/filmcraft/src/main.rs b/apps/filmcraft/src/main.rs
index 8c9271aea..ec481124a 100644
--- a/apps/filmcraft/src/main.rs
+++ b/apps/filmcraft/src/main.rs
@@ -3,6 +3,9 @@
//! Usage: `filmcraft [--control <port>] [--demo|--empty] [--recover|--no-recover] [--data-dir <dir>]
//! [project.fcproj | media files…]`
//!
+//! Without a project, `--demo` or `--empty`, Settings ▸ General ▸ At Startup decides: Show Home
+//! (the demo project), Open Most Recent, or an empty project.
+//!
//! `--control <port>` (or `FILMCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control server;
//! see `filmcraft_ui_egui::control` for the methods.
//!
@@ -30,14 +33,16 @@ fn main() -> eframe::Result {
let mut control_port: Option<u16> = std::env::var("FILMCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok());
let mut files = Vec::new();
let mut demo = true;
+ // --demo / --empty given: skip Settings ▸ General ▸ At Startup
+ let mut startup_flag = false;
let mut recover: Option<bool> = None;
let mut data_dir = None;
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
match a.as_str() {
"--control" => control_port = args.next().and_then(|p| p.parse().ok()),
- "--demo" => demo = true,
- "--empty" => demo = false,
+ "--demo" => (demo, startup_flag) = (true, true),
+ "--empty" => (demo, startup_flag) = (false, true),
"--recover" => recover = Some(true),
"--no-recover" => recover = Some(false),
"--data-dir" => data_dir = args.next().map(std::path::PathBuf::from),
@@ -79,6 +84,20 @@ fn main() -> eframe::Result {
if let Err(e) = session.execute("file.open", json!({"path": p})) {
eprintln!("filmcraft: {e}");
}
+ } else if !startup_flag && session.prefs.general.at_startup == "openMostRecent" {
+ // Settings ▸ General ▸ At Startup ▸ Open Most Recent
+ let recent = session.prefs.general.recent_projects.iter().find(|p| std::path::Path::new(p).exists()).cloned();
+ match recent {
+ Some(p) => {
+ if let Err(e) = session.execute("file.open", json!({"path": p})) {
+ eprintln!("filmcraft: {e}");
+ }
+ }
+ None => {
+ let _ = session.execute("file.openDemoProject", json!({}));
+ }
+ }
+ } else if !startup_flag && session.prefs.general.at_startup == "emptyProject" {
} else if demo {
let _ = session.execute("file.openDemoProject", json!({}));
}
@@ -104,6 +123,7 @@ fn main() -> eframe::Result {
app.set_wgpu(rs);
}
if let Some(out) = audio::CpalOut::new() {
+ // Settings ▸ Audio Hardware is applied on the first frame (`apply_prefs`)
app.audio = Some(Box::new(out));
}
app.hooks.pick_files = Some(Box::new(|exts: &[&str]| {
diff --git a/apps/filmcraft/src/native_menu.rs b/apps/filmcraft/src/native_menu.rs
index 9288db793..be15f6ecc 100644
--- a/apps/filmcraft/src/native_menu.rs
+++ b/apps/filmcraft/src/native_menu.rs
@@ -27,11 +27,19 @@ pub fn install(app: &FilmcraftApp, ctx: egui::Context) -> (Receiver<String>, Sho
let mut native: Vec<(String, MenuItem)> = Vec::new();
let bar = Menu::new();
let app_menu = Submenu::new("FilmCraft", true);
+ // FilmCraft ▸ Settings ▸ <category> (Premiere's app-menu layout; General is Cmd+,)
+ let settings = Submenu::new("Settings", true);
+ for it in items.iter().filter(|i| i.id.starts_with("app.settings.")) {
+ let label = it.label.trim_end_matches('…').to_string();
+ let mi = MenuItem::with_id(it.id.clone(), label, true, it.shortcut.as_deref().and_then(accel));
+ native.push((it.id.clone(), mi.clone()));
+ let _ = settings.append(&mi);
+ }
let _ = app_menu.append_items(&[
&MenuItem::with_id("app.about", "About FilmCraft", true, None),
&MenuItem::with_id("help.discord", "Join the ArtCraft Discord…", true, None),
&PredefinedMenuItem::separator(),
- &MenuItem::with_id("app.preferences.autoSave", "Settings…", true, None),
+ &settings,
&PredefinedMenuItem::separator(),
&PredefinedMenuItem::hide(None),
&PredefinedMenuItem::hide_others(None),
@@ -41,7 +49,7 @@ pub fn install(app: &FilmcraftApp, ctx: egui::Context) -> (Receiver<String>, Sho
let _ = bar.append(&app_menu);
for top in MENUS {
let sub = Submenu::new(top, true);
- let mine: Vec<&Item> = items.iter().filter(|i| i.path.first().map(String::as_str) == Some(top)).collect();
+ let mine: Vec<&Item> = items.iter().filter(|i| i.path.first().map(String::as_str) == Some(top) && !i.id.starts_with("app.settings.")).collect();
// submenus by path prefix (e.g. Clip ▸ Video Options ▸ Time Interpolation), created where
// their first item appears
let mut subs: Vec<(Vec<String>, Submenu)> = Vec::new();
diff --git a/crates/engine/src/autosave.rs b/crates/engine/src/autosave.rs
index c129da86c..cd8578659 100644
--- a/crates/engine/src/autosave.rs
+++ b/crates/engine/src/autosave.rs
@@ -29,6 +29,8 @@ use filmcraft_project::Project;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
+use crate::settings;
+
// ------------------------------------------------------------------ preferences
/// Preferences ▸ Auto Save.
@@ -63,7 +65,7 @@ impl AutoSavePrefs {
}
}
-/// Preferences ▸ Playback (the parts trim-mode loop playback uses).
+/// Settings ▸ Playback.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct PlaybackPrefs {
@@ -71,44 +73,112 @@ pub struct PlaybackPrefs {
pub preroll_seconds: f64,
/// "Postroll: N seconds".
pub postroll_seconds: f64,
+ /// "Step forward/back many: N frames" (Shift+Right / Shift+Left).
+ pub step_many_frames: u32,
+ pub pause_encoder_queue: bool,
+ pub enable_transmit: bool,
+ pub disable_video_in_background: bool,
}
impl Default for PlaybackPrefs {
fn default() -> Self {
- Self { preroll_seconds: 3.0, postroll_seconds: 2.0 }
+ Self {
+ preroll_seconds: 3.0,
+ postroll_seconds: 2.0,
+ step_many_frames: 5,
+ pause_encoder_queue: true,
+ enable_transmit: false,
+ disable_video_in_background: true,
+ }
}
}
-/// Preferences ▸ Trim.
+/// Settings ▸ Trim.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct TrimPrefs {
/// "Large Trim Offset: N frames" (Trim Forward/Backward Many, the Trim Monitor's ±N buttons).
pub large_trim_offset: u32,
+ /// The audio Large Trim Offset (audio time units).
+ pub large_trim_offset_audio: u32,
+ /// "Allow Selection tool to choose Roll and Ripple trims without modifier key".
+ pub selection_tool_roll_ripple: bool,
+ pub tool_changes_trim_type: bool,
+ pub shift_overlapping_clips: bool,
+ pub ripple_adds_edits: bool,
/// "Playhead position determines trim monitor loop playback" (else the edit point does).
pub playhead_determines_loop: bool,
+ pub dynamic_ripple_updates: bool,
}
impl Default for TrimPrefs {
fn default() -> Self {
- Self { large_trim_offset: 5, playhead_determines_loop: false }
+ Self {
+ large_trim_offset: 5,
+ large_trim_offset_audio: 100,
+ selection_tool_roll_ripple: false,
+ tool_changes_trim_type: true,
+ shift_overlapping_clips: false,
+ ripple_adds_edits: false,
+ playhead_determines_loop: false,
+ dynamic_ripple_updates: true,
+ }
}
}
/// User preferences (persisted as JSON in the per-user data directory). Keys are dotted camelCase
/// paths: `autoSave.enabled`, `autoSave.intervalMinutes`, `playback.prerollSeconds`, …
-#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct Preferences {
- pub auto_save: AutoSavePrefs,
+ /// File layout version ([`crate::settings::PREFS_VERSION`]); older files are migrated on load.
+ pub version: u32,
+ pub general: settings::GeneralPrefs,
+ pub appearance: settings::AppearancePrefs,
pub audio: AudioPrefs,
+ pub audio_hardware: settings::AudioHardwarePrefs,
+ pub auto_save: AutoSavePrefs,
+ pub color: settings::ColorPrefs,
+ pub graphics: settings::GraphicsPrefs,
+ pub labels: settings::LabelPrefs,
+ pub media: MediaPrefs,
+ pub media_analysis: settings::MediaAnalysisPrefs,
+ pub media_cache: settings::MediaCachePrefs,
+ pub memory: settings::MemoryPrefs,
pub playback: PlaybackPrefs,
+ pub plugins: settings::PluginPrefs,
+ pub timeline: settings::TimelinePrefs,
pub trim: TrimPrefs,
- pub media: MediaPrefs,
pub essential_sound: EssentialSoundPrefs,
pub guides: GuidePrefs,
}
+impl Default for Preferences {
+ fn default() -> Self {
+ Self {
+ version: settings::PREFS_VERSION,
+ general: Default::default(),
+ appearance: Default::default(),
+ audio: Default::default(),
+ audio_hardware: Default::default(),
+ auto_save: Default::default(),
+ color: Default::default(),
+ graphics: Default::default(),
+ labels: Default::default(),
+ media: Default::default(),
+ media_analysis: Default::default(),
+ media_cache: Default::default(),
+ memory: Default::default(),
+ playback: Default::default(),
+ plugins: Default::default(),
+ timeline: Default::default(),
+ trim: Default::default(),
+ essential_sound: Default::default(),
+ guides: Default::default(),
+ }
+ }
+}
+
/// View ▸ Guide Templates: guide sets saved from the Program Monitor.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
@@ -132,13 +202,61 @@ pub struct Guide {
pub position: f64,
}
-/// Preferences ▸ Media.
-#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+/// Settings ▸ Media.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct MediaPrefs {
+ /// "Indeterminate Media Timebase": the frame rate of stills (`29.97df`, `25`, …).
+ pub indeterminate_timebase: String,
+ /// "Timecode": `useMediaSource` | `generate`.
+ pub timecode: String,
+ /// "Frame Count": `startAt0` | `startAt1` | `timecodeConversion`.
+ pub frame_count: String,
+ /// "Default Media Scaling": `none` | `scaleToFrameSize` | `setToFrameSize`.
+ pub default_media_scaling: String,
+ pub write_xmp_id: bool,
+ pub validate_content_credentials: bool,
+ pub write_clip_markers_to_xmp: bool,
+ pub enable_xmp_linking: bool,
+ pub include_captions_on_import: bool,
/// "Enable proxies": playback and monitors read attached proxies (the monitors' Toggle
/// Proxies button). Export always uses full-resolution media.
pub enable_proxies: bool,
+ pub allow_duplicate_media: bool,
+ pub create_folder_for_imported_projects: bool,
+ pub auto_hide_dependent_clips: bool,
+ pub import_image_sequences: bool,
+ pub refresh_growing_files: bool,
+ pub resume_growing_playback: bool,
+ pub growing_refresh_seconds: u32,
+ pub hardware_decoding: bool,
+ pub prores_hardware_encoding: bool,
+}
+
+impl Default for MediaPrefs {
+ fn default() -> Self {
+ Self {
+ indeterminate_timebase: "29.97df".into(),
+ timecode: "useMediaSource".into(),
+ frame_count: "startAt0".into(),
+ default_media_scaling: "none".into(),
+ write_xmp_id: false,
+ validate_content_credentials: true,
+ write_clip_markers_to_xmp: false,
+ enable_xmp_linking: false,
+ include_captions_on_import: true,
+ enable_proxies: false,
+ allow_duplicate_media: false,
+ create_folder_for_imported_projects: false,
+ auto_hide_dependent_clips: false,
+ import_image_sequences: false,
+ refresh_growing_files: true,
+ resume_growing_playback: false,
+ growing_refresh_seconds: 60,
+ hardware_decoding: true,
+ prores_hardware_encoding: true,
+ }
+ }
}
/// Essential Sound: user presets saved from the panel (built-in presets live in
@@ -171,6 +289,19 @@ pub struct AudioPrefs {
pub minimum_time_ms: u32,
/// Track Mixer ▸ "Switch to Touch after Write".
pub switch_to_touch_after_write: bool,
+ /// "5.1 Mixdown Type": `front` | `frontRear` | `frontLfe` | `frontRearLfe`.
+ pub mixdown_type: String,
+ pub sum_to_mono_in_source: bool,
+ pub scrub_audio: bool,
+ pub maintain_pitch_shuttling: bool,
+ pub mute_input_during_recording: bool,
+ pub generate_waveforms_on_import: bool,
+ pub multithreaded_waveforms: bool,
+ pub render_audio_with_video: bool,
+ pub auto_tag_audio_types: bool,
+ pub always_override_audio_tags: bool,
+ /// "Render Edit in Audition files to": `scratch` | `nextToMedia`.
+ pub edit_in_audition_location: String,
/// Essential Sound Loudness Auto-Match targets (integrated LUFS) per audio type.
pub dialogue_target_lufs: f64,
pub music_target_lufs: f64,
@@ -187,6 +318,17 @@ impl Default for AudioPrefs {
minimum_time_interval_thinning: false,
minimum_time_ms: 20,
switch_to_touch_after_write: true,
+ mixdown_type: "frontRear".into(),
+ sum_to_mono_in_source: true,
+ scrub_audio: true,
+ maintain_pitch_shuttling: true,
+ mute_input_during_recording: false,
+ generate_waveforms_on_import: true,
+ multithreaded_waveforms: false,
+ render_audio_with_video: false,
+ auto_tag_audio_types: true,
+ always_override_audio_tags: false,
+ edit_in_audition_location: "nextToMedia".into(),
dialogue_target_lufs: -23.0,
music_target_lufs: -25.0,
sfx_target_lufs: -21.0,
@@ -228,6 +370,17 @@ impl Preferences {
self.playback.preroll_seconds = secs(self.playback.preroll_seconds);
self.playback.postroll_seconds = secs(self.playback.postroll_seconds);
self.trim.large_trim_offset = self.trim.large_trim_offset.clamp(1, 1000);
+ self.labels.sanitize_labels();
+ self.version = settings::PREFS_VERSION;
+ }
+
+ /// Parse a preferences document: migrate older layouts, repair values against the schema.
+ pub fn from_value(mut v: Value) -> Self {
+ settings::migrate(&mut v);
+ settings::sanitize(&mut v, &Self::default().to_value());
+ let mut p: Preferences = serde_json::from_value(v).unwrap_or_default();
+ p.clamp();
+ p
}
pub fn to_value(&self) -> Value {
@@ -266,7 +419,10 @@ impl Preferences {
if slot.is_object() {
return Err(format!("`{key}` is a group; set one of its keys"));
}
+ settings::validate(key, &value)?;
let value = match (&*slot, value) {
+ // Numeric choices (buffer size, sample rate) arrive as strings from the dialog.
+ (Value::Number(_), Value::String(t)) if t.parse::<u64>().is_ok() => Value::from(t.parse::<u64>().unwrap_or_default()),
// Accept 5.0 for integer prefs (agents often send floats).
(Value::Number(n), Value::Number(m)) if n.is_u64() && !m.is_u64() => {
Value::from(m.as_f64().filter(|f| f.is_finite() && *f >= 0.0).ok_or_else(|| format!("`{key}` must be a non-negative number"))?.round() as u64)
@@ -274,6 +430,8 @@ impl Preferences {
(_, v) => v,
};
*slot = value;
+ let _: Preferences = serde_json::from_value(v.clone()).map_err(|e| format!("`{key}`: {e}"))?;
+ settings::sanitize(&mut v, &Self::default().to_value());
let mut p: Preferences = serde_json::from_value(v).map_err(|e| format!("`{key}`: {e}"))?;
p.clamp();
*self = p;
@@ -281,9 +439,7 @@ impl Preferences {
}
pub fn load(path: &Path) -> Self {
- let mut p: Preferences = fs::read(path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
- p.clamp();
- p
+ fs::read(path).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok()).map(Self::from_value).unwrap_or_default()
}
pub fn save(&self, path: &Path) -> io::Result<()> {
diff --git a/crates/engine/src/clip_ops.rs b/crates/engine/src/clip_ops.rs
index 2ce26488a..544113da9 100644
--- a/crates/engine/src/clip_ops.rs
+++ b/crates/engine/src/clip_ops.rs
@@ -577,7 +577,8 @@ fn sequence_from_clip(s: &mut Session, p: &Value) -> Result<Value> {
let mut at = Tick::ZERO;
let mut placed = Vec::new();
for item in items {
- let Some(range) = item_range(&s.project, item) else { continue };
+ let still = s.prefs.timeline.still_duration(item_rate(&s.project, item));
+ let Some(range) = item_range(&s.project, item, still) else { continue };
let tg = s.targeting();
let ids = place_item(s, item, range, at, tg.video_dest, tg.audio_dest, false, "New Sequence From Clip", None)?;
at = s.active_sequence().map(|q| q.duration()).unwrap_or(at);
@@ -590,12 +591,13 @@ fn sequence_from_clip(s: &mut Session, p: &Value) -> Result<Value> {
}
/// The media range an item edits in with: its In/Out marks, a subclip's range, or the whole item.
-fn item_range(p: &Project, id: ItemId) -> Option<TimeRange> {
+fn item_range(p: &Project, id: ItemId, still: Tick) -> Option<TimeRange> {
let it = p.item(id)?;
let rate = item_rate(p, id);
Some(match &it.kind {
ItemKind::Media(m) => {
- let full = if m.info.duration.0 > 0 { m.info.duration } else { p.settings.default_still_duration };
+ let is_still = matches!(m.info.kind, filmcraft_media::MediaKind::Still);
+ let full = if m.info.duration.0 > 0 && !is_still { m.info.duration } else { still };
let a = m.mark_in.unwrap_or(Tick::ZERO);
let b = m.mark_out.map(|o| o + rate.frame_duration()).unwrap_or(full);
TimeRange::from_bounds(a, b.max(a + rate.frame_duration()))
@@ -1018,7 +1020,9 @@ fn subclip_plan(s: &Session, p: &Value) -> Result<(ItemId, TimeRange, String, La
let (root, m, sub) = media_root(&s.project, item).ok_or_else(|| bad("clip.makeSubclip", "only media clips can be subclipped"))?;
let pi = s.project.item(item).expect("resolved");
let rate = m.frame_rate();
- let full = sub.unwrap_or(TimeRange::new(Tick::ZERO, if m.info.duration.0 > 0 { m.info.duration } else { s.project.settings.default_still_duration }));
+ let still = s.prefs.timeline.still_duration(rate);
+ let is_still = matches!(m.info.kind, filmcraft_media::MediaKind::Still);
+ let full = sub.unwrap_or(TimeRange::new(Tick::ZERO, if m.info.duration.0 > 0 && !is_still { m.info.duration } else { still }));
let range = if sub.is_some() {
full
} else {
@@ -1575,7 +1579,7 @@ fn replace_with(s: &mut Session, p: &Value, how: Replace) -> Result<Value> {
let (has_v, has_a) = (pi.has_video(), pi.has_audio());
// where the replacement starts in its media: Source In (or the subclip / item start)
let in_point = match how {
- Replace::Bin => item_range(&s.project, new_item).map(|r| r.start).unwrap_or_default(),
+ Replace::Bin => item_range(&s.project, new_item, s.prefs.timeline.still_duration(s.sequence_rate())).map(|r| r.start).unwrap_or_default(),
_ => source_range(s).map(|(_, r)| r.start).unwrap_or_default(),
};
let src_ph = s.state.source_playhead;
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 9db124484..ccf93c404 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -231,12 +231,15 @@ fn import_source(
identity: filmcraft_project::MediaIdentity,
bin: Option<filmcraft_project::BinId>,
) -> Result<ItemId> {
- let info = src.info().clone();
- let label = match info.kind {
- filmcraft_media::MediaKind::AudioOnly => Label::Caribbean,
- filmcraft_media::MediaKind::Still | filmcraft_media::MediaKind::ImageSequence => Label::Lavender,
- _ => Label::Iris,
- };
+ let mut info = src.info().clone();
+ // Settings ▸ Labels ▸ Label Defaults
+ let label = s.prefs.labels.for_media(info.kind, info.has_video(), info.has_audio());
+ // Settings ▸ Media ▸ Indeterminate Media Timebase: the frame rate stills report
+ if info.kind == filmcraft_media::MediaKind::Still
+ && let Some(v) = info.video.as_mut()
+ {
+ v.frame_rate = crate::settings::timebase_rate(&s.prefs.media.indeterminate_timebase);
+ }
let path_s = path.to_string();
let id = s.edit(&format!("Import {name}"), |p, _| {
Ok(p.add_item(
@@ -303,6 +306,8 @@ pub(crate) fn place_item(
.unwrap_or((1920, 1080));
let seq_id = s.state.active_sequence.ok_or(EngineError::NoSequence)?;
let media = s.media.clone();
+ let scaling = s.prefs.media.default_media_scaling.clone();
+ let is_media = matches!(pi.kind, ItemKind::Media(_) | ItemKind::Subclip { .. });
s.edit(label, |p, st| {
let seq = p.sequence(seq_id).ok_or(EngineError::NoSequence)?;
let rate = seq.settings.frame_rate;
@@ -315,6 +320,9 @@ pub(crate) fn place_item(
for e in &mut v.effects {
resolve_auto_points(e, frame, src_size);
}
+ if is_media && src_size != frame {
+ crate::settings::apply_media_scaling(&mut v, &scaling, frame, src_size);
+ }
placements.push((vdest.expect("checked"), v));
}
if has_a {
@@ -364,7 +372,7 @@ pub(crate) fn source_range(s: &Session) -> Option<(ItemId, TimeRange)> {
let item = s.state.source_item?;
let pi = s.project.item(item)?;
let dur = match &pi.kind {
- ItemKind::Media(m) if matches!(m.info.kind, filmcraft_media::MediaKind::Still) => s.project.settings.default_still_duration,
+ ItemKind::Media(m) if matches!(m.info.kind, filmcraft_media::MediaKind::Still) => s.prefs.timeline.still_duration(s.sequence_rate()),
_ => pi.duration(),
};
let (mi, mo) = match &pi.kind {
@@ -470,8 +478,12 @@ fn build() -> Vec<CommandSpec> {
let na = u64_p(p, "audio").unwrap_or(3) as usize;
let n = s.project.sequences().count() + 1;
let name = str_p(p, "name").map(str::to_string).unwrap_or_else(|| format!("Sequence {n:02}"));
+ let seq_label = s.prefs.labels.defaults.sequence;
let id = s.edit("New Sequence", |pr, st2| {
let id = pr.new_sequence(&name, st, nv, na, None);
+ if let Some(it) = pr.item_mut(id) {
+ it.label = seq_label;
+ }
st2.active_sequence = Some(id);
if !st2.open_sequences.contains(&id) {
st2.open_sequences.push(id);
@@ -612,6 +624,20 @@ fn build() -> Vec<CommandSpec> {
}
// Project Settings ▸ Ingest: copy / transcode / create proxies
let item_ids: Vec<ItemId> = ids.iter().map(|i| ItemId(*i)).collect();
+ // Settings ▸ Media Analysis & Transcription ▸ Automatically transcribe clips
+ let ma = &s.prefs.media_analysis;
+ if ma.auto_transcribe
+ && ma.auto_transcribe_scope == "allImported"
+ && !ids.is_empty()
+ && (s.transcriber.is_some() || crate::transcript::speech_available())
+ {
+ let audio: Vec<u64> = ids.iter().copied().filter(|i| s.project.item(ItemId(*i)).is_some_and(|it| it.has_audio())).collect();
+ if !audio.is_empty()
+ && let Err(e) = s.execute("transcript.generate", json!({"items": audio}))
+ {
+ errors.push(format!("transcription: {e}"));
+ }
+ }
let ingest = match crate::proxies::ingest(s, &item_ids) {
Ok(v) => v,
Err(e) => {
@@ -744,8 +770,16 @@ fn build() -> Vec<CommandSpec> {
s.set_prefs(next).map_err(|e| EngineError::Other(format!("saving preferences: {e}")))?;
Ok(s.prefs.to_value())
}),
- cmd!("prefs.reset", "Reset Preferences", [], None, "{}", always, |s, _| {
- s.set_prefs(Default::default()).map_err(|e| EngineError::Other(format!("saving preferences: {e}")))?;
+ cmd!("prefs.reset", "Reset Preferences", [], None, r#"{"category":str?}"#, always, |s, p| {
+ let next = match str_p(p, "category") {
+ Some(c) => {
+ let mut n = s.prefs.clone();
+ n.reset_category(c).map_err(|e| bad("prefs.reset", e))?;
+ n
+ }
+ None => Default::default(),
+ };
+ s.set_prefs(next).map_err(|e| EngineError::Other(format!("saving preferences: {e}")))?;
Ok(s.prefs.to_value())
}),
cmd!(
@@ -1330,9 +1364,15 @@ fn build() -> Vec<CommandSpec> {
}),
cmd!("playhead.stepForward", "Step Forward One Frame", [], Some("Right"), "{}", has_seq, |s, _| s.execute("playhead.step", json!({"frames": 1}))),
cmd!("playhead.stepBack", "Step Back One Frame", [], Some("Left"), "{}", has_seq, |s, _| s.execute("playhead.step", json!({"frames": -1}))),
- cmd!("playhead.stepForward5", "Step Forward Five Frames", [], Some("Shift+Right"), "{}", has_seq, |s, _| s
- .execute("playhead.step", json!({"frames": 5}))),
- cmd!("playhead.stepBack5", "Step Back Five Frames", [], Some("Shift+Left"), "{}", has_seq, |s, _| s.execute("playhead.step", json!({"frames": -5}))),
+ // Settings ▸ Playback ▸ Step forward/back many
+ cmd!("playhead.stepForward5", "Step Forward Five Frames", [], Some("Shift+Right"), "{}", has_seq, |s, _| {
+ let n = s.prefs.playback.step_many_frames as i64;
+ s.execute("playhead.step", json!({"frames": n}))
+ }),
+ cmd!("playhead.stepBack5", "Step Back Five Frames", [], Some("Shift+Left"), "{}", has_seq, |s, _| {
+ 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)) {
@@ -1399,10 +1439,12 @@ fn build() -> Vec<CommandSpec> {
let a = track_p(s, p, "audioTrack").or(tg.audio_dest);
let pi = s.project.item(item).ok_or_else(|| bad("timeline.place", "no such item"))?;
let full = match &pi.kind {
+ // Settings ▸ Timeline ▸ Still Image Default Duration
ItemKind::Media(m)
- if matches!(m.info.kind, filmcraft_media::MediaKind::Still | filmcraft_media::MediaKind::Synthetic) && m.info.duration.0 <= 0 =>
+ if matches!(m.info.kind, filmcraft_media::MediaKind::Still)
+ || (matches!(m.info.kind, filmcraft_media::MediaKind::Synthetic) && m.info.duration.0 <= 0) =>
{
- s.project.settings.default_still_duration
+ s.prefs.timeline.still_duration(s.sequence_rate())
}
_ => pi.duration(),
};
@@ -2004,6 +2046,7 @@ fn build() -> Vec<CommandSpec> {
];
crate::sequence_tools::splice(&mut v);
v.extend(crate::captions::commands());
+ v.extend(crate::settings::commands());
v.extend(crate::mixer::commands());
v.extend(crate::multicam::commands());
v.extend(crate::essential_sound::commands());
@@ -2362,8 +2405,12 @@ fn apply_transition(s: &mut Session, p: &Value, kind: TrackKind) -> Result<Value
.unwrap_or_else(|| if kind == TrackKind::Video { s.state.default_video_transition.clone() } else { s.state.default_audio_transition.clone() });
let def = filmcraft_project::effect::find_effect_by_name(&eff_id).ok_or_else(|| bad("transition", format!("unknown transition `{eff_id}`")))?;
let rate = s.sequence_rate();
- let frames = p.get("frames").and_then(Value::as_i64).unwrap_or(s.project.settings.default_transition_duration_frames);
- let dur = rate.tick_of(frames);
+ // Settings ▸ Timeline ▸ Video / Audio Transition Default Duration
+ let dur = match p.get("frames").and_then(Value::as_i64) {
+ Some(frames) => rate.tick_of(frames),
+ None if kind == TrackKind::Video => s.prefs.timeline.video_transition_duration(rate),
+ None => s.prefs.timeline.audio_transition_duration(rate),
+ };
let t = s.playhead();
let clip = clip_p(p, "clip");
let edge = str_p(p, "edge").map(str::to_string);
@@ -2515,6 +2562,7 @@ fn write_project(s: &mut Session, path: &str, adopt: bool) -> Result<Value> {
if adopt {
s.path = Some(path.to_string());
s.previews_follow_path();
+ s.note_recent_project();
s.saved_revision = s.revision;
s.loaded_schema = filmcraft_format::SCHEMA_VERSION;
}
@@ -2557,6 +2605,7 @@ fn open_project(s: &mut Session, path: &str) -> Result<Value> {
let loaded = filmcraft_format::decode(&bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
let (from, migrated) = (loaded.schema_version, loaded.migrated());
install_project(s, loaded.project, Some(path.to_string()), true);
+ s.note_recent_project();
s.loaded_schema = from;
if migrated {
s.toast(format!("Upgraded project from schema v{from} to v{}; the original is kept as a backup when you save", filmcraft_format::SCHEMA_VERSION));
diff --git a/crates/engine/src/graphics.rs b/crates/engine/src/graphics.rs
index ce4780edf..e53d2ac3e 100644
--- a/crates/engine/src/graphics.rs
+++ b/crates/engine/src/graphics.rs
@@ -725,6 +725,9 @@ pub fn commands() -> Vec<CommandSpec> {
has_seq,
|s, p| {
let text = str_p(p, "text").unwrap_or("New Text").to_string();
+ // Settings ▸ Graphics ▸ Text: smart quotes, ligatures, default font
+ let gp = s.prefs.graphics.clone();
+ let text = if gp.smart_quotes { crate::settings::smart_quotes(&text) } else { text };
let (w, h) = s.active_sequence().map(|q| (q.settings.width, q.settings.height)).unwrap_or((1920, 1080));
let pos = vec2_p(p, "position").unwrap_or(Vec2::new(w as f64 / 2.0, h as f64 / 2.0));
let size = f64_p(p, "size").unwrap_or(100.0);
@@ -733,6 +736,10 @@ pub fn commands() -> Vec<CommandSpec> {
} else {
new_text_layer(&text, pos, size)
};
+ layer.params.insert("ligatures".into(), filmcraft_project::Param::new(ParamValue::Bool(gp.ligatures)));
+ if !gp.default_font.trim().is_empty() {
+ layer.params.insert("font".into(), filmcraft_project::Param::new(ParamValue::Text(gp.default_font.trim().into())));
+ }
for (k, id) in [("font", "font"), ("fontStyle", "font_style")] {
if let Some(v) = str_p(p, k) {
layer.params.insert(id.into(), filmcraft_project::Param::new(ParamValue::Text(v.into())));
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index aa392e958..1c1178c77 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -27,6 +27,7 @@ pub mod project_manager;
pub mod proxies;
pub mod relink;
pub mod sequence_tools;
+pub mod settings;
pub mod shortcut_presets;
pub mod shortcuts;
pub mod sync;
@@ -389,6 +390,7 @@ impl Session {
self.shortcuts.set_dir(&cfg.data_dir);
self.presets.set_dir(&cfg.data_dir);
self.prefs_path = Some(prefs_path);
+ self.apply_media_cache();
self.persistence = Some(autosave::Persistence::start(&cfg, self.prefs.auto_save.clone())?);
self.sync_persistence();
Ok(())
@@ -446,7 +448,11 @@ impl Session {
/// Replace preferences (persisting them and updating the worker).
pub fn set_prefs(&mut self, p: autosave::Preferences) -> std::io::Result<()> {
+ let cache_changed = self.prefs.media_cache != p.media_cache;
self.prefs = p;
+ if cache_changed {
+ self.apply_media_cache();
+ }
if self.media.use_proxies() != self.prefs.media.enable_proxies {
self.media.set_use_proxies(self.prefs.media.enable_proxies);
self.bump_view();
@@ -753,6 +759,8 @@ mod relink_tests;
#[cfg(test)]
mod sequence_tools_tests;
#[cfg(test)]
+mod settings_tests;
+#[cfg(test)]
mod shortcuts_tests;
#[cfg(test)]
mod tests;
diff --git a/crates/engine/src/previews.rs b/crates/engine/src/previews.rs
index f3fd54106..3e8d654ba 100644
--- a/crates/engine/src/previews.rs
+++ b/crates/engine/src/previews.rs
@@ -69,6 +69,8 @@ type AudioMemo = (Arc<Project>, ItemId, Arc<Vec<AudioSegment>>);
#[derive(Default)]
pub struct PreviewStore {
dir: RwLock<Option<PathBuf>>,
+ /// Where unsaved projects' previews go (Settings ▸ Media Cache); None = the system temp dir.
+ temp_root: RwLock<Option<PathBuf>>,
/// File names present: `<hash>.mov` (video) and `<hash>.wav` (audio).
files: RwLock<HashSet<String>>,
/// Opened preview files (most recent last).
@@ -100,7 +102,20 @@ impl PreviewStore {
/// Switch to a fresh temp folder (new unsaved project).
pub fn reset_temp(&self) {
- self.set_dir(default_temp_dir());
+ let root = self.temp_root();
+ self.set_dir(match root {
+ Some(r) => Some(untitled_dir(&r)),
+ None => default_temp_dir(),
+ });
+ }
+
+ /// The folder unsaved projects' previews go into (None = the system temp dir).
+ pub fn temp_root(&self) -> Option<PathBuf> {
+ self.temp_root.read().unwrap_or_else(|e| e.into_inner()).clone()
+ }
+
+ pub fn set_temp_root(&self, root: Option<PathBuf>) {
+ *self.temp_root.write().unwrap_or_else(|e| e.into_inner()) = root;
}
pub fn dir(&self) -> Option<PathBuf> {
@@ -136,7 +151,7 @@ impl PreviewStore {
return;
}
if let Some(old) = &old
- && old.starts_with(std::env::temp_dir())
+ && (old.starts_with(std::env::temp_dir()) || self.temp_root().is_some_and(|r| old.starts_with(r)))
{
let _ = std::fs::create_dir_all(&dir);
for name in self.files.read().unwrap_or_else(|e| e.into_inner()).iter() {
@@ -373,8 +388,13 @@ fn default_temp_dir() -> Option<PathBuf> {
if cfg!(target_arch = "wasm32") {
return None;
}
+ Some(untitled_dir(&std::env::temp_dir().join("FilmCraft Previews")))
+}
+
+/// A fresh per-process folder for an unsaved project's previews under `root`.
+fn untitled_dir(root: &Path) -> PathBuf {
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
- Some(std::env::temp_dir().join("FilmCraft Previews").join(format!("untitled-{}-{nanos:x}", std::process::id())))
+ root.join(format!("untitled-{}-{nanos:x}", std::process::id()))
}
/// The preview folder of a project saved at `project_path`.
diff --git a/crates/engine/src/settings.rs b/crates/engine/src/settings.rs
new file mode 100644
index 000000000..4f6d0eb31
--- /dev/null
+++ b/crates/engine/src/settings.rs
@@ -0,0 +1,1425 @@
+//! **Settings** (Premiere: app menu ▸ Settings ▸ <category>; the window is titled "Preferences").
+//!
+//! The values live in [`crate::autosave::Preferences`] (persisted as `preferences.json` in the
+//! per-user data directory, never in the project). Every value is a dotted camelCase key whose first
+//! segment is the category id (`timeline.stillImageDuration`, `labels.colors.violet.name`), so the
+//! `prefs.get` / `prefs.set` / `prefs.reset` commands reach all of them from the CLI, the control
+//! channel and MCP, and the Settings dialog's controls carry the automation id `settings.<key>`.
+//!
+//! This module holds the categories' value types, the field schema the dialog is drawn from
+//! ([`categories`]; also returned by `prefs.schema` so agents can discover choices and ranges),
+//! validation/migration, and the engine-side helpers that make the values take effect (default
+//! durations, label colours, the media cache, audio output mapping, smart quotes…).
+
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+
+use filmcraft_project::Label;
+use filmcraft_time::{FrameRate, Tick};
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+
+use crate::commands::{CommandSpec, always, bad, bool_p, str_p};
+use crate::{EngineError, Result, Session};
+
+/// Version of the preferences file layout ([`crate::autosave::Preferences::version`]).
+/// v1: Auto Save, Audio (mixer automation), Playback (pre/postroll), Trim, Media (proxies), guides,
+/// Essential Sound presets. v2: every Settings category.
+pub const PREFS_VERSION: u32 = 2;
+
+// ------------------------------------------------------------------ category values
+
+/// Settings ▸ General.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct GeneralPrefs {
+ /// "At Startup": `showHome` (FilmCraft: the demo project), `openMostRecent`, `emptyProject`.
+ pub at_startup: String,
+ /// "When Opening a Project": `showOpenDialog` | `showHome`.
+ pub when_opening_project: String,
+ /// Bins ▸ Double-click / + Cmd / + Opt: `openInPlace` | `openNewTab` | `openNewWindow`.
+ pub bins_double_click: String,
+ pub bins_cmd_double_click: String,
+ pub bins_opt_double_click: String,
+ /// Projects ▸ Double-click / + Opt.
+ pub projects_double_click: String,
+ pub projects_opt_double_click: String,
+ pub show_event_indicator: bool,
+ pub show_tool_tips: bool,
+ pub show_rich_tool_tips: bool,
+ pub show_workspace_reset_warning: bool,
+ pub show_project_load_errors: bool,
+ pub show_compatibility_issues: bool,
+ pub show_project_bin_in_tab: bool,
+ pub show_mask_tracker_preview: bool,
+ /// Most recently opened / saved projects (newest first; not shown in the dialog).
+ pub recent_projects: Vec<String>,
+}
+
+impl Default for GeneralPrefs {
+ fn default() -> Self {
+ Self {
+ at_startup: "showHome".into(),
+ when_opening_project: "showOpenDialog".into(),
+ bins_double_click: "openInPlace".into(),
+ bins_cmd_double_click: "openNewTab".into(),
+ bins_opt_double_click: "openNewWindow".into(),
+ projects_double_click: "openNewTab".into(),
+ projects_opt_double_click: "openNewWindow".into(),
+ show_event_indicator: true,
+ show_tool_tips: true,
+ show_rich_tool_tips: true,
+ show_workspace_reset_warning: true,
+ show_project_load_errors: true,
+ show_compatibility_issues: true,
+ show_project_bin_in_tab: true,
+ show_mask_tracker_preview: true,
+ recent_projects: Vec::new(),
+ }
+ }
+}
+
+/// Settings ▸ Appearance.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct AppearancePrefs {
+ /// "Color Theme": `darkest` (default) | `dark` | `light`.
+ pub color_theme: String,
+ /// "Accessible color contrast": brighter secondary text and borders.
+ pub accessible_contrast: bool,
+ /// Highlight (accent) colour of selections, focus and primary buttons (`#rrggbb`).
+ pub highlight_color: String,
+}
+
+impl Default for AppearancePrefs {
+ fn default() -> Self {
+ Self { color_theme: "darkest".into(), accessible_contrast: false, highlight_color: DEFAULT_HIGHLIGHT.into() }
+ }
+}
+
+pub const DEFAULT_HIGHLIGHT: &str = "#2f6bdf";
+
+/// Settings ▸ Audio Hardware (the cpal output on desktop).
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct AudioHardwarePrefs {
+ /// "Device Class": the audio host (`CoreAudio`, `WASAPI`, `ALSA`…); empty = system default.
+ pub device_class: String,
+ /// "Default Input" / "Default Output": device names; empty = the system default device.
+ pub default_input: String,
+ pub default_output: String,
+ /// "I/O Buffer Size" (samples).
+ pub buffer_size: u32,
+ /// "Sample Rate" (Hz).
+ pub sample_rate: u32,
+ /// "Attempt to force hardware to document sample rate": open the device at the sequence rate.
+ pub force_document_rate: bool,
+ /// Output Mapping: the device channels (0-based) the programme's left and right go to.
+ pub map_left: u32,
+ pub map_right: u32,
+}
+
+impl Default for AudioHardwarePrefs {
+ fn default() -> Self {
+ Self {
+ device_class: String::new(),
+ default_input: String::new(),
+ default_output: String::new(),
+ buffer_size: 512,
+ sample_rate: 48_000,
+ force_document_rate: false,
+ map_left: 0,
+ map_right: 1,
+ }
+ }
+}
+
+/// Settings ▸ Color.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct ColorPrefs {
+ pub display_color_management: bool,
+ pub extended_dynamic_range: bool,
+ /// HDR Graphics White (nits): `100` | `203` | `300`.
+ pub hdr_graphics_white: String,
+}
+
+impl Default for ColorPrefs {
+ fn default() -> Self {
+ Self { display_color_management: false, extended_dynamic_range: false, hdr_graphics_white: "203".into() }
+ }
+}
+
+/// Settings ▸ Graphics (Text, Shapes, Closed Captions).
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct GraphicsPrefs {
+ pub ligatures: bool,
+ pub hindi_digits: bool,
+ pub smart_quotes: bool,
+ /// `ltr` | `rtl`.
+ pub paragraph_direction: String,
+ /// `miter` | `round` | `bevel`.
+ pub text_line_join: String,
+ pub text_miter_limit: f64,
+ /// `butt` | `round` | `square`.
+ pub text_line_cap: String,
+ /// `allLines` | `perLine`.
+ pub background_fill: String,
+ pub default_font: String,
+ pub missing_font_replacement: String,
+ pub emoji_font: String,
+ pub shape_line_join: String,
+ pub shape_miter_limit: f64,
+ pub shape_line_cap: String,
+ pub caption_font: String,
+ pub caption_monospace_only: bool,
+ pub cea708_wide: bool,
+}
+
+impl Default for GraphicsPrefs {
+ fn default() -> Self {
+ Self {
+ ligatures: true,
+ hindi_digits: false,
+ smart_quotes: true,
+ paragraph_direction: "ltr".into(),
+ text_line_join: "miter".into(),
+ text_miter_limit: 2.5,
+ text_line_cap: "butt".into(),
+ background_fill: "allLines".into(),
+ default_font: "Inter".into(),
+ missing_font_replacement: "Inter".into(),
+ emoji_font: String::new(),
+ shape_line_join: "miter".into(),
+ shape_miter_limit: 2.5,
+ shape_line_cap: "butt".into(),
+ caption_font: "JetBrains Mono".into(),
+ caption_monospace_only: true,
+ cea708_wide: false,
+ }
+ }
+}
+
+/// One editable label colour.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct LabelColor {
+ pub name: String,
+ /// `#rrggbb`.
+ pub color: String,
+}
+
+impl Default for LabelColor {
+ fn default() -> Self {
+ Self { name: String::new(), color: "#808080".into() }
+ }
+}
+
+/// Settings ▸ Labels ▸ Label Defaults (which label new items get).
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct LabelDefaults {
+ pub movie: Label,
+ pub video: Label,
+ pub audio: Label,
+ pub still: Label,
+ pub sequence: Label,
+ pub dynamic_link: Label,
+ pub bin: Label,
+ pub captions: Label,
+}
+
+impl Default for LabelDefaults {
+ fn default() -> Self {
+ Self {
+ movie: Label::Iris,
+ video: Label::Violet,
+ audio: Label::Caribbean,
+ still: Label::Lavender,
+ sequence: Label::Forest,
+ dynamic_link: Label::Rose,
+ bin: Label::Mango,
+ captions: Label::Mango,
+ }
+ }
+}
+
+/// Settings ▸ Labels: names and colours of the 16 labels (keyed by the label's id, e.g.
+/// `labels.colors.violet.name`) and the label defaults.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct LabelPrefs {
+ pub colors: BTreeMap<String, LabelColor>,
+ pub defaults: LabelDefaults,
+}
+
+impl Default for LabelPrefs {
+ fn default() -> Self {
+ Self { colors: Label::ALL.iter().map(|l| (label_id(*l), default_label_color(*l))).collect(), defaults: LabelDefaults::default() }
+ }
+}
+
+/// The key of a label in [`LabelPrefs::colors`] (`violet`, `iris`, …).
+pub fn label_id(l: Label) -> String {
+ l.name().to_ascii_lowercase()
+}
+
+fn default_label_color(l: Label) -> LabelColor {
+ LabelColor { name: l.name().into(), color: hex(l.rgb()) }
+}
+
+pub fn hex(c: [u8; 3]) -> String {
+ format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2])
+}
+
+/// `#rrggbb` (or `rrggbb`) → bytes.
+pub fn parse_hex(s: &str) -> Option<[u8; 3]> {
+ let s = s.strip_prefix('#').unwrap_or(s);
+ if s.len() != 6 || !s.bytes().all(|b| b.is_ascii_hexdigit()) {
+ return None;
+ }
+ let p = |i: usize| u8::from_str_radix(&s[i..i + 2], 16).ok();
+ Some([p(0)?, p(2)?, p(4)?])
+}
+
+impl LabelPrefs {
+ /// The colour of label `l` (the user's, else the built-in one).
+ pub fn rgb(&self, l: Label) -> [u8; 3] {
+ self.colors.get(&label_id(l)).and_then(|c| parse_hex(&c.color)).unwrap_or_else(|| l.rgb())
+ }
+ /// The display name of label `l`.
+ pub fn name(&self, l: Label) -> String {
+ self.colors.get(&label_id(l)).map(|c| c.name.trim()).filter(|n| !n.is_empty()).unwrap_or(l.name()).to_string()
+ }
+ /// The label a new media item of `kind` gets.
+ pub fn for_media(&self, kind: filmcraft_media::MediaKind, has_video: bool, has_audio: bool) -> Label {
+ use filmcraft_media::MediaKind as K;
+ match kind {
+ K::AudioOnly => self.defaults.audio,
+ K::Still | K::ImageSequence => self.defaults.still,
+ _ if has_video && !has_audio => self.defaults.video,
+ _ if !has_video && has_audio => self.defaults.audio,
+ _ => self.defaults.movie,
+ }
+ }
+ pub(crate) fn sanitize_labels(&mut self) {
+ for l in Label::ALL {
+ let c = self.colors.entry(label_id(l)).or_insert_with(|| default_label_color(l));
+ if parse_hex(&c.color).is_none() {
+ c.color = hex(l.rgb());
+ }
+ c.name = c.name.chars().take(64).collect();
+ }
+ self.colors.retain(|k, _| Label::ALL.iter().any(|l| label_id(*l) == *k));
+ }
+}
+
+/// Settings ▸ Media Analysis & Transcription.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct MediaAnalysisPrefs {
+ /// "Cache analysis results for re-use": `mediaCache` | `project`.
+ pub cache_results: String,
+ pub analyze_imported_media: bool,
+ /// "Automatically transcribe clips".
+ pub auto_transcribe: bool,
+ /// `allImported` (transcribe on import) | `sequenceClips` (only clips edited into sequences).
+ pub auto_transcribe_scope: String,
+ /// "Speaker Labeling": `on` | `off`.
+ pub speaker_labeling: String,
+ pub language_auto_detect: bool,
+ /// "Default language" (ISO 639-1).
+ pub default_language: String,
+ /// Speech model (`transcript.models`).
+ pub whisper_model: String,
+}
+
+impl Default for MediaAnalysisPrefs {
+ fn default() -> Self {
+ Self {
+ cache_results: "mediaCache".into(),
+ analyze_imported_media: true,
+ auto_transcribe: false,
+ auto_transcribe_scope: "sequenceClips".into(),
+ speaker_labeling: "on".into(),
+ language_auto_detect: false,
+ default_language: "en".into(),
+ whisper_model: filmcraft_speech::models::DEFAULT_MODEL.into(),
+ }
+ }
+}
+
+/// Settings ▸ Media Cache.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct MediaCachePrefs {
+ /// Media Cache Files location; empty = `<data dir>/Media Cache`.
+ pub location: String,
+ pub save_next_to_media: bool,
+ /// Media Cache Database location; empty = the files location.
+ pub database_location: String,
+ /// `never` | `olderThan` | `exceedsSize`.
+ pub management: String,
+ pub older_than_days: u32,
+ pub max_size_gb: u32,
+}
+
+impl Default for MediaCachePrefs {
+ fn default() -> Self {
+ Self {
+ location: String::new(),
+ save_next_to_media: false,
+ database_location: String::new(),
+ management: "never".into(),
+ older_than_days: 90,
+ max_size_gb: 92,
+ }
+ }
+}
+
+/// Settings ▸ Memory.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct MemoryPrefs {
+ /// "RAM reserved for other applications" (GB).
+ pub ram_reserved_gb: u32,
+ /// Decoded-frame cache budget of the monitors and thumbnails (MB).
+ pub frame_cache_mb: u32,
+}
+
+impl Default for MemoryPrefs {
+ fn default() -> Self {
+ Self { ram_reserved_gb: 4, frame_cache_mb: 768 }
+ }
+}
+
+/// Settings ▸ Timeline.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct TimelinePrefs {
+ pub video_transition_duration: f64,
+ /// `frames` | `seconds`.
+ pub video_transition_unit: String,
+ pub audio_transition_duration: f64,
+ pub audio_transition_unit: String,
+ pub still_image_duration: f64,
+ pub still_image_unit: String,
+ /// "Timeline Playback Auto-Scrolling": `noScroll` | `pageScroll` | `smoothScroll`.
+ pub auto_scroll: String,
+ /// "Timeline Mouse Scrolling": `vertical` | `horizontal`.
+ pub mouse_scrolling: String,
+ /// Default Audio Tracks per media type: `useFile` | `mono` | `stereo` | `5.1` | `adaptive`.
+ pub mono_media_tracks: String,
+ pub stereo_media_tracks: String,
+ pub surround_media_tracks: String,
+ pub multichannel_mono_media_tracks: String,
+ pub focus_timeline_on_edit: bool,
+ pub snap_playhead: bool,
+ pub return_to_beginning: bool,
+ pub out_of_sync_unlinked: bool,
+ pub play_after_rendering: bool,
+ pub clip_mismatch_warning: bool,
+ pub match_frame_sets_in: bool,
+ pub restore_open_sequences: bool,
+ pub add_tracks_automatically: bool,
+}
+
+impl Default for TimelinePrefs {
+ fn default() -> Self {
+ Self {
+ video_transition_duration: 30.0,
+ video_transition_unit: "frames".into(),
+ audio_transition_duration: 1.0,
+ audio_transition_unit: "seconds".into(),
+ still_image_duration: 5.0,
+ still_image_unit: "seconds".into(),
+ auto_scroll: "pageScroll".into(),
+ mouse_scrolling: "vertical".into(),
+ mono_media_tracks: "useFile".into(),
+ stereo_media_tracks: "useFile".into(),
+ surround_media_tracks: "useFile".into(),
+ multichannel_mono_media_tracks: "useFile".into(),
+ focus_timeline_on_edit: false,
+ snap_playhead: false,
+ return_to_beginning: true,
+ out_of_sync_unlinked: false,
+ play_after_rendering: true,
+ clip_mismatch_warning: true,
+ match_frame_sets_in: false,
+ restore_open_sequences: true,
+ add_tracks_automatically: true,
+ }
+ }
+}
+
+fn duration_in(value: f64, unit: &str, rate: FrameRate) -> Tick {
+ let d = if unit == "frames" { rate.tick_of(value.max(1.0).round() as i64) } else { rate.snap_nearest(Tick::from_seconds_f64(value.max(0.0))) };
+ d.max(rate.frame_duration())
+}
+
+impl TimelinePrefs {
+ /// "Still Image Default Duration" at a sequence rate (whole frames, at least one).
+ pub fn still_duration(&self, rate: FrameRate) -> Tick {
+ duration_in(self.still_image_duration, &self.still_image_unit, rate)
+ }
+ /// "Video Transition Default Duration".
+ pub fn video_transition_duration(&self, rate: FrameRate) -> Tick {
+ duration_in(self.video_transition_duration, &self.video_transition_unit, rate)
+ }
+ /// "Audio Transition Default Duration".
+ pub fn audio_transition_duration(&self, rate: FrameRate) -> Tick {
+ duration_in(self.audio_transition_duration, &self.audio_transition_unit, rate)
+ }
+}
+
+/// Settings ▸ Plugins.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct PluginPrefs {
+ pub developer_mode: bool,
+}
+
+/// Indeterminate Media Timebase choices → frame rates.
+pub fn timebase_rate(v: &str) -> FrameRate {
+ match v {
+ "23.976" => FrameRate::FPS_23_976,
+ "24" => FrameRate::FPS_24,
+ "25" => FrameRate::FPS_25,
+ "30" => FrameRate::FPS_30,
+ "50" => FrameRate::FPS_50,
+ "59.94" | "59.94df" => FrameRate::FPS_59_94,
+ "60" => FrameRate::FPS_60,
+ _ => FrameRate::FPS_29_97,
+ }
+}
+
+// ------------------------------------------------------------------ schema
+
+/// What kind of control a field is.
+#[derive(Clone, Copy, Debug)]
+pub enum Kind {
+ Bool,
+ /// Whole number with a range and unit.
+ Int {
+ min: f64,
+ max: f64,
+ unit: &'static str,
+ },
+ /// Real number with a range, shown decimals and unit.
+ Float {
+ min: f64,
+ max: f64,
+ decimals: usize,
+ unit: &'static str,
+ },
+ /// One of (value, label).
+ Choice(&'static [(&'static str, &'static str)]),
+ /// A number whose unit is the choice field `unit_key` (`frames` / `seconds`).
+ Duration {
+ unit_key: &'static str,
+ },
+ /// Free text.
+ Text,
+ /// A folder; empty = the default location.
+ Path,
+ /// `#rrggbb`.
+ Color,
+ /// A font family name.
+ Font,
+ /// An audio device chosen from what the host reports.
+ Device(DeviceList),
+ /// One of the 16 labels.
+ Label,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum DeviceList {
+ Hosts,
+ Inputs,
+ Outputs,
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct Field {
+ /// Preference key (`timeline.stillImageDuration`); the control's automation id is
+ /// `settings.<key>`.
+ pub key: &'static str,
+ pub label: &'static str,
+ pub kind: Kind,
+ /// Drawn indented under the previous field.
+ pub indent: bool,
+ /// Only editable while this boolean key is on.
+ pub enabled_by: Option<&'static str>,
+ /// Whether FilmCraft acts on the value (false = remembered for parity, no effect yet).
+ pub wired: bool,
+}
+
+#[derive(Clone, Copy, Debug)]
+pub enum Row {
+ Field(Field),
+ /// A titled group box.
+ Group(&'static str, &'static [Row]),
+ /// Explanatory text.
+ Note(&'static str),
+ /// A button running a command (`settings.<id>` automation id).
+ Button {
+ id: &'static str,
+ label: &'static str,
+ command: &'static str,
+ },
+ /// A page section the frontend draws itself (`labelColors`, `memoryInfo`, `mediaCacheInfo`,
+ /// `outputMapping`).
+ Custom(&'static str),
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct Category {
+ /// Category id: first segment of its keys, `app.settings.<id>` command, `settings.category.<id>`.
+ pub id: &'static str,
+ pub title: &'static str,
+ pub rows: &'static [Row],
+}
+
+const fn f(key: &'static str, label: &'static str, kind: Kind, wired: bool) -> Row {
+ Row::Field(Field { key, label, kind, indent: false, enabled_by: None, wired })
+}
+const fn b(key: &'static str, label: &'static str, wired: bool) -> Row {
+ f(key, label, Kind::Bool, wired)
+}
+const fn sub(key: &'static str, label: &'static str, kind: Kind, by: &'static str, wired: bool) -> Row {
+ Row::Field(Field { key, label, kind, indent: true, enabled_by: Some(by), wired })
+}
+const fn int(min: f64, max: f64, unit: &'static str) -> Kind {
+ Kind::Int { min, max, unit }
+}
+const fn float(min: f64, max: f64, decimals: usize, unit: &'static str) -> Kind {
+ Kind::Float { min, max, decimals, unit }
+}
+
+const STARTUP: &[(&str, &str)] = &[("showHome", "Show Home"), ("openMostRecent", "Open Most Recent"), ("emptyProject", "Start with an Empty Project")];
+const OPENING: &[(&str, &str)] = &[("showOpenDialog", "Show Open Dialog"), ("showHome", "Show Home")];
+const BIN_OPEN: &[(&str, &str)] = &[("openInPlace", "Open in place"), ("openNewTab", "Open new tab"), ("openNewWindow", "Open in new window")];
+const PROJECT_OPEN: &[(&str, &str)] = &[("openNewTab", "Open new tab"), ("openNewWindow", "Open in new window")];
+const THEMES: &[(&str, &str)] = &[("darkest", "Darkest"), ("dark", "Dark"), ("light", "Light")];
+const MIXDOWN: &[(&str, &str)] = &[("front", "Front Only"), ("frontRear", "Front + Rear"), ("frontLfe", "Front + LFE"), ("frontRearLfe", "Front + Rear + LFE")];
+const AUDITION: &[(&str, &str)] = &[("scratch", "Scratch disk location for Captured Audio"), ("nextToMedia", "Next to original media files")];
+const BUFFERS: &[(&str, &str)] = &[("64", "64"), ("128", "128"), ("256", "256"), ("512", "512"), ("1024", "1024"), ("2048", "2048"), ("4096", "4096")];
+const RATES: &[(&str, &str)] = &[("44100", "44100"), ("48000", "48000"), ("88200", "88200"), ("96000", "96000")];
+const HDR_WHITE: &[(&str, &str)] = &[("100", "100 (75% HLG, 58% PQ)"), ("203", "203 (75% HLG, 58% PQ)"), ("300", "300 (75% HLG, 58% PQ)")];
+const DIRECTION: &[(&str, &str)] = &[("ltr", "Left to right"), ("rtl", "Right to left")];
+const JOIN: &[(&str, &str)] = &[("miter", "Miter join"), ("round", "Round join"), ("bevel", "Bevel join")];
+const CAP: &[(&str, &str)] = &[("butt", "Butt cap"), ("round", "Round cap"), ("square", "Projecting cap")];
+const BG_FILL: &[(&str, &str)] = &[("allLines", "All lines"), ("perLine", "Per line")];
+const TIMEBASE: &[(&str, &str)] = &[
+ ("23.976", "23.976 fps"),
+ ("24", "24 fps"),
+ ("25", "25 fps"),
+ ("29.97df", "29.97 fps Drop-Frame"),
+ ("29.97", "29.97 fps Non Drop-Frame"),
+ ("30", "30 fps"),
+ ("50", "50 fps"),
+ ("59.94df", "59.94 fps Drop-Frame"),
+ ("59.94", "59.94 fps Non Drop-Frame"),
+ ("60", "60 fps"),
+];
+const TIMECODE: &[(&str, &str)] = &[("useMediaSource", "Use Media Source"), ("generate", "Generate Timecode")];
+const FRAME_COUNT: &[(&str, &str)] = &[("startAt0", "Start at 0"), ("startAt1", "Start at 1"), ("timecodeConversion", "Timecode Conversion")];
+const SCALING: &[(&str, &str)] = &[("none", "None"), ("scaleToFrameSize", "Scale to frame size"), ("setToFrameSize", "Set to frame size")];
+const ANALYSIS_CACHE: &[(&str, &str)] = &[("mediaCache", "In the Media Cache"), ("project", "In the project")];
+const TRANSCRIBE_SCOPE: &[(&str, &str)] =
+ &[("sequenceClips", "Auto-transcribe only clips in sequences"), ("allImported", "Auto-transcribe all imported clips")];
+const SPEAKERS: &[(&str, &str)] = &[("on", "Label speakers"), ("off", "Don't label speakers")];
+const LANGUAGES: &[(&str, &str)] = &[
+ ("en", "English"),
+ ("es", "Spanish"),
+ ("fr", "French"),
+ ("de", "German"),
+ ("it", "Italian"),
+ ("pt", "Portuguese"),
+ ("nl", "Dutch"),
+ ("ja", "Japanese"),
+ ("ko", "Korean"),
+ ("zh", "Chinese"),
+ ("ru", "Russian"),
+ ("hi", "Hindi"),
+];
+const MODELS: &[(&str, &str)] =
+ &[("whisper-tiny", "Whisper tiny (fastest)"), ("whisper-base", "Whisper base (balanced)"), ("whisper-small", "Whisper small (most accurate)")];
+const CACHE_MGMT: &[(&str, &str)] = &[
+ ("never", "Do not delete cache files automatically"),
+ ("olderThan", "Automatically delete cache files older than"),
+ ("exceedsSize", "Automatically delete oldest cache files when cache exceeds"),
+];
+const AUTO_SCROLL: &[(&str, &str)] = &[("noScroll", "No Scroll"), ("pageScroll", "Page Scroll"), ("smoothScroll", "Smooth Scroll")];
+const MOUSE_SCROLL: &[(&str, &str)] = &[("vertical", "Vertical"), ("horizontal", "Horizontal")];
+const TRACKS: &[(&str, &str)] = &[("useFile", "Use File"), ("mono", "Mono"), ("stereo", "Stereo"), ("5.1", "5.1"), ("adaptive", "Adaptive")];
+pub const DURATION_UNITS: &[(&str, &str)] = &[("frames", "Frames"), ("seconds", "Seconds")];
+
+/// The Settings categories in Premiere's order (Adobe-cloud-only ones are left out; Plugins is a
+/// stub).
+pub fn categories() -> &'static [Category] {
+ CATEGORIES
+}
+
+pub fn category(id: &str) -> Option<&'static Category> {
+ CATEGORIES.iter().find(|c| c.id == id)
+}
+
+static CATEGORIES: &[Category] = &[
+ Category {
+ id: "general",
+ title: "General",
+ rows: &[
+ f("general.atStartup", "At Startup", Kind::Choice(STARTUP), true),
+ f("general.whenOpeningProject", "When Opening a Project", Kind::Choice(OPENING), false),
+ Row::Group(
+ "Bins",
+ &[
+ f("general.binsDoubleClick", "Double-click", Kind::Choice(BIN_OPEN), false),
+ f("general.binsCmdDoubleClick", "+ Cmd", Kind::Choice(BIN_OPEN), false),
+ f("general.binsOptDoubleClick", "+ Opt", Kind::Choice(BIN_OPEN), false),
+ ],
+ ),
+ Row::Group(
+ "Projects",
+ &[
+ f("general.projectsDoubleClick", "Double-click", Kind::Choice(PROJECT_OPEN), false),
+ f("general.projectsOptDoubleClick", "+ Opt", Kind::Choice(PROJECT_OPEN), false),
+ ],
+ ),
+ b("general.showEventIndicator", "Show Event Indicator", false),
+ b("general.showToolTips", "Show Tool Tips", true),
+ sub("general.showRichToolTips", "Show Rich Tool Tips", Kind::Bool, "general.showToolTips", false),
+ b("general.showWorkspaceResetWarning", "Show Workspace Reset Warning dialog on double click", false),
+ b("general.showProjectLoadErrors", "Show Project Load Error Dialog", false),
+ b("general.showCompatibilityIssues", "Show system compatibility issues at startup", false),
+ b("general.showProjectBinInTab", "Show \"Project:\" and \"Bin:\" in Project panel tab", false),
+ b("general.showMaskTrackerPreview", "Show Mask Tracker Preview", false),
+ ],
+ },
+ Category {
+ id: "appearance",
+ title: "Appearance",
+ rows: &[
+ f("appearance.colorTheme", "Color Theme", Kind::Choice(THEMES), true),
+ b("appearance.accessibleContrast", "Accessible color contrast", true),
+ f("appearance.highlightColor", "Highlight Color", Kind::Color, true),
+ ],
+ },
+ Category {
+ id: "audio",
+ title: "Audio",
+ rows: &[
+ f("audio.automatchTime", "Automatch Time", float(0.0, 30.0, 3, "seconds"), true),
+ f("audio.mixdownType", "5.1 Mixdown Type", Kind::Choice(MIXDOWN), false),
+ f("audio.largeVolumeAdjustment", "Large Volume Adjustment", float(0.0, 96.0, 0, "dB"), true),
+ b("audio.sumToMonoInSource", "Sum multichannel outputs to mono in Source Monitor", false),
+ b("audio.scrubAudio", "Play audio while scrubbing in Source and Program Monitors", false),
+ b("audio.maintainPitchShuttling", "Maintain pitch while shuttling", false),
+ b("audio.muteInputDuringRecording", "Mute input during timeline recording", false),
+ b("audio.generateWaveformsOnImport", "Generate waveforms automatically during import", false),
+ b("audio.multithreadedWaveforms", "Generate waveforms and conform audio using multithreading", false),
+ b("audio.renderAudioWithVideo", "Render audio when rendering video", false),
+ b("audio.autoTagAudioTypes", "Auto-tag audio types in the timeline", false),
+ b("audio.alwaysOverrideAudioTags", "Always override audio tags", false),
+ Row::Group(
+ "Automation Keyframe Optimization",
+ &[
+ b("audio.linearKeyframeThinning", "Linear keyframe thinning", true),
+ b("audio.minimumTimeIntervalThinning", "Minimum time interval thinning", true),
+ sub("audio.minimumTimeMs", "Minimum time", int(1.0, 10_000.0, "milliseconds"), "audio.minimumTimeIntervalThinning", true),
+ ],
+ ),
+ Row::Group("Render Edit in Audition files to:", &[f("audio.editInAuditionLocation", "Location", Kind::Choice(AUDITION), false)]),
+ ],
+ },
+ Category {
+ id: "audioHardware",
+ title: "Audio Hardware",
+ rows: &[
+ f("audioHardware.deviceClass", "Device Class", Kind::Device(DeviceList::Hosts), true),
+ f("audioHardware.defaultInput", "Default Input", Kind::Device(DeviceList::Inputs), false),
+ f("audioHardware.defaultOutput", "Default Output", Kind::Device(DeviceList::Outputs), true),
+ f("audioHardware.bufferSize", "I/O Buffer Size", Kind::Choice(BUFFERS), true),
+ f("audioHardware.sampleRate", "Sample Rate", Kind::Choice(RATES), true),
+ b("audioHardware.forceDocumentRate", "Attempt to force hardware to document sample rate", true),
+ Row::Group(
+ "Output Mapping",
+ &[
+ f("audioHardware.mapLeft", "Left channel to device output", int(0.0, 63.0, ""), true),
+ f("audioHardware.mapRight", "Right channel to device output", int(0.0, 63.0, ""), true),
+ Row::Custom("outputMapping"),
+ ],
+ ),
+ ],
+ },
+ Category {
+ id: "autoSave",
+ title: "Auto Save",
+ rows: &[
+ Row::Group(
+ "Local Projects",
+ &[
+ b("autoSave.enabled", "Automatically save projects", true),
+ sub("autoSave.intervalMinutes", "Automatically Save Every", int(1.0, 1440.0, "minute(s)"), "autoSave.enabled", true),
+ sub("autoSave.maxVersions", "Maximum Project Versions", int(1.0, 1000.0, ""), "autoSave.enabled", true),
+ sub("autoSave.saveCurrentProject", "Auto Save also saves the current project(s)", Kind::Bool, "autoSave.enabled", true),
+ ],
+ ),
+ Row::Group(
+ "Crash Recovery",
+ &[
+ b("autoSave.recoveryJournal", "Keep a recovery copy of unsaved changes", true),
+ sub("autoSave.recoveryIntervalSeconds", "Update it at least every", int(1.0, 600.0, "second(s)"), "autoSave.recoveryJournal", true),
+ Row::Note(
+ "Changes are copied in the background a moment after each edit. If FilmCraft quits unexpectedly, they are offered the next time it starts.",
+ ),
+ Row::Custom("autoSaveStatus"),
+ ],
+ ),
+ ],
+ },
+ Category {
+ id: "color",
+ title: "Color",
+ rows: &[
+ Row::Group(
+ "Display Color Settings",
+ &[
+ b("color.displayColorManagement", "Display Color Management", false),
+ b("color.extendedDynamicRange", "Extended Dynamic Range Monitoring", false),
+ f("color.hdrGraphicsWhite", "HDR Graphics White (Nits)", Kind::Choice(HDR_WHITE), false),
+ ],
+ ),
+ Row::Note("For color management parameters, go to the Settings tab in the Lumetri Color panel."),
+ ],
+ },
+ Category {
+ id: "graphics",
+ title: "Graphics",
+ rows: &[
+ Row::Group(
+ "Text",
+ &[
+ b("graphics.ligatures", "Ligatures", true),
+ b("graphics.hindiDigits", "Hindi digits", false),
+ b("graphics.smartQuotes", "Smart quotes", true),
+ f("graphics.paragraphDirection", "Default paragraph direction", Kind::Choice(DIRECTION), false),
+ f("graphics.textLineJoin", "Stroke line join", Kind::Choice(JOIN), false),
+ f("graphics.textMiterLimit", "Miter limit", float(1.0, 100.0, 1, ""), false),
+ f("graphics.textLineCap", "Stroke line cap", Kind::Choice(CAP), false),
+ f("graphics.backgroundFill", "Background fill", Kind::Choice(BG_FILL), false),
+ f("graphics.defaultFont", "Default subtitle and text font", Kind::Font, true),
+ f("graphics.missingFontReplacement", "Missing font replacement", Kind::Font, false),
+ f("graphics.emojiFont", "Default Emoji font", Kind::Font, false),
+ ],
+ ),
+ Row::Group(
+ "Shapes",
+ &[
+ f("graphics.shapeLineJoin", "Stroke line join", Kind::Choice(JOIN), false),
+ f("graphics.shapeMiterLimit", "Miter limit", float(1.0, 100.0, 1, ""), false),
+ f("graphics.shapeLineCap", "Stroke line cap", Kind::Choice(CAP), false),
+ ],
+ ),
+ Row::Group(
+ "Closed Captions",
+ &[
+ f("graphics.captionFont", "Default closed caption font", Kind::Font, false),
+ b("graphics.captionMonospaceOnly", "Monospace only", false),
+ b("graphics.cea708Wide", "Always import embedded CEA-708 closed captions with wide aspect.", false),
+ ],
+ ),
+ ],
+ },
+ Category {
+ id: "labels",
+ title: "Labels",
+ rows: &[
+ Row::Custom("labelColors"),
+ Row::Group(
+ "Label Defaults",
+ &[
+ f("labels.defaults.movie", "Movie (audio and video)", Kind::Label, true),
+ f("labels.defaults.video", "Video", Kind::Label, true),
+ f("labels.defaults.audio", "Audio", Kind::Label, true),
+ f("labels.defaults.still", "Still", Kind::Label, true),
+ f("labels.defaults.sequence", "Sequence", Kind::Label, true),
+ f("labels.defaults.dynamicLink", "Dynamic Link", Kind::Label, false),
+ f("labels.defaults.bin", "Bin", Kind::Label, false),
+ f("labels.defaults.captions", "Captions", Kind::Label, false),
+ ],
+ ),
+ ],
+ },
+ Category {
+ id: "media",
+ title: "Media",
+ rows: &[
+ f("media.indeterminateTimebase", "Indeterminate Media Timebase", Kind::Choice(TIMEBASE), true),
+ f("media.timecode", "Timecode", Kind::Choice(TIMECODE), false),
+ f("media.frameCount", "Frame Count", Kind::Choice(FRAME_COUNT), false),
+ f("media.defaultMediaScaling", "Default Media Scaling", Kind::Choice(SCALING), true),
+ b("media.writeXmpId", "Write XMP ID to files on import", false),
+ b("media.validateContentCredentials", "Validate Content Credentials on import", false),
+ b("media.writeClipMarkersToXmp", "Write clip markers to XMP", false),
+ b("media.enableXmpLinking", "Enable clip and XMP metadata linking", false),
+ b("media.includeCaptionsOnImport", "Include captions on import", false),
+ b("media.enableProxies", "Enable proxies", true),
+ b("media.allowDuplicateMedia", "Allow duplicate media during project import", false),
+ b("media.createFolderForImportedProjects", "Create folder for imported projects", false),
+ b("media.autoHideDependentClips", "Automatically Hide Dependent Clips", false),
+ b("media.importImageSequences", "Import numbered stills as image sequences", false),
+ Row::Group(
+ "Growing Files",
+ &[
+ b("media.refreshGrowingFiles", "Automatically refresh growing files", false),
+ b("media.resumeGrowingPlayback", "Automatically resume playback for growing files in Source Monitor", false),
+ sub("media.growingRefreshSeconds", "Refresh growing Files Every", int(1.0, 3600.0, "seconds"), "media.refreshGrowingFiles", false),
+ ],
+ ),
+ b("media.hardwareDecoding", "Enable hardware accelerated decoding (requires restart)", false),
+ b("media.proresHardwareEncoding", "Enable ProRes hardware accelerated encoding, if available", false),
+ ],
+ },
+ Category {
+ id: "mediaAnalysis",
+ title: "Media Analysis & Transcription",
+ rows: &[
+ f("mediaAnalysis.cacheResults", "Cache analysis results for re-use", Kind::Choice(ANALYSIS_CACHE), false),
+ Row::Note(
+ "Media analysis and transcriptions will be cached in the Media Cache folder. Reanalysis won't be required if the media is imported into another project on this computer.",
+ ),
+ Row::Group("Media Analysis", &[b("mediaAnalysis.analyzeImportedMedia", "Analyze all imported media to search for visuals or audio", false)]),
+ Row::Group(
+ "Transcription",
+ &[
+ b("mediaAnalysis.autoTranscribe", "Automatically transcribe clips", true),
+ sub("mediaAnalysis.autoTranscribeScope", "Transcription preferences", Kind::Choice(TRANSCRIBE_SCOPE), "mediaAnalysis.autoTranscribe", true),
+ f("mediaAnalysis.speakerLabeling", "Speaker Labeling", Kind::Choice(SPEAKERS), true),
+ b("mediaAnalysis.languageAutoDetect", "Enable language auto-detection", true),
+ f("mediaAnalysis.defaultLanguage", "Default language", Kind::Choice(LANGUAGES), true),
+ f("mediaAnalysis.whisperModel", "Speech model", Kind::Choice(MODELS), true),
+ ],
+ ),
+ ],
+ },
+ Category {
+ id: "mediaCache",
+ title: "Media Cache",
+ rows: &[
+ Row::Group(
+ "Media Cache Files",
+ &[
+ f("mediaCache.location", "Location", Kind::Path, true),
+ b("mediaCache.saveNextToMedia", "Save .cfa and .pek media cache files next to original media files when possible", false),
+ Row::Button { id: "mediaCache.clean", label: "Delete…", command: "mediaCache.clean" },
+ Row::Custom("mediaCacheInfo"),
+ ],
+ ),
+ Row::Group("Media Cache Database", &[f("mediaCache.databaseLocation", "Location", Kind::Path, false)]),
+ Row::Group(
+ "Media Cache Management",
+ &[
+ f("mediaCache.management", "Policy", Kind::Choice(CACHE_MGMT), true),
+ f("mediaCache.olderThanDays", "Delete files older than", int(1.0, 3650.0, "days"), true),
+ f("mediaCache.maxSizeGb", "Delete oldest files when the cache exceeds", int(1.0, 100_000.0, "GB"), true),
+ ],
+ ),
+ Row::Note(
+ "The media cache holds render previews of unsaved projects and other files FilmCraft can recreate. Deleting them is always safe; FilmCraft rebuilds them as needed.",
+ ),
+ ],
+ },
+ Category {
+ id: "memory",
+ title: "Memory",
+ rows: &[
+ Row::Custom("memoryInfo"),
+ f("memory.ramReservedGb", "RAM reserved for other applications", int(1.0, 1024.0, "GB"), false),
+ f("memory.frameCacheMb", "Frame cache for monitors and thumbnails", int(64.0, 65_536.0, "MB"), true),
+ ],
+ },
+ Category {
+ id: "playback",
+ title: "Playback",
+ rows: &[
+ f("playback.prerollSeconds", "Preroll", float(0.0, 60.0, 0, "seconds"), true),
+ f("playback.postrollSeconds", "Postroll", float(0.0, 60.0, 0, "seconds"), true),
+ f("playback.stepManyFrames", "Step forward/back many", int(1.0, 1000.0, "frames"), true),
+ b("playback.pauseEncoderQueue", "Pause Media Encoder queue during playback", false),
+ b("playback.enableTransmit", "Enable Mercury Transmit", false),
+ b("playback.disableVideoInBackground", "Disable video output when in the background", false),
+ ],
+ },
+ Category {
+ id: "plugins",
+ title: "Plugins",
+ rows: &[
+ Row::Group("Plugins", &[b("plugins.developerMode", "Enable developer mode", false)]),
+ Row::Note("No plugins are installed. Changes will take effect the next time you start FilmCraft."),
+ ],
+ },
+ Category {
+ id: "timeline",
+ title: "Timeline",
+ rows: &[
+ f("timeline.videoTransitionDuration", "Video Transition Default Duration", Kind::Duration { unit_key: "timeline.videoTransitionUnit" }, true),
+ f("timeline.audioTransitionDuration", "Audio Transition Default Duration", Kind::Duration { unit_key: "timeline.audioTransitionUnit" }, true),
+ f("timeline.stillImageDuration", "Still Image Default Duration", Kind::Duration { unit_key: "timeline.stillImageUnit" }, true),
+ f("timeline.autoScroll", "Timeline Playback Auto-Scrolling", Kind::Choice(AUTO_SCROLL), true),
+ f("timeline.mouseScrolling", "Timeline Mouse Scrolling", Kind::Choice(MOUSE_SCROLL), false),
+ Row::Group(
+ "Default Audio Tracks",
+ &[
+ f("timeline.monoMediaTracks", "Mono Media", Kind::Choice(TRACKS), false),
+ f("timeline.stereoMediaTracks", "Stereo Media", Kind::Choice(TRACKS), false),
+ f("timeline.surroundMediaTracks", "5.1 Media", Kind::Choice(TRACKS), false),
+ f("timeline.multichannelMonoMediaTracks", "Multichannel Mono Media", Kind::Choice(TRACKS), false),
+ ],
+ ),
+ b("timeline.focusTimelineOnEdit", "Set focus on the Timeline when performing Insert/Overwrite edits", true),
+ b("timeline.snapPlayhead", "Snap playhead in Timeline when Snap is enabled", true),
+ b("timeline.returnToBeginning", "At playback end, return to beginning when restarting playback", true),
+ b("timeline.outOfSyncUnlinked", "Display out of sync indicators for unlinked clips", false),
+ b("timeline.playAfterRendering", "Play after rendering previews", true),
+ b("timeline.clipMismatchWarning", "Show Clip Mismatch Warning dialog", false),
+ b("timeline.matchFrameSetsIn", "Match frame sets in point", false),
+ b("timeline.restoreOpenSequences", "Restore open sequences when opening projects", false),
+ b("timeline.addTracksAutomatically", "Add tracks automatically when editing source clips onto the Timeline", false),
+ ],
+ },
+ Category {
+ id: "trim",
+ title: "Trim",
+ rows: &[
+ f("trim.largeTrimOffset", "Large Trim Offset", int(1.0, 1000.0, "frames"), true),
+ f("trim.largeTrimOffsetAudio", "", int(1.0, 100_000.0, "Audio Time Units"), false),
+ b("trim.selectionToolRollRipple", "Allow Selection tool to choose Roll and Ripple trims without modifier key", true),
+ b("trim.toolChangesTrimType", "Allow current tool to change trim type of previously selected edit point", false),
+ b("trim.shiftOverlappingClips", "Shift clips that overlap trim point during ripple trimming", false),
+ sub("trim.rippleAddsEdits", "Ripple trim adds edits to keep both sides of trim in sync", Kind::Bool, "trim.shiftOverlappingClips", false),
+ b("trim.playheadDeterminesLoop", "Playhead position determines trim monitor loop playback", true),
+ b("trim.dynamicRippleUpdates", "Update timeline dynamically during ripple edits.", false),
+ ],
+ },
+];
+
+/// Every field of every category (groups flattened), in dialog order.
+pub fn fields() -> Vec<(&'static str, Field)> {
+ fn walk(cat: &'static str, rows: &'static [Row], out: &mut Vec<(&'static str, Field)>) {
+ for r in rows {
+ match r {
+ Row::Field(f) => out.push((cat, *f)),
+ Row::Group(_, inner) => walk(cat, inner, out),
+ _ => {}
+ }
+ }
+ }
+ let mut out = Vec::new();
+ for c in CATEGORIES {
+ walk(c.id, c.rows, &mut out);
+ }
+ out
+}
+
+pub fn field(key: &str) -> Option<Field> {
+ fields().into_iter().map(|(_, f)| f).find(|f| f.key == key)
+}
+
+/// Check a value for `key` against the schema (choices, colours). Ranges are clamped later.
+pub fn validate(key: &str, v: &Value) -> std::result::Result<(), String> {
+ let kind = match field(key) {
+ Some(f) => f.kind,
+ None if is_unit_key(key) => Kind::Choice(DURATION_UNITS),
+ None if key.starts_with("labels.colors.") && key.ends_with(".color") => Kind::Color,
+ None => return Ok(()),
+ };
+ match kind {
+ Kind::Choice(opts) => {
+ let s = match v {
+ Value::String(s) => s.clone(),
+ Value::Number(n) => n.to_string(),
+ _ => return Err(format!("`{key}` must be one of {}", opts.iter().map(|o| o.0).collect::<Vec<_>>().join(", "))),
+ };
+ if opts.iter().any(|o| o.0 == s) {
+ Ok(())
+ } else {
+ Err(format!("`{key}` must be one of {}", opts.iter().map(|o| o.0).collect::<Vec<_>>().join(", ")))
+ }
+ }
+ Kind::Color if v.as_str().and_then(parse_hex).is_none() => Err(format!("`{key}` must be a colour like \"#2f6bdf\"")),
+ _ => Ok(()),
+ }
+}
+
+/// Whether `key` is the unit (`frames` / `seconds`) of a duration field.
+pub fn is_unit_key(key: &str) -> bool {
+ fields().iter().any(|(_, f)| matches!(f.kind, Kind::Duration { unit_key } if unit_key == key))
+}
+
+/// Repair a preferences value in place against the schema: unknown choices and bad colours go back
+/// to their defaults, numbers are clamped to their ranges.
+pub fn sanitize(v: &mut Value, defaults: &Value) {
+ for (_, f) in fields() {
+ if let Kind::Duration { unit_key } = f.kind {
+ let ptr = format!("/{}", unit_key.replace('.', "/"));
+ let def = defaults.pointer(&ptr).cloned().unwrap_or(json!("seconds"));
+ if let Some(slot) = v.pointer_mut(&ptr)
+ && validate(unit_key, slot).is_err()
+ {
+ *slot = def;
+ }
+ }
+ }
+ for (_, f) in fields() {
+ let path: Vec<&str> = f.key.split('.').collect();
+ let Some(slot) = path.iter().try_fold(&mut *v, |v, k| v.get_mut(*k)) else { continue };
+ let def = path.iter().try_fold(defaults, |v, k| v.get(*k)).cloned().unwrap_or(Value::Null);
+ match f.kind {
+ Kind::Choice(_) | Kind::Color => {
+ if validate(f.key, slot).is_err() {
+ *slot = def;
+ }
+ }
+ Kind::Int { min, max, .. } => match slot.as_f64().filter(|x| x.is_finite()) {
+ Some(x) => *slot = json!(x.round().clamp(min, max) as u64),
+ None => *slot = def,
+ },
+ Kind::Float { min, max, .. } => match slot.as_f64().filter(|x| x.is_finite()) {
+ Some(x) => *slot = json!(x.clamp(min, max)),
+ None => *slot = def,
+ },
+ Kind::Duration { unit_key } => {
+ let ptr = format!("/{}", unit_key.replace('.', "/"));
+ let unit = v.pointer(&ptr).or(defaults.pointer(&ptr)).and_then(Value::as_str).unwrap_or("seconds").to_string();
+ let Some(slot) = path.iter().try_fold(&mut *v, |v, k| v.get_mut(*k)) else { continue };
+ let max = if unit == "frames" { 100_000.0 } else { 3600.0 };
+ let min = if unit == "frames" { 1.0 } else { 0.01 };
+ match slot.as_f64().filter(|x| x.is_finite()) {
+ Some(x) if unit == "frames" => *slot = json!(x.round().clamp(min, max)),
+ Some(x) => *slot = json!(x.clamp(min, max)),
+ None => *slot = def,
+ }
+ }
+ _ => {}
+ }
+ }
+}
+
+/// Upgrade an older preferences file (`version` missing = v1) to [`PREFS_VERSION`].
+pub fn migrate(v: &mut Value) {
+ let Some(m) = v.as_object_mut() else { return };
+ let ver = m.get("version").and_then(Value::as_u64).unwrap_or(1);
+ if ver < 2 {
+ // v1 kept the Trim Monitor's loop choice and pre/postroll; v2 adds every other category
+ // (filled in from defaults by serde). The v1 "Auto Save" dialog wrote integer seconds for
+ // pre/postroll; v2 stores them as reals, which serde reads either way.
+ m.insert("version".into(), json!(2));
+ }
+}
+
+impl crate::autosave::Preferences {
+ /// Values of one category as a JSON object.
+ pub fn category_value(&self, id: &str) -> Option<Value> {
+ self.to_value().get(id).cloned()
+ }
+ /// Reset one category to its defaults (`recentProjects` survives a General reset).
+ pub fn reset_category(&mut self, id: &str) -> std::result::Result<(), String> {
+ if category(id).is_none() {
+ return Err(format!("unknown settings category `{id}`"));
+ }
+ let mut v = self.to_value();
+ let d = Self::default().to_value();
+ let keep = self.general.recent_projects.clone();
+ v[id] = d[id].clone();
+ *self = serde_json::from_value(v).map_err(|e| e.to_string())?;
+ self.general.recent_projects = keep;
+ Ok(())
+ }
+ /// Remember a project as the most recent one.
+ pub fn note_recent(&mut self, path: &str) {
+ let r = &mut self.general.recent_projects;
+ r.retain(|p| p != path);
+ r.insert(0, path.to_string());
+ r.truncate(10);
+ }
+}
+
+// ------------------------------------------------------------------ helpers used by the engine
+
+/// Typographer's quotes: `"a 'b'"` → `“a ‘b’”`, apostrophes inside words → `’`.
+pub fn smart_quotes(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ let mut prev: Option<char> = None;
+ for c in s.chars() {
+ let opening = prev.is_none_or(|p| p.is_whitespace() || "([{-–—“‘".contains(p));
+ out.push(match c {
+ '"' if opening => '“',
+ '"' => '”',
+ '\'' if opening => '‘',
+ '\'' => '’',
+ c => c,
+ });
+ prev = Some(c);
+ }
+ out
+}
+
+/// Interleave a stereo mix into a device buffer of `ch` channels following Output Mapping: left
+/// to device channel `map[0]`, right to `map[1]` (others silent). A mono device gets the sum.
+/// Out-of-range mappings fall back to channels 0/1.
+pub fn map_output(left: &[f32], right: &[f32], out: &mut [f32], ch: usize, map: [u32; 2]) {
+ let ch = ch.max(1);
+ let n = (out.len() / ch).min(left.len()).min(right.len());
+ out.iter_mut().for_each(|s| *s = 0.0);
+ if ch == 1 {
+ for i in 0..n {
+ out[i] = (0.5 * (left[i] + right[i])).clamp(-1.0, 1.0);
+ }
+ return;
+ }
+ let pick = |m: u32, d: usize| if (m as usize) < ch { m as usize } else { d };
+ let (l, r) = (pick(map[0], 0), pick(map[1], 1));
+ for i in 0..n {
+ out[i * ch + l] += left[i];
+ out[i * ch + r] += right[i];
+ out[i * ch + l] = out[i * ch + l].clamp(-1.0, 1.0);
+ out[i * ch + r] = out[i * ch + r].clamp(-1.0, 1.0);
+ }
+}
+
+/// Settings ▸ Media ▸ Default Media Scaling for a clip of `src` size placed in a `frame`-sized
+/// sequence: `scaleToFrameSize` turns on Scale to Frame Size (rasterised at frame size),
+/// `setToFrameSize` sets Motion ▸ Scale so the picture fits the frame.
+pub fn apply_media_scaling(ti: &mut filmcraft_project::TrackItem, scaling: &str, frame: (u32, u32), src: (u32, u32)) {
+ if src.0 == 0 || src.1 == 0 {
+ return;
+ }
+ match scaling {
+ "scaleToFrameSize" => ti.scale_to_frame = true,
+ "setToFrameSize" => {
+ let fit = (frame.0 as f64 / src.0 as f64).min(frame.1 as f64 / src.1 as f64);
+ if let Some(m) = ti.effects.iter_mut().find(|e| e.effect == "motion") {
+ m.params.insert("scale".into(), filmcraft_project::Param::new(filmcraft_project::ParamValue::Float((fit * 1000.0).round() / 10.0)));
+ }
+ }
+ _ => {}
+ }
+}
+
+// ------------------------------------------------------------------ media cache
+
+/// The media cache folder: the configured location, else `<data dir>/Media Cache`.
+pub fn media_cache_dir(prefs: &MediaCachePrefs, data_dir: Option<&Path>) -> Option<PathBuf> {
+ if !prefs.location.trim().is_empty() {
+ return Some(PathBuf::from(prefs.location.trim()));
+ }
+ data_dir.map(|d| d.join("Media Cache"))
+}
+
+/// Where unsaved projects keep their render previews inside the media cache.
+pub fn previews_root(cache: &Path) -> PathBuf {
+ cache.join("Previews")
+}
+
+/// Files under `dir` (recursively): (path, bytes, modified).
+fn cache_files(dir: &Path) -> Vec<(PathBuf, u64, std::time::SystemTime)> {
+ let mut out = Vec::new();
+ let mut stack = vec![dir.to_path_buf()];
+ while let Some(d) = stack.pop() {
+ let Ok(rd) = std::fs::read_dir(&d) else { continue };
+ for e in rd.flatten() {
+ let Ok(md) = e.metadata() else { continue };
+ if md.is_dir() {
+ stack.push(e.path());
+ } else {
+ out.push((e.path(), md.len(), md.modified().unwrap_or(std::time::UNIX_EPOCH)));
+ }
+ }
+ }
+ out
+}
+
+/// Size and file count of the media cache.
+pub fn cache_usage(dir: &Path) -> (u64, usize) {
+ let f = cache_files(dir);
+ (f.iter().map(|x| x.1).sum(), f.len())
+}
+
+/// Remove files under `dir`, skipping anything inside `keep`; returns (files, bytes) removed.
+fn remove_files(files: &[(PathBuf, u64, std::time::SystemTime)], keep: Option<&Path>) -> (usize, u64) {
+ let mut n = (0usize, 0u64);
+ for (p, len, _) in files {
+ if keep.is_some_and(|k| p.starts_with(k)) {
+ continue;
+ }
+ if std::fs::remove_file(p).is_ok() {
+ n.0 += 1;
+ n.1 += len;
+ }
+ }
+ n
+}
+
+fn prune_empty_dirs(dir: &Path, keep: Option<&Path>) {
+ let Ok(rd) = std::fs::read_dir(dir) else { return };
+ for e in rd.flatten() {
+ let p = e.path();
+ if p.is_dir() && keep.is_none_or(|k| !k.starts_with(&p)) {
+ prune_empty_dirs(&p, keep);
+ let _ = std::fs::remove_dir(&p);
+ } else if p.is_dir() {
+ prune_empty_dirs(&p, keep);
+ }
+ }
+}
+
+/// Media Cache Management: apply the automatic deletion policy to `dir` at `now`, never touching
+/// `keep` (the open project's files). Returns (files, bytes) removed.
+pub fn enforce_policy(dir: &Path, prefs: &MediaCachePrefs, keep: Option<&Path>, now: std::time::SystemTime) -> (usize, u64) {
+ let mut files = cache_files(dir);
+ let removed = match prefs.management.as_str() {
+ "olderThan" => {
+ let max_age = std::time::Duration::from_secs(prefs.older_than_days as u64 * 86_400);
+ let old: Vec<_> = files.into_iter().filter(|f| now.duration_since(f.2).is_ok_and(|a| a > max_age)).collect();
+ remove_files(&old, keep)
+ }
+ "exceedsSize" => {
+ let limit = prefs.max_size_gb as u64 * 1_000_000_000;
+ let mut total: u64 = files.iter().map(|f| f.1).sum();
+ files.sort_by_key(|f| f.2);
+ let mut doomed = Vec::new();
+ for f in files {
+ if total <= limit {
+ break;
+ }
+ if keep.is_some_and(|k| f.0.starts_with(k)) {
+ continue;
+ }
+ total -= f.1;
+ doomed.push(f);
+ }
+ remove_files(&doomed, keep)
+ }
+ _ => (0, 0),
+ };
+ prune_empty_dirs(dir, keep);
+ removed
+}
+
+/// Delete everything in the media cache except `keep` ("Delete…" ▸ unused files).
+pub fn clean(dir: &Path, keep: Option<&Path>) -> (usize, u64) {
+ let files = cache_files(dir);
+ let r = remove_files(&files, keep);
+ prune_empty_dirs(dir, keep);
+ r
+}
+
+impl Session {
+ /// The media cache folder (None without a data directory, e.g. tests and the web).
+ pub fn media_cache_dir(&self) -> Option<PathBuf> {
+ if cfg!(target_arch = "wasm32") {
+ return None;
+ }
+ media_cache_dir(&self.prefs.media_cache, self.prefs_path.as_deref().and_then(Path::parent))
+ }
+
+ /// Point unsaved projects' render previews into the media cache and apply the automatic
+ /// deletion policy (on startup and when the Media Cache settings change).
+ pub fn apply_media_cache(&mut self) {
+ let Some(dir) = self.media_cache_dir() else { return };
+ let root = previews_root(&dir);
+ if self.previews.temp_root() != Some(root.clone()) {
+ self.previews.set_temp_root(Some(root));
+ if self.path.is_none() && self.previews.count() == 0 {
+ self.previews.reset_temp();
+ }
+ }
+ let keep = self.previews.dir();
+ enforce_policy(&dir, &self.prefs.media_cache, keep.as_deref(), std::time::SystemTime::now());
+ }
+
+ /// Note a project file as the most recent one (General ▸ At Startup ▸ Open Most Recent).
+ pub fn note_recent_project(&mut self) {
+ let Some(p) = self.path.clone() else { return };
+ if self.prefs.general.recent_projects.first() == Some(&p) {
+ return;
+ }
+ let mut next = self.prefs.clone();
+ next.note_recent(&p);
+ let _ = self.set_prefs(next);
+ }
+}
+
+// ------------------------------------------------------------------ commands
+
+fn spec(id: &'static str, label: &'static str, params: &'static str, run: fn(&mut Session, &Value) -> Result<Value>, journal: bool) -> CommandSpec {
+ CommandSpec { id, label, menu: &[], shortcut: None, params, enabled: always, run, journal }
+}
+
+fn kind_json(k: Kind) -> Value {
+ match k {
+ Kind::Bool => json!({"type": "bool"}),
+ Kind::Int { min, max, unit } => json!({"type": "int", "min": min, "max": max, "unit": unit}),
+ Kind::Float { min, max, decimals, unit } => json!({"type": "float", "min": min, "max": max, "decimals": decimals, "unit": unit}),
+ Kind::Choice(o) => json!({"type": "choice", "choices": o.iter().map(|(v, l)| json!({"value": v, "label": l})).collect::<Vec<_>>()}),
+ Kind::Duration { unit_key } => json!({"type": "duration", "unitKey": unit_key}),
+ Kind::Text => json!({"type": "text"}),
+ Kind::Path => json!({"type": "path"}),
+ Kind::Color => json!({"type": "color"}),
+ Kind::Font => json!({"type": "font"}),
+ Kind::Device(d) => json!({"type": "device", "list": format!("{d:?}").to_ascii_lowercase()}),
+ Kind::Label => json!({"type": "label", "choices": Label::ALL.iter().map(|l| l.name()).collect::<Vec<_>>()}),
+ }
+}
+
+fn schema(s: &mut Session, p: &Value) -> Result<Value> {
+ let want = str_p(p, "category");
+ let cats: Vec<Value> = CATEGORIES
+ .iter()
+ .filter(|c| want.is_none_or(|w| w == c.id))
+ .map(|c| {
+ let fields: Vec<Value> = fields()
+ .into_iter()
+ .filter(|(cat, _)| *cat == c.id)
+ .map(|(_, f)| {
+ json!({"key": f.key, "label": f.label, "kind": kind_json(f.kind), "wired": f.wired, "enabledBy": f.enabled_by, "value": s.prefs.get(f.key)})
+ })
+ .collect();
+ json!({"id": c.id, "title": c.title, "command": format!("app.settings.{}", c.id), "fields": fields})
+ })
+ .collect();
+ if let Some(w) = want
+ && cats.is_empty()
+ {
+ return Err(bad("prefs.schema", format!("unknown category `{w}`")));
+ }
+ Ok(json!({"categories": cats}))
+}
+
+fn cache_info(s: &mut Session, _: &Value) -> Result<Value> {
+ let dir = s.media_cache_dir();
+ let (bytes, files) = dir.as_deref().map(cache_usage).unwrap_or((0, 0));
+ Ok(json!({"location": dir.map(|d| d.to_string_lossy().into_owned()), "bytes": bytes, "files": files, "policy": s.prefs.media_cache.management}))
+}
+
+fn cache_clean(s: &mut Session, p: &Value) -> Result<Value> {
+ let dir = s.media_cache_dir().ok_or_else(|| EngineError::Other("there is no media cache folder in this session".into()))?;
+ // the open project's previews stay unless `all` is set
+ let keep = if bool_p(p, "all") == Some(true) { None } else { s.previews.dir() };
+ let (files, bytes) = clean(&dir, keep.as_deref());
+ if keep.is_none() {
+ s.previews.set_dir(s.previews.dir());
+ }
+ Ok(json!({"files": files, "bytes": bytes, "location": dir.to_string_lossy()}))
+}
+
+pub fn commands() -> Vec<CommandSpec> {
+ vec![
+ spec("prefs.schema", "Settings Schema", r#"{"category":str?}"#, schema, false),
+ spec("mediaCache.info", "Media Cache Info", "{}", cache_info, false),
+ spec("mediaCache.clean", "Delete Media Cache Files", r#"{"all":bool?}"#, cache_clean, true),
+ ]
+}
diff --git a/crates/engine/src/settings_tests.rs b/crates/engine/src/settings_tests.rs
new file mode 100644
index 000000000..390622aea
--- /dev/null
+++ b/crates/engine/src/settings_tests.rs
@@ -0,0 +1,482 @@
+//! Settings: schema, persistence, defaults, migration, validation, and every engine-side behaviour
+//! the settings drive.
+
+use std::path::Path;
+
+use filmcraft_project::{ItemId, ItemKind, Label, ParamValue};
+use filmcraft_time::{FrameRate, Tick};
+use serde_json::{Value, json};
+
+use crate::Session;
+use crate::autosave::Preferences;
+use crate::media_test_util::tmp_dir;
+use crate::settings::{self, Kind};
+
+fn demo() -> Session {
+ let mut s = Session::default();
+ s.execute("file.openDemoProject", json!({})).unwrap();
+ s
+}
+
+fn set(s: &mut Session, key: &str, value: Value) {
+ s.execute("prefs.set", json!({"key": key, "value": value})).unwrap_or_else(|e| panic!("{key}: {e}"));
+}
+
+fn write_png(path: &Path, w: u32, h: u32) {
+ image::RgbaImage::from_pixel(w, h, image::Rgba([200, 40, 40, 255])).save(path).unwrap();
+}
+
+/// Import a `w`×`h` PNG; returns its item.
+fn import_png(s: &mut Session, dir: &Path, name: &str, w: u32, h: u32) -> ItemId {
+ let p = dir.join(name);
+ write_png(&p, w, h);
+ let r = s.execute("file.import", json!({"paths": [p.to_string_lossy()]})).unwrap();
+ ItemId(r["items"][0].as_u64().unwrap_or_else(|| panic!("{r}")))
+}
+
+#[test]
+fn categories_follow_premiere_order() {
+ let ids: Vec<&str> = settings::categories().iter().map(|c| c.id).collect();
+ assert_eq!(
+ ids,
+ [
+ "general",
+ "appearance",
+ "audio",
+ "audioHardware",
+ "autoSave",
+ "color",
+ "graphics",
+ "labels",
+ "media",
+ "mediaAnalysis",
+ "mediaCache",
+ "memory",
+ "playback",
+ "plugins",
+ "timeline",
+ "trim"
+ ]
+ );
+}
+
+#[test]
+fn every_schema_key_exists_with_a_valid_default() {
+ let p = Preferences::default();
+ let keys = p.keys();
+ let fields = settings::fields();
+ assert!(fields.len() > 140, "{} fields", fields.len());
+ let mut seen = std::collections::HashSet::new();
+ for (cat, f) in fields {
+ assert!(seen.insert(f.key), "duplicate {}", f.key);
+ assert!(f.key.starts_with(&format!("{cat}.")), "{} is not under {cat}", f.key);
+ let v = p.get(f.key).unwrap_or_else(|| panic!("no preference {}", f.key));
+ assert!(keys.iter().any(|k| k == f.key), "{} not a leaf key", f.key);
+ settings::validate(f.key, &v).unwrap_or_else(|e| panic!("default of {}: {e}", f.key));
+ match f.kind {
+ Kind::Bool => assert!(v.is_boolean(), "{}", f.key),
+ Kind::Int { .. } | Kind::Float { .. } => assert!(v.is_number(), "{}", f.key),
+ Kind::Duration { unit_key } => assert!(v.is_number() && p.get(unit_key).is_some(), "{}", f.key),
+ _ => {}
+ }
+ if let Some(by) = f.enabled_by {
+ assert!(p.get(by).is_some_and(|v| v.is_boolean()), "{} enabled by {by}", f.key);
+ }
+ }
+ // Premiere's factory defaults
+ assert_eq!(p.get("timeline.videoTransitionDuration"), Some(json!(30.0)));
+ assert_eq!(p.get("timeline.videoTransitionUnit"), Some(json!("frames")));
+ assert_eq!(p.get("timeline.stillImageDuration"), Some(json!(5.0)));
+ assert_eq!(p.get("playback.stepManyFrames"), Some(json!(5)));
+ assert_eq!(p.get("media.indeterminateTimebase"), Some(json!("29.97df")));
+ assert_eq!(p.get("labels.colors.violet.color"), Some(json!("#380ea7")));
+ assert_eq!(p.get("labels.defaults.movie"), Some(json!("Iris")));
+ assert_eq!(p.get("audioHardware.bufferSize"), Some(json!(512)));
+ assert_eq!(p.version, settings::PREFS_VERSION);
+}
+
+#[test]
+fn prefs_persist_through_the_data_directory() {
+ let dir = tmp_dir("prefs-persist");
+ let mut s = Session::default();
+ s.start_autosave(crate::autosave::AutosaveConfig::new(&dir)).unwrap();
+ s.execute(
+ "prefs.set",
+ json!({"values": {"timeline.stillImageDuration": 3, "appearance.colorTheme": "light", "labels.colors.rose.name": "Hero", "audioHardware.sampleRate": "96000"}}),
+ )
+ .unwrap();
+ s.shutdown();
+ let file: Value = serde_json::from_slice(&std::fs::read(dir.join("preferences.json")).unwrap()).unwrap();
+ assert_eq!(file["version"], settings::PREFS_VERSION);
+ assert_eq!(file["timeline"]["stillImageDuration"], 3.0);
+
+ let mut s2 = Session::default();
+ s2.start_autosave(crate::autosave::AutosaveConfig::new(&dir)).unwrap();
+ assert_eq!(s2.prefs.timeline.still_image_duration, 3.0);
+ assert_eq!(s2.prefs.appearance.color_theme, "light");
+ assert_eq!(s2.prefs.labels.name(Label::Rose), "Hero");
+ assert_eq!(s2.prefs.audio_hardware.sample_rate, 96_000);
+ let got = s2.execute("prefs.get", json!({"key": "labels.colors.rose.name"})).unwrap();
+ assert_eq!(got, "Hero");
+ s2.shutdown();
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn v1_preferences_migrate_and_bad_values_are_repaired() {
+ let dir = tmp_dir("prefs-migrate");
+ let path = dir.join("preferences.json");
+ // a v1 file: only the old groups, no version
+ let v1 = json!({
+ "autoSave": {"enabled": false, "intervalMinutes": 9, "maxVersions": 3},
+ "playback": {"prerollSeconds": 4, "postrollSeconds": 1},
+ "trim": {"largeTrimOffset": 12, "playheadDeterminesLoop": true},
+ "media": {"enableProxies": true},
+ "guides": {"templates": [{"name": "T", "guides": [{"vertical": true, "position": 10.0}]}]}
+ });
+ std::fs::write(&path, serde_json::to_vec(&v1).unwrap()).unwrap();
+ let p = Preferences::load(&path);
+ assert_eq!(p.version, settings::PREFS_VERSION);
+ assert!(!p.auto_save.enabled);
+ assert_eq!((p.auto_save.interval_minutes, p.auto_save.max_versions), (9, 3));
+ assert_eq!((p.playback.preroll_seconds, p.playback.postroll_seconds), (4.0, 1.0));
+ assert_eq!(p.playback.step_many_frames, 5, "new key gets its default");
+ assert_eq!((p.trim.large_trim_offset, p.trim.playhead_determines_loop), (12, true));
+ assert!(p.media.enable_proxies);
+ assert_eq!(p.media.default_media_scaling, "none");
+ assert_eq!(p.guides.templates[0].name, "T");
+ assert_eq!(p.timeline, settings::TimelinePrefs::default());
+ assert_eq!(p.labels.colors.len(), 16);
+
+ // values a hand-edited (or future) file may carry are repaired, not fatal
+ let bad = json!({
+ "version": 2,
+ "timeline": {"autoScroll": "sideways", "stillImageDuration": -4, "stillImageUnit": "fortnights", "videoTransitionDuration": 1e9},
+ "appearance": {"highlightColor": "blue"},
+ "memory": {"frameCacheMb": 1},
+ "labels": {"colors": {"violet": {"name": "Purple-ish", "color": "#zzzzzz"}, "nope": {"name": "x", "color": "#000000"}}},
+ "unknownCategory": {"x": 1}
+ });
+ std::fs::write(&path, serde_json::to_vec(&bad).unwrap()).unwrap();
+ let p = Preferences::load(&path);
+ assert_eq!(p.timeline.auto_scroll, "pageScroll");
+ assert_eq!(p.timeline.still_image_unit, "seconds");
+ assert_eq!(p.timeline.still_image_duration, 0.01);
+ assert_eq!(p.timeline.video_transition_duration, 100_000.0);
+ assert_eq!(p.appearance.highlight_color, settings::DEFAULT_HIGHLIGHT);
+ assert_eq!(p.memory.frame_cache_mb, 64);
+ assert_eq!(p.labels.name(Label::Violet), "Purple-ish");
+ assert_eq!(p.labels.rgb(Label::Violet), Label::Violet.rgb());
+ assert!(!p.labels.colors.contains_key("nope"));
+ // a broken file falls back to defaults
+ std::fs::write(&path, b"{not json").unwrap();
+ assert_eq!(Preferences::load(&path), Preferences::default());
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn prefs_set_validates_and_reset_works_per_category() {
+ let mut s = Session::default();
+ let e = s.execute("prefs.set", json!({"key": "timeline.autoScroll", "value": "sideways"})).unwrap_err().to_string();
+ assert!(e.contains("noScroll"), "{e}");
+ assert!(s.execute("prefs.set", json!({"key": "appearance.highlightColor", "value": "blue"})).is_err());
+ assert!(s.execute("prefs.set", json!({"key": "timeline.stillImageUnit", "value": "weeks"})).is_err());
+ assert!(s.execute("prefs.set", json!({"key": "labels.defaults.movie", "value": "Chartreuse"})).is_err());
+ assert!(s.execute("prefs.set", json!({"key": "nope.key", "value": 1})).is_err());
+ // numeric choices accept numbers and strings; ints accept floats; ranges clamp
+ set(&mut s, "audioHardware.bufferSize", json!("1024"));
+ assert_eq!(s.prefs.audio_hardware.buffer_size, 1024);
+ set(&mut s, "audioHardware.bufferSize", json!(256));
+ assert_eq!(s.prefs.audio_hardware.buffer_size, 256);
+ assert!(s.execute("prefs.set", json!({"key": "audioHardware.bufferSize", "value": 300})).is_err());
+ set(&mut s, "playback.stepManyFrames", json!(12.0));
+ assert_eq!(s.prefs.playback.step_many_frames, 12);
+ set(&mut s, "memory.frameCacheMb", json!(10_000_000));
+ assert_eq!(s.prefs.memory.frame_cache_mb, 65_536);
+ set(&mut s, "labels.defaults.movie", json!("Rose"));
+ set(&mut s, "timeline.autoScroll", json!("smoothScroll"));
+ set(&mut s, "general.showToolTips", json!(false));
+ s.prefs.general.recent_projects = vec!["/a.fcproj".into()];
+ // reset one category
+ s.execute("prefs.reset", json!({"category": "timeline"})).unwrap();
+ assert_eq!(s.prefs.timeline.auto_scroll, "pageScroll");
+ assert_eq!(s.prefs.labels.defaults.movie, Label::Rose, "other categories keep their values");
+ s.execute("prefs.reset", json!({"category": "general"})).unwrap();
+ assert!(s.prefs.general.show_tool_tips);
+ assert_eq!(s.prefs.general.recent_projects, ["/a.fcproj"], "recent projects survive a reset");
+ assert!(s.execute("prefs.reset", json!({"category": "nope"})).is_err());
+ s.execute("prefs.reset", json!({})).unwrap();
+ assert_eq!(s.prefs, Preferences::default());
+}
+
+#[test]
+fn schema_command_describes_every_category() {
+ let mut s = Session::default();
+ let r = s.execute("prefs.schema", json!({})).unwrap();
+ let cats = r["categories"].as_array().unwrap();
+ assert_eq!(cats.len(), settings::categories().len());
+ let tl = cats.iter().find(|c| c["id"] == "timeline").unwrap();
+ assert_eq!(tl["command"], "app.settings.timeline");
+ let auto = tl["fields"].as_array().unwrap().iter().find(|f| f["key"] == "timeline.autoScroll").unwrap();
+ assert_eq!(auto["value"], "pageScroll");
+ assert_eq!(auto["wired"], true);
+ assert!(auto["kind"]["choices"].as_array().unwrap().iter().any(|c| c["value"] == "smoothScroll"));
+ let one = s.execute("prefs.schema", json!({"category": "trim"})).unwrap();
+ assert_eq!(one["categories"].as_array().unwrap().len(), 1);
+ assert!(s.execute("prefs.schema", json!({"category": "nope"})).is_err());
+}
+
+#[test]
+fn still_image_default_duration_and_indeterminate_timebase() {
+ let dir = tmp_dir("prefs-still");
+ let mut s = demo();
+ let rate = s.sequence_rate();
+ set(&mut s, "media.indeterminateTimebase", json!("25"));
+ let still = import_png(&mut s, &dir, "a.png", 64, 36);
+ let m = s.project.item(still).unwrap().as_media().unwrap();
+ assert_eq!(m.info.frame_rate(), FrameRate::FPS_25, "stills take the indeterminate media timebase");
+ set(&mut s, "timeline.stillImageDuration", json!(3));
+ let end = s.active_sequence().unwrap().duration();
+ let r = s.execute("timeline.place", json!({"item": still.0, "track": "V1", "time": end.0})).unwrap();
+ let clip = filmcraft_project::ClipId(r["clips"][0].as_u64().unwrap());
+ let dur = s.active_sequence().unwrap().find_item(clip).unwrap().1.duration;
+ assert_eq!(dur, rate.snap_nearest(Tick::from_seconds_f64(3.0)));
+ // in frames
+ s.execute("prefs.set", json!({"values": {"timeline.stillImageUnit": "frames", "timeline.stillImageDuration": 10}})).unwrap();
+ let end = s.active_sequence().unwrap().duration();
+ let r = s.execute("timeline.place", json!({"item": still.0, "track": "V1", "time": end.0})).unwrap();
+ let clip = filmcraft_project::ClipId(r["clips"][0].as_u64().unwrap());
+ assert_eq!(s.active_sequence().unwrap().find_item(clip).unwrap().1.duration, rate.tick_of(10));
+ // Source monitor insert of a still uses it too
+ s.execute("source.open", json!({"item": still.0})).unwrap();
+ let (_, range) = crate::commands::source_range(&s).unwrap();
+ assert_eq!(range.duration, rate.tick_of(10));
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+fn transition_duration(s: &Session, r: &Value) -> Tick {
+ let id = r["transition"].as_u64().unwrap_or_else(|| panic!("{r}"));
+ let q = s.active_sequence().unwrap();
+ q.all_tracks().flat_map(|t| t.transitions.iter()).find(|t| t.id.0 == id).unwrap().duration
+}
+
+#[test]
+fn default_transition_durations() {
+ let mut s = demo();
+ let rate = s.sequence_rate();
+ let q = s.active_sequence().unwrap();
+ let cut = q.video_tracks[0].items[2].start;
+ let aclip = q.audio_tracks[0].items[1].id.0;
+ set(&mut s, "timeline.videoTransitionDuration", json!(10));
+ s.execute("playhead.set", json!({"time": cut.0})).unwrap();
+ let r = s.execute("sequence.applyVideoTransition", json!({})).unwrap();
+ assert_eq!(transition_duration(&s, &r), rate.tick_of(10));
+ // audio: 0.5 seconds, snapped to frames
+ s.execute("prefs.set", json!({"values": {"timeline.audioTransitionDuration": 0.5, "timeline.audioTransitionUnit": "seconds"}})).unwrap();
+ let r = s.execute("sequence.applyAudioTransition", json!({"clip": aclip})).unwrap();
+ assert_eq!(transition_duration(&s, &r), rate.snap_nearest(Tick::from_seconds_f64(0.5)));
+ // explicit frames still win
+ let cut2 = s.active_sequence().unwrap().video_tracks[0].items[3].start;
+ s.execute("playhead.set", json!({"time": cut2.0})).unwrap();
+ let r = s.execute("sequence.applyVideoTransition", json!({"frames": 4})).unwrap();
+ assert_eq!(transition_duration(&s, &r), rate.tick_of(4));
+}
+
+#[test]
+fn step_many_frames() {
+ let mut s = demo();
+ let rate = s.sequence_rate();
+ s.execute("playhead.set", json!({"frame": 50})).unwrap();
+ s.execute("playhead.stepForward5", json!({})).unwrap();
+ assert_eq!(rate.frame_at(s.playhead()), 55);
+ set(&mut s, "playback.stepManyFrames", json!(12));
+ s.execute("playhead.stepForward5", json!({})).unwrap();
+ assert_eq!(rate.frame_at(s.playhead()), 67);
+ s.execute("playhead.stepBack5", json!({})).unwrap();
+ s.execute("playhead.stepBack5", json!({})).unwrap();
+ assert_eq!(rate.frame_at(s.playhead()), 43);
+}
+
+#[test]
+fn label_defaults_names_and_colours() {
+ let dir = tmp_dir("prefs-labels");
+ let mut s = Session::default();
+ let a = import_png(&mut s, &dir, "a.png", 32, 18);
+ assert_eq!(s.project.item(a).unwrap().label, Label::Lavender);
+ set(&mut s, "labels.defaults.still", json!("Yellow"));
+ let b = import_png(&mut s, &dir, "b.png", 32, 18);
+ assert_eq!(s.project.item(b).unwrap().label, Label::Yellow);
+ set(&mut s, "labels.defaults.sequence", json!("Teal"));
+ let r = s.execute("file.newSequence", json!({"name": "S"})).unwrap();
+ let seq = ItemId(r["sequence"].as_u64().unwrap());
+ assert_eq!(s.project.item(seq).unwrap().label, Label::Teal);
+ // movie / video-only / audio-only media
+ let l = &s.prefs.labels;
+ use filmcraft_media::MediaKind as K;
+ assert_eq!(l.for_media(K::Movie, true, true), Label::Iris);
+ assert_eq!(l.for_media(K::Movie, true, false), Label::Violet);
+ assert_eq!(l.for_media(K::AudioOnly, false, true), Label::Caribbean);
+ // editable names and colours
+ s.execute("prefs.set", json!({"values": {"labels.colors.teal.name": "B-roll", "labels.colors.teal.color": "#00ff80"}})).unwrap();
+ assert_eq!(s.prefs.labels.name(Label::Teal), "B-roll");
+ assert_eq!(s.prefs.labels.rgb(Label::Teal), [0, 255, 128]);
+ assert!(s.execute("prefs.set", json!({"key": "labels.colors.teal.color", "value": "green"})).is_err());
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn default_media_scaling() {
+ let dir = tmp_dir("prefs-scaling");
+ let mut s = demo();
+ let (w, h) = s.active_sequence().map(|q| (q.settings.width, q.settings.height)).unwrap();
+ let big = import_png(&mut s, &dir, "big.png", w * 2, h * 2);
+ let place = |s: &mut Session| {
+ let end = s.active_sequence().unwrap().duration();
+ let r = s.execute("timeline.place", json!({"item": big.0, "track": "V1", "time": end.0})).unwrap();
+ let c = filmcraft_project::ClipId(r["clips"][0].as_u64().unwrap());
+ s.active_sequence().unwrap().find_item(c).unwrap().1.clone()
+ };
+ let none = place(&mut s);
+ assert!(!none.scale_to_frame);
+ assert_eq!(none.effect("motion").unwrap().params["scale"].value, ParamValue::Float(100.0));
+ set(&mut s, "media.defaultMediaScaling", json!("scaleToFrameSize"));
+ assert!(place(&mut s).scale_to_frame);
+ set(&mut s, "media.defaultMediaScaling", json!("setToFrameSize"));
+ let set_to = place(&mut s);
+ assert!(!set_to.scale_to_frame);
+ assert_eq!(set_to.effect("motion").unwrap().params["scale"].value, ParamValue::Float(50.0));
+ // media already at frame size is left alone
+ let fit = import_png(&mut s, &dir, "fit.png", w, h);
+ let end = s.active_sequence().unwrap().duration();
+ let r = s.execute("timeline.place", json!({"item": fit.0, "track": "V1", "time": end.0})).unwrap();
+ let c = filmcraft_project::ClipId(r["clips"][0].as_u64().unwrap());
+ let it = s.active_sequence().unwrap().find_item(c).unwrap().1.clone();
+ assert_eq!(it.effect("motion").unwrap().params["scale"].value, ParamValue::Float(100.0));
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn recent_projects_are_remembered() {
+ let dir = tmp_dir("prefs-recent");
+ let mut s = demo();
+ let a = dir.join("a.fcproj").to_string_lossy().into_owned();
+ let b = dir.join("b.fcproj").to_string_lossy().into_owned();
+ s.execute("file.saveAs", json!({"path": a})).unwrap();
+ s.execute("file.saveAs", json!({"path": b})).unwrap();
+ s.execute("file.open", json!({"path": a})).unwrap();
+ assert_eq!(s.prefs.general.recent_projects, [a.clone(), b.clone()]);
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn media_cache_location_policy_and_clean() {
+ let dir = tmp_dir("prefs-cache");
+ let mut s = Session::default();
+ s.start_autosave(crate::autosave::AutosaveConfig::new(dir.join("data"))).unwrap();
+ let cache = s.media_cache_dir().unwrap();
+ assert_eq!(cache, dir.join("data").join("Media Cache"));
+ // unsaved projects keep their previews in the media cache
+ assert!(s.previews.dir().unwrap().starts_with(cache.join("Previews")), "{:?}", s.previews.dir());
+ // a custom location moves them
+ let custom = dir.join("cache2");
+ set(&mut s, "mediaCache.location", json!(custom.to_string_lossy()));
+ assert_eq!(s.media_cache_dir().unwrap(), custom);
+ assert!(s.previews.dir().unwrap().starts_with(custom.join("Previews")));
+ // stale files from earlier sessions
+ let stale = custom.join("Previews").join("untitled-1-old");
+ std::fs::create_dir_all(&stale).unwrap();
+ let old = stale.join("0123456789abcdef0123456789abcdef.mov");
+ std::fs::write(&old, vec![0u8; 1000]).unwrap();
+ let ten_days = std::time::Duration::from_secs(10 * 86_400);
+ std::fs::File::options().write(true).open(&old).unwrap().set_modified(std::time::SystemTime::now() - ten_days).unwrap();
+ let fresh = stale.join("fedcba9876543210fedcba9876543210.wav");
+ std::fs::write(&fresh, vec![0u8; 500]).unwrap();
+ let mine = s.previews.dir().unwrap();
+ std::fs::create_dir_all(&mine).unwrap();
+ std::fs::write(mine.join("00000000000000000000000000000000.mov"), vec![0u8; 100]).unwrap();
+ let info = s.execute("mediaCache.info", json!({})).unwrap();
+ assert_eq!((info["files"].as_u64(), info["bytes"].as_u64()), (Some(3), Some(1600)));
+ // "older than 5 days" removes only the old file
+ let mut p = settings::MediaCachePrefs { management: "olderThan".into(), older_than_days: 5, ..Default::default() };
+ assert_eq!(settings::enforce_policy(&custom, &p, Some(&mine), std::time::SystemTime::now()), (1, 1000));
+ assert!(!old.exists() && fresh.exists());
+ // "exceeds size" with a 0 GB limit removes everything but the open project's previews
+ p.management = "exceedsSize".into();
+ p.max_size_gb = 0;
+ settings::enforce_policy(&custom, &p, Some(&mine), std::time::SystemTime::now());
+ assert!(!fresh.exists() && !stale.exists());
+ assert!(mine.join("00000000000000000000000000000000.mov").exists());
+ // Delete… keeps the open project's files unless `all`
+ let r = s.execute("mediaCache.clean", json!({})).unwrap();
+ assert_eq!(r["files"], 0);
+ let r = s.execute("mediaCache.clean", json!({"all": true})).unwrap();
+ assert_eq!(r["files"], 1);
+ s.shutdown();
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn output_mapping_and_smart_quotes() {
+ let (l, r) = ([0.5f32, 0.25], [-0.5f32, 1.5]);
+ let mut out = [9.0f32; 8];
+ settings::map_output(&l, &r, &mut out, 4, [2, 3]);
+ assert_eq!(out, [0.0, 0.0, 0.5, -0.5, 0.0, 0.0, 0.25, 1.0]);
+ let mut st = [0.0f32; 4];
+ settings::map_output(&l, &r, &mut st, 2, [1, 0]);
+ assert_eq!(st, [-0.5, 0.5, 1.0, 0.25], "swapped");
+ settings::map_output(&l, &r, &mut st, 2, [7, 9]);
+ assert_eq!(st, [0.5, -0.5, 0.25, 1.0], "out-of-range mapping falls back to 1:1");
+ let mut mono = [0.0f32; 2];
+ settings::map_output(&l, &r, &mut mono, 1, [0, 1]);
+ assert_eq!(mono, [0.0, 0.875]);
+ assert_eq!(settings::smart_quotes(r#"He said "it's 'fine'" (ok)"#), "He said “it’s ‘fine’” (ok)");
+}
+
+#[test]
+fn graphics_text_uses_the_text_settings() {
+ let mut s = demo();
+ s.execute("graphics.newText", json!({"text": "\"Hi\""})).unwrap();
+ let layer = |s: &Session| {
+ let c = s.state.selection[0];
+ let it = s.active_sequence().unwrap().find_item(c).unwrap().1.clone();
+ it.effects.iter().rev().find(|e| e.effect.contains("text")).cloned().unwrap()
+ };
+ let l = layer(&s);
+ assert_eq!(l.params["text"].value, ParamValue::Text("“Hi”".into()));
+ assert_eq!(l.params["ligatures"].value, ParamValue::Bool(true));
+ s.execute("prefs.set", json!({"values": {"graphics.smartQuotes": false, "graphics.ligatures": false, "graphics.defaultFont": "JetBrains Mono"}})).unwrap();
+ s.execute("graphics.newText", json!({"text": "\"Hi\"", "newClip": true})).unwrap();
+ let l = layer(&s);
+ assert_eq!(l.params["text"].value, ParamValue::Text("\"Hi\"".into()));
+ assert_eq!(l.params["ligatures"].value, ParamValue::Bool(false));
+ assert_eq!(l.params["font"].value, ParamValue::Text("JetBrains Mono".into()));
+}
+
+#[test]
+fn auto_transcribe_on_import_and_transcription_defaults() {
+ use filmcraft_project::{Transcript, Word};
+ let dir = tmp_dir("prefs-transcribe");
+ let mov = dir.join("talk.mov");
+ crate::media_test_util::make_movie(&mov, filmcraft_media::DemoScene::OceanSunset, 64, 36, 24);
+ let mut s = Session::default();
+ let mut t = Transcript { language: "en".into(), ..Default::default() };
+ t.words.push(Word::new("hello", Tick::ZERO, Tick::from_seconds_f64(0.4)));
+ s.transcriber = Some(std::sync::Arc::new(filmcraft_speech::FixedTranscriber { transcript: t, id: "fixed".into() }));
+ // off by default
+ let r = s.execute("file.import", json!({"paths": [mov.to_string_lossy()]})).unwrap();
+ let a = ItemId(r["items"][0].as_u64().unwrap());
+ assert!(!s.project.transcripts.contains_key(&a));
+ // on, but only for clips in sequences (Premiere's default scope): still nothing on import
+ set(&mut s, "mediaAnalysis.autoTranscribe", json!(true));
+ let r = s.execute("file.import", json!({"paths": [mov.to_string_lossy()]})).unwrap();
+ assert!(!s.project.transcripts.contains_key(&ItemId(r["items"][0].as_u64().unwrap())));
+ set(&mut s, "mediaAnalysis.autoTranscribeScope", json!("allImported"));
+ let r = s.execute("file.import", json!({"paths": [mov.to_string_lossy()]})).unwrap();
+ let c = ItemId(r["items"][0].as_u64().unwrap());
+ assert_eq!(s.project.transcripts[&c].words[0].text, "hello");
+ assert!(matches!(s.project.item(c).unwrap().kind, ItemKind::Media(_)));
+ // the model setting is validated against the catalogue
+ assert!(s.execute("prefs.set", json!({"key": "mediaAnalysis.whisperModel", "value": "whisper-huge"})).is_err());
+ set(&mut s, "mediaAnalysis.whisperModel", json!("whisper-tiny"));
+ let _ = std::fs::remove_dir_all(&dir);
+}
diff --git a/crates/engine/src/shortcut_presets.rs b/crates/engine/src/shortcut_presets.rs
index a82d143e6..f769ccf12 100644
--- a/crates/engine/src/shortcut_presets.rs
+++ b/crates/engine/src/shortcut_presets.rs
@@ -57,7 +57,7 @@ pub const PREMIERE: &[Entry] = &[
("multicam.recordToggle", "0", ""),
("multicam.toggleView", "Shift+0", ""),
// Application
- ("app.preferences.autoSave", "Cmd+,", ""),
+ ("app.settings.general", "Cmd+,", ""),
("app.keyboardShortcuts", "Cmd+Alt+K", ""),
// File
("file.newProject", "Cmd+Alt+N", ""),
diff --git a/crates/engine/src/transcript.rs b/crates/engine/src/transcript.rs
index 0dfab5ecc..ad1823902 100644
--- a/crates/engine/src/transcript.rs
+++ b/crates/engine/src/transcript.rs
@@ -117,7 +117,8 @@ fn transcriber(s: &Session, p: &Value) -> Result<Arc<dyn Transcriber>> {
if let Some(t) = &s.transcriber {
return Ok(t.clone());
}
- let model = str_p(p, "model").unwrap_or(filmcraft_speech::models::DEFAULT_MODEL);
+ // Settings ▸ Media Analysis & Transcription ▸ Speech model
+ let model = str_p(p, "model").unwrap_or(&s.prefs.media_analysis.whisper_model);
if filmcraft_speech::models::find(model).is_none() {
return Err(speech_err(SpeechError::UnknownModel(model.into())));
}
@@ -136,9 +137,15 @@ fn generate(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad("transcript.generate", "nothing to transcribe (pass `items`, select clips, or open a sequence with audio)"));
}
let t = transcriber(s, p)?;
+ // Settings ▸ Media Analysis & Transcription: language (or auto-detect) and speaker labelling
+ let ma = &s.prefs.media_analysis;
+ let default_language = if ma.language_auto_detect { None } else { Some(ma.default_language.clone()) };
let opts = Options {
- language: str_p(p, "language").filter(|l| !l.is_empty() && *l != "auto").map(str::to_string),
- diarize: bool_p(p, "diarize").unwrap_or(true),
+ language: match str_p(p, "language") {
+ Some(l) => Some(l).filter(|l| !l.is_empty() && *l != "auto").map(str::to_string),
+ None => default_language,
+ },
+ diarize: bool_p(p, "diarize").unwrap_or(ma.speaker_labeling != "off"),
max_speakers: u64_p(p, "maxSpeakers").map(|n| n.clamp(1, 32) as usize).unwrap_or(Options::default().max_speakers),
};
let mut done: Vec<(ItemId, Transcript)> = Vec::new();
diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs
index 93f4b8071..c4702e56c 100644
--- a/crates/project/src/lib.rs
+++ b/crates/project/src/lib.rs
@@ -968,6 +968,8 @@ pub struct ProjectSettings {
pub renderer: String,
pub video_display: filmcraft_time::TimeDisplay,
pub audio_display_samples: bool,
+ /// Kept for file compatibility; the editor uses Settings ▸ Timeline (user preferences) for
+ /// still and transition default durations, as Premiere does.
pub default_still_duration: Tick,
pub default_transition_duration_frames: i64,
pub default_audio_transition_duration: Tick,
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 9e39f018b..4b68a21d6 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -125,10 +125,16 @@ pub fn handle(app: &mut FilmcraftApp, ctx: &egui::Context, req: &ControlRequest)
}
if let Some(th) = s("theme") {
match crate::theme::ThemeKind::from_name(th) {
- Some(k) => app.set_theme(ctx, k),
+ Some(k) => crate::panels::settings::set_theme(app, ctx, k),
None => return err("unknown theme (dark, medium, light)"),
}
}
+ // the open Settings dialog: page and draft values (`{"page": id, "values": {key: value}}`)
+ if let Some(st) = p.get("settings")
+ && let Err(e) = crate::panels::settings::patch(app, st)
+ {
+ return err(e);
+ }
if let Some(f) = s("focused").and_then(PanelKind::from_name) {
app.ui.focused = f;
}
diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rs
index 254709d0f..50f33bc26 100644
--- a/crates/ui-egui/src/frames.rs
+++ b/crates/ui-egui/src/frames.rs
@@ -296,6 +296,24 @@ pub fn playback_plan(render_cost: f64, fps: f64, workers: usize) -> (i64, i64) {
}
impl FrameServer {
+ /// Settings ▸ Memory ▸ frame cache budget (bytes); evicts down to it right away.
+ pub fn set_cache_budget(&self, bytes: usize) {
+ let mut c = self.shared.done.lock().unwrap_or_else(|e| e.into_inner());
+ c.budget = bytes.max(16 << 20);
+ if c.bytes > c.budget
+ && let Some((k, v)) = c.map.iter().next().map(|(k, (v, _))| (*k, v.clone()))
+ {
+ // re-inserting an entry runs the eviction pass
+ c.insert(k, v);
+ }
+ }
+
+ /// (bytes cached, budget).
+ pub fn cache_usage(&self) -> (usize, usize) {
+ let c = self.shared.done.lock().unwrap_or_else(|e| e.into_inner());
+ (c.bytes, c.budget)
+ }
+
pub fn new(pool: Arc<MediaPool>, services: Arc<dyn Services>, previews: Arc<PreviewStore>, workers: usize) -> Self {
let shared = Arc::new(Shared {
queue: Mutex::new(VecDeque::new()),
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 44e8e435c..3e830ae13 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -42,6 +42,25 @@ pub trait AudioOut {
fn sample_rate(&self) -> u32;
/// Frames played since `start` (the playback master clock), if the device reports it.
fn played_frames(&self) -> Option<u64>;
+ /// Hosts and devices that can be chosen in Settings ▸ Audio Hardware.
+ fn devices(&self) -> AudioDevices {
+ AudioDevices::default()
+ }
+ /// Apply Settings ▸ Audio Hardware (device class/output, buffer size, sample rate). Takes
+ /// effect at the next `start`; `document_rate` is the sequence sample rate for "Attempt to
+ /// force hardware to document sample rate".
+ fn configure(&mut self, _hw: &filmcraft_engine::settings::AudioHardwarePrefs, _document_rate: Option<u32>) {}
+}
+
+/// What the platform audio layer can open (Settings ▸ Audio Hardware).
+#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
+pub struct AudioDevices {
+ /// Audio hosts / device classes (`CoreAudio`, `WASAPI`, `ALSA`…).
+ pub hosts: Vec<String>,
+ pub inputs: Vec<String>,
+ pub outputs: Vec<String>,
+ /// Output channels of the selected output device.
+ pub output_channels: u16,
}
/// Host hooks for native file dialogs etc.
@@ -69,7 +88,7 @@ pub enum Dialog {
About,
Shortcuts,
NewSequence,
- /// Preferences ▸ Auto Save.
+ /// Settings (Preferences window; page in `UiState::settings`).
Preferences,
/// "Recover unsaved changes from <time>?" (shown at startup when a dead session left some).
Recovery,
@@ -150,6 +169,8 @@ pub struct FilmcraftApp {
pub gpu: Option<GpuState>,
/// Preview render job being watched (job id, where to start playing when it completes).
watched_render: Option<(u64, Tick)>,
+ /// Settings last applied to the UI (theme, tooltips, frame cache, audio device).
+ applied_prefs: Option<filmcraft_engine::autosave::Preferences>,
}
pub struct GpuState {
@@ -238,6 +259,7 @@ impl FilmcraftApp {
command_inbox: None,
gpu: None,
watched_render: None,
+ applied_prefs: None,
}
}
@@ -261,15 +283,54 @@ impl FilmcraftApp {
));
self.textures.clear();
self.tl.reset_media_caches();
+ // the new frame server needs the Memory settings
+ self.applied_prefs = None;
}
}
+ /// Show theme `k` with the Settings ▸ Appearance highlight colour and contrast.
pub fn set_theme(&mut self, ctx: &egui::Context, k: ThemeKind) {
- self.tokens = Tokens::for_kind(k);
+ let a = &self.session.prefs.appearance;
+ let highlight = filmcraft_engine::settings::parse_hex(&a.highlight_color);
+ self.tokens = Tokens::for_kind(k).with_appearance(highlight, a.accessible_contrast);
theme::apply_visuals(ctx, &self.tokens);
+ self.apply_tooltips(ctx);
self.ui.dark = k != ThemeKind::Light;
}
+ fn apply_tooltips(&self, ctx: &egui::Context) {
+ // Settings ▸ General ▸ Show Tool Tips
+ let delay = if self.session.prefs.general.show_tool_tips { 0.5 } else { 1.0e9 };
+ ctx.global_style_mut(|s| s.interaction.tooltip_delay = delay);
+ }
+
+ /// Make the UI follow the settings after they change (theme, tooltips, frame cache budget,
+ /// play after rendering, audio device).
+ pub fn apply_prefs(&mut self, ctx: &egui::Context) {
+ if self.applied_prefs.as_ref() == Some(&self.session.prefs) {
+ return;
+ }
+ let p = self.session.prefs.clone();
+ let prev = self.applied_prefs.take();
+ if prev.as_ref().is_none_or(|q| q.appearance != p.appearance || q.general.show_tool_tips != p.general.show_tool_tips) {
+ self.set_theme(ctx, ThemeKind::from_pref(&p.appearance.color_theme));
+ }
+ self.frames.set_cache_budget(p.memory.frame_cache_mb as usize * (1 << 20));
+ self.ui.play_after_render = p.timeline.play_after_rendering;
+ if prev.as_ref().is_none_or(|q| q.audio_hardware != p.audio_hardware) {
+ let rate = self.session.active_sequence().map(|q| q.settings.sample_rate);
+ let playing = self.playback.playing && self.playback.audio_clock;
+ if let Some(a) = self.audio.as_mut() {
+ a.stop();
+ a.configure(&p.audio_hardware, rate);
+ }
+ if playing {
+ self.start_audio();
+ }
+ }
+ self.applied_prefs = Some(p);
+ }
+
pub fn set_workspace(&mut self, name: &str) {
self.ui.workspace = name.to_string();
self.ui.dock = dock::workspace(name);
@@ -315,9 +376,10 @@ impl FilmcraftApp {
if self.session.active_sequence().is_none() {
return;
}
- // restart from the end → from the start
+ // restart from the end → from the start (Settings ▸ Timeline ▸ "At playback end, return to
+ // beginning when restarting playback")
let dur = self.session.active_sequence().map(|q| q.duration()).unwrap_or_default();
- if speed > 0.0 && self.session.playhead() >= dur - self.session.sequence_rate().frame_duration() {
+ if speed > 0.0 && self.session.prefs.timeline.return_to_beginning && self.session.playhead() >= dur - self.session.sequence_rate().frame_duration() {
self.session.set_playhead(Tick::ZERO);
}
// A loop restart keeps counting into the same meter.
@@ -382,6 +444,8 @@ impl FilmcraftApp {
let provider = self.session.media.provider(project.clone(), self.session.services.clone());
let previews = self.session.previews.clone();
let start_tick = self.session.playhead();
+ // Settings ▸ Audio Hardware ▸ Output Mapping
+ let map = [self.session.prefs.audio_hardware.map_left, self.session.prefs.audio_hardware.map_right];
let Some(a) = self.audio.as_mut() else { return };
let sr = a.sample_rate();
let mut cursor = start_tick.to_units_floor(sr as i64);
@@ -408,11 +472,7 @@ impl FilmcraftApp {
}
out
};
- for i in 0..n {
- for c in 0..ch {
- buf[i * ch + c] = mix.channels[c.min(1)][i].clamp(-1.0, 1.0);
- }
- }
+ filmcraft_engine::settings::map_output(&mix.channels[0], &mix.channels[1.min(mix.channels.len() - 1)], buf, ch, map);
cursor += n as i64;
});
match a.start(fill) {
@@ -804,6 +864,7 @@ impl FilmcraftApp {
ctx.request_repaint_after(std::time::Duration::from_secs(1));
}
self.sync_pool();
+ self.apply_prefs(&ctx);
for ev in self.session.drain_events() {
match ev {
filmcraft_engine::Event::OpenSequence(_) => {
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index cb5096bd8..d0a2d0ada 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -113,7 +113,22 @@ pub const UI_COMMANDS: &[UiCommand] = &[
uic!("help.reportIssue", "Report an Issue…", ["Help"], None),
uic!("app.about", "About FilmCraft", ["Help"], None),
uic!("app.keyboardShortcuts", "Keyboard Shortcuts…", ["Edit"], Some("Cmd+Alt+K")),
- uic!("app.preferences.autoSave", "Auto Save…", ["Edit", "Preferences"], Some("Cmd+,")),
+ uic!("app.settings.general", "General…", ["Edit", "Preferences"], Some("Cmd+,")),
+ uic!("app.settings.appearance", "Appearance…", ["Edit", "Preferences"], None),
+ uic!("app.settings.audio", "Audio…", ["Edit", "Preferences"], None),
+ uic!("app.settings.audioHardware", "Audio Hardware…", ["Edit", "Preferences"], None),
+ uic!("app.settings.autoSave", "Auto Save…", ["Edit", "Preferences"], None),
+ uic!("app.settings.color", "Color…", ["Edit", "Preferences"], None),
+ uic!("app.settings.graphics", "Graphics…", ["Edit", "Preferences"], None),
+ uic!("app.settings.labels", "Labels…", ["Edit", "Preferences"], None),
+ uic!("app.settings.media", "Media…", ["Edit", "Preferences"], None),
+ uic!("app.settings.mediaAnalysis", "Media Analysis & Transcription…", ["Edit", "Preferences"], None),
+ uic!("app.settings.mediaCache", "Media Cache…", ["Edit", "Preferences"], None),
+ uic!("app.settings.memory", "Memory…", ["Edit", "Preferences"], None),
+ uic!("app.settings.playback", "Playback…", ["Edit", "Preferences"], None),
+ uic!("app.settings.plugins", "Plugins…", ["Edit", "Preferences"], None),
+ uic!("app.settings.timeline", "Timeline…", ["Edit", "Preferences"], None),
+ uic!("app.settings.trim", "Trim…", ["Edit", "Preferences"], None),
];
pub fn panel_command_id(p: PanelKind) -> String {
@@ -154,6 +169,9 @@ pub fn invoke(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: Val
if let Some(r) = crate::panels::clip_dialogs::route(app, id, &params) {
return r;
}
+ if let Some(r) = crate::panels::settings::route(app, id) {
+ return r;
+ }
if let Some(r) = crate::panels::media_dialogs::route(app, id, &params) {
if let Err(e) = &r {
app.ui.status = e.clone();
@@ -236,11 +254,6 @@ pub fn invoke(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: Val
crate::panels::shortcuts_dialog::open(app);
return Ok(Value::Null);
}
- "app.preferences" | "app.preferences.autoSave" => {
- app.file_dialogs.prefs_draft = Some(app.session.prefs.auto_save.clone());
- app.dialog = Some(crate::Dialog::Preferences);
- return Ok(Value::Null);
- }
// Audio Gain from the menu or G opens the dialog; with params it applies directly.
"clip.audioGain" if params.as_object().is_none_or(|m| m.is_empty()) => {
filmcraft_engine::find_command("clip.audioGain").map_or(Ok(()), |c| (c.enabled)(&app.session))?;
@@ -287,7 +300,7 @@ pub fn invoke(app: &mut FilmcraftApp, ctx: &egui::Context, id: &str, params: Val
}
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);
+ crate::panels::settings::set_theme(app, ctx, k);
return Ok(Value::Null);
}
// File dialogs for commands that need a path.
@@ -341,9 +354,14 @@ pub fn menu_items_for(session: &filmcraft_engine::Session) -> Vec<MenuItem> {
if c.menu.is_empty() {
continue;
}
+ // Edit ▸ Label items carry the names from Settings ▸ Labels
+ let label = match c.id.strip_prefix("edit.label.").and_then(filmcraft_project::Label::from_name) {
+ Some(l) => session.prefs.labels.name(l),
+ None => c.label.into(),
+ };
out.push(MenuItem {
id: c.id.into(),
- label: c.label.into(),
+ label,
path: c.menu.iter().map(|s| s.to_string()).collect(),
shortcut: session.shortcuts.primary(c.id),
enabled: session.is_enabled(c.id),
diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs
index 217c3353d..4e689df35 100644
--- a/crates/ui-egui/src/panels/dialogs.rs
+++ b/crates/ui-egui/src/panels/dialogs.rs
@@ -1,5 +1,5 @@
-//! Modal dialogs (About; Keyboard Shortcuts in `shortcuts_dialog`; Preferences/Recovery/Revert in
-//! `file_dialogs`).
+//! Modal dialogs (About; Keyboard Shortcuts in `shortcuts_dialog`; Settings in `settings`;
+//! Recovery/Revert in `file_dialogs`).
use crate::{Dialog, FilmcraftApp};
diff --git a/crates/ui-egui/src/panels/effect_controls.rs b/crates/ui-egui/src/panels/effect_controls.rs
index 813f029a0..8c4080a65 100644
--- a/crates/ui-egui/src/panels/effect_controls.rs
+++ b/crates/ui-egui/src/panels/effect_controls.rs
@@ -511,7 +511,7 @@ pub fn properties_panel(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
// header: clip name + menu
let (hr, _) = bui.allocate_exact_size(vec2(bui.available_width(), 30.0), Sense::hover());
let sw = Rect::from_center_size(pos2(hr.min.x + 8.0, hr.center().y), vec2(12.0, 12.0));
- let lc = it.label.rgb();
+ let lc = app.session.prefs.labels.rgb(it.label);
bui.painter().rect_filled(sw, 2.0, Color32::from_rgb(lc[0], lc[1], lc[2]));
bui.painter().text(pos2(hr.min.x + 22.0, hr.center().y), Align2::LEFT_CENTER, &it.name, Tokens::semibold(12.5), t.text);
let row = |ui: &mut egui::Ui, label: &str| -> Rect {
diff --git a/crates/ui-egui/src/panels/file_dialogs.rs b/crates/ui-egui/src/panels/file_dialogs.rs
index 791ebe00e..b9009b5b7 100644
--- a/crates/ui-egui/src/panels/file_dialogs.rs
+++ b/crates/ui-egui/src/panels/file_dialogs.rs
@@ -1,20 +1,18 @@
-//! Preferences ▸ Auto Save, the crash-recovery prompt and the Revert confirmation.
+//! The crash-recovery prompt and the Revert confirmation (Settings ▸ Auto Save lives in
+//! `panels::settings`).
//!
-//! Automation ids: `prefs.autoSave.<key>` (controls), `prefs.category.autoSave`, `prefs.reset`,
-//! `prefs.cancel`, `prefs.ok`; `recovery.item.<n>`, `recovery.recover`, `recovery.discard`,
-//! `recovery.later`; `revert.yes`, `revert.no`.
+//! Automation ids: `recovery.item.<n>`, `recovery.recover`, `recovery.discard`, `recovery.later`;
+//! `revert.yes`, `revert.no`.
-use egui::{Align2, Color32, CornerRadius, Frame, Margin, RichText, Stroke, Ui, vec2};
-use filmcraft_engine::autosave::AutoSavePrefs;
+use egui::{Color32, CornerRadius, Frame, Margin, RichText, Stroke, Ui, vec2};
use serde_json::json;
use crate::theme::Tokens;
use crate::{Dialog, FilmcraftApp};
-/// Dialog-local state (the Preferences draft is applied on OK).
+/// Dialog-local state.
#[derive(Default)]
pub struct FileDialogState {
- pub prefs_draft: Option<AutoSavePrefs>,
pub recovery_choice: usize,
}
@@ -35,143 +33,6 @@ fn button(app: &mut FilmcraftApp, ui: &mut Ui, id: &str, label: &str, primary: b
r.clicked()
}
-/// A Premiere-style group box: 1-px rounded border with the title inset in the top edge.
-fn group(ui: &mut Ui, t: &Tokens, title: &str, add: impl FnOnce(&mut Ui)) {
- ui.add_space(8.0);
- let r = Frame::new()
- .stroke(Stroke::new(1.0, t.field_border))
- .corner_radius(CornerRadius::same(4))
- .inner_margin(Margin { left: 14, right: 14, top: 18, bottom: 12 })
- .show(ui, |ui| {
- ui.set_width(ui.available_width());
- ui.spacing_mut().item_spacing.y = 10.0;
- add(ui);
- });
- let rect = r.response.rect;
- let galley = ui.painter().layout_no_wrap(title.to_string(), Tokens::ui(12.5), t.text_dim);
- let pos = rect.left_top() + vec2(14.0, -galley.size().y / 2.0);
- ui.painter().rect_filled(egui::Rect::from_min_size(pos - vec2(5.0, 0.0), galley.size() + vec2(10.0, 0.0)), 0.0, t.panel_bg);
- ui.painter().galley(pos, galley, t.text_dim);
- ui.add_space(6.0);
-}
-
-fn checkbox(app: &mut FilmcraftApp, ui: &mut Ui, id: &str, value: &mut bool, label: &str) {
- let r = ui.checkbox(value, RichText::new(label).size(13.0));
- app.auto.add(id, r.rect, label);
-}
-
-fn number(app: &mut FilmcraftApp, ui: &mut Ui, id: &str, label: &str, value: &mut u32, range: (u32, u32), unit: &str) {
- ui.horizontal(|ui| {
- ui.add_sized(vec2(230.0, 24.0), egui::Label::new(RichText::new(label).size(13.0)));
- let r = ui.add_sized(vec2(90.0, 26.0), egui::DragValue::new(value).range(range.0..=range.1).speed(0.2));
- app.auto.add(id, r.rect, label);
- if !unit.is_empty() {
- ui.label(RichText::new(unit).size(13.0));
- }
- });
-}
-
-pub fn show_preferences(app: &mut FilmcraftApp, ctx: &egui::Context) -> bool {
- let t = app.tokens;
- let mut draft = app.file_dialogs.prefs_draft.clone().unwrap_or_else(|| app.session.prefs.auto_save.clone());
- let mut close = false;
- let status = app.session.execute("file.autoSaveStatus", json!({})).unwrap_or_default();
- let resp = egui::Modal::new(egui::Id::new("prefs-modal")).frame(modal_frame(&t)).show(ctx, |ui| {
- ui.set_width(780.0);
- // title bar
- let (bar, _) = ui.allocate_exact_size(vec2(780.0, 34.0), egui::Sense::hover());
- ui.painter().rect_filled(bar, CornerRadius { nw: 10, ne: 10, sw: 0, se: 0 }, t.header_bg);
- ui.painter().text(bar.center(), Align2::CENTER_CENTER, "Preferences", Tokens::semibold(13.0), t.text_dim);
- ui.horizontal_top(|ui| {
- ui.add_space(16.0);
- // category list
- ui.vertical(|ui| {
- ui.add_space(14.0);
- let (list, _) = ui.allocate_exact_size(vec2(190.0, 420.0), egui::Sense::hover());
- ui.painter().rect(list, 2.0, t.app_bg, Stroke::new(1.0, t.separator), egui::StrokeKind::Inside);
- let row = egui::Rect::from_min_size(list.min + vec2(2.0, 4.0), vec2(186.0, 24.0));
- ui.painter().rect_filled(row, 0.0, t.row_selected);
- ui.painter().text(row.left_center() + vec2(8.0, 0.0), Align2::LEFT_CENTER, "Auto Save", Tokens::ui(13.0), t.text);
- app.auto.add("prefs.category.autoSave", row, "Auto Save");
- });
- ui.add_space(16.0);
- ui.vertical(|ui| {
- ui.set_width(540.0);
- ui.add_space(14.0);
- group(ui, &t, "Local Projects", |ui| {
- checkbox(app, ui, "prefs.autoSave.enabled", &mut draft.enabled, "Automatically save projects");
- ui.add_enabled_ui(draft.enabled, |ui| {
- number(app, ui, "prefs.autoSave.intervalMinutes", "Automatically Save Every:", &mut draft.interval_minutes, (1, 1440), "minute(s)");
- number(app, ui, "prefs.autoSave.maxVersions", "Maximum Project Versions:", &mut draft.max_versions, (1, 1000), "");
- checkbox(app, ui, "prefs.autoSave.saveCurrentProject", &mut draft.save_current_project, "Auto Save also saves the current project(s)");
- });
- let dir = status["autoSaveDir"].as_str().unwrap_or("Auto-Save folder next to the project");
- ui.label(RichText::new(format!("Auto-saves go to: {dir}")).size(11.5).color(t.text_dim));
- });
- group(ui, &t, "Crash Recovery", |ui| {
- checkbox(app, ui, "prefs.autoSave.recoveryJournal", &mut draft.recovery_journal, "Keep a recovery copy of unsaved changes");
- ui.add_enabled_ui(draft.recovery_journal, |ui| {
- number(
- app,
- ui,
- "prefs.autoSave.recoveryIntervalSeconds",
- "Update it at least every:",
- &mut draft.recovery_interval_seconds,
- (1, 600),
- "second(s)",
- );
- });
- ui.label(
- RichText::new("Changes are copied in the background a moment after each edit. If FilmCraft quits unexpectedly, they are offered the next time it starts.")
- .size(11.5)
- .color(t.text_dim),
- );
- if let Some(dir) = status["sessionDir"].as_str() {
- ui.label(RichText::new(format!("Location: {dir}")).size(11.5).color(t.text_dim));
- }
- let last = match (status["lastAutoSaveAt"].as_str(), status["lastJournalAt"].as_str()) {
- (Some(a), Some(j)) => format!("Last auto-save {a} · last recovery copy {j}"),
- (Some(a), None) => format!("Last auto-save {a}"),
- (None, Some(j)) => format!("Last recovery copy {j}"),
- (None, None) => String::new(),
- };
- if !last.is_empty() {
- ui.label(RichText::new(last).size(11.5).color(t.text_dim));
- }
- });
- });
- });
- ui.add_space(14.0);
- ui.horizontal(|ui| {
- ui.add_space(16.0);
- if button(app, ui, "prefs.reset", "Reset…", false) {
- draft = AutoSavePrefs::default();
- }
- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- ui.add_space(16.0);
- if button(app, ui, "prefs.ok", "OK", true) {
- let values = serde_json::to_value(&draft).unwrap_or_default();
- let map: serde_json::Map<String, serde_json::Value> =
- values.as_object().map(|m| m.iter().map(|(k, v)| (format!("autoSave.{k}"), v.clone())).collect()).unwrap_or_default();
- if let Err(e) = app.session.execute("prefs.set", json!({ "values": map })) {
- app.ui.status = e.to_string();
- }
- close = true;
- }
- if button(app, ui, "prefs.cancel", "Cancel", false) {
- close = true;
- }
- });
- });
- ui.add_space(14.0);
- });
- if resp.should_close() || ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
- close = true;
- }
- app.file_dialogs.prefs_draft = if close { None } else { Some(draft) };
- !close
-}
-
pub fn show_recovery(app: &mut FilmcraftApp, ctx: &egui::Context) -> bool {
let t = app.tokens;
let list = app.session.execute("file.recoveryList", json!({})).unwrap_or_default();
@@ -275,7 +136,7 @@ pub fn show_revert(app: &mut FilmcraftApp, ctx: &egui::Context) -> bool {
/// Draw the dialog if it is one of ours; returns Some(still open).
pub fn show(app: &mut FilmcraftApp, ctx: &egui::Context, d: Dialog) -> Option<bool> {
match d {
- Dialog::Preferences => Some(show_preferences(app, ctx)),
+ Dialog::Preferences => Some(crate::panels::settings::show(app, ctx)),
Dialog::Recovery => Some(show_recovery(app, ctx)),
Dialog::RevertConfirm => Some(show_revert(app, ctx)),
_ => None,
diff --git a/crates/ui-egui/src/panels/graphics.rs b/crates/ui-egui/src/panels/graphics.rs
index 5f3a56d59..464a9914b 100644
--- a/crates/ui-egui/src/panels/graphics.rs
+++ b/crates/ui-egui/src/panels/graphics.rs
@@ -987,7 +987,7 @@ pub fn properties(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
egui::ScrollArea::vertical().id_salt("gfx-props-scroll").auto_shrink([false, false]).show(&mut bui, |ui| {
// header
let (hr, _) = ui.allocate_exact_size(vec2(ui.available_width(), 30.0), Sense::hover());
- let lc = it.label.rgb();
+ let lc = app.session.prefs.labels.rgb(it.label);
ui.painter().rect_filled(Rect::from_center_size(pos2(hr.min.x + 8.0, hr.center().y), vec2(12.0, 12.0)), 2.0, Color32::from_rgb(lc[0], lc[1], lc[2]));
ui.painter().text(pos2(hr.min.x + 22.0, hr.center().y), Align2::LEFT_CENTER, &it.name, Tokens::semibold(12.5), t.text);
// ---- layers (front first)
diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs
index f959783c0..3b36c3d21 100644
--- a/crates/ui-egui/src/panels/mod.rs
+++ b/crates/ui-egui/src/panels/mod.rs
@@ -22,6 +22,7 @@ pub mod monitor_view;
pub mod multicam;
pub mod presets;
pub mod project;
+pub mod settings;
pub mod shortcuts_dialog;
pub mod text;
pub mod timeline;
diff --git a/crates/ui-egui/src/panels/project.rs b/crates/ui-egui/src/panels/project.rs
index 2fb5458f5..390a1a28e 100644
--- a/crates/ui-egui/src/panels/project.rs
+++ b/crates/ui-egui/src/panels/project.rs
@@ -279,7 +279,7 @@ fn list_bin(
let cols = columns(r);
let x = r.min.x + 6.0 + depth as f32 * 14.0;
// label swatch
- let lc = it.label.rgb();
+ let lc = app.session.prefs.labels.rgb(it.label);
ui.painter().rect_filled(Rect::from_center_size(pos2(x + 5.0, r.center().y), vec2(8.0, 12.0)), 1.5, Color32::from_rgb(lc[0], lc[1], lc[2]));
icons::paint(ui.painter(), Rect::from_center_size(pos2(x + 20.0, r.center().y), vec2(14.0, 14.0)), item_icon(&it.kind), t.icon);
let name_clip = ui.painter().with_clip_rect(Rect::from_min_max(r.min, pos2(cols[1] - 6.0, r.max.y)));
@@ -444,7 +444,7 @@ fn icon_view(app: &mut FilmcraftApp, ui: &mut egui::Ui, root: &Bin, filter: &str
if selected {
ui.painter().rect_stroke(r, 3.0, Stroke::new(2.0, t.accent), StrokeKind::Outside);
}
- let lc = it.label.rgb();
+ let lc = app.session.prefs.labels.rgb(it.label);
ui.painter().rect_filled(Rect::from_min_size(pos2(r.min.x, r.max.y + 6.0), vec2(8.0, 12.0)), 1.5, Color32::from_rgb(lc[0], lc[1], lc[2]));
let secs = dur.seconds().max(0.0) as u64;
let dtext =
diff --git a/crates/ui-egui/src/panels/settings.rs b/crates/ui-egui/src/panels/settings.rs
new file mode 100644
index 000000000..564fbb594
--- /dev/null
+++ b/crates/ui-egui/src/panels/settings.rs
@@ -0,0 +1,605 @@
+//! The Settings dialog (app menu ▸ Settings ▸ <category>; Edit ▸ Preferences in the in-window
+//! menu bar; General is Cmd+,). One window titled "Preferences": the category list on the left,
+//! the category's fields on the right, Help / Reset… / Cancel / OK at the bottom. The page layout
+//! comes from the engine's field schema ([`filmcraft_engine::settings::categories`]); edits go to a
+//! draft (`UiState::settings`, serde so `ui.inspect` / `ui.set` reach it) and are applied with
+//! `prefs.set` on OK.
+//!
+//! Automation ids: `settings.category.<id>` (list rows), `settings.<key>` for every control (the
+//! preference key, e.g. `settings.timeline.stillImageDuration`), `settings.<key>.<value>` for the
+//! items of an open dropdown, `settings.<key>.browse` (folder fields), `settings.<key>.hex`
+//! (colour fields), `settings.labels.colors.<label>.name|color`, `settings.mediaCache.clean`,
+//! `settings.help`, `settings.reset`, `settings.cancel`, `settings.ok`.
+
+use egui::{Align, Align2, Color32, CornerRadius, Frame, Layout, Margin, Rect, RichText, Sense, Stroke, Ui, vec2};
+use filmcraft_engine::settings::{self, DeviceList, Field, Kind, Row};
+use filmcraft_project::Label;
+use serde::{Deserialize, Serialize};
+use serde_json::{Map, Value, json};
+
+use crate::theme::Tokens;
+use crate::{AudioDevices, Dialog, FilmcraftApp};
+
+/// Window size (Premiere's is 927 × 724 pt).
+const W: f32 = 900.0;
+const BODY_H: f32 = 600.0;
+const LIST_W: f32 = 216.0;
+const ROW_H: f32 = 24.6;
+const LABEL_W: f32 = 250.0;
+
+/// The open dialog: current page and the preferences being edited (the whole preferences
+/// document, as `prefs.get` returns it).
+#[derive(Clone, Debug, Default, Serialize, Deserialize)]
+pub struct SettingsDraft {
+ pub page: String,
+ pub values: Value,
+ /// Result of the last button (Delete… media cache) or an error from OK.
+ #[serde(default)]
+ pub message: String,
+ /// `mediaCache.info` when the Media Cache page was shown.
+ #[serde(default)]
+ pub cache_info: Value,
+ /// Audio devices reported by the platform (Audio Hardware page).
+ #[serde(default)]
+ pub devices: Option<AudioDevices>,
+}
+
+/// Open the dialog on a category page.
+pub fn open(app: &mut FilmcraftApp, page: &str) -> Result<Value, String> {
+ let cat = settings::category(page).ok_or_else(|| format!("unknown settings category `{page}`"))?;
+ app.ui.settings = Some(SettingsDraft { page: cat.id.into(), values: app.session.prefs.to_value(), ..Default::default() });
+ app.dialog = Some(Dialog::Preferences);
+ Ok(json!({"dialog": "settings", "page": cat.id}))
+}
+
+/// `app.settings.<category>` (and the older `app.preferences[.autoSave]` ids).
+pub fn route(app: &mut FilmcraftApp, id: &str) -> Option<Result<Value, String>> {
+ if let Some(page) = id.strip_prefix("app.settings.") {
+ return Some(open(app, page));
+ }
+ match id {
+ "app.settings" => Some(open(app, "general")),
+ "app.preferences" | "app.preferences.autoSave" => Some(open(app, "autoSave")),
+ _ => None,
+ }
+}
+
+/// The colour of a label (Settings ▸ Labels).
+pub fn label_color(app: &FilmcraftApp, l: Label) -> Color32 {
+ let c = app.session.prefs.labels.rgb(l);
+ Color32::from_rgb(c[0], c[1], c[2])
+}
+
+/// Choose a theme from View ▸ Appearance or `ui.set`: stored as Settings ▸ Appearance ▸ Color Theme.
+pub fn set_theme(app: &mut FilmcraftApp, ctx: &egui::Context, k: crate::theme::ThemeKind) {
+ if let Err(e) = app.session.execute("prefs.set", json!({"key": "appearance.colorTheme", "value": k.pref_name()})) {
+ app.ui.status = e.to_string();
+ }
+ app.apply_prefs(ctx);
+ app.set_theme(ctx, k);
+}
+
+/// Patch the open dialog's draft (`ui.set {"settings": {"page": "trim", "values": {key: value}}}`).
+pub fn patch(app: &mut FilmcraftApp, p: &Value) -> Result<(), String> {
+ let d = app.ui.settings.as_mut().ok_or("the Settings dialog is not open")?;
+ if let Some(page) = p.get("page").and_then(Value::as_str) {
+ d.page = settings::category(page).ok_or_else(|| format!("unknown settings category `{page}`"))?.id.into();
+ }
+ if let Some(m) = p.get("values").and_then(Value::as_object) {
+ for (k, v) in m {
+ let slot = d.values.pointer_mut(&ptr(k)).ok_or_else(|| format!("unknown preference `{k}`"))?;
+ *slot = v.clone();
+ }
+ }
+ Ok(())
+}
+
+fn ptr(key: &str) -> String {
+ format!("/{}", key.replace('.', "/"))
+}
+
+fn get<'a>(v: &'a Value, key: &str) -> &'a Value {
+ v.pointer(&ptr(key)).unwrap_or(&Value::Null)
+}
+
+fn put(v: &mut Value, key: &str, x: Value) {
+ if let Some(s) = v.pointer_mut(&ptr(key)) {
+ *s = x;
+ }
+}
+
+/// Leaf values of `new` that differ from `old`, as dotted keys.
+fn diff(prefix: &str, old: &Value, new: &Value, out: &mut Map<String, Value>) {
+ match (old, new) {
+ (Value::Object(a), Value::Object(b)) => {
+ for (k, nv) in b {
+ let key = if prefix.is_empty() { k.clone() } else { format!("{prefix}.{k}") };
+ diff(&key, a.get(k).unwrap_or(&Value::Null), nv, out);
+ }
+ }
+ _ if old != new && !prefix.is_empty() => {
+ out.insert(prefix.to_string(), new.clone());
+ }
+ _ => {}
+ }
+}
+
+fn modal_frame(t: &Tokens) -> Frame {
+ Frame::new().fill(t.panel_bg).stroke(Stroke::new(1.0, t.separator)).corner_radius(CornerRadius::same(10)).inner_margin(Margin::same(0))
+}
+
+fn button(app: &mut FilmcraftApp, ui: &mut Ui, id: &str, label: &str, primary: bool) -> bool {
+ let t = app.tokens;
+ let text = RichText::new(label).size(13.0).color(if primary { Color32::WHITE } else { t.text });
+ let b = egui::Button::new(text)
+ .min_size(vec2(82.0, 30.0))
+ .corner_radius(CornerRadius::same(15))
+ .fill(if primary { t.accent } else { Color32::TRANSPARENT })
+ .stroke(if primary { Stroke::NONE } else { Stroke::new(1.5, t.text_faint) });
+ let r = ui.add(b);
+ app.auto.add(id, r.rect, label);
+ r.clicked()
+}
+
+/// Premiere's "fieldset" group box: a 1-px rounded border with the title inset in the top edge.
+fn group(ui: &mut Ui, t: &Tokens, title: &str, add: impl FnOnce(&mut Ui)) {
+ ui.add_space(10.0);
+ let r = Frame::new()
+ .stroke(Stroke::new(1.0, t.field_border))
+ .corner_radius(CornerRadius::same(4))
+ .inner_margin(Margin { left: 14, right: 14, top: 16, bottom: 10 })
+ .show(ui, |ui| {
+ ui.set_width(ui.available_width());
+ ui.spacing_mut().item_spacing.y = 8.0;
+ add(ui);
+ });
+ let rect = r.response.rect;
+ let galley = ui.painter().layout_no_wrap(title.to_string(), Tokens::ui(12.0), t.text_dim);
+ let pos = rect.left_top() + vec2(12.0, -galley.size().y / 2.0);
+ ui.painter().rect_filled(Rect::from_min_size(pos - vec2(4.0, 0.0), galley.size() + vec2(8.0, 0.0)), 0.0, t.panel_bg);
+ ui.painter().galley(pos, galley, t.text_dim);
+ ui.add_space(4.0);
+}
+
+/// A right-aligned field label in the fixed label column.
+fn field_label(ui: &mut Ui, text: &str) {
+ let w = LABEL_W.min(ui.available_width() * 0.45);
+ ui.allocate_ui_with_layout(vec2(w, 24.0), Layout::right_to_left(Align::Center), |ui| {
+ if !text.is_empty() {
+ ui.label(RichText::new(format!("{text}:")).size(12.5));
+ }
+ });
+}
+
+fn unit(ui: &mut Ui, u: &str) {
+ if !u.is_empty() {
+ ui.label(RichText::new(u).size(12.5));
+ }
+}
+
+fn choice_text(v: &Value) -> String {
+ match v {
+ Value::String(s) => s.clone(),
+ Value::Number(n) => n.to_string(),
+ Value::Bool(b) => b.to_string(),
+ _ => String::new(),
+ }
+}
+
+/// A dropdown of (value, label) options; returns the chosen value.
+fn combo(app: &mut FilmcraftApp, ui: &mut Ui, key: &str, current: &str, opts: &[(String, String)], width: f32) -> Option<String> {
+ let shown = opts.iter().find(|o| o.0 == current).map(|o| o.1.clone()).unwrap_or_else(|| current.to_string());
+ let mut chosen = None;
+ let mut items: Vec<(String, Rect, String)> = Vec::new();
+ let r = egui::ComboBox::from_id_salt(("settings", key)).selected_text(RichText::new(&shown).size(12.5)).width(width).height(480.0).show_ui(ui, |ui| {
+ for (v, l) in opts {
+ let r = ui.selectable_label(v == current, l);
+ items.push((format!("settings.{key}.{v}"), r.rect, l.clone()));
+ if r.clicked() {
+ chosen = Some(v.clone());
+ }
+ }
+ });
+ app.auto.add(&format!("settings.{key}"), r.response.rect, &shown);
+ for (id, rect, l) in items {
+ app.auto.add(&id, rect, &l);
+ }
+ chosen
+}
+
+fn static_opts(o: &[(&str, &str)]) -> Vec<(String, String)> {
+ o.iter().map(|(v, l)| (v.to_string(), l.to_string())).collect()
+}
+
+fn device_opts(app: &mut FilmcraftApp, d: &mut SettingsDraft, list: DeviceList) -> Vec<(String, String)> {
+ if d.devices.is_none() {
+ d.devices = Some(app.audio.as_ref().map(|a| a.devices()).unwrap_or_default());
+ }
+ let dev = d.devices.clone().unwrap_or_default();
+ let names = match list {
+ DeviceList::Hosts => dev.hosts,
+ DeviceList::Inputs => dev.inputs,
+ DeviceList::Outputs => dev.outputs,
+ };
+ let mut v = vec![(String::new(), "System Default".to_string())];
+ v.extend(names.into_iter().map(|n| (n.clone(), n)));
+ v
+}
+
+fn number(app: &mut FilmcraftApp, ui: &mut Ui, key: &str, value: f64, range: (f64, f64), decimals: usize, label: &str) -> Option<f64> {
+ let mut x = value;
+ let speed = ((range.1 - range.0) / 2000.0).clamp(0.05, 1.0);
+ let dv = egui::DragValue::new(&mut x).range(range.0..=range.1).speed(speed).fixed_decimals(decimals);
+ let r = ui.add_sized(vec2(84.0, 24.0), dv);
+ app.auto.add(&format!("settings.{key}"), r.rect, label);
+ (r.changed() && x != value).then_some(x)
+}
+
+fn draw_field(app: &mut FilmcraftApp, ui: &mut Ui, d: &mut SettingsDraft, f: &Field) {
+ let enabled = f.enabled_by.is_none_or(|k| get(&d.values, k).as_bool().unwrap_or(true));
+ let cur = get(&d.values, f.key).clone();
+ ui.add_enabled_ui(enabled, |ui| {
+ ui.horizontal(|ui| {
+ if f.indent {
+ ui.add_space(22.0);
+ }
+ match f.kind {
+ Kind::Bool => {
+ let mut b = cur.as_bool().unwrap_or(false);
+ let r = ui.checkbox(&mut b, RichText::new(f.label).size(12.5));
+ app.auto.add(&format!("settings.{}", f.key), r.rect, f.label);
+ if r.changed() {
+ put(&mut d.values, f.key, json!(b));
+ }
+ }
+ Kind::Int { min, max, unit: u } => {
+ field_label(ui, f.label);
+ if let Some(x) = number(app, ui, f.key, cur.as_f64().unwrap_or(min), (min, max), 0, f.label) {
+ put(&mut d.values, f.key, json!(x.round() as u64));
+ }
+ unit(ui, u);
+ }
+ Kind::Float { min, max, decimals, unit: u } => {
+ field_label(ui, f.label);
+ if let Some(x) = number(app, ui, f.key, cur.as_f64().unwrap_or(min), (min, max), decimals, f.label) {
+ put(&mut d.values, f.key, json!(x));
+ }
+ unit(ui, u);
+ }
+ Kind::Duration { unit_key } => {
+ field_label(ui, f.label);
+ let u = choice_text(get(&d.values, unit_key));
+ let (range, decimals) = if u == "frames" { ((1.0, 100_000.0), 0) } else { ((0.01, 3600.0), 2) };
+ if let Some(x) = number(app, ui, f.key, cur.as_f64().unwrap_or(1.0), range, decimals, f.label) {
+ put(&mut d.values, f.key, json!(if u == "frames" { x.round() } else { x }));
+ }
+ if let Some(v) = combo(app, ui, unit_key, &u, &static_opts(settings::DURATION_UNITS), 90.0) {
+ put(&mut d.values, unit_key, json!(v));
+ }
+ }
+ Kind::Choice(opts) => {
+ field_label(ui, f.label);
+ if let Some(v) = combo(app, ui, f.key, &choice_text(&cur), &static_opts(opts), 300.0) {
+ let x = if cur.is_number() { v.parse::<u64>().map(Value::from).unwrap_or(json!(v)) } else { json!(v) };
+ put(&mut d.values, f.key, x);
+ }
+ }
+ Kind::Device(list) => {
+ field_label(ui, f.label);
+ let opts = device_opts(app, d, list);
+ if let Some(v) = combo(app, ui, f.key, &choice_text(&cur), &opts, 300.0) {
+ put(&mut d.values, f.key, json!(v));
+ }
+ }
+ Kind::Label => {
+ field_label(ui, f.label);
+ let opts: Vec<(String, String)> = Label::ALL.iter().map(|l| (l.name().to_string(), app.session.prefs.labels.name(*l))).collect();
+ let cur_s = choice_text(&cur);
+ if let Some(l) = Label::from_name(&cur_s) {
+ let (sw, _) = ui.allocate_exact_size(vec2(14.0, 14.0), Sense::hover());
+ let c = settings::parse_hex(&choice_text(get(&d.values, &format!("labels.colors.{}.color", settings::label_id(l))))).unwrap_or(l.rgb());
+ ui.painter().rect_filled(sw, 2.0, Color32::from_rgb(c[0], c[1], c[2]));
+ }
+ if let Some(v) = combo(app, ui, f.key, &cur_s, &opts, 160.0) {
+ put(&mut d.values, f.key, json!(v));
+ }
+ }
+ Kind::Text | Kind::Font | Kind::Path => {
+ field_label(ui, f.label);
+ let mut s = choice_text(&cur);
+ let hint = match f.kind {
+ Kind::Path => "Default location",
+ Kind::Font => "Font family",
+ _ => "",
+ };
+ let r = ui.add(egui::TextEdit::singleline(&mut s).desired_width(if matches!(f.kind, Kind::Path) { 300.0 } else { 220.0 }).hint_text(hint));
+ app.auto.add(&format!("settings.{}", f.key), r.rect, f.label);
+ if r.changed() {
+ put(&mut d.values, f.key, json!(s));
+ }
+ if matches!(f.kind, Kind::Path) {
+ let b = ui.button("Browse…");
+ app.auto.add(&format!("settings.{}.browse", f.key), b.rect, "Browse…");
+ if b.clicked()
+ && let Some(dir) = app.hooks.pick_folder.as_mut().and_then(|p| p())
+ {
+ put(&mut d.values, f.key, json!(dir));
+ }
+ }
+ }
+ Kind::Color => {
+ field_label(ui, f.label);
+ color_field(app, ui, d, f.key, f.label);
+ }
+ }
+ });
+ });
+}
+
+/// A colour swatch (opens a picker) and its `#rrggbb` text.
+fn color_field(app: &mut FilmcraftApp, ui: &mut Ui, d: &mut SettingsDraft, key: &str, label: &str) {
+ let hex = choice_text(get(&d.values, key));
+ let mut rgb = settings::parse_hex(&hex).unwrap_or([128, 128, 128]);
+ let r = egui::color_picker::color_edit_button_srgb(ui, &mut rgb);
+ app.auto.add(&format!("settings.{key}"), r.rect, label);
+ if r.changed() {
+ put(&mut d.values, key, json!(settings::hex(rgb)));
+ }
+ let mut text = choice_text(get(&d.values, key));
+ let t = ui.add(egui::TextEdit::singleline(&mut text).desired_width(70.0).font(egui::TextStyle::Monospace));
+ app.auto.add(&format!("settings.{key}.hex"), t.rect, label);
+ if t.changed() && settings::parse_hex(&text).is_some() {
+ put(&mut d.values, key, json!(settings::hex(settings::parse_hex(&text).unwrap_or(rgb))));
+ }
+}
+
+fn note(ui: &mut Ui, t: &Tokens, text: &str) {
+ ui.add(egui::Label::new(RichText::new(text).size(11.5).color(t.text_dim)).wrap());
+}
+
+fn mb(bytes: u64) -> String {
+ if bytes >= 1 << 30 { format!("{:.1} GB", bytes as f64 / (1u64 << 30) as f64) } else { format!("{:.1} MB", bytes as f64 / (1u64 << 20) as f64) }
+}
+
+fn custom(app: &mut FilmcraftApp, ui: &mut Ui, d: &mut SettingsDraft, name: &str) {
+ let t = app.tokens;
+ match name {
+ "labelColors" => {
+ let tt = t;
+ group(ui, &tt, "Label Colors", |ui| {
+ egui::Grid::new("settings-label-colors").num_columns(2).spacing(vec2(10.0, 5.0)).show(ui, |ui| {
+ for l in Label::ALL.iter() {
+ let id = settings::label_id(*l);
+ let nk = format!("labels.colors.{id}.name");
+ let mut name = choice_text(get(&d.values, &nk));
+ let r = ui.add_sized(vec2(136.0, 22.0), egui::TextEdit::singleline(&mut name));
+ app.auto.add(&format!("settings.{nk}"), r.rect, l.name());
+ if r.changed() {
+ put(&mut d.values, &nk, json!(name));
+ }
+ let ck = format!("labels.colors.{id}.color");
+ let mut rgb = settings::parse_hex(&choice_text(get(&d.values, &ck))).unwrap_or(l.rgb());
+ let c = egui::color_picker::color_edit_button_srgb(ui, &mut rgb);
+ app.auto.add(&format!("settings.{ck}"), c.rect, l.name());
+ if c.changed() {
+ put(&mut d.values, &ck, json!(settings::hex(rgb)));
+ }
+ ui.end_row();
+ }
+ });
+ });
+ }
+ "memoryInfo" => {
+ let (used, budget) = app.frames.cache_usage();
+ note(ui, &t, &format!("Decoded frames held for the monitors and thumbnails: {} of {}.", mb(used as u64), mb(budget as u64)));
+ note(ui, &t, "FilmCraft keeps the rest of the RAM free for other applications.");
+ }
+ "mediaCacheInfo" => {
+ if d.cache_info.is_null() {
+ d.cache_info = app.session.execute("mediaCache.info", json!({})).unwrap_or(json!({}));
+ }
+ let loc = d.cache_info["location"].as_str().unwrap_or("not available in this session").to_string();
+ let size = mb(d.cache_info["bytes"].as_u64().unwrap_or(0));
+ let files = d.cache_info["files"].as_u64().unwrap_or(0);
+ note(ui, &t, &format!("Currently: {loc} — {files} file(s), {size}"));
+ }
+ "outputMapping" => {
+ let ch = d.devices.as_ref().map(|x| x.output_channels).unwrap_or(0);
+ let l = get(&d.values, "audioHardware.mapLeft").as_u64().unwrap_or(0) + 1;
+ let r = get(&d.values, "audioHardware.mapRight").as_u64().unwrap_or(1) + 1;
+ let dev = if ch > 0 { format!(" ({ch} output channels)") } else { String::new() };
+ note(
+ ui,
+ &t,
+ &format!("Programme left → device output {l}, right → device output {r}{dev}. Outputs beyond the device's channels fall back to 1 and 2."),
+ );
+ }
+ "autoSaveStatus" => {
+ let status = app.session.execute("file.autoSaveStatus", json!({})).unwrap_or_default();
+ if let Some(dir) = status["autoSaveDir"].as_str() {
+ note(ui, &t, &format!("Auto-saves go to: {dir}"));
+ }
+ if let Some(dir) = status["sessionDir"].as_str() {
+ note(ui, &t, &format!("Recovery copy: {dir}"));
+ }
+ let last = match (status["lastAutoSaveAt"].as_str(), status["lastJournalAt"].as_str()) {
+ (Some(a), Some(j)) => format!("Last auto-save {a} · last recovery copy {j}"),
+ (Some(a), None) => format!("Last auto-save {a}"),
+ (None, Some(j)) => format!("Last recovery copy {j}"),
+ (None, None) => String::new(),
+ };
+ if !last.is_empty() {
+ note(ui, &t, &last);
+ }
+ }
+ _ => {}
+ }
+}
+
+fn rows(app: &mut FilmcraftApp, ui: &mut Ui, d: &mut SettingsDraft, list: &[Row]) {
+ let t = app.tokens;
+ let mut skip = false;
+ for (i, r) in list.iter().enumerate() {
+ if std::mem::take(&mut skip) {
+ continue;
+ }
+ // Labels: Label Colors on the left, the row after it (Label Defaults) on the right
+ if matches!(r, Row::Custom("labelColors")) {
+ let next = list.get(i + 1).copied();
+ ui.horizontal_top(|ui| {
+ ui.allocate_ui(vec2(250.0, 0.0), |ui| {
+ ui.vertical(|ui| custom(app, ui, d, "labelColors"));
+ });
+ ui.add_space(12.0);
+ if let Some(n) = next {
+ ui.vertical(|ui| rows(app, ui, d, &[n]));
+ }
+ });
+ skip = true;
+ continue;
+ }
+ match r {
+ Row::Field(f) => draw_field(app, ui, d, f),
+ Row::Group(title, inner) => group(ui, &t, title, |ui| rows(app, ui, d, inner)),
+ Row::Note(text) => note(ui, &t, text),
+ Row::Button { id, label, command } => {
+ ui.horizontal(|ui| {
+ field_label(ui, "Remove Media Cache Files");
+ let b = ui.button(*label);
+ app.auto.add(&format!("settings.{id}"), b.rect, label);
+ if b.clicked() {
+ d.message = match app.session.execute(command, json!({})) {
+ Ok(v) => format!("Deleted {} file(s), {}.", v["files"].as_u64().unwrap_or(0), mb(v["bytes"].as_u64().unwrap_or(0))),
+ Err(e) => e.to_string(),
+ };
+ d.cache_info = Value::Null;
+ }
+ });
+ }
+ Row::Custom(name) => custom(app, ui, d, name),
+ }
+ ui.add_space(2.0);
+ }
+}
+
+/// Draw the dialog; returns whether it stays open.
+pub fn show(app: &mut FilmcraftApp, ctx: &egui::Context) -> bool {
+ let Some(mut d) = app.ui.settings.take() else { return false };
+ let t = app.tokens;
+ let mut close = false;
+ let mut apply = false;
+ let resp = egui::Modal::new(egui::Id::new("settings-modal")).frame(modal_frame(&t)).show(ctx, |ui| {
+ ui.set_width(W);
+ // title bar (Premiere keeps "Preferences" as the window title)
+ let (bar, _) = ui.allocate_exact_size(vec2(W, 30.0), Sense::hover());
+ ui.painter().rect_filled(bar, CornerRadius { nw: 10, ne: 10, sw: 0, se: 0 }, t.header_bg);
+ ui.painter().text(bar.center(), Align2::CENTER_CENTER, "Preferences", Tokens::semibold(13.0), t.text_dim);
+ app.auto.add("settings.window", bar, "Preferences");
+ ui.add_space(14.0);
+ ui.horizontal_top(|ui| {
+ ui.add_space(20.0);
+ // category list
+ let (list, _) = ui.allocate_exact_size(vec2(LIST_W, BODY_H), Sense::hover());
+ ui.painter().rect(list, 2.0, t.field_bg, Stroke::new(1.0, t.separator), egui::StrokeKind::Inside);
+ for (i, c) in settings::categories().iter().enumerate() {
+ let row = Rect::from_min_size(list.min + vec2(1.0, 1.0 + i as f32 * ROW_H), vec2(LIST_W - 2.0, ROW_H));
+ let r = ui.interact(row, egui::Id::new(("settings-cat", c.id)), Sense::click());
+ let sel = d.page == c.id;
+ if sel {
+ ui.painter().rect_filled(row, 0.0, t.row_alt);
+ } else if r.hovered() {
+ ui.painter().rect_filled(row, 0.0, t.hover.gamma_multiply(0.6));
+ }
+ ui.painter().text(row.left_center() + vec2(8.0, 0.0), Align2::LEFT_CENTER, c.title, Tokens::ui(12.5), if sel { t.text } else { t.text_dim });
+ app.auto.add(&format!("settings.category.{}", c.id), row, c.title);
+ if r.clicked() {
+ d.page = c.id.into();
+ d.message.clear();
+ }
+ }
+ ui.add_space(20.0);
+ // the page
+ let Some(cat) = settings::category(&d.page) else { return };
+ ui.vertical(|ui| {
+ ui.set_width(W - LIST_W - 60.0);
+ ui.set_height(BODY_H);
+ egui::ScrollArea::vertical().id_salt(("settings-page", cat.id)).auto_shrink([false, false]).max_height(BODY_H).show(ui, |ui| {
+ ui.spacing_mut().item_spacing.y = 6.0;
+ rows(app, ui, &mut d, cat.rows);
+ if !d.message.is_empty() {
+ ui.add_space(6.0);
+ note(ui, &t, &d.message);
+ }
+ });
+ });
+ });
+ ui.add_space(14.0);
+ ui.horizontal(|ui| {
+ ui.add_space(20.0);
+ if button(app, ui, "settings.help", "Help", false) {
+ crate::links::open(ctx, &format!("{}/blob/main/docs/project-files.md#settings", crate::links::GITHUB));
+ }
+ if button(app, ui, "settings.reset", "Reset…", false) {
+ // this category back to its defaults (OK applies it)
+ let defaults = filmcraft_engine::autosave::Preferences::default().to_value();
+ let keep = get(&d.values, "general.recentProjects").clone();
+ d.values[d.page.as_str()] = defaults[d.page.as_str()].clone();
+ put(&mut d.values, "general.recentProjects", keep);
+ }
+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
+ ui.add_space(20.0);
+ if button(app, ui, "settings.ok", "OK", true) {
+ apply = true;
+ }
+ if button(app, ui, "settings.cancel", "Cancel", false) {
+ close = true;
+ }
+ });
+ });
+ ui.add_space(14.0);
+ });
+ if apply {
+ let mut changes = Map::new();
+ diff("", &app.session.prefs.to_value(), &d.values, &mut changes);
+ match if changes.is_empty() { Ok(Value::Null) } else { app.session.execute("prefs.set", json!({ "values": changes })) } {
+ Ok(_) => {
+ close = true;
+ app.apply_prefs(ctx);
+ }
+ Err(e) => d.message = e.to_string(),
+ }
+ }
+ if resp.should_close() || ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
+ close = true;
+ }
+ if !close {
+ app.ui.settings = Some(d);
+ }
+ !close
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn diff_lists_changed_leaves() {
+ let a = json!({"timeline": {"x": 1, "y": "a"}, "labels": {"colors": {"rose": {"name": "Rose"}}}});
+ let b = json!({"timeline": {"x": 2, "y": "a"}, "labels": {"colors": {"rose": {"name": "Hero"}}}});
+ let mut out = Map::new();
+ diff("", &a, &b, &mut out);
+ assert_eq!(Value::Object(out), json!({"timeline.x": 2, "labels.colors.rose.name": "Hero"}));
+ }
+
+ #[test]
+ fn selection_tool_trim_kinds() {
+ use crate::panels::timeline::selection_trim_kind as k;
+ assert_eq!(k(false, false, false, 0.0, true), "trim");
+ assert_eq!(k(false, true, false, 0.0, true), "ripple");
+ assert_eq!(k(false, true, true, 5.0, true), "roll");
+ // Settings ▸ Trim ▸ Allow Selection tool to choose Roll and Ripple trims without modifier key
+ assert_eq!(k(true, false, false, 1.0, true), "roll");
+ assert_eq!(k(true, false, false, 6.0, true), "ripple");
+ assert_eq!(k(true, false, false, 1.0, false), "ripple", "no clip on the other side: ripple");
+ }
+}
diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rs
index 317c79c7b..d97f7a887 100644
--- a/crates/ui-egui/src/panels/timeline.rs
+++ b/crates/ui-egui/src/panels/timeline.rs
@@ -107,9 +107,8 @@ pub fn zoom_about(v: &mut TimelineView, factor: f64, anchor_secs: f64, width: f3
v.target_scroll = (anchor_secs - x as f64 / new).max(0.0);
}
-fn label_color(l: filmcraft_project::Label) -> Color32 {
- let c = l.rgb();
- Color32::from_rgb(c[0], c[1], c[2])
+fn label_color(app: &FilmcraftApp, l: filmcraft_project::Label) -> Color32 {
+ crate::panels::settings::label_color(app, l)
}
pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
@@ -159,12 +158,21 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
v.scroll = v.target_scroll;
}
}
- // follow playhead while playing (page scroll)
- if app.playback.playing && app.ui.timeline.follow {
+ // follow playhead while playing (Settings ▸ Timeline ▸ Timeline Playback Auto-Scrolling)
+ let auto_scroll = app.session.prefs.timeline.auto_scroll.clone();
+ if app.playback.playing && app.ui.timeline.follow && auto_scroll != "noScroll" {
let v = &mut app.ui.timeline;
- let px = (app.session.playhead().seconds() - v.scroll) * v.pps;
- if px > content.width() as f64 * 0.95 || px < 0.0 {
- v.target_scroll = (app.session.playhead().seconds() - content.width() as f64 * 0.05 / v.pps).max(0.0);
+ let ph = app.session.playhead().seconds();
+ let w = content.width() as f64;
+ let px = (ph - v.scroll) * v.pps;
+ if auto_scroll == "smoothScroll" {
+ // the playhead stays in the middle once it gets there
+ if px > w * 0.5 || px < 0.0 {
+ v.target_scroll = (ph - w * 0.5 / v.pps).max(0.0);
+ v.scroll = v.target_scroll;
+ }
+ } else if px > w * 0.95 || px < 0.0 {
+ v.target_scroll = (ph - w * 0.05 / v.pps).max(0.0);
v.scroll = v.target_scroll;
}
}
@@ -438,7 +446,7 @@ fn draw_clip(
t: &Tokens,
rate: FrameRate,
) {
- let base = label_color(it.label);
+ let base = label_color(app, it.label);
let inr = in_range(app, it);
let fill = if !it.enabled {
Color32::from_rgb(0x2a, 0x2a, 0x2a)
@@ -1106,6 +1114,37 @@ fn vertical_scrollbar(ui: &mut egui::Ui, bar: Rect, value: &mut f32, max: f32, i
let _ = t;
}
+/// How close (px) to a cut the Selection tool rolls instead of rippling when Settings ▸ Trim ▸
+/// "Allow Selection tool to choose Roll and Ripple trims without modifier key" is on.
+pub const ROLL_PX: f32 = 2.5;
+
+/// The trim the Selection tool starts at an edit point: Cmd+Shift = roll, Cmd = ripple. With the
+/// Trim setting on (`no_modifier`), no modifier is needed: right on the cut (when a clip is on the
+/// other side) rolls, elsewhere on the edge ripples. Otherwise a plain drag is a regular trim.
+pub fn selection_trim_kind(no_modifier: bool, cmd: bool, shift: bool, dist_px: f32, has_neighbour: bool) -> &'static str {
+ if cmd && shift {
+ "roll"
+ } else if cmd {
+ "ripple"
+ } else if no_modifier {
+ if has_neighbour && dist_px <= ROLL_PX { "roll" } else { "ripple" }
+ } else {
+ "trim"
+ }
+}
+
+/// Distance (px) from `x` to the cut at `clip`'s `edge`, and whether a clip touches that cut on
+/// the other side.
+fn edge_geometry(seq: &Sequence, layout: &Layout, track: filmcraft_project::TrackId, clip: ClipId, edge: filmcraft_edit::Edge, x: f32) -> (f32, bool) {
+ let Some(tr) = seq.track(track) else { return (f32::MAX, false) };
+ let Some(it) = tr.item(clip) else { return (f32::MAX, false) };
+ let (cut, neighbour) = match edge {
+ filmcraft_edit::Edge::Out => (it.end(), tr.items.iter().any(|x| x.start == it.end())),
+ filmcraft_edit::Edge::In => (it.start, tr.items.iter().any(|x| x.end() == it.start)),
+ };
+ ((layout.x_of(cut) - x).abs(), neighbour)
+}
+
/// Snap `t` to nearby candidates (edits, playhead, markers, in/out). Returns snapped tick.
fn snap(app: &mut FilmcraftApp, seq: &Sequence, layout: &Layout, t: Tick, exclude: &[ClipId]) -> Tick {
if !app.session.state.snapping {
@@ -1372,14 +1411,15 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
let _ = app.session.execute("timeline.select", json!({"clips": ids}));
None
}
- (Tool::Selection | Tool::Ripple | Tool::Rolling, Hit::Clip { clip, edge: Some(edge), .. }) if resp.clicked() => {
+ (Tool::Selection | Tool::Ripple | Tool::Rolling, Hit::Clip { clip, edge: Some(edge), track }) if resp.clicked() => {
// click an edge = select it as an edit point (trim mode); Shift adds
- let kind = if tool == Tool::Rolling || (mods.command && mods.shift) {
- "roll"
- } else if tool == Tool::Ripple || mods.command {
- "ripple"
- } else {
- "trim"
+ let kind = match tool {
+ Tool::Rolling => "roll",
+ Tool::Ripple => "ripple",
+ _ => {
+ let (dist, neighbour) = edge_geometry(seq, layout, track, clip, edge, p.x);
+ selection_trim_kind(app.session.prefs.trim.selection_tool_roll_ripple, mods.command, mods.shift, dist, neighbour)
+ }
};
let e = if edge == filmcraft_edit::Edge::In { "in" } else { "out" };
let r = app.session.execute("trim.selectEditPoint", json!({"clip": clip.0, "edge": e, "kind": kind, "add": mods.shift && !mods.command}));
@@ -1390,12 +1430,14 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
}
(Tool::Selection | Tool::Ripple | Tool::Rolling | Tool::RateStretch, Hit::Clip { clip, edge: Some(edge), track }) => {
let tr = seq.track(track).expect("track");
- let mode = if tool == Tool::Ripple || (tool == Tool::Selection && mods.command) {
- filmcraft_edit::TrimMode::Ripple
+ let sel_kind = if tool == Tool::Selection {
+ let (dist, neighbour) = edge_geometry(seq, layout, track, clip, edge, p.x);
+ selection_trim_kind(app.session.prefs.trim.selection_tool_roll_ripple, mods.command, mods.shift, dist, neighbour)
} else {
- filmcraft_edit::TrimMode::Regular
+ ""
};
- if tool == Tool::Rolling || (tool == Tool::Selection && mods.command && mods.shift) {
+ let mode = if tool == Tool::Ripple || sel_kind == "ripple" { filmcraft_edit::TrimMode::Ripple } else { filmcraft_edit::TrimMode::Regular };
+ if tool == Tool::Rolling || sel_kind == "roll" {
// roll the cut between this and its neighbour
let it = tr.item(clip).expect("clip");
let (l, r) = match edge {
@@ -1466,7 +1508,8 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
let new = match d {
Drag::Scrub => {
let mut tt = rate.snap_nearest(t_here.max(Tick::ZERO));
- if mods.shift {
+ // Shift snaps; Settings ▸ Timeline ▸ "Snap playhead in Timeline when Snap is enabled"
+ if mods.shift || app.session.prefs.timeline.snap_playhead {
tt = snap(app, seq, layout, tt, &[]);
}
app.session.set_playhead(tt);
@@ -1634,7 +1677,9 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
{
let row = layout.row_at(p.y).cloned();
let t = snap(app, seq, layout, rate.snap_nearest(layout.tick_at(p.x).max(Tick::ZERO)), &[]);
- let dur = app.session.project.item(item).map(|i| i.duration()).filter(|d| d.0 > 0).unwrap_or(app.session.project.settings.default_still_duration);
+ let still = app.session.prefs.timeline.still_duration(rate);
+ let is_still = app.session.project.item(item).and_then(|i| i.as_media()).is_some_and(|m| m.info.kind == filmcraft_media::MediaKind::Still);
+ let dur = app.session.project.item(item).map(|i| i.duration()).filter(|d| d.0 > 0 && !is_still).unwrap_or(still);
if let Some(row) = &row {
let r = Rect::from_min_max(pos2(layout.x_of(t), row.rect.min.y + 1.0), pos2(layout.x_of(t + dur), row.rect.max.y - 1.0));
ui.painter().rect_filled(r, 3.0, Color32::from_white_alpha(40));
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index ba71b96ea..22729080d 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -387,6 +387,9 @@ pub struct UiState {
/// Preferences ▸ Playback: play the rendered range when a preview render finishes.
#[serde(default = "yes")]
pub play_after_render: bool,
+ /// Settings dialog (open when Some): page and the values being edited.
+ #[serde(default)]
+ pub settings: Option<crate::panels::settings::SettingsDraft>,
/// Audio Track Mixer: effects and sends section expanded.
#[serde(default)]
pub mixer_fx_open: bool,
@@ -698,6 +701,7 @@ impl Default for UiState {
transcript_search: String::new(),
play_after_render: true,
mixer_fx_open: false,
+ settings: None,
audio_gain: AudioGainDraft::default(),
delete_tracks: DeleteTracksDraft::default(),
gfx_edit: None,
diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs
index 9f938841a..5191ef405 100644
--- a/crates/ui-egui/src/theme.rs
+++ b/crates/ui-egui/src/theme.rs
@@ -19,6 +19,21 @@ pub enum ThemeKind {
}
impl ThemeKind {
+ /// Settings ▸ Appearance ▸ Color Theme value (`darkest`, `dark`, `light`).
+ pub fn pref_name(self) -> &'static str {
+ match self {
+ ThemeKind::Dark => "darkest",
+ ThemeKind::Medium => "dark",
+ ThemeKind::Light => "light",
+ }
+ }
+ pub fn from_pref(s: &str) -> ThemeKind {
+ match s {
+ "dark" => ThemeKind::Medium,
+ "light" => ThemeKind::Light,
+ _ => ThemeKind::Dark,
+ }
+ }
pub fn from_name(s: &str) -> Option<ThemeKind> {
match s.to_ascii_lowercase().as_str() {
"dark" | "darkest" => Some(ThemeKind::Dark),
@@ -178,6 +193,31 @@ impl Tokens {
}
}
+ /// Settings ▸ Appearance on top of a theme: the highlight colour (selections, focus, primary
+ /// buttons) and accessible colour contrast (brighter secondary text and borders).
+ pub fn with_appearance(mut self, highlight: Option<[u8; 3]>, accessible_contrast: bool) -> Self {
+ if let Some([r, g, b]) = highlight {
+ let c = Color32::from_rgb(r, g, b);
+ let lift = |v: u8| v.saturating_add(16);
+ self.accent = c;
+ self.accent_hover = Color32::from_rgb(lift(r), lift(g), lift(b));
+ }
+ if accessible_contrast {
+ if self.kind == ThemeKind::Light {
+ self.text_dim = Color32::from_rgb(40, 40, 40);
+ self.text_faint = Color32::from_rgb(80, 80, 80);
+ self.field_border = Color32::from_rgb(110, 110, 110);
+ } else {
+ self.text_dim = self.text;
+ self.text_faint = Color32::from_rgb(0xa8, 0xa8, 0xa8);
+ self.tab_text = self.tab_text_active;
+ self.field_border = Color32::from_rgb(0x6a, 0x6a, 0x6a);
+ self.separator = Color32::from_rgb(0x50, 0x50, 0x50);
+ }
+ }
+ self
+ }
+
/// Mono font for timecode.
pub fn mono(size: f32) -> FontId {
FontId::new(size, FontFamily::Monospace)
diff --git a/crates/ui-egui/tests/settings_ui.rs b/crates/ui-egui/tests/settings_ui.rs
new file mode 100644
index 000000000..d28549eb9
--- /dev/null
+++ b/crates/ui-egui/tests/settings_ui.rs
@@ -0,0 +1,333 @@
+//! The Settings dialog, driven headless through the control channel: opening categories from the
+//! `app.settings.<category>` commands and Cmd+,, editing fields by automation id (checkboxes,
+//! dropdowns, numbers, label names), OK / Cancel / Escape / Reset… semantics, and settings that
+//! change the UI right away (theme, label names in the Edit ▸ Label menu, tooltips).
+//!
+//! With `FILMCRAFT_UI_SHOTS=<dir>` the test also renders the UI with wgpu and writes
+//! `settings-*.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(3);
+ r
+ }
+ fn click(&mut self, id: &str) {
+ self.ok("ui.click", json!({"id": id}));
+ self.frames(3);
+ }
+ fn has(&mut self, id: &str) -> bool {
+ let v = self.ok("ui.elements", json!({"prefix": id}));
+ v.as_array().unwrap().iter().any(|e| e["id"] == id)
+ }
+ fn inspect(&mut self) -> Value {
+ self.ok("ui.inspect", json!({}))
+ }
+ /// The open dialog's draft (`UiState::settings`), Null when closed.
+ fn draft(&mut self) -> Value {
+ self.inspect()["ui"]["settings"].clone()
+ }
+ fn pref(&mut self, key: &str) -> Value {
+ self.exec("prefs.get", json!({"key": key}))
+ }
+ fn shot(&mut self, name: &str) {
+ let Some(dir) = self.shots.clone() else { return };
+ self.frames(4);
+ let img = self.harness.render().expect("wgpu render");
+ std::fs::create_dir_all(&dir).unwrap();
+ img.save(dir.join(format!("settings-{name}.png"))).unwrap();
+ }
+}
+
+const CATEGORIES: [&str; 16] = [
+ "general",
+ "appearance",
+ "audio",
+ "audioHardware",
+ "autoSave",
+ "color",
+ "graphics",
+ "labels",
+ "media",
+ "mediaAnalysis",
+ "mediaCache",
+ "memory",
+ "playback",
+ "plugins",
+ "timeline",
+ "trim",
+];
+
+#[test]
+fn every_category_opens_from_its_command_and_menu() {
+ let mut d = Driver::demo();
+ let menu = d.ok("ui.menu.list", json!({}));
+ for c in CATEGORIES {
+ let id = format!("app.settings.{c}");
+ let item = menu.as_array().unwrap().iter().find(|m| m["id"] == id.as_str()).unwrap_or_else(|| panic!("no menu item {id}"));
+ assert_eq!(item["path"], json!(["Edit", "Preferences"]));
+ }
+ let general = menu.as_array().unwrap().iter().find(|m| m["id"] == "app.settings.general").unwrap();
+ assert_eq!(general["shortcut"], "Cmd+,");
+ for c in CATEGORIES {
+ let r = d.menu(&format!("app.settings.{c}"));
+ assert_eq!(r["page"], c);
+ let ui = d.inspect();
+ assert_eq!(ui["dialog"], "Preferences");
+ assert_eq!(ui["ui"]["settings"]["page"], c);
+ for other in CATEGORIES {
+ assert!(d.has(&format!("settings.category.{other}")), "category list row {other} on {c}");
+ }
+ assert!(d.has("settings.ok") && d.has("settings.cancel") && d.has("settings.reset") && d.has("settings.help"));
+ d.shot(c);
+ d.click("settings.cancel");
+ assert!(d.inspect()["dialog"].is_null(), "Cancel closes ({c})");
+ }
+ // the first field of a few pages, by automation id
+ for (c, field) in [
+ ("general", "settings.general.atStartup"),
+ ("timeline", "settings.timeline.stillImageDuration"),
+ ("timeline", "settings.timeline.stillImageUnit"),
+ ("trim", "settings.trim.largeTrimOffset"),
+ ("labels", "settings.labels.colors.violet.name"),
+ ("labels", "settings.labels.defaults.movie"),
+ ("autoSave", "settings.autoSave.enabled"),
+ ("mediaCache", "settings.mediaCache.clean"),
+ ("audioHardware", "settings.audioHardware.defaultOutput"),
+ ("appearance", "settings.appearance.highlightColor"),
+ ] {
+ d.menu(&format!("app.settings.{c}"));
+ assert!(d.has(field), "{field} on {c}");
+ d.click("settings.cancel");
+ }
+ assert!(d.exec("prefs.get", json!({})).is_object());
+ // unknown category
+ let r = d.call("ui.menu.invoke", json!({"id": "app.settings.nope"}));
+ assert_eq!(r["ok"], false);
+}
+
+#[test]
+fn cmd_comma_opens_general_and_the_list_switches_pages() {
+ let mut d = Driver::demo();
+ d.ok("ui.key", json!({"key": "Cmd+,"}));
+ d.frames(3);
+ assert_eq!(d.draft()["page"], "general");
+ d.click("settings.category.playback");
+ assert_eq!(d.draft()["page"], "playback");
+ assert!(d.has("settings.playback.stepManyFrames"));
+ assert!(!d.has("settings.general.atStartup"), "only the shown page's fields are on screen");
+ // Escape cancels
+ d.ok("ui.key", json!({"key": "Escape"}));
+ d.frames(3);
+ assert!(d.draft().is_null());
+}
+
+#[test]
+fn checkbox_edits_apply_on_ok_and_not_on_cancel() {
+ let mut d = Driver::demo();
+ d.menu("app.settings.trim");
+ assert_eq!(d.draft()["values"]["trim"]["selectionToolRollRipple"], false);
+ d.click("settings.trim.selectionToolRollRipple");
+ assert_eq!(d.draft()["values"]["trim"]["selectionToolRollRipple"], true, "the draft changes");
+ assert_eq!(d.pref("trim.selectionToolRollRipple"), false, "nothing applied before OK");
+ d.click("settings.cancel");
+ assert_eq!(d.pref("trim.selectionToolRollRipple"), false, "Cancel discards");
+
+ d.menu("app.settings.trim");
+ d.click("settings.trim.selectionToolRollRipple");
+ d.click("settings.category.timeline");
+ d.click("settings.timeline.snapPlayhead");
+ d.click("settings.ok");
+ assert!(d.draft().is_null(), "OK closes");
+ assert_eq!(d.pref("trim.selectionToolRollRipple"), true, "edits on several pages apply together");
+ assert_eq!(d.pref("timeline.snapPlayhead"), true);
+}
+
+#[test]
+fn dropdowns_numbers_and_reset() {
+ let mut d = Driver::demo();
+ d.menu("app.settings.timeline");
+ // dropdown: open it, pick an item by its automation id
+ d.click("settings.timeline.autoScroll");
+ assert!(d.has("settings.timeline.autoScroll.smoothScroll"), "items of the open dropdown carry ids");
+ d.click("settings.timeline.autoScroll.smoothScroll");
+ assert_eq!(d.draft()["values"]["timeline"]["autoScroll"], "smoothScroll");
+ // duration unit dropdown
+ d.click("settings.timeline.stillImageUnit");
+ d.click("settings.timeline.stillImageUnit.frames");
+ // numbers through ui.set on the draft (agents) …
+ d.ok("ui.set", json!({"settings": {"values": {"timeline.stillImageDuration": 48}}}));
+ d.click("settings.ok");
+ assert_eq!(d.pref("timeline.autoScroll"), "smoothScroll");
+ assert_eq!(d.pref("timeline.stillImageUnit"), "frames");
+ assert_eq!(d.pref("timeline.stillImageDuration"), 48.0);
+ // … or typed into the field
+ d.menu("app.settings.playback");
+ d.ok("ui.click", json!({"id": "settings.playback.stepManyFrames"}));
+ d.frames(3);
+ d.ok("ui.key", json!({"key": "Cmd+A"}));
+ d.ok("ui.type", json!({"text": "9"}));
+ d.ok("ui.key", json!({"key": "Enter"}));
+ d.frames(3);
+ assert_eq!(d.draft()["values"]["playback"]["stepManyFrames"], 9);
+ d.click("settings.ok");
+ assert_eq!(d.pref("playback.stepManyFrames"), 9);
+ // Reset… puts the page back to its defaults (applied with OK)
+ d.menu("app.settings.timeline");
+ d.click("settings.reset");
+ assert_eq!(d.draft()["values"]["timeline"]["autoScroll"], "pageScroll");
+ assert_eq!(d.pref("timeline.autoScroll"), "smoothScroll", "not yet applied");
+ d.click("settings.ok");
+ assert_eq!(d.pref("timeline.autoScroll"), "pageScroll");
+ assert_eq!(d.pref("playback.stepManyFrames"), 9, "other pages untouched");
+ // ui.set rejects unknown keys
+ d.menu("app.settings.trim");
+ let r = d.call("ui.set", json!({"settings": {"values": {"trim.nope": 1}}}));
+ assert_eq!(r["ok"], false);
+ d.ok("ui.set", json!({"settings": {"page": "memory"}}));
+ assert_eq!(d.draft()["page"], "memory");
+}
+
+#[test]
+fn appearance_labels_and_tooltips_take_effect() {
+ let mut d = Driver::demo();
+ assert_eq!(d.inspect()["ui"]["dark"], true);
+ d.menu("app.settings.appearance");
+ d.click("settings.appearance.colorTheme");
+ d.click("settings.appearance.colorTheme.light");
+ d.ok("ui.set", json!({"settings": {"values": {"appearance.highlightColor": "#e0457b"}}}));
+ d.click("settings.ok");
+ d.frames(2);
+ assert_eq!(d.inspect()["ui"]["dark"], false, "Light theme applied");
+ assert_eq!(d.pref("appearance.highlightColor"), "#e0457b");
+ assert_eq!(d.harness.state().tokens.accent, egui::Color32::from_rgb(0xe0, 0x45, 0x7b));
+ // View ▸ Appearance writes the setting
+ d.menu("view.theme.dark");
+ assert_eq!(d.pref("appearance.colorTheme"), "darkest");
+ assert_eq!(d.inspect()["ui"]["dark"], true);
+
+ // label names show in Edit ▸ Label
+ d.menu("app.settings.labels");
+ d.ok("ui.click", json!({"id": "settings.labels.colors.rose.name"}));
+ d.frames(2);
+ d.ok("ui.key", json!({"key": "Cmd+A"}));
+ d.ok("ui.type", json!({"text": "Interview"}));
+ d.frames(2);
+ assert_eq!(d.draft()["values"]["labels"]["colors"]["rose"]["name"], "Interview");
+ d.click("settings.category.labels");
+ d.click("settings.labels.defaults.sequence");
+ d.click("settings.labels.defaults.sequence.Teal");
+ d.click("settings.ok");
+ let menu = d.ok("ui.menu.list", json!({}));
+ let rose = menu.as_array().unwrap().iter().find(|m| m["id"] == "edit.label.rose").unwrap();
+ assert_eq!(rose["label"], "Interview");
+ let r = d.exec("file.newSequence", json!({"name": "Labelled"}));
+ let seq = r["sequence"].as_u64().unwrap();
+ assert_eq!(d.harness.state().session.project.item(filmcraft_project::ItemId(seq)).unwrap().label, filmcraft_project::Label::Teal);
+
+ // Show Tool Tips off → egui never shows them
+ d.menu("app.settings.general");
+ d.click("settings.general.showToolTips");
+ d.click("settings.ok");
+ let delay = d.harness.ctx.global_style().interaction.tooltip_delay;
+ assert!(delay > 1.0e6, "tooltips disabled: delay {delay}");
+ d.exec("prefs.set", json!({"key": "general.showToolTips", "value": true}));
+ d.frames(2);
+ assert!(d.harness.ctx.global_style().interaction.tooltip_delay < 1.0);
+}
+
+#[test]
+fn memory_and_media_cache_pages() {
+ let mut d = Driver::demo();
+ d.menu("app.settings.memory");
+ d.ok("ui.set", json!({"settings": {"values": {"memory.frameCacheMb": 256}}}));
+ d.click("settings.ok");
+ assert_eq!(d.harness.state().frames.cache_usage().1, 256 << 20, "frame cache budget follows Memory");
+ // Media Cache: no data directory in this session → the button reports it
+ d.menu("app.settings.mediaCache");
+ assert!(d.draft()["cache_info"].is_object());
+ d.click("settings.mediaCache.clean");
+ assert!(d.draft()["message"].as_str().unwrap().contains("no media cache"), "{}", d.draft());
+ d.click("settings.cancel");
+ // play after rendering previews follows Timeline
+ d.exec("prefs.set", json!({"key": "timeline.playAfterRendering", "value": false}));
+ d.frames(2);
+ assert_eq!(d.inspect()["ui"]["play_after_render"], false);
+}
+
+#[test]
+fn snap_playhead_and_return_to_beginning() {
+ let mut d = Driver::demo();
+ // At playback end, return to beginning
+ let dur = d.harness.state().session.active_sequence().unwrap().duration();
+ d.exec("playhead.set", json!({"time": dur.0}));
+ d.exec("prefs.set", json!({"key": "timeline.returnToBeginning", "value": false}));
+ d.frames(2);
+ d.ok("ui.playback", json!({"action": "play"}));
+ let ph = d.harness.state().session.playhead();
+ d.ok("ui.playback", json!({"action": "stop"}));
+ assert!(ph.0 > 0, "stays at the end");
+ d.exec("prefs.set", json!({"key": "timeline.returnToBeginning", "value": true}));
+ d.exec("playhead.set", json!({"time": dur.0}));
+ d.ok("ui.playback", json!({"action": "play"}));
+ let ph = d.harness.state().session.playhead();
+ d.ok("ui.playback", json!({"action": "stop"}));
+ assert!(ph.0 < dur.0 / 2, "restarts from the beginning: {ph:?}");
+}
diff --git a/docs/project-files.md b/docs/project-files.md
index 4d1424d43..0bc53e1b7 100644
--- a/docs/project-files.md
+++ b/docs/project-files.md
@@ -170,13 +170,55 @@ write (two fsynced files).
| `file.autoSaveNow` | write an auto-save now (if anything is unsaved) |
| `file.autoSaveStatus` | prefs, folders, last auto-save / journal times, last encode/write ms and bytes |
| `file.listAutoSaves` | auto-save files of the current project, newest first |
-| `prefs.get {key?}` / `prefs.set {key, value}` or `{values:{…}}` / `prefs.reset` | preferences |
+| `prefs.get {key?}` / `prefs.set {key, value}` or `{values:{…}}` / `prefs.reset {category?}` | settings (below) |
-UI automation ids: `prefs.autoSave.enabled`, `prefs.autoSave.intervalMinutes`,
-`prefs.autoSave.maxVersions`, `prefs.autoSave.saveCurrentProject`, `prefs.autoSave.recoveryJournal`,
-`prefs.autoSave.recoveryIntervalSeconds`, `prefs.ok`, `prefs.cancel`, `prefs.reset`;
-`recovery.recover`, `recovery.later`, `recovery.discard`, `recovery.item.<n>`; `revert.yes`,
-`revert.no` (File ▸ Revert asks first when invoked without params).
+UI automation ids: `recovery.recover`, `recovery.later`, `recovery.discard`, `recovery.item.<n>`;
+`revert.yes`, `revert.no` (File ▸ Revert asks first when invoked without params).
+
+## Settings
+
+Premiere's Settings dialog (app menu ▸ Settings ▸ <category> on macOS, Edit ▸ Preferences
+elsewhere; General is Cmd+,; the window is titled "Preferences"). The values are user preferences,
+not project data: they live in `preferences.json` in the per-user data directory (written
+atomically on every change) and never touch the `.fcproj` schema. The file carries a `version`
+(currently 2); older files are migrated on load, unknown dropdown values, bad colours and
+out-of-range numbers are repaired to defaults/limits, and an unreadable file falls back to the
+defaults.
+
+Every value is a dotted key whose first segment is its category: `timeline.stillImageDuration`,
+`labels.colors.rose.name`. `prefs.get` / `prefs.set` / `prefs.reset {category?}` reach them from the
+CLI, the control channel and MCP; `prefs.set` rejects values that are not one of a dropdown's
+choices. `prefs.schema {category?}` lists every category with its fields (label, kind, choices,
+range, unit, current value, and `wired`: whether FilmCraft acts on it yet). `app.settings.<category>`
+opens the dialog on a page.
+
+| Category | Takes effect |
+|---|---|
+| General | At Startup (Show Home = demo project, Open Most Recent, empty project; recent projects are remembered on open/save), Show Tool Tips |
+| Appearance | Color Theme (Darkest / Dark / Light; View ▸ Appearance writes it too), highlight colour, accessible contrast |
+| Audio | Automatch Time, Large Volume Adjustment, automation keyframe thinning (linear, minimum time) |
+| Audio Hardware | device class (cpal host), output device, I/O buffer size, sample rate, force document rate, Output Mapping (programme L/R → device channels) |
+| Auto Save | the auto-save ring and the crash-recovery journal |
+| Color | stored only (display colour management, EDR monitoring, HDR graphics white) |
+| Graphics | new text layers: smart quotes, ligatures, default font |
+| Labels | the 16 label names and colours (timeline, Project panel, Edit ▸ Label), label defaults for imported movies / video / audio / stills and new sequences |
+| Media | Indeterminate Media Timebase (frame rate of stills), Default Media Scaling (Scale to / Set to frame size when a clip of another size is edited in), Enable proxies |
+| Media Analysis & Transcription | auto-transcribe imported clips (scope "all imported"), speech model, default language / auto-detect, speaker labelling (defaults of `transcript.generate`) |
+| Media Cache | location (`<data dir>/Media Cache` by default; unsaved projects' render previews live there), automatic deletion (older than N days / beyond N GB), Delete… (`mediaCache.clean {all?}`, `mediaCache.info`) |
+| Memory | frame cache budget of the monitors and thumbnails |
+| Playback | preroll / postroll (Play Around, trim loop), Step forward/back many |
+| Plugins | stub (no plugins) |
+| Timeline | video / audio transition and still image default durations (frames or seconds), playback auto-scrolling (none / page / smooth), snap playhead, return to beginning at playback end, play after rendering previews |
+| Trim | Large Trim Offset, Selection tool picks roll (on the cut) / ripple (on the edge) without a modifier, playhead determines trim loop |
+
+The remaining fields are kept for parity and shown, but have no effect yet (`wired: false`).
+
+UI automation ids: `settings.category.<id>`; `settings.<key>` for every control (for example
+`settings.timeline.autoScroll`, `settings.labels.colors.rose.color`); `settings.<key>.<value>` for
+the items of an open dropdown; `settings.<key>.browse`, `settings.<key>.hex`;
+`settings.mediaCache.clean`; `settings.help`, `settings.reset` (this page back to its defaults),
+`settings.cancel`, `settings.ok`. The open dialog's page and draft are `ui.settings` in `ui.inspect`;
+`ui.set {"settings": {"page": id, "values": {key: value}}}` edits the draft (OK applies it).
## Media: offline, relinking, proxies, ingest
diff --git a/docs/testing.md b/docs/testing.md
index 3a6c49bf4..73c77e27d 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -18,6 +18,7 @@ FILMCRAFT_REQUIRE_ORACLES=1 cargo test --workspace # CI: missing ffmpeg fails
| 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`) |
+| Settings | `crates/engine/src/settings_tests.rs`, `crates/ui-egui/tests/settings_ui.rs` | schema keys and defaults, persistence in the data directory, v1 → v2 migration and repair of bad values, validation, per-category reset; each wired setting (still / transition durations, step many, label defaults and colours, media scaling, timebase, recent projects, media cache policy, output mapping, smart quotes, auto-transcribe); the dialog: every category from its command and Cmd+,, edits by automation id, OK / Cancel / Escape / Reset…, theme, label names in Edit ▸ Label, tooltips, frame cache (`FILMCRAFT_UI_SHOTS=<dir>` writes `settings-*.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 |