Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(desktop): editor text interactions, decorative frames, offset auto-calc flag, and stability fixes

Richie McIlroyf940985db1b0
diff --git a/apps/cli/src/selftest/playback.rs b/apps/cli/src/selftest/playback.rs
index eede85ec4..f66f55435 100644
--- a/apps/cli/src/selftest/playback.rs
+++ b/apps/cli/src/selftest/playback.rs
@@ -910,7 +910,11 @@ mod fixture {
keyboard_segments: Vec::new(),
audio_segments: Vec::new(),
}),
- clips: vec![ClipConfiguration { index: 0, offsets }],
+ clips: vec![ClipConfiguration {
+ index: 0,
+ offsets,
+ offsets_auto_calculated: true,
+ }],
..Default::default()
};
project_config
diff --git a/apps/desktop/src-tauri/src/camera_legacy.rs b/apps/desktop/src-tauri/src/camera_legacy.rs
index 828c2eec7..cf3bc35ae 100644
--- a/apps/desktop/src-tauri/src/camera_legacy.rs
+++ b/apps/desktop/src-tauri/src/camera_legacy.rs
@@ -392,7 +392,10 @@ impl WsBlurState {
// heaviest preview cost). Returning `None` makes the caller fall back to
// packing the raw camera rows, so the preview is unblurred but cheap.
// The UI blur toggle is unaffected; it just has no visual effect here.
- if is_low_spec_preview() {
+ // Same fallback when crash recovery disabled blur: bail before creating
+ // any GPU resources at all, since the whole blur stack is suspect on
+ // this machine.
+ if is_low_spec_preview() || cap_camera_effects::blur_disabled() {
return None;
}
@@ -603,6 +606,19 @@ fn try_drain_readback(
}
fn init_headless_blur() -> Option<WsBlurResources> {
+ // Arm the sentinel's blur marker around the blur-dedicated wgpu
+ // adapter/device setup too, so a native death here is attributed to blur.
+ // Deliberately not `enter_gpu_init_phase`: that would cross-trigger WARP
+ // software-graphics recovery and cripple the editor for a blur-only crash.
+ crate::crash_sentinel::enter_blur_session();
+ struct BlurSessionGuard;
+ impl Drop for BlurSessionGuard {
+ fn drop(&mut self) {
+ crate::crash_sentinel::exit_blur_session();
+ }
+ }
+ let _guard = BlurSessionGuard;
+
let instance = cap_rendering::create_wgpu_instance_sync();
let force_software_adapter = cap_rendering::force_software_wgpu_adapter();
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
diff --git a/apps/desktop/src-tauri/src/crash_sentinel.rs b/apps/desktop/src-tauri/src/crash_sentinel.rs
index f3b0807fc..f394c8f9b 100644
--- a/apps/desktop/src-tauri/src/crash_sentinel.rs
+++ b/apps/desktop/src-tauri/src/crash_sentinel.rs
@@ -35,12 +35,28 @@ struct SessionRecord {
/// mode, so a follow-up crash doesn't chain into recovery forever.
#[serde(default)]
graphics_recovery: bool,
+ /// True while any camera-background-blur processor is alive (ONNX/DirectML
+ /// session + dedicated GPU work), and for a linger period after the last
+ /// one is released — deferred driver/D3D12 faults have been observed
+ /// killing the process tens of seconds after blur teardown. Native crashes
+ /// in that stack never reach a panic handler; if the process dies inside
+ /// this window the next launch attributes the death to blur and disables it.
+ #[serde(default)]
+ blur_active: bool,
+ /// True when this session already ran with blur disabled by crash recovery,
+ /// for diagnostics on the next-launch report.
+ #[serde(default)]
+ blur_recovery: bool,
}
struct ActiveSession {
path: PathBuf,
record: SessionRecord,
gpu_init_depth: u32,
+ blur_session_depth: u32,
+ /// Bumped on every blur enter/exit so a scheduled linger-disarm can tell
+ /// whether blur activity happened after it was scheduled.
+ blur_generation: u64,
}
static SESSION: Mutex<Option<ActiveSession>> = Mutex::new(None);
@@ -54,6 +70,8 @@ pub struct UnexpectedTermination {
pub during_gpu_init: bool,
/// The session was already running in software-graphics recovery mode.
pub in_graphics_recovery: bool,
+ /// The process died while a camera-background-blur processor was alive.
+ pub blur_active: bool,
}
/// Arm the sentinel for this session and, if a previous session's sentinel survived,
@@ -76,6 +94,7 @@ pub fn init(logs_dir: &Path, app_version: &str) -> Option<UnexpectedTermination>
previous_termination = Some(UnexpectedTermination {
during_gpu_init: prev.gpu_init_phase,
in_graphics_recovery: prev.graphics_recovery,
+ blur_active: prev.blur_active,
});
}
Err(error) => {
@@ -101,6 +120,8 @@ pub fn init(logs_dir: &Path, app_version: &str) -> Option<UnexpectedTermination>
liquid_glass: "unknown".to_string(),
gpu_init_phase: false,
graphics_recovery: false,
+ blur_active: false,
+ blur_recovery: false,
};
write_record(&path, &record);
@@ -115,6 +136,8 @@ pub fn init(logs_dir: &Path, app_version: &str) -> Option<UnexpectedTermination>
path,
record,
gpu_init_depth: 0,
+ blur_session_depth: 0,
+ blur_generation: 0,
});
previous_termination
@@ -149,6 +172,79 @@ pub fn exit_gpu_init_phase() {
}
}
+/// How long `blur_active` stays armed after the last blur processor is
+/// released. Deferred D3D12/DML/driver faults have been observed killing the
+/// process up to ~50s after blur teardown finished (the fault surfaces
+/// asynchronously); disarming immediately would miss exactly those deaths and
+/// leave the crash loop unbroken.
+const BLUR_DISARM_LINGER: std::time::Duration = std::time::Duration::from_secs(120);
+
+/// Arm the blur marker while a camera-background-blur processor is alive. If the
+/// process dies inside this window the next launch sees `blur_active` and can
+/// disable blur. Nestable (editor render + camera preview can overlap); the
+/// marker persists until a linger period after the last exit call.
+pub fn enter_blur_session() {
+ if let Ok(mut guard) = SESSION.lock()
+ && let Some(session) = guard.as_mut()
+ {
+ session.blur_session_depth += 1;
+ session.blur_generation = session.blur_generation.wrapping_add(1);
+ if !session.record.blur_active {
+ session.record.blur_active = true;
+ write_record(&session.path, &session.record);
+ }
+ }
+}
+
+/// Schedule the blur marker to disarm once the linger window passes with no new
+/// blur session. The generation check makes a stale disarm from an earlier
+/// exit a no-op if blur was re-armed in the meantime.
+pub fn exit_blur_session() {
+ let scheduled_generation = {
+ let Ok(mut guard) = SESSION.lock() else {
+ return;
+ };
+ let Some(session) = guard.as_mut() else {
+ return;
+ };
+ session.blur_session_depth = session.blur_session_depth.saturating_sub(1);
+ session.blur_generation = session.blur_generation.wrapping_add(1);
+ if session.blur_session_depth != 0 || !session.record.blur_active {
+ return;
+ }
+ session.blur_generation
+ };
+
+ std::thread::spawn(move || {
+ std::thread::sleep(BLUR_DISARM_LINGER);
+ if let Ok(mut guard) = SESSION.lock()
+ && let Some(session) = guard.as_mut()
+ && session.blur_generation == scheduled_generation
+ && session.blur_session_depth == 0
+ && session.record.blur_active
+ {
+ session.record.blur_active = false;
+ write_record(&session.path, &session.record);
+ }
+ });
+}
+
+/// Record that this session is running with camera background blur disabled by
+/// crash recovery, for diagnostics on a follow-up unexpected-termination report.
+pub fn mark_blur_recovery() {
+ if let Ok(mut guard) = SESSION.lock()
+ && let Some(session) = guard.as_mut()
+ && !session.record.blur_recovery
+ {
+ session.record.blur_recovery = true;
+ write_record(&session.path, &session.record);
+ }
+
+ sentry::configure_scope(|scope| {
+ scope.set_tag("camera_blur_recovery", "true");
+ });
+}
+
/// Record that this session is running in software-graphics recovery mode, so an
/// unexpected termination of *this* session doesn't chain into recovery again.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
@@ -203,6 +299,8 @@ fn report_unexpected_termination(prev: &SessionRecord) {
prev_liquid_glass = %prev.liquid_glass,
prev_gpu_init_phase = prev.gpu_init_phase,
prev_graphics_recovery = prev.graphics_recovery,
+ prev_blur_active = prev.blur_active,
+ prev_blur_recovery = prev.blur_recovery,
"Previous Cap session terminated without a clean shutdown"
);
@@ -215,6 +313,8 @@ fn report_unexpected_termination(prev: &SessionRecord) {
scope.set_tag("prev.macos_liquid_glass", &prev.liquid_glass);
scope.set_tag("prev.gpu_init_phase", prev.gpu_init_phase.to_string());
scope.set_tag("prev.graphics_recovery", prev.graphics_recovery.to_string());
+ scope.set_tag("prev.blur_active", prev.blur_active.to_string());
+ scope.set_tag("prev.blur_recovery", prev.blur_recovery.to_string());
scope.set_extra("prev.pid", prev.pid.into());
scope.set_extra("prev.started_at", prev.started_at.clone().into());
},
diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rs
index a9dd08a15..3046e91b7 100644
--- a/apps/desktop/src-tauri/src/export.rs
+++ b/apps/desktop/src-tauri/src/export.rs
@@ -1547,6 +1547,7 @@ async fn generate_export_preview_inner(
&project_config,
&render_segment.cursor,
total_duration,
+ render_constants.options.screen_size,
);
zoom_timeline.ensure_precomputed_until((frame_number as f32 + 1.0) / settings.fps as f32);
@@ -1791,8 +1792,12 @@ async fn generate_export_preview_fast_inner(
.map(|t| t.duration())
.unwrap_or(0.0);
- let mut zoom_timeline =
- ZoomTransformTimeline::from_project(&project_config, &segment_media.cursor, total_duration);
+ let mut zoom_timeline = ZoomTransformTimeline::from_project(
+ &project_config,
+ &segment_media.cursor,
+ total_duration,
+ editor.render_constants.options.screen_size,
+ );
zoom_timeline.ensure_precomputed_until((frame_number as f32 + 1.0) / settings.fps as f32);
let uniforms = ProjectUniforms::new(
diff --git a/apps/desktop/src-tauri/src/general_settings.rs b/apps/desktop/src-tauri/src/general_settings.rs
index 1ba762ff4..b55359477 100644
--- a/apps/desktop/src-tauri/src/general_settings.rs
+++ b/apps/desktop/src-tauri/src/general_settings.rs
@@ -228,6 +228,12 @@ pub struct GeneralSettingsStore {
pub out_of_process_muxer: bool,
#[serde(default)]
pub recordings_path: Option<String>,
+ /// App version at which camera background blur was disabled after a crash
+ /// was attributed to the blur pipeline; `None` means blur is allowed.
+ /// Cleared automatically when the app version changes (one retry per
+ /// update, since a new ort/wgpu/driver stack may have fixed the crash).
+ #[serde(default)]
+ pub camera_blur_disabled_by_crash: Option<String>,
}
fn default_enable_native_camera_preview() -> bool {
@@ -327,6 +333,7 @@ impl Default for GeneralSettingsStore {
enable_telemetry: true,
out_of_process_muxer: cap_recording::DEFAULT_OUT_OF_PROCESS_MUXER,
recordings_path: None,
+ camera_blur_disabled_by_crash: None,
}
}
}
diff --git a/apps/desktop/src-tauri/src/import.rs b/apps/desktop/src-tauri/src/import.rs
index c94fa6ef8..7d57163e1 100644
--- a/apps/desktop/src-tauri/src/import.rs
+++ b/apps/desktop/src-tauri/src/import.rs
@@ -395,8 +395,13 @@ fn add_clip_configs(
if let Some(existing) = config.clips.iter_mut().find(|clip| clip.index == index) {
existing.offsets = offsets;
+ existing.offsets_auto_calculated = true;
} else {
- config.clips.push(ClipConfiguration { index, offsets });
+ config.clips.push(ClipConfiguration {
+ index,
+ offsets,
+ offsets_auto_calculated: true,
+ });
}
}
}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 42898e466..7cf9f0161 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -212,6 +212,7 @@ mod tests {
UnexpectedTermination {
during_gpu_init: false,
in_graphics_recovery: false,
+ blur_active: false,
}
)));
@@ -220,6 +221,7 @@ mod tests {
UnexpectedTermination {
during_gpu_init: true,
in_graphics_recovery: false,
+ blur_active: false,
}
)));
@@ -229,15 +231,66 @@ mod tests {
UnexpectedTermination {
during_gpu_init: true,
in_graphics_recovery: true,
+ blur_active: false,
}
)));
assert!(!should_engage_graphics_recovery(Some(
UnexpectedTermination {
during_gpu_init: false,
in_graphics_recovery: true,
+ blur_active: false,
}
)));
}
+
+ #[test]
+ fn camera_blur_crash_recovery_disables_and_heals_on_update() {
+ use crash_sentinel::UnexpectedTermination;
+
+ let died_with_blur = Some(UnexpectedTermination {
+ during_gpu_init: false,
+ in_graphics_recovery: false,
+ blur_active: true,
+ });
+ let died_without_blur = Some(UnexpectedTermination {
+ during_gpu_init: false,
+ in_graphics_recovery: false,
+ blur_active: false,
+ });
+
+ // Clean exit, blur never disabled: stays enabled.
+ assert_eq!(next_camera_blur_disabled_version(None, None, "1.0"), None);
+
+ // Deaths unrelated to blur must not disable it.
+ assert_eq!(
+ next_camera_blur_disabled_version(None, died_without_blur, "1.0"),
+ None
+ );
+
+ // A death with blur active disables it at the current version.
+ assert_eq!(
+ next_camera_blur_disabled_version(None, died_with_blur, "1.0"),
+ Some("1.0".into())
+ );
+
+ // The disable persists across clean launches of the same version.
+ assert_eq!(
+ next_camera_blur_disabled_version(Some("1.0"), None, "1.0"),
+ Some("1.0".into())
+ );
+
+ // An app update heals: the new stack gets one retry.
+ assert_eq!(
+ next_camera_blur_disabled_version(Some("1.0"), None, "1.1"),
+ None
+ );
+
+ // But a fresh blur-attributed death beats version optimism.
+ assert_eq!(
+ next_camera_blur_disabled_version(Some("1.0"), died_with_blur, "1.1"),
+ Some("1.1".into())
+ );
+ }
}
#[derive(Default)]
@@ -4634,6 +4687,71 @@ fn configure_windows_graphics_recovery(
) {
}
+/// Decides what `camera_blur_disabled_by_crash` should hold for this launch: a
+/// death with the blur pipeline active disables blur at the current version
+/// (fresh crash evidence beats version optimism), an existing disable carries
+/// over within the same app version, and an app update clears it so the new
+/// ort/wgpu/driver stack gets one retry.
+fn next_camera_blur_disabled_version(
+ stored: Option<&str>,
+ previous_termination: Option<crash_sentinel::UnexpectedTermination>,
+ current_version: &str,
+) -> Option<String> {
+ if previous_termination.is_some_and(|prev| prev.blur_active) {
+ return Some(current_version.to_string());
+ }
+ stored.filter(|v| *v == current_version).map(String::from)
+}
+
+/// Breaks the camera-background-blur crash loop: a native DirectML/driver crash
+/// never reaches a panic handler, and the blur toggle is persisted frontend-side,
+/// so without this the next camera open repeats the crash forever. Blur init is
+/// lazy (first camera frame / editor render), so running this during setup is
+/// early enough. Windows-only at runtime (matching graphics recovery) but
+/// compiled everywhere so non-Windows builds keep it honest.
+fn configure_camera_blur_recovery(
+ app: &AppHandle,
+ previous_termination: Option<crash_sentinel::UnexpectedTermination>,
+) {
+ if !cfg!(target_os = "windows") {
+ return;
+ }
+
+ let current_version = env!("CARGO_PKG_VERSION");
+ let stored = GeneralSettingsStore::get(app)
+ .ok()
+ .flatten()
+ .and_then(|settings| settings.camera_blur_disabled_by_crash);
+ let next =
+ next_camera_blur_disabled_version(stored.as_deref(), previous_termination, current_version);
+
+ if next != stored {
+ let value = next.clone();
+ if let Err(error) = GeneralSettingsStore::update(app, |settings| {
+ settings.camera_blur_disabled_by_crash = value;
+ }) {
+ warn!(%error, "Failed to persist camera blur crash-recovery state");
+ }
+ }
+
+ if next.is_some() {
+ cap_camera_effects::set_blur_disabled(true);
+ crash_sentinel::mark_blur_recovery();
+ if stored.is_none() {
+ error!(
+ "Previous Cap session died with camera background blur active; disabling blur until the next app update"
+ );
+ } else {
+ warn!("Camera background blur remains disabled by crash recovery for this launch");
+ }
+ } else if stored.is_some() {
+ info!(
+ prev_version = stored.as_deref(),
+ "App version changed; re-enabling camera background blur for one retry"
+ );
+ }
+}
+
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
// Arm the unexpected-termination sentinel before anything else can crash, and
@@ -4641,6 +4759,17 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
let previous_termination = crash_sentinel::init(&logs_dir, env!("CARGO_PKG_VERSION"));
configure_windows_graphics_recovery(previous_termination);
+ // Keep the sentinel's blur marker in sync with live BlurProcessor instances
+ // (camera preview and editor render alike), so a native blur crash is
+ // attributable on the next launch.
+ cap_camera_effects::set_blur_session_observer(|active| {
+ if active {
+ crash_sentinel::enter_blur_session();
+ } else {
+ crash_sentinel::exit_blur_session();
+ }
+ });
+
ffmpeg::init()
.map_err(|e| {
error!("Failed to initialize ffmpeg: {e}");
@@ -5027,6 +5156,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
specta_builder.mount_events(&app);
hotkeys::init(&app);
general_settings::init(&app);
+ configure_camera_blur_recovery(&app, previous_termination);
fake_window::init(&app);
app.manage(target_select_overlay::WindowFocusManager::default());
app.manage(EditorWindowIds::default());
diff --git a/apps/desktop/src-tauri/src/permissions.rs b/apps/desktop/src-tauri/src/permissions.rs
index e239f8a8e..d8475d42b 100644
--- a/apps/desktop/src-tauri/src/permissions.rs
+++ b/apps/desktop/src-tauri/src/permissions.rs
@@ -160,13 +160,24 @@ fn macos_sync_activation_policy(app: &tauri::AppHandle, should_show_dock: bool)
}
}
+// Changing the activation policy (which `set_dock_visibility` also does under
+// the hood) while any window owns a fullscreen Space makes AppKit throw an
+// NSException that aborts the process when it unwinds into Rust. Callers must
+// leave the policy alone until fullscreen exits.
+#[cfg(target_os = "macos")]
+fn macos_any_window_fullscreen(app: &tauri::AppHandle) -> bool {
+ app.webview_windows()
+ .values()
+ .any(|window| window.is_fullscreen().unwrap_or(false))
+}
+
#[cfg(target_os = "macos")]
pub(crate) fn prepare_macos_panel_window(
app: &tauri::AppHandle,
) -> MacosPanelWindowActivationGuard {
let prev = MACOS_PENDING_PANEL_WINDOWS.fetch_add(1, Ordering::AcqRel);
- if prev == 0 {
+ if prev == 0 && !macos_any_window_fullscreen(app) {
if let Err(err) = app.set_activation_policy(tauri::ActivationPolicy::Accessory) {
tracing::warn!("Failed to prepare macOS panel activation policy: {err}");
}
@@ -181,6 +192,10 @@ pub(crate) fn sync_macos_dock_visibility(app: &tauri::AppHandle) {
return;
}
+ if macos_any_window_fullscreen(app) {
+ return;
+ }
+
let should_hide_dock = GeneralSettingsStore::get(app)
.ok()
.flatten()
diff --git a/apps/desktop/src-tauri/src/platform/macos/delegates.rs b/apps/desktop/src-tauri/src/platform/macos/delegates.rs
index 65db4237f..5b6536b7f 100644
--- a/apps/desktop/src-tauri/src/platform/macos/delegates.rs
+++ b/apps/desktop/src-tauri/src/platform/macos/delegates.rs
@@ -32,18 +32,35 @@ pub fn position_window_controls(
inset: &LogicalPosition<f64>,
) {
use cocoa::{
- appkit::{NSView, NSWindow, NSWindowButton},
+ appkit::{NSView, NSWindow, NSWindowButton, NSWindowStyleMask},
base::id,
foundation::NSRect,
};
let ns_window = ns_window_handle.0 as id;
unsafe {
+ // In native fullscreen the standard window buttons are hosted in a
+ // system-managed titlebar overlay; resizing their superviews there
+ // makes AppKit throw an NSException, which aborts the process once it
+ // unwinds into Rust. The system positions them itself in fullscreen.
+ if ns_window
+ .styleMask()
+ .contains(NSWindowStyleMask::NSFullScreenWindowMask)
+ {
+ return;
+ }
+
let close = ns_window.standardWindowButton_(NSWindowButton::NSWindowCloseButton);
let minimize = ns_window.standardWindowButton_(NSWindowButton::NSWindowMiniaturizeButton);
let zoom = ns_window.standardWindowButton_(NSWindowButton::NSWindowZoomButton);
+ if close.is_null() || minimize.is_null() || zoom.is_null() {
+ return;
+ }
let title_bar_container_view = close.superview().superview();
+ if title_bar_container_view.is_null() {
+ return;
+ }
let close_rect: NSRect = msg_send![close, frame];
let button_height = close_rect.size.height;
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 5b1ceaafb..578e3e0d8 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -3057,8 +3057,16 @@ async fn handle_recording_end(
let main_window = CapWindowId::Main.get(&handle);
+ // When the finish path handed the foreground to an editor window, leave
+ // the main window alone: un-minimizing it here (Windows `Close` behaviour
+ // minimizes; macOS `Minimise` miniaturizes) would restore it on top of the
+ // editor that just opened.
+ let editor_took_foreground = matches!(&res, Some(Ok(true)));
+
if let Some(window) = main_window {
- window.unminimize().ok();
+ if !editor_took_foreground {
+ window.unminimize().ok();
+ }
if let Err(err) = app.ensure_selected_mic_ready().await {
warn!("Failed to restore microphone preview after recording: {err}");
}
@@ -3086,7 +3094,7 @@ async fn handle_recording_end(
CurrentRecordingChanged.emit(&handle).ok();
if let Some(res) = res {
- res?;
+ let _editor_took_foreground: bool = res?;
}
Ok(())
@@ -3104,11 +3112,14 @@ fn compute_studio_duration_secs(recording_dir: &std::path::Path) -> f64 {
.unwrap_or(0.0)
}
+/// Returns `true` when an editor window took the foreground (in-editor
+/// re-record, or the post-recording behaviour opened the editor). Callers use
+/// this to keep the main window suppressed so it can't cover the editor.
async fn apply_post_studio_editor_behaviour(
app: &AppHandle,
recording_dir: PathBuf,
duration_secs: f64,
-) {
+) -> bool {
if let Some(editor_path) = EditorRecordingTarget::take(app) {
if let Some(editor_window) = editor_window_for_path(app, &editor_path) {
let _ = editor_window.unminimize();
@@ -3122,7 +3133,7 @@ async fn apply_post_studio_editor_behaviour(
}
.emit(app);
- return;
+ return true;
}
let default = GeneralSettingsStore::get(app)
@@ -3143,6 +3154,8 @@ async fn apply_post_studio_editor_behaviour(
}
.show(app)
.await;
+
+ true
}
Some(PostStudioRecordingBehaviour::ShowOverlay) => {
let _ = ShowCapWindow::RecordingsOverlay.show(app).await;
@@ -3155,21 +3168,26 @@ async fn apply_post_studio_editor_behaviour(
}
.emit(&app);
});
+
+ false
}
None => {
let _ = NewStudioRecordingAdded {
path: recording_dir,
}
.emit(app);
+
+ false
}
}
}
-// runs when a recording successfully finishes
+// runs when a recording successfully finishes; Ok(true) means an editor
+// window took the foreground and the main window must stay suppressed
async fn handle_recording_finish(
app: &AppHandle,
completed_recording: CompletedRecording,
-) -> Result<(), String> {
+) -> Result<bool, String> {
let recording_dir = completed_recording.project_path().clone();
let screenshots_dir = recording_dir.join("screenshots");
@@ -3203,7 +3221,8 @@ async fn handle_recording_finish(
finalizing_state.start_finalizing(recording_dir.clone());
let duration = compute_studio_duration_secs(&recording_dir);
- apply_post_studio_editor_behaviour(app, recording_dir.clone(), duration).await;
+ let editor_took_foreground =
+ apply_post_studio_editor_behaviour(app, recording_dir.clone(), duration).await;
AppSounds::StopRecording.play();
@@ -3243,7 +3262,7 @@ async fn handle_recording_finish(
.finish_finalizing(&recording_dir_for_finalize);
});
- return Ok(());
+ return Ok(editor_took_foreground);
}
let updated_studio_meta = recording.meta.clone();
@@ -3304,7 +3323,7 @@ async fn handle_recording_finish(
}
.emit(app)
.ok();
- return Ok(());
+ return Ok(false);
}
let app = app.clone();
@@ -3444,6 +3463,7 @@ async fn handle_recording_finish(
);
}
+ let mut editor_took_foreground = false;
if let RecordingMetaInner::Studio(_) = meta_inner {
let duration = compute_studio_duration_secs(&recording_dir);
crate::automation::run_studio_recording_automations(
@@ -3451,13 +3471,14 @@ async fn handle_recording_finish(
recording_dir.clone(),
duration,
);
- apply_post_studio_editor_behaviour(app, recording_dir, duration).await;
+ editor_took_foreground =
+ apply_post_studio_editor_behaviour(app, recording_dir, duration).await;
}
// Play sound to indicate recording has stopped
AppSounds::StopRecording.play();
- Ok(())
+ Ok(editor_took_foreground)
}
async fn finalize_studio_recording(
diff --git a/apps/desktop/src-tauri/src/screenshot_editor.rs b/apps/desktop/src-tauri/src/screenshot_editor.rs
index 2b75c8d7b..222da938b 100644
--- a/apps/desktop/src-tauri/src/screenshot_editor.rs
+++ b/apps/desktop/src-tauri/src/screenshot_editor.rs
@@ -398,8 +398,12 @@ impl ScreenshotEditorInstances {
ProjectUniforms::get_base_size(&constants.options, &current_config);
let cursor_events = cap_project::CursorEvents::default();
- let mut zoom_timeline =
- ZoomTransformTimeline::from_project(&current_config, &cursor_events, 0.0);
+ let mut zoom_timeline = ZoomTransformTimeline::from_project(
+ &current_config,
+ &cursor_events,
+ 0.0,
+ constants.options.screen_size,
+ );
zoom_timeline.ensure_precomputed_until(1.0 / 30.0);
let uniforms = ProjectUniforms::new(
@@ -865,6 +869,7 @@ pub async fn prewarm_screenshot_renderer() {
&cursor_events,
config.screen_movement_spring,
0.0,
+ None,
);
zoom_timeline.ensure_precomputed_until(1.0 / 30.0);
let uniforms = ProjectUniforms::new(
@@ -1657,7 +1662,12 @@ pub async fn render_screenshot_png(instance: &ScreenshotEditorInstance) -> Resul
segment_has_camera: false,
};
let cursor_events = cap_project::CursorEvents::default();
- let mut zoom_timeline = ZoomTransformTimeline::from_project(&config, &cursor_events, 0.0);
+ let mut zoom_timeline = ZoomTransformTimeline::from_project(
+ &config,
+ &cursor_events,
+ 0.0,
+ constants.options.screen_size,
+ );
zoom_timeline.ensure_precomputed_until(1.0 / 30.0);
let uniforms = ProjectUniforms::new(
&constants,
diff --git a/apps/desktop/src-tauri/src/thumbnails/windows.rs b/apps/desktop/src-tauri/src/thumbnails/windows.rs
index ec6307b3d..dde0fae69 100644
--- a/apps/desktop/src-tauri/src/thumbnails/windows.rs
+++ b/apps/desktop/src-tauri/src/thumbnails/windows.rs
@@ -9,12 +9,16 @@ pub async fn capture_display_thumbnail(display: &scap_targets::Display) -> Optio
let (tx, rx) = std::sync::mpsc::channel();
- let settings = Settings {
+ let mut settings = Settings {
is_cursor_capture_enabled: Some(false),
pixel_format: scap_direct3d::PixelFormat::R8G8B8A8Unorm,
..Default::default()
};
+ if let Ok(true) = Settings::can_is_border_required() {
+ settings.is_border_required = Some(false);
+ }
+
let mut capturer = Capturer::new(
item,
settings.clone(),
@@ -148,12 +152,16 @@ pub async fn capture_window_thumbnail(window: &scap_targets::Window) -> Option<S
let (tx, rx) = std::sync::mpsc::channel();
- let settings = Settings {
+ let mut settings = Settings {
is_cursor_capture_enabled: Some(false),
pixel_format: scap_direct3d::PixelFormat::R8G8B8A8Unorm,
..Default::default()
};
+ if let Ok(true) = Settings::can_is_border_required() {
+ settings.is_border_required = Some(false);
+ }
+
let mut capturer = Capturer::new(
item,
settings.clone(),
diff --git a/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx b/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx
index 13784370b..fb85e5b61 100644
--- a/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx
@@ -1746,16 +1746,6 @@ function Page() {
setShouldRevealMainWindowAfterPicker,
] = createSignal(false);
- // Remember the mode of the in-flight recording. currentRecording.data goes
- // null the instant a recording ends, so capture it while it's live to decide
- // what to do with the main window afterwards.
- let lastRecordingMode: string | null = null;
- let wasRecordingForPicker = false;
- createEffect(() => {
- const rec = currentRecording.data;
- if (rec) lastRecordingMode = rec.mode;
- });
-
createEffect(() => {
const pickerActive = rawOptions.targetMode != null;
const pickerSource = rawOptions.targetModeSource ?? "main";
@@ -1779,25 +1769,38 @@ function Page() {
setHasHiddenMainWindowForPicker(false);
const shouldRevealMainWindow = shouldRevealMainWindowAfterPicker();
setShouldRevealMainWindowAfterPicker(false);
- // After a studio recording the editor takes over the foreground, so keep
- // the main window hidden. For a cancelled picker or a finished instant
- // recording, bring the main window back.
- if (
- shouldRevealMainWindow &&
- !(wasRecordingForPicker && lastRecordingMode === "studio")
- ) {
+ // Whether the main window may come back is decided by WHY the picker
+ // was dismissed, which travels with the dismissal itself
+ // (targetModeDismissal is written in the same setOptions call that
+ // nulls targetMode). Reconstructing the outcome here from query state
+ // or effect ordering is unsound: this webview is hidden and may have
+ // been suspended, so those signals can be stale by a whole recording.
+ // A studio recording hands the foreground to the editor and this
+ // window is always-on-top — revealing it then covers the editor.
+ const dismissal = rawOptions.targetModeDismissal ?? "cancelled";
+ const dismissalReveals =
+ dismissal === "cancelled" ||
+ dismissal === "screenshot" ||
+ dismissal === "recordingInstant";
+ if (shouldRevealMainWindow && dismissalReveals) {
const currentWindow = getCurrentWindow();
void currentWindow.show();
void currentWindow.setFocus();
}
}
-
- wasRecordingForPicker = recording;
});
onCleanup(() => {
if (!hasHiddenMainWindowForPicker()) return;
setHasHiddenMainWindowForPicker(false);
- if (shouldRevealMainWindowAfterPicker()) void getCurrentWindow().show();
+ // Restore on dispose only when the picker is still open with no recording
+ // in flight (e.g. dev HMR mid-picker). Disposal after a recording started
+ // must not resurface the main window over the recording UI or the editor.
+ if (
+ shouldRevealMainWindowAfterPicker() &&
+ rawOptions.targetMode != null &&
+ !currentRecording.data
+ )
+ void getCurrentWindow().show();
});
const handleMouseEnter = () => {
@@ -2132,7 +2135,11 @@ function Page() {
await commands.openTargetSelectOverlays(null, null, targetMode);
setOptions({ targetMode, targetModeSource: "main" });
} else {
- setOptions({ targetMode, targetModeSource: null });
+ setOptions({
+ targetMode,
+ targetModeSource: null,
+ targetModeDismissal: "cancelled",
+ });
await currentWindow.show();
await currentWindow.setFocus();
void commands.closeTargetSelectOverlays().catch((error) => {
@@ -2188,7 +2195,13 @@ function Page() {
targetModeSource: "main",
});
} else {
- setOptions({ targetMode: newTargetMode });
+ // Rust clears the target mode when it shows the main window
+ // itself (e.g. tray "Open Main Window"), so this dismissal may
+ // reveal — matching the window Rust just made visible anyway.
+ setOptions({
+ targetMode: newTargetMode,
+ targetModeDismissal: "cancelled",
+ });
await commands.closeTargetSelectOverlays();
}
},
@@ -2364,7 +2377,8 @@ function Page() {
);
setOptions({ targetMode: nextMode, targetModeSource: "main" });
} else {
- setOptions("targetMode", nextMode);
+ // Toggling the active mode off is a user cancel of the picker.
+ setOptions({ targetMode: nextMode, targetModeDismissal: "cancelled" });
await commands.closeTargetSelectOverlays();
}
};
diff --git a/apps/desktop/src/routes/editor/CanvasElementsOverlay.tsx b/apps/desktop/src/routes/editor/CanvasElementsOverlay.tsx
index 91401884b..3556b026d 100644
--- a/apps/desktop/src/routes/editor/CanvasElementsOverlay.tsx
+++ b/apps/desktop/src/routes/editor/CanvasElementsOverlay.tsx
@@ -118,8 +118,12 @@ export function useCanvasSnapTargets() {
});
});
+ // The classic camera-inset margin lines only make sense for the camera
+ // and display; for text/mask boxes they just cause spurious re-snaps
+ // right next to the frame-edge lines.
+ const wantsMargin = exclude === "camera" || exclude === "display";
return buildSnapTargets(rects, {
- margin: layout ? classicMargin(layout) : undefined,
+ margin: layout && wantsMargin ? classicMargin(layout) : undefined,
});
};
}
@@ -488,19 +492,27 @@ export function CanvasElementsOverlay(props: { size: Size }) {
const frameAspect = W / H;
// Normalized display width at padding 0 (aspect-fit).
const maxWidth = Math.min(1, contentAspect / frameAspect);
- const padding0 = project.background.padding;
- // Two-point linear model width(padding); only affects pointer
- // gain — the box re-anchors to the real rect every frame.
- const gain =
- padding0 > 0 && rect.w < maxWidth
- ? (1 - rect.w / maxWidth) / padding0
- : 0.0044;
+ // Mirror of the renderer's sizing law (get_base_size /
+ // display_base_offset in crates/rendering):
+ // width = maxWidth / (1 + paddingScale * padding)
+ // with padding in [0, 100] and paddingScale = 2k * 0.4 / 100
+ // (0.4 = SCREEN_MAX_PADDING). Without a fixed aspect ratio the
+ // padded base keeps the content aspect (k = 1); with one,
+ // padding is measured against the crop's larger dimension
+ // while the fit is constrained by a single axis, so k rescales
+ // that basis onto the constrained axis.
+ const k = !project.aspectRatio
+ ? 1
+ : contentAspect <= frameAspect
+ ? Math.max(1, contentAspect)
+ : Math.max(1, 1 / contentAspect);
+ const paddingScale = (2 * k * 0.4) / 100;
return {
rect,
targets: snapTargetsFor("display"),
maxWidth,
- gain,
+ paddingScale,
moved: false,
};
},
@@ -511,18 +523,19 @@ export function CanvasElementsOverlay(props: { size: Size }) {
};
const scale = resolveScale(e, state, initialMouse, dirX, dirY, anchor);
- const newWidth = clamp(
- state.rect.w * scale,
- state.maxWidth * Math.max(1 - state.gain * 100, 0.05),
- state.maxWidth,
- );
+ // Invert the renderer's law for the dragged width, then re-derive
+ // the outline from the clamped padding so the outline always lands
+ // exactly where the renderer will draw the display — including at
+ // the minimum size (padding 100).
+ const targetWidth = Math.max(state.rect.w * scale, 1e-6);
const newPadding = clamp(
- (1 - newWidth / state.maxWidth) / state.gain,
+ (state.maxWidth / targetWidth - 1) / state.paddingScale,
0,
100,
);
setProject("background", "padding", newPadding);
+ const newWidth = state.maxWidth / (1 + state.paddingScale * newPadding);
const applied = newWidth / state.rect.w;
const w = state.rect.w * applied;
const h = state.rect.h * applied;
@@ -765,15 +778,14 @@ function ElementBox(props: {
<Show when={showHandles()}>
<For each={corners()}>
{(corner) => (
+ // The hit target must not change size on hover — the grow
+ // effect lives on an inner, pointer-events-none span,
+ // otherwise the handle scales out from under the cursor and
+ // hover flickers in a mouseenter/leave loop.
<div
class={cx(
- "absolute w-3 h-3 rounded-full border border-white shadow-xs",
- props.resizable
- ? cx(
- "bg-blue-9 transition-transform hover:scale-125",
- corner.cursor,
- )
- : "bg-gray-8 cursor-not-allowed opacity-60",
+ "absolute w-3 h-3 group/handle",
+ props.resizable ? corner.cursor : "cursor-not-allowed",
corner.class,
)}
onMouseDown={(e) => {
@@ -784,7 +796,16 @@ function ElementBox(props: {
}
props.resizeHandler(corner.dirX, corner.dirY)(e);
}}
- />
+ >
+ <span
+ class={cx(
+ "block size-full rounded-full border border-white shadow-xs pointer-events-none",
+ props.resizable
+ ? "bg-blue-9 transition-transform group-hover/handle:scale-125"
+ : "bg-gray-8 opacity-60",
+ )}
+ />
+ </div>
)}
</For>
</Show>
diff --git a/apps/desktop/src/routes/editor/ClipsSidebar.tsx b/apps/desktop/src/routes/editor/ClipsSidebar.tsx
index f4fa2896e..e587fb0ec 100644
--- a/apps/desktop/src/routes/editor/ClipsSidebar.tsx
+++ b/apps/desktop/src/routes/editor/ClipsSidebar.tsx
@@ -304,7 +304,16 @@ function ClipsSidebarInner(props: { open: boolean; class?: string }) {
const resetRecordingTarget = () => {
const targetMode = untrack(() => rawOptions.targetMode);
if (targetMode != null) {
- setOptions("targetMode", null);
+ const source = untrack(() => rawOptions.targetModeSource) ?? "main";
+ // "superseded" only for a picker the editor owns: the editor is taking
+ // it over, so the main window must not treat the dismissal as a cancel
+ // and resurface itself. A main-owned picker dismissed from here keeps
+ // cancel semantics — the main window hid itself for that picker and
+ // must stay reachable.
+ setOptions({
+ targetMode: null,
+ targetModeDismissal: source === "main" ? "cancelled" : "superseded",
+ });
void commands.closeTargetSelectOverlays().catch(() => {});
}
void commands.setEditorRecordingTarget(null).catch(() => {});
diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
index 4b6928016..a8bb226a5 100644
--- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx
+++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
@@ -64,6 +64,8 @@ import {
type CursorAnimationStyle,
type CursorType,
commands,
+ type FrameConfiguration,
+ type FrameStyle,
type KeyboardTrackSegment,
type SceneMode,
type SceneSegment,
@@ -73,8 +75,13 @@ import {
type XY,
type ZoomSegment,
} from "~/utils/tauri";
+import IconLucideAppWindow from "~icons/lucide/app-window";
+import IconLucideAppWindowMac from "~icons/lucide/app-window-mac";
+import IconLucideBan from "~icons/lucide/ban";
import IconLucideBoxSelect from "~icons/lucide/box-select";
import IconLucideColumns2 from "~icons/lucide/columns-2";
+import IconLucideGlobe from "~icons/lucide/globe";
+import IconLucideLaptop from "~icons/lucide/laptop";
import IconLucideEyeOff from "~icons/lucide/eye-off";
import IconLucideGauge from "~icons/lucide/gauge";
import IconLucideGrid from "~icons/lucide/grid";
@@ -116,7 +123,11 @@ import {
} from "./projectConfig";
import ShadowSettings from "./ShadowSettings";
import { TextInput } from "./TextInput";
-import type { TextSegment } from "./text";
+import {
+ TEXT_FONT_SIZE_MAX,
+ TEXT_FONT_SIZE_MIN,
+ type TextSegment,
+} from "./text";
import {
ComingSoonTooltip,
EditorButton,
@@ -150,6 +161,13 @@ const BACKGROUND_SOURCES = {
none: "None",
} satisfies Record<BackgroundSourceTab, string>;
+const DEFAULT_FRAME_CONFIG: FrameConfiguration = {
+ style: "none",
+ theme: "dark",
+ url: "Cap.so",
+ title: "",
+};
+
const BACKGROUND_ICONS = {
wallpaper: imageBg,
image: transparentBg,
@@ -2542,6 +2560,110 @@ function BackgroundConfig(props: {
/>
</div>
</Field>
+ <Field name="Frame" icon={<IconLucideAppWindowMac class="size-4" />}>
+ <div class="flex flex-col gap-3">
+ <KTabs
+ value={project.background.frame?.style ?? "none"}
+ onChange={(v) => {
+ const style = v as FrameStyle;
+ setProject("background", "frame", {
+ ...(project.background.frame ?? DEFAULT_FRAME_CONFIG),
+ style,
+ });
+ }}
+ >
+ <KTabs.List class="grid grid-cols-2 gap-2">
+ <KTabs.Trigger value="none" class={SCENE_MODE_TRIGGER_CLASS}>
+ <IconLucideBan class="size-3.5" />
+ None
+ </KTabs.Trigger>
+ <KTabs.Trigger value="macOS" class={SCENE_MODE_TRIGGER_CLASS}>
+ <IconLucideAppWindowMac class="size-3.5" />
+ macOS Window
+ </KTabs.Trigger>
+ <KTabs.Trigger value="windows" class={SCENE_MODE_TRIGGER_CLASS}>
+ <IconLucideAppWindow class="size-3.5" />
+ Windows
+ </KTabs.Trigger>
+ <KTabs.Trigger value="browser" class={SCENE_MODE_TRIGGER_CLASS}>
+ <IconLucideGlobe class="size-3.5" />
+ Browser
+ </KTabs.Trigger>
+ <KTabs.Trigger value="macbook" class={SCENE_MODE_TRIGGER_CLASS}>
+ <IconLucideLaptop class="size-3.5" />
+ MacBook
+ </KTabs.Trigger>
+ </KTabs.List>
+ </KTabs>
+ <Show
+ when={
+ (project.background.frame?.style ?? "none") !== "none" &&
+ project.background.frame
+ }
+ >
+ {(frame) => (
+ <>
+ <Subfield name="Theme">
+ <KTabs
+ value={frame().theme}
+ onChange={(v) =>
+ setProject("background", "frame", {
+ ...frame(),
+ theme: v as FrameConfiguration["theme"],
+ })
+ }
+ >
+ <KTabs.List class="grid grid-cols-2 gap-2 min-w-44">
+ <KTabs.Trigger
+ value="light"
+ class={SCENE_MODE_TRIGGER_CLASS}
+ >
+ Light
+ </KTabs.Trigger>
+ <KTabs.Trigger
+ value="dark"
+ class={SCENE_MODE_TRIGGER_CLASS}
+ >
+ Dark
+ </KTabs.Trigger>
+ </KTabs.List>
+ </KTabs>
+ </Subfield>
+ <Show when={frame().style === "browser"}>
+ <Subfield name="URL">
+ <TextInput
+ class="w-full max-w-52 px-2.5 py-1.5 text-xs rounded-lg border bg-gray-1 border-gray-3 text-gray-12 focus:border-gray-7 outline-none"
+ value={frame().url}
+ placeholder="cap.so"
+ onInput={(e) =>
+ setProject("background", "frame", {
+ ...frame(),
+ url: e.currentTarget.value,
+ })
+ }
+ />
+ </Subfield>
+ </Show>
+ <Show when={frame().style === "macOS"}>
+ <Subfield name="Title">
+ <TextInput
+ class="w-full max-w-52 px-2.5 py-1.5 text-xs rounded-lg border bg-gray-1 border-gray-3 text-gray-12 focus:border-gray-7 outline-none"
+ value={frame().title}
+ placeholder="Window title (optional)"
+ onInput={(e) =>
+ setProject("background", "frame", {
+ ...frame(),
+ title: e.currentTarget.value,
+ })
+ }
+ />
+ </Subfield>
+ </Show>
+ </>
+ )}
+ </Show>
+ </div>
+ </Field>
<Field name="Motion Blur" icon={<IconLucideWind class="size-4" />}>
<Slider
value={[
@@ -3241,7 +3363,7 @@ function TextSegmentConfig(props: {
}) {
const { setProject } = useEditorContext();
const clampNumber = (value: number, min: number, max: number) =>
- Math.min(Math.max(Number.isFinite(value) ? value : min), max);
+ Math.min(Math.max(Number.isFinite(value) ? value : min, min), max);
const updateSegment = (fn: (segment: TextSegment) => void) => {
setProject(
@@ -3286,28 +3408,39 @@ function TextSegmentConfig(props: {
</Field>
<Field name="Size" icon={<IconCapEnlarge class="size-4" />}>
<Slider
- value={[clampNumber(props.segment.fontSize, 8, 200)]}
+ value={[
+ clampNumber(
+ props.segment.fontSize,
+ TEXT_FONT_SIZE_MIN,
+ TEXT_FONT_SIZE_MAX,
+ ),
+ ]}
onChange={([value]) =>
updateSegment((segment) => {
- const newFontSize = clampNumber(value, 8, 200);
+ const newFontSize = clampNumber(
+ value,
+ TEXT_FONT_SIZE_MIN,
+ TEXT_FONT_SIZE_MAX,
+ );
const oldFontSize = segment.fontSize || 48;
const scale = newFontSize / oldFontSize;
segment.fontSize = newFontSize;
- if (
- segment.size &&
- segment.size.x > 0.025 &&
- segment.size.y > 0.025
- ) {
- const maxSize = 0.95;
- segment.size.x = Math.min(segment.size.x * scale, maxSize);
- segment.size.y = Math.min(segment.size.y * scale, maxSize);
+ // Scale the box with the font so line wrapping is
+ // preserved; keep the top edge fixed since the renderer
+ // anchors text at the top of the box (the canvas overlay
+ // re-hugs the box to the exact glyph bounds when visible).
+ if (segment.size && segment.center) {
+ const topEdge = segment.center.y - segment.size.y / 2;
+ segment.size.x = Math.min(segment.size.x * scale, 1);
+ segment.size.y = segment.size.y * scale;
+ segment.center.y = topEdge + segment.size.y / 2;
}
})
}
- minValue={8}
- maxValue={200}
+ minValue={TEXT_FONT_SIZE_MIN}
+ maxValue={TEXT_FONT_SIZE_MAX}
step={1}
/>
</Field>
@@ -4362,6 +4495,8 @@ function ClipSegmentConfig(props: {
const clipConfig = () =>
project.clips?.find((c) => c.index === props.segmentIndex);
const offsets = () => clipConfig()?.offsets || {};
+ const offsetsAutoCalculated = () =>
+ clipConfig()?.offsetsAutoCalculated === true;
function setOffset(type: keyof ClipOffsets, offset: number) {
if (Number.isNaN(offset)) return;
@@ -4379,6 +4514,7 @@ function ClipSegmentConfig(props: {
}
clip.offsets[type] = offset / 1000;
+ clip.offsetsAutoCalculated = false;
}),
);
}
@@ -4445,12 +4581,19 @@ function ClipSegmentConfig(props: {
<p class="text-gray-11">
These settings apply to all segments for the current clip
</p>
+ <Show when={offsetsAutoCalculated()}>
+ <p class="text-gray-11">
+ Cap calculated these offsets automatically to keep audio in sync
+ with the video. Adjust them if anything still sounds off.
+ </p>
+ </Show>
</div>
{meta().hasSystemAudio && (
<SourceOffsetField
name="System Audio Offset"
value={offsets().system_audio}
+ autoCalculated={offsetsAutoCalculated()}
onChange={(offset) => {
setOffset("system_audio", offset);
}}
@@ -4460,6 +4603,7 @@ function ClipSegmentConfig(props: {
<SourceOffsetField
name="Microphone Offset"
value={offsets().mic}
+ autoCalculated={offsetsAutoCalculated()}
onChange={(offset) => {
setOffset("mic", offset);
}}
@@ -4469,6 +4613,7 @@ function ClipSegmentConfig(props: {
<SourceOffsetField
name="Camera Offset"
value={offsets().camera}
+ autoCalculated={offsetsAutoCalculated()}
onChange={(offset) => {
setOffset("camera", offset);
}}
@@ -4493,6 +4638,7 @@ function SourceOffsetField(props: {
name: string;
// seconds
value?: number;
+ autoCalculated?: boolean;
onChange: (value: number) => void;
}) {
const rawValue = () => Math.round((props.value ?? 0) * 1000);
@@ -4500,7 +4646,10 @@ function SourceOffsetField(props: {
const [value, setValue] = createSignal(rawValue().toString());
return (
- <Field name={props.name}>
+ <Field
+ name={props.name}
+ badge={props.autoCalculated ? "Auto-synced" : undefined}
+ >
<div class="flex flex-row justify-between items-center -mt-2 w-full">
<div class="flex flex-row items-end space-x-1">
<NumberField.Root
diff --git a/apps/desktop/src/routes/editor/Header.tsx b/apps/desktop/src/routes/editor/Header.tsx
index bff2e33aa..549e512af 100644
--- a/apps/desktop/src/routes/editor/Header.tsx
+++ b/apps/desktop/src/routes/editor/Header.tsx
@@ -125,22 +125,6 @@ export function Header() {
<span class="text-sm text-gray-11">.cap</span>
</div>
<div data-tauri-drag-region class="flex-1 h-full" />
- <EditorButton
- onClick={() => {
- if (clearTimelineSelection()) return;
- }}
- tooltipText="Captions"
- leftIcon={<IconCapCaptions class="w-5" />}
- comingSoon={true}
- />
- <EditorButton
- onClick={() => {
- if (clearTimelineSelection()) return;
- }}
- tooltipText="Performance"
- leftIcon={<IconCapGauge class="w-[18px]" />}
- comingSoon={true}
- />
</div>
<div
diff --git a/apps/desktop/src/routes/editor/TextOverlay.tsx b/apps/desktop/src/routes/editor/TextOverlay.tsx
index c4d75cd7c..a67c512e8 100644
--- a/apps/desktop/src/routes/editor/TextOverlay.tsx
+++ b/apps/desktop/src/routes/editor/TextOverlay.tsx
@@ -1,4 +1,7 @@
-import { createEventListenerMap } from "@solid-primitives/event-listener";
+import {
+ createEventListener,
+ createEventListenerMap,
+} from "@solid-primitives/event-listener";
import { throttle } from "@solid-primitives/scheduled";
import { cx } from "cva";
import {
@@ -9,19 +12,33 @@ import {
For,
on,
onCleanup,
- onMount,
+ Show,
} from "solid-js";
import { produce } from "solid-js/store";
import type { TextSegment as TauriTextSegment } from "~/utils/tauri";
import { useCanvasSnapTargets } from "./CanvasElementsOverlay";
import { FPS, useEditorContext } from "./context";
import { SNAP_PX, snapMovingRect } from "./snapping";
-import type { TextSegment } from "./text";
+import {
+ TEXT_FONT_SIZE_MAX,
+ TEXT_FONT_SIZE_MIN,
+ TEXT_REFERENCE_HEIGHT,
+ type TextSegment,
+} from "./text";
+
+// Figma-style text manipulation on the canvas: the selection box always hugs
+// the rendered glyphs (a hidden measure div mirrors the renderer's font
+// sizing), corner handles scale the font uniformly around the opposite
+// corner, dragging moves, double-click edits inline. `size` in the config is
+// purely the text's bounding box — `fontSize` alone controls glyph scale.
type TextOverlayProps = {
size: { width: number; height: number };
};
+const clamp = (value: number, min: number, max: number) =>
+ min > max ? (min + max) / 2 : Math.min(Math.max(value, min), max);
+
export function TextOverlay(props: TextOverlayProps) {
const {
project,
@@ -49,13 +66,6 @@ export function TextOverlay(props: TextOverlayProps) {
return selection.indices[0] ?? null;
});
- const clamp = (value: number, min: number, max: number) => {
- if (min > max) {
- return (min + max) / 2;
- }
- return Math.min(Math.max(value, min), max);
- };
-
const updateSegmentByIndex = (
index: number,
fn: (segment: TextSegment) => void,
@@ -71,41 +81,74 @@ export function TextOverlay(props: TextOverlayProps) {
);
};
- function createMouseDownDrag<T>(
- setup: () => T,
+ // Drags update visuals once per display frame (rAF-coalesced mousemove) so
+ // the box tracks the cursor with no perceptible lag; the heavier work of
+ // committing to the project store (and thus pushing config to the preview
+ // renderer) is throttled separately by the handlers.
+ function createMouseDownDrag<T extends { moved: boolean }>(
+ setup: () => T | null,
update: (
e: MouseEvent,
value: T,
initialMouse: { x: number; y: number },
+ isFinal: boolean,
) => void,
+ onFinish?: () => void,
) {
return (downEvent: MouseEvent) => {
+ if (downEvent.button !== 0) return;
+ const initial = setup();
+ if (!initial) return;
+ const state = initial;
+
downEvent.preventDefault();
downEvent.stopPropagation();
- const initial = setup();
const initialMouse = { x: downEvent.clientX, y: downEvent.clientY };
const resumeHistory = projectHistory.pause();
- function handleUpdate(event: MouseEvent) {
- update(event, initial, initialMouse);
+ function handleUpdate(event: MouseEvent, isFinal: boolean) {
+ // A plain click (e.g. the first half of a double-click) must not
+ // write config.
+ if (
+ !state.moved &&
+ Math.hypot(
+ event.clientX - initialMouse.x,
+ event.clientY - initialMouse.y,
+ ) < 2
+ )
+ return;
+ state.moved = true;
+ update(event, state, initialMouse, isFinal);
}
- const throttledUpdate = throttle(handleUpdate, 1000 / FPS);
+ let pendingEvent: MouseEvent | null = null;
+ let rafId: number | undefined;
+ function scheduleUpdate(event: MouseEvent) {
+ pendingEvent = event;
+ if (rafId !== undefined) return;
+ rafId = requestAnimationFrame(() => {
+ rafId = undefined;
+ const next = pendingEvent;
+ pendingEvent = null;
+ if (next) handleUpdate(next, false);
+ });
+ }
function finish(finalEvent: MouseEvent) {
- throttledUpdate.clear();
- handleUpdate(finalEvent);
+ if (rafId !== undefined) cancelAnimationFrame(rafId);
+ rafId = undefined;
+ pendingEvent = null;
+ handleUpdate(finalEvent, true);
resumeHistory();
setSnapGuides([]);
+ onFinish?.();
dispose();
}
- handleUpdate(downEvent);
-
const dispose = createRoot((dispose) => {
createEventListenerMap(window, {
- mousemove: throttledUpdate,
+ mousemove: scheduleUpdate,
mouseup: finish,
});
return dispose;
@@ -113,9 +156,7 @@ export function TextOverlay(props: TextOverlayProps) {
};
}
- const handleSelectSegment = (index: number, e: MouseEvent) => {
- e.preventDefault();
- e.stopPropagation();
+ const handleSelectSegment = (index: number) => {
setEditorState("timeline", "selection", {
type: "text",
indices: [index],
@@ -132,6 +173,51 @@ export function TextOverlay(props: TextOverlayProps) {
const hasTextSelection = () => selectedTextIndex() !== null;
+ // Arrow-key nudge for the selected text (1px, Shift = 10px), Escape
+ // deselects. Held keys repeat.
+ createEventListener(document, "keydown", (e: KeyboardEvent) => {
+ const index = selectedTextIndex();
+ if (index === null) return;
+ if (!visibleTextSegments().some((v) => v.index === index)) return;
+ const target = e.target as HTMLElement | null;
+ if (
+ target &&
+ (target.tagName === "INPUT" ||
+ target.tagName === "TEXTAREA" ||
+ target.isContentEditable)
+ )
+ return;
+
+ if (e.key === "Escape") {
+ setEditorState("timeline", "selection", null);
+ return;
+ }
+
+ const arrows: Record<string, [number, number]> = {
+ ArrowLeft: [-1, 0],
+ ArrowRight: [1, 0],
+ ArrowUp: [0, -1],
+ ArrowDown: [0, 1],
+ };
+ const dir = arrows[e.key];
+ if (!dir) return;
+
+ e.preventDefault();
+ const px = e.shiftKey ? 10 : 1;
+ updateSegmentByIndex(index, (s) => {
+ s.center.x = clamp(
+ s.center.x + (dir[0] * px) / props.size.width,
+ s.size.x / 2,
+ 1 - s.size.x / 2,
+ );
+ s.center.y = clamp(
+ s.center.y + (dir[1] * px) / props.size.height,
+ s.size.y / 2,
+ 1 - s.size.y / 2,
+ );
+ });
+ });
+
return (
<div
class="absolute inset-0"
@@ -145,10 +231,9 @@ export function TextOverlay(props: TextOverlayProps) {
segment={segment}
index={index}
isSelected={selectedTextIndex() === index}
- onSelect={(e) => handleSelectSegment(index, e)}
+ onSelect={() => handleSelectSegment(index)}
updateSegment={(fn) => updateSegmentByIndex(index, fn)}
createMouseDownDrag={createMouseDownDrag}
- clamp={clamp}
/>
)}
</For>
@@ -177,7 +262,7 @@ function normalizeSegment(segment: TauriTextSegment): SegmentWithDefaults {
enabled: segment.enabled ?? true,
content: segment.content ?? "Text",
center: segment.center ?? { x: 0.5, y: 0.5 },
- size: segment.size ?? { x: 0.01, y: 0.01 },
+ size: segment.size ?? { x: 0.35, y: 0.2 },
fontFamily: segment.fontFamily ?? "sans-serif",
fontSize: segment.fontSize ?? 48,
fontWeight: segment.fontWeight ?? 700,
@@ -186,151 +271,169 @@ function normalizeSegment(segment: TauriTextSegment): SegmentWithDefaults {
};
}
+// Extra normalized width the stored box gets over the measured ink, so small
+// font-metric differences between the browser and the renderer's shaper
+// (cosmic-text) can't cause a surprise line wrap.
+const WIDTH_SLACK_PX = 2;
+
function TextSegmentOverlay(props: {
size: { width: number; height: number };
segment: TauriTextSegment;
index: number;
isSelected: boolean;
- onSelect: (e: MouseEvent) => void;
+ onSelect: () => void;
updateSegment: (fn: (segment: TextSegment) => void) => void;
- createMouseDownDrag: <T>(
- setup: () => T,
+ createMouseDownDrag: <T extends { moved: boolean }>(
+ setup: () => T | null,
update: (
e: MouseEvent,
value: T,
initialMouse: { x: number; y: number },
+ isFinal: boolean,
) => void,
+ onFinish?: () => void,
) => (downEvent: MouseEvent) => void;
- clamp: (value: number, min: number, max: number) => number;
}) {
const segment = createMemo(() => normalizeSegment(props.segment));
- const { setSnapGuides } = useEditorContext();
+ const { setProject, setSnapGuides, projectHistory, projectActions } =
+ useEditorContext();
const snapTargetsFor = useCanvasSnapTargets();
- let hiddenMeasureRef: HTMLDivElement | undefined;
- const [mounted, setMounted] = createSignal(false);
- const [isResizing, setIsResizing] = createSignal(false);
- let pendingResizeCleanup: (() => void) | null = null;
-
- onMount(() => {
- setMounted(true);
- });
-
- onCleanup(() => {
- if (pendingResizeCleanup) {
- pendingResizeCleanup();
- pendingResizeCleanup = null;
- }
- setIsResizing(false);
- });
-
- const isDefaultSize = (size: { x: number; y: number }) =>
- size.x <= 0.025 || size.y <= 0.025;
-
- const [lastContent, setLastContent] = createSignal(segment().content);
- const [lastFontSize, setLastFontSize] = createSignal(segment().fontSize);
-
- const measureAndUpdateSize = (forceUpdate = false) => {
- if (!hiddenMeasureRef) return false;
+ let measureRef: HTMLDivElement | undefined;
+ let textareaRef: HTMLTextAreaElement | undefined;
+ const [resizing, setResizing] = createSignal(false);
+ const [hovered, setHovered] = createSignal(false);
+ const [editing, setEditing] = createSignal(false);
+
+ // During a drag the box follows this override at display rate; the store
+ // (and with it the preview renderer + undo history) receives throttled
+ // commits plus a final one on release, so cursor tracking never waits on
+ // config serialization.
+ const [dragOverride, setDragOverride] = createSignal<{
+ center: { x: number; y: number };
+ size: { x: number; y: number };
+ fontSize: number;
+ } | null>(null);
+
+ const view = () => {
+ const override = dragOverride();
+ if (override) return override;
const seg = segment();
- if (!forceUpdate && !isDefaultSize(seg.size)) return true;
+ return { center: seg.center, size: seg.size, fontSize: seg.fontSize };
+ };
- const { width: naturalWidth, height: naturalHeight } =
- hiddenMeasureRef.getBoundingClientRect();
+ // The exact pixel size the renderer draws this segment's glyphs at, in
+ // preview coordinates: fontSize is 1080p-relative, the preview canvas maps
+ // 1:1 onto the output frame. Reads the committed store value (not the
+ // drag override) so the measure div and hug effect don't churn on every
+ // pointer frame mid-drag.
+ const fontPx = () =>
+ (segment().fontSize * props.size.height) / TEXT_REFERENCE_HEIGHT;
+
+ const measureInk = () => {
+ if (!measureRef || !props.size.width || !props.size.height) return null;
+ const { width, height } = measureRef.getBoundingClientRect();
+ if (width === 0 || height === 0) return null;
+ return {
+ x: Math.min((width + WIDTH_SLACK_PX) / props.size.width, 1),
+ y: height / props.size.height,
+ };
+ };
+ // Fit the stored box to the measured text. The box adapts to the glyphs,
+ // never the other way around: the top edge and horizontal center stay
+ // fixed (the renderer anchors text at the top of the box and centers each
+ // line), so a hug never moves pixels on screen.
+ const applyHug = () => {
+ const ink = measureInk();
+ if (!ink) return;
+ const seg = segment();
+ const epsX = 0.5 / props.size.width;
+ const epsY = 0.5 / props.size.height;
if (
- naturalWidth === 0 ||
- naturalHeight === 0 ||
- !props.size.width ||
- !props.size.height
+ Math.abs(ink.x - seg.size.x) < epsX &&
+ Math.abs(ink.y - seg.size.y) < epsY
)
- return false;
-
- const normalizedWidth = naturalWidth / props.size.width;
- const normalizedHeight = naturalHeight / props.size.height;
-
+ return;
props.updateSegment((s) => {
- s.size.x = normalizedWidth;
- s.size.y = normalizedHeight;
+ const topEdge = s.center.y - s.size.y / 2;
+ s.size.x = ink.x;
+ s.size.y = ink.y;
+ s.center.y = topEdge + ink.y / 2;
});
- return true;
};
- createEffect(
- on(
- () => ({
- mounted: mounted(),
- containerWidth: props.size.width,
- containerHeight: props.size.height,
- }),
- () => {
- if (!mounted()) return;
- const tryMeasure = () => {
- if (!measureAndUpdateSize()) {
- requestAnimationFrame(tryMeasure);
- }
- };
- queueMicrotask(tryMeasure);
- },
- ),
- );
-
createEffect(
on(
() => ({
content: segment().content,
- fontSize: segment().fontSize,
+ fontPx: fontPx(),
fontWeight: segment().fontWeight,
fontFamily: segment().fontFamily,
italic: segment().italic,
+ width: props.size.width,
+ height: props.size.height,
}),
- (current) => {
- if (!mounted()) return;
- if (isResizing()) return;
-
- const contentChanged = current.content !== lastContent();
- const fontSizeChanged = current.fontSize !== lastFontSize();
-
- if (contentChanged || fontSizeChanged) {
- setLastContent(current.content);
- setLastFontSize(current.fontSize);
-
- queueMicrotask(() => {
- requestAnimationFrame(() => {
- if (!isResizing()) {
- measureAndUpdateSize(true);
- }
- });
- });
- }
+ () => {
+ if (resizing()) return;
+ applyHug();
+ // Re-check on the next frame: right after mount (or a font swap)
+ // the first layout pass can measure before the final metrics.
+ const raf = requestAnimationFrame(() => {
+ if (!resizing()) applyHug();
+ });
+ onCleanup(() => cancelAnimationFrame(raf));
},
),
);
const rect = () => {
- const seg = segment();
- const minDimension = 20;
- const width = Math.max(seg.size.x * props.size.width, minDimension);
- const height = Math.max(seg.size.y * props.size.height, minDimension);
- const left = Math.max(0, seg.center.x * props.size.width - width / 2);
- const top = Math.max(0, seg.center.y * props.size.height - height / 2);
- return { width, height, left, top };
+ const { center, size } = view();
+ const width = size.x * props.size.width;
+ const height = size.y * props.size.height;
+ return {
+ width,
+ height,
+ left: center.x * props.size.width - width / 2,
+ top: center.y * props.size.height - height / 2,
+ };
};
+ const thresholds = () => ({
+ x: SNAP_PX / Math.max(props.size.width, 1),
+ y: SNAP_PX / Math.max(props.size.height, 1),
+ });
+
+ const commitCenter = (center: { x: number; y: number }) =>
+ props.updateSegment((s) => {
+ s.center.x = center.x;
+ s.center.y = center.y;
+ });
+
const onMove = props.createMouseDownDrag(
() => {
+ if (editing()) return null;
const seg = segment();
return {
- startPos: { ...seg.center },
+ startCenter: { ...seg.center },
startSize: { ...seg.size },
+ startFontSize: seg.fontSize,
targets: snapTargetsFor({ text: props.index }),
+ commit: throttle(commitCenter, 1000 / FPS),
+ moved: false,
};
},
- (e, { startPos, startSize, targets }, initialMouse) => {
+ (e, state, initialMouse, isFinal) => {
const dx = (e.clientX - initialMouse.x) / props.size.width;
const dy = (e.clientY - initialMouse.y) / props.size.height;
+ const { startCenter, startSize } = state;
- const minPadding = 0.02;
+ const raw = {
+ x: startCenter.x + dx - startSize.x / 2,
+ y: startCenter.y + dy - startSize.y / 2,
+ w: startSize.x,
+ h: startSize.y,
+ };
let snapDx = 0;
let snapDy = 0;
@@ -338,163 +441,252 @@ function TextSegmentOverlay(props: {
setSnapGuides([]);
} else {
const snap = snapMovingRect(
- {
- x: startPos.x + dx - startSize.x / 2,
- y: startPos.y + dy - startSize.y / 2,
- w: startSize.x,
- h: startSize.y,
- },
- targets,
- SNAP_PX / props.size.width,
- SNAP_PX / props.size.height,
+ raw,
+ state.targets,
+ thresholds().x,
+ thresholds().y,
);
snapDx = snap.dx;
snapDy = snap.dy;
setSnapGuides(snap.guides);
}
- props.updateSegment((s) => {
- const newX = startPos.x + dx + snapDx;
- const newY = startPos.y + dy + snapDy;
-
- const halfW = s.size.x / 2;
- const halfH = s.size.y / 2;
+ // The box stays fully inside the frame (clamp() centers it if the
+ // box is somehow wider than the frame).
+ const center = {
+ x: clamp(
+ startCenter.x + dx + snapDx,
+ startSize.x / 2,
+ 1 - startSize.x / 2,
+ ),
+ y: clamp(
+ startCenter.y + dy + snapDy,
+ startSize.y / 2,
+ 1 - startSize.y / 2,
+ ),
+ };
- s.center.x = props.clamp(
- newX,
- halfW + minPadding,
- 1 - halfW - minPadding,
- );
- s.center.y = props.clamp(
- newY,
- halfH + minPadding,
- 1 - halfH - minPadding,
- );
+ setDragOverride({
+ center,
+ size: startSize,
+ fontSize: state.startFontSize,
});
+ if (isFinal) {
+ state.commit.clear();
+ commitCenter(center);
+ } else {
+ state.commit(center);
+ }
},
+ () => setDragOverride(null),
);
- const createResizeHandler = (dirX: -1 | 0 | 1, dirY: -1 | 0 | 1) => {
- const isCorner = dirX !== 0 && dirY !== 0;
+ const commitScaled = (next: {
+ center: { x: number; y: number };
+ size: { x: number; y: number };
+ fontSize: number;
+ }) =>
+ props.updateSegment((s) => {
+ s.fontSize = Math.round(next.fontSize * 10) / 10;
+ s.size.x = next.size.x;
+ s.size.y = next.size.y;
+ s.center.x = next.center.x;
+ s.center.y = next.center.y;
+ });
- const handler = props.createMouseDownDrag(
+ // Uniform, Figma-style scale: the dragged corner (or edge, when one dir
+ // is 0) tracks the pointer's projection onto its anchor line exactly (no
+ // gain heuristics — tight hug boxes made those feel twitchy), anchored at
+ // the opposite corner/edge while the box fits; at a frame edge the box
+ // pins and keeps scaling toward the remaining space.
+ const createResizeHandler = (dirX: 1 | 0 | -1, dirY: 1 | 0 | -1) =>
+ props.createMouseDownDrag(
() => {
- if (isCorner) {
- setIsResizing(true);
- }
+ if (editing()) return null;
+ setResizing(true);
const seg = segment();
+ const corner = {
+ x: seg.center.x + (dirX * seg.size.x) / 2,
+ y: seg.center.y + (dirY * seg.size.y) / 2,
+ };
return {
- startPos: { ...seg.center },
- startSize: { ...seg.size },
startFontSize: seg.fontSize,
+ startCenter: { ...seg.center },
+ startSize: { ...seg.size },
+ corner,
+ anchor: {
+ x: seg.center.x - (dirX * seg.size.x) / 2,
+ y: seg.center.y - (dirY * seg.size.y) / 2,
+ },
+ commit: throttle(commitScaled, 1000 / FPS),
+ moved: false,
};
},
- (e, { startPos, startSize, startFontSize }, initialMouse) => {
- const dx = (e.clientX - initialMouse.x) / props.size.width;
- const dy = (e.clientY - initialMouse.y) / props.size.height;
-
- const isSide = dirX !== 0 && dirY === 0;
-
- const minSize = 0.03;
- const maxSize = 0.95;
- const minPadding = 0.02;
-
- props.updateSegment((s) => {
- if (isSide) {
- const targetWidth = startSize.x + dx * dirX;
- const clampedWidth = props.clamp(targetWidth, minSize, maxSize);
- const appliedDelta = clampedWidth - startSize.x;
-
- s.size.x = clampedWidth;
-
- const halfWidth = s.size.x / 2;
- const halfHeight = s.size.y / 2;
- s.center.x = props.clamp(
- startPos.x + (dirX * appliedDelta) / 2,
- halfWidth + minPadding,
- 1 - halfWidth - minPadding,
- );
- s.center.y = props.clamp(
- s.center.y,
- halfHeight + minPadding,
- 1 - halfHeight - minPadding,
- );
- } else if (isCorner) {
- const currentHeightPx = startSize.y * props.size.height;
- const deltaPxY = dy * props.size.height * dirY;
-
- const scaleY = (currentHeightPx + deltaPxY) / currentHeightPx;
- const scale = scaleY;
-
- if (scale > 0.1 && scale < 10) {
- const newFontSize = props.clamp(startFontSize * scale, 8, 400);
- const newSizeX = props.clamp(
- startSize.x * scale,
- minSize,
- maxSize,
- );
- const newSizeY = props.clamp(
- startSize.y * scale,
- minSize,
- maxSize,
- );
-
- s.fontSize = newFontSize;
- s.size.x = newSizeX;
- s.size.y = newSizeY;
-
- const widthDiff = s.size.x - startSize.x;
- const heightDiff = s.size.y - startSize.y;
-
- const halfWidth = s.size.x / 2;
- const halfHeight = s.size.y / 2;
- s.center.x = props.clamp(
- startPos.x + (widthDiff * dirX) / 2,
- halfWidth + minPadding,
- 1 - halfWidth - minPadding,
- );
- s.center.y = props.clamp(
- startPos.y + (heightDiff * dirY) / 2,
- halfHeight + minPadding,
- 1 - halfHeight - minPadding,
- );
- }
- }
- });
+ (e, state, initialMouse, isFinal) => {
+ const { anchor, corner, startCenter, startSize, startFontSize } = state;
+ const pointer = {
+ x: corner.x + (e.clientX - initialMouse.x) / props.size.width,
+ y: corner.y + (e.clientY - initialMouse.y) / props.size.height,
+ };
+ const d = { x: corner.x - anchor.x, y: corner.y - anchor.y };
+ const dLen2 = d.x * d.x + d.y * d.y;
+ let scale =
+ dLen2 > 0
+ ? ((pointer.x - anchor.x) * d.x + (pointer.y - anchor.y) * d.y) /
+ dLen2
+ : 1;
+
+ // No guide snapping while scaling — a snapped corner multiplies
+ // across the whole box and reads as an abrupt jump. The only
+ // limits are the font range and "the box fits in the frame".
+ const minScale = TEXT_FONT_SIZE_MIN / startFontSize;
+ const maxScale = Math.min(
+ TEXT_FONT_SIZE_MAX / startFontSize,
+ 1 / Math.max(startSize.x, startSize.y),
+ );
+ scale = clamp(scale, minScale, Math.max(maxScale, minScale));
+
+ // Scale around the anchor, then slide the box back in-bounds.
+ // While everything fits the anchor stays put; once the dragged
+ // corner reaches an edge the box pins there and keeps growing
+ // toward the other side instead of freezing.
+ const size = { x: startSize.x * scale, y: startSize.y * scale };
+ const center = {
+ x: clamp(
+ anchor.x + (startCenter.x - anchor.x) * scale,
+ size.x / 2,
+ 1 - size.x / 2,
+ ),
+ y: clamp(
+ anchor.y + (startCenter.y - anchor.y) * scale,
+ size.y / 2,
+ 1 - size.y / 2,
+ ),
+ };
+ const next = { fontSize: startFontSize * scale, size, center };
+
+ setDragOverride(next);
+ if (isFinal) {
+ state.commit.clear();
+ commitScaled(next);
+ } else {
+ state.commit(next);
+ }
+ },
+ () => {
+ setResizing(false);
+ setDragOverride(null);
+ // The box was scaled geometrically during the drag; snap it back
+ // to the true measured ink.
+ requestAnimationFrame(() => applyHug());
},
);
- return (downEvent: MouseEvent) => {
- handler(downEvent);
- if (isCorner) {
- const onMouseUp = () => {
- setIsResizing(false);
- window.removeEventListener("mouseup", onMouseUp);
- pendingResizeCleanup = null;
- };
- window.addEventListener("mouseup", onMouseUp);
- pendingResizeCleanup = () => {
- setIsResizing(false);
- window.removeEventListener("mouseup", onMouseUp);
- };
- }
+ // Inline editing: the rendered text is hidden (hiddenTextSegments reaches
+ // the renderer but never persists) and a transparent textarea styled to
+ // match takes its place. History is paused so the whole edit is one undo
+ // entry.
+ let endEditing: (() => void) | null = null;
+ const startEditing = () => {
+ if (editing()) return;
+ const resumeHistory = projectHistory.pause();
+ setEditing(true);
+ setProject("hiddenTextSegments", [props.index]);
+ queueMicrotask(() => {
+ textareaRef?.focus();
+ textareaRef?.select();
+ });
+ endEditing = () => {
+ endEditing = null;
+ setEditing(false);
+ setProject("hiddenTextSegments", []);
+ const empty = segment().content.trim() === "";
+ if (empty) projectActions.deleteTextSegments([props.index]);
+ resumeHistory();
};
};
+ onCleanup(() => {
+ endEditing?.();
+ setResizing(false);
+ });
+
+ // Invisible strips along the border: dragging an edge scales the text,
+ // anchored at the opposite edge (e.g. pulling the bottom edge down grows
+ // the text with its top pinned). Inset so the corner dots win at the ends.
+ const edges = [
+ {
+ dirX: 0 as const,
+ dirY: -1 as const,
+ class: "top-0 inset-x-2.5 h-2.5 -translate-y-1/2 cursor-ns-resize",
+ },
+ {
+ dirX: 0 as const,
+ dirY: 1 as const,
+ class: "bottom-0 inset-x-2.5 h-2.5 translate-y-1/2 cursor-ns-resize",
+ },
+ {
+ dirX: -1 as const,
+ dirY: 0 as const,
+ class: "left-0 inset-y-2.5 w-2.5 -translate-x-1/2 cursor-ew-resize",
+ },
+ {
+ dirX: 1 as const,
+ dirY: 0 as const,
+ class: "right-0 inset-y-2.5 w-2.5 translate-x-1/2 cursor-ew-resize",
+ },
+ ];
+
+ const corners = [
+ {
+ dirX: -1 as const,
+ dirY: -1 as const,
+ class: "top-0 left-0 -translate-x-1/2 -translate-y-1/2 cursor-nw-resize",
+ },
+ {
+ dirX: 1 as const,
+ dirY: -1 as const,
+ class: "top-0 right-0 translate-x-1/2 -translate-y-1/2 cursor-ne-resize",
+ },
+ {
+ dirX: -1 as const,
+ dirY: 1 as const,
+ class:
+ "bottom-0 left-0 -translate-x-1/2 translate-y-1/2 cursor-sw-resize",
+ },
+ {
+ dirX: 1 as const,
+ dirY: 1 as const,
+ class:
+ "bottom-0 right-0 translate-x-1/2 translate-y-1/2 cursor-se-resize",
+ },
+ ];
+
+ // The letterbox wrapper has `contain: strict`, so keep the label inside
+ // the visible area when the box touches the frame's top edge.
+ const labelStyle = () => ({
+ left: `${Math.max(6, 6 - rect().left)}px`,
+ top: rect().top >= 28 ? "-24px" : `${Math.max(6, 6 - rect().top)}px`,
+ });
+
+ const textStyle = () => ({
+ "font-family": segment().fontFamily,
+ "font-size": `${fontPx()}px`,
+ "font-weight": segment().fontWeight,
+ "font-style": segment().italic ? "italic" : "normal",
+ "line-height": 1.2,
+ });
return (
<>
<div
- ref={hiddenMeasureRef}
+ ref={measureRef}
style={{
+ ...textStyle(),
position: "absolute",
visibility: "hidden",
+ "pointer-events": "none",
"white-space": "pre-wrap",
"word-break": "break-word",
- "font-family": segment().fontFamily,
- "font-size": `${segment().fontSize}px`,
- "font-weight": segment().fontWeight,
- "font-style": segment().italic ? "italic" : "normal",
- "line-height": 1.2,
"max-width": `${props.size.width}px`,
width: "fit-content",
height: "auto",
@@ -509,8 +701,8 @@ function TextSegmentOverlay(props: {
<div
class="absolute pointer-events-auto"
classList={{
- "cursor-move": !props.isSelected,
- group: props.isSelected,
+ "cursor-move": !editing(),
+ "cursor-text": editing(),
}}
style={{
left: `${rect().left}px`,
@@ -519,64 +711,88 @@ function TextSegmentOverlay(props: {
height: `${rect().height}px`,
}}
onMouseDown={(e) => {
- if (!props.isSelected) {
- props.onSelect(e);
- }
+ if (e.button !== 0) return;
+ if (!props.isSelected) props.onSelect();
onMove(e);
}}
+ onDblClick={() => startEditing()}
+ onMouseEnter={() => setHovered(true)}
+ onMouseLeave={() => setHovered(false)}
>
<div
- class="absolute inset-0 rounded-md border-2 transition-colors"
+ class="absolute inset-0 border-2 transition-colors rounded-md pointer-events-none"
classList={{
- "border-blue-9 bg-blue-9/10 cursor-move": props.isSelected,
- "border-transparent hover:border-blue-6 hover:bg-blue-9/5":
- !props.isSelected,
+ "border-blue-9": props.isSelected,
+ "border-blue-6": !props.isSelected && hovered(),
+ "border-transparent": !props.isSelected && !hovered(),
}}
/>
- {props.isSelected && (
- <>
- <ResizeHandle
- class="top-0 left-0 -translate-x-1/2 -translate-y-1/2 cursor-nw-resize"
- onMouseDown={createResizeHandler(-1, -1)}
- />
- <ResizeHandle
- class="top-0 right-0 translate-x-1/2 -translate-y-1/2 cursor-ne-resize"
- onMouseDown={createResizeHandler(1, -1)}
- />
- <ResizeHandle
- class="bottom-0 left-0 -translate-x-1/2 translate-y-1/2 cursor-sw-resize"
- onMouseDown={createResizeHandler(-1, 1)}
- />
- <ResizeHandle
- class="bottom-0 right-0 translate-x-1/2 translate-y-1/2 cursor-se-resize"
- onMouseDown={createResizeHandler(1, 1)}
- />
- <ResizeHandle
- class="left-0 top-1/2 -translate-x-1/2 -translate-y-1/2 cursor-w-resize"
- onMouseDown={createResizeHandler(-1, 0)}
- />
- <ResizeHandle
- class="right-0 top-1/2 translate-x-1/2 -translate-y-1/2 cursor-e-resize"
- onMouseDown={createResizeHandler(1, 0)}
- />
- </>
- )}
+ <Show when={(props.isSelected || hovered()) && !editing()}>
+ <div
+ class="absolute px-1.5 py-0.5 text-[11px] font-medium text-white bg-blue-9 rounded pointer-events-none select-none"
+ style={labelStyle()}
+ >
+ Text
+ </div>
+ </Show>
+ <Show when={editing()}>
+ <textarea
+ ref={textareaRef}
+ class="absolute inset-0 p-0 text-center bg-transparent border-none outline-none resize-none overflow-hidden"
+ style={{
+ ...textStyle(),
+ color: segment().color,
+ "caret-color": segment().color,
+ "white-space": "pre-wrap",
+ "word-break": "break-word",
+ }}
+ value={segment().content}
+ onInput={(e) =>
+ props.updateSegment((s) => {
+ s.content = e.currentTarget.value;
+ })
+ }
+ onKeyDown={(e) => {
+ e.stopPropagation();
+ if (e.key === "Escape") {
+ e.preventDefault();
+ textareaRef?.blur();
+ }
+ }}
+ onMouseDown={(e) => e.stopPropagation()}
+ onBlur={() => endEditing?.()}
+ />
+ </Show>
+ <Show when={(props.isSelected || hovered()) && !editing()}>
+ <For each={edges}>
+ {(edge) => (
+ <div
+ class={cx("absolute", edge.class)}
+ onMouseDown={createResizeHandler(edge.dirX, edge.dirY)}
+ />
+ )}
+ </For>
+ <For each={corners}>
+ {(corner) => (
+ // The hit target is larger than the visible dot (text boxes
+ // hug the glyphs, so corners are small targets), and must
+ // not change size on hover — the grow effect lives on an
+ // inner, pointer-events-none span, otherwise the handle
+ // scales out from under the cursor and hover flickers in a
+ // mouseenter/leave loop.
+ <div
+ class={cx(
+ "absolute w-5 h-5 grid place-items-center group/handle",
+ corner.class,
+ )}
+ onMouseDown={createResizeHandler(corner.dirX, corner.dirY)}
+ >
+ <span class="w-3 h-3 rounded-full border border-white shadow-xs pointer-events-none bg-blue-9 transition-transform group-hover/handle:scale-125" />
+ </div>
+ )}
+ </For>
+ </Show>
</div>
</>
);
}
-
-function ResizeHandle(props: {
- class?: string;
- onMouseDown: (e: MouseEvent) => void;
-}) {
- return (
- <div
- class={cx(
- "absolute w-3 h-3 bg-blue-9 border border-white rounded-full shadow-xs transition-transform hover:scale-125",
- props.class,
- )}
- onMouseDown={props.onMouseDown}
- />
- );
-}
diff --git a/apps/desktop/src/routes/editor/Timeline/TextTrack.tsx b/apps/desktop/src/routes/editor/Timeline/TextTrack.tsx
index 92e291c55..1e8500f24 100644
--- a/apps/desktop/src/routes/editor/Timeline/TextTrack.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/TextTrack.tsx
@@ -136,6 +136,20 @@ export function TextTrack(props: {
sortTrackSegments(segments);
}),
);
+
+ // Select the new segment right away so its canvas box and config
+ // sidebar appear without an extra click.
+ const newIndex = (project.timeline?.textSegments ?? []).findIndex(
+ (segment) =>
+ segment.start === placement.start &&
+ getSegmentTrack(segment) === props.laneIndex,
+ );
+ if (newIndex !== -1) {
+ setEditorState("timeline", "selection", {
+ type: "text",
+ indices: [newIndex],
+ });
+ }
};
const newSegmentDetails = createMemo(() => {
diff --git a/apps/desktop/src/routes/editor/text.ts b/apps/desktop/src/routes/editor/text.ts
index 4044a3c3f..96b23f6ef 100644
--- a/apps/desktop/src/routes/editor/text.ts
+++ b/apps/desktop/src/routes/editor/text.ts
@@ -1,5 +1,11 @@
import type { XY } from "~/utils/tauri";
+// Font sizes are authored in pixels against a 1080p-tall reference frame;
+// the renderer scales them by outputHeight / 1080 (crates/rendering/text.rs).
+export const TEXT_REFERENCE_HEIGHT = 1080;
+export const TEXT_FONT_SIZE_MIN = 8;
+export const TEXT_FONT_SIZE_MAX = 400;
+
export type TextSegment = {
start: number;
end: number;
@@ -26,7 +32,9 @@ export const defaultTextSegment = (
enabled: true,
content: "Text",
center: { x: 0.5, y: 0.5 },
- size: { x: 0.35, y: 0.2 },
+ // Rough hug of "Text" at 48px/1080p; the canvas overlay measures and
+ // fits the box to the exact glyph bounds as soon as it renders.
+ size: { x: 0.1, y: 0.055 },
fontFamily: "sans-serif",
fontSize: 48,
fontWeight: 700,
diff --git a/apps/desktop/src/routes/target-select-overlay.tsx b/apps/desktop/src/routes/target-select-overlay.tsx
index 7a34da63a..f0a58a9cd 100644
--- a/apps/desktop/src/routes/target-select-overlay.tsx
+++ b/apps/desktop/src/routes/target-select-overlay.tsx
@@ -314,11 +314,30 @@ function Inner() {
});
const unsubOnEscapePress = events.onEscapePress.listen(() => {
- setOptions("targetMode", null);
+ setOptions({ targetMode: null, targetModeDismissal: "cancelled" });
commands.closeTargetSelectOverlays();
});
onCleanup(() => unsubOnEscapePress.then((f) => f()));
+ // Dismiss the picker because a recording is starting. The dismissal reason
+ // rides along with `targetMode: null` so the main window never has to guess
+ // (from possibly-stale query state) whether it may reveal itself again.
+ const dismissPickerForRecordingStart = () => {
+ if (options.mode === "screenshot") return;
+ const targetModeDismissal =
+ options.mode === "instant" ? "recordingInstant" : "recordingStudio";
+ if (options.targetModeSource === "editor") {
+ setOptions({
+ targetMode: null,
+ targetModeSource: "editorRecording",
+ targetModeDismissal,
+ });
+ } else {
+ setOptions({ targetMode: null, targetModeDismissal });
+ }
+ commands.closeTargetSelectOverlays();
+ };
+
// This prevents browser keyboard shortcuts from firing.
// Eg. on Windows Ctrl+P would open the print dialog without this
createEventListener(document, "keydown", (e) => e.preventDefault());
@@ -340,8 +359,12 @@ function Inner() {
<RecordingControls
target={{ variant: "cameraOnly" } as ScreenCaptureTarget}
showBackground
+ onRecordingStart={dismissPickerForRecordingStart}
onClose={() => {
- setOptions("targetMode", null);
+ setOptions({
+ targetMode: null,
+ targetModeDismissal: "cancelled",
+ });
commands.closeTargetSelectOverlays();
}}
/>
@@ -390,8 +413,12 @@ function Inner() {
<RecordingControls
setToggleModeSelect={setToggleModeSelect}
target={{ variant: "display", id: displayId() }}
+ onRecordingStart={dismissPickerForRecordingStart}
onClose={() => {
- setOptions("targetMode", null);
+ setOptions({
+ targetMode: null,
+ targetModeDismissal: "cancelled",
+ });
commands.closeTargetSelectOverlays();
}}
/>
@@ -625,20 +652,33 @@ function Inner() {
}}
onRecordingStart={() => {
setOriginalCameraBounds(null);
- if (options.targetModeSource === "editor") {
- setOptions({
- targetMode: null,
- targetModeSource: "editorRecording",
- });
+ if (options.mode === "screenshot") {
+ // The window variant has always dismissed the picker
+ // for screenshots too; keep that, tagged as such.
+ if (options.targetModeSource === "editor") {
+ setOptions({
+ targetMode: null,
+ targetModeSource: "editorRecording",
+ targetModeDismissal: "screenshot",
+ });
+ } else {
+ setOptions({
+ targetMode: null,
+ targetModeDismissal: "screenshot",
+ });
+ }
+ commands.closeTargetSelectOverlays();
} else {
- setOptions("targetMode", null);
+ dismissPickerForRecordingStart();
}
- commands.closeTargetSelectOverlays();
}}
onClose={() => {
setSelectedWindow(null);
setLockedIcon(null);
- setOptions("targetMode", null);
+ setOptions({
+ targetMode: null,
+ targetModeDismissal: "cancelled",
+ });
commands.closeTargetSelectOverlays();
}}
/>
@@ -1126,9 +1166,15 @@ function Inner() {
}}
disabled={!isValid()}
showBackground={controllerInside()}
- onRecordingStart={() => setOriginalCameraBounds(null)}
+ onRecordingStart={() => {
+ setOriginalCameraBounds(null);
+ dismissPickerForRecordingStart();
+ }}
onClose={() => {
- setOptions("targetMode", null);
+ setOptions({
+ targetMode: null,
+ targetModeDismissal: "cancelled",
+ });
commands.closeTargetSelectOverlays();
}}
/>
@@ -1673,7 +1719,10 @@ function RecordingControls(props: {
if (props.onClose) {
props.onClose();
} else {
- setOptions("targetMode", null);
+ setOptions({
+ targetMode: null,
+ targetModeDismissal: "cancelled",
+ });
commands.setEditorRecordingTarget(null);
commands.closeTargetSelectOverlays();
}
diff --git a/apps/desktop/src/utils/queries.ts b/apps/desktop/src/utils/queries.ts
index 613b33cbf..4118d0cb9 100644
--- a/apps/desktop/src/utils/queries.ts
+++ b/apps/desktop/src/utils/queries.ts
@@ -150,6 +150,20 @@ export const isSystemAudioSupported = queryOptions({
type CameraCaptureTarget = ScreenCaptureTarget | { variant: "cameraOnly" };
type ExtendedRecordingTargetMode = RecordingTargetMode | "camera" | null;
type RecordingTargetModeSource = "main" | "editor" | "editorRecording" | null;
+/**
+ * Why the target picker was last dismissed. Written in the same `setOptions`
+ * call that sets `targetMode: null`, so it reaches other webviews atomically
+ * with the dismissal. The main window's reveal logic keys off this instead of
+ * reconstructing the outcome from query data or effect ordering — the hidden
+ * main webview can be suspended by WebKit, which makes any state it derives
+ * "at dismissal time" arbitrarily stale.
+ */
+export type TargetModeDismissal =
+ | "recordingStudio"
+ | "recordingInstant"
+ | "screenshot"
+ | "superseded"
+ | "cancelled";
export function createOptionsQuery() {
const PERSIST_KEY = "recording-options-query-2";
@@ -160,6 +174,7 @@ export function createOptionsQuery() {
captureSystemAudio?: boolean;
targetMode?: ExtendedRecordingTargetMode;
targetModeSource?: RecordingTargetModeSource;
+ targetModeDismissal?: TargetModeDismissal | null;
cameraID?: DeviceOrModelID | null;
organizationId?: string | null;
/** @deprecated */
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 4f2f6b9f5..53da4a754 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -599,9 +599,15 @@ export type BackgroundBlurMode = "off" | "light" | "heavy"
export type BackgroundConfiguration = { source: BackgroundSource; blur: number; padding: number; rounding: number; roundingType: CornerStyle; inset: number; crop: Crop | null;
/**
* Normalized (0-1) center of the display rect in output-frame space.
- * `None` keeps the display centered.
+ * `None` keeps the display centered. When a frame is active this is the
+ * center of the framed card (chrome included), not the bare video.
*/
-displayPosition: XY<number> | null; shadow: number; advancedShadow: ShadowConfiguration | null; border: BorderConfiguration | null }
+displayPosition: XY<number> | null; shadow: number; advancedShadow: ShadowConfiguration | null; border: BorderConfiguration | null;
+/**
+ * Decorative frame around the recording. `None` (or `FrameStyle::None`)
+ * renders the bare video exactly as before the feature existed.
+ */
+frame: FrameConfiguration | null }
export type BackgroundSource = { type: "wallpaper"; path: string | null } | { type: "image"; path: string | null } | { type: "color"; value: [number, number, number]; alpha?: number } | { type: "gradient"; from: [number, number, number]; to: [number, number, number]; angle?: number; noise_intensity?: number | null; noise_scale?: number | null; animated?: boolean | null; animation_speed?: number | null }
export type BorderConfiguration = { enabled: boolean; width: number; color: [number, number, number]; opacity: number }
export type Camera = { hide: boolean; mirror: boolean; position: CameraPosition;
@@ -647,7 +653,13 @@ export type CliInstallStatus = { installDir: string; shimPath: string; targetPat
*/
pathConfigured: boolean }
export type ClickSpringConfig = { tension: number; mass: number; friction: number }
-export type ClipConfiguration = { index: number; offsets: ClipOffsets }
+export type ClipConfiguration = { index: number; offsets: ClipOffsets;
+/**
+ * Whether `offsets` were computed automatically (recording start-time
+ * alignment + device sync calibration) rather than entered by the user.
+ * Cleared by the editor UI once the user edits an offset.
+ */
+offsetsAutoCalculated?: boolean }
export type ClipOffsets = { camera?: number; mic?: number; system_audio?: number }
export type ClipboardSource = "raw" | "rendered"
export type CommercialLicense = { licenseKey: string; expiryDate: number | null; refresh: number; activatedOn: number }
@@ -680,13 +692,57 @@ export type ExportProfile = { format: ExportFormat; fps?: number; resolutionBase
export type ExportSettings = ({ format: "Mp4" } & Mp4ExportSettings) | ({ format: "Gif" } & GifExportSettings) | ({ format: "Mov" } & MovExportSettings)
export type FileType = "recording" | "screenshot"
export type Flags = { captions: boolean }
+export type FrameConfiguration = { style: FrameStyle; theme: FrameTheme;
+/**
+ * Text shown in the browser style's URL pill.
+ */
+url: string;
+/**
+ * Text shown in the macOS window style's title bar.
+ */
+title: string }
/**
* Rendered display/camera placement of the latest preview frame, in
* output-frame pixels — consumed by the editor's on-canvas layout overlay.
*/
export type FrameLayoutEvent = { display: [number, number, number, number]; camera: [number, number, number, number] | null; output_width: number; output_height: number }
+/**
+ * Decorative frame drawn around the screen recording (browser window,
+ * macOS window, MacBook bezel, ...). The video is inset inside the frame's
+ * chrome; the framed card as a whole follows padding / position / zoom
+ * exactly like the bare video does today.
+ */
+export type FrameStyle =
+/**
+ * No frame: the video renders bare, exactly as before this feature.
+ */
+"none" |
+/**
+ * A macOS window title bar with traffic-light buttons.
+ */
+"macOS" |
+/**
+ * A Windows 11 window title bar with minimize/maximize/close controls.
+ */
+"windows" |
+/**
+ * A browser toolbar: traffic lights plus a centered URL pill.
+ */
+"browser" |
+/**
+ * A MacBook mockup: black bezel, aluminum body and deck.
+ */
+"macbook"
+export type FrameTheme = "dark" | "light"
export type FramesRendered = { renderedCount: number; totalFrames: number; type: "FramesRendered" }
-export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?: boolean; hideDockIcon?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; commercialLicense?: CommercialLicense | null; lastVersion?: string | null; windowTransparency?: boolean; postStudioRecordingBehaviour?: PostStudioRecordingBehaviour; mainWindowRecordingStartBehaviour?: MainWindowRecordingStartBehaviour; custom_cursor_capture2?: boolean; serverUrl?: string; recordingCountdown?: number | null; enableNativeCameraPreview: boolean; autoZoomOnClicks?: boolean; captureKeyboardEvents?: boolean; postDeletionBehaviour?: PostDeletionBehaviour; excludedWindows?: WindowExclusion[]; deleteInstantRecordingsAfterUpload?: boolean; instantModeMaxResolution?: number; defaultProjectNameTemplate?: string | null; crashRecoveryRecording?: boolean; maxFps?: number; transcriptionHints?: string[]; editorPreviewQuality?: EditorPreviewQuality; studioRecordingQuality?: StudioRecordingQuality; mainWindowPosition?: WindowPosition | null; cameraWindowPosition?: WindowPosition | null; cameraWindowPositionsByMonitorName?: { [key in string]: WindowPosition }; hasCompletedOnboarding?: boolean; enableTelemetry?: boolean; outOfProcessMuxer?: boolean; recordingsPath?: string | null }
+export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?: boolean; hideDockIcon?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; commercialLicense?: CommercialLicense | null; lastVersion?: string | null; windowTransparency?: boolean; postStudioRecordingBehaviour?: PostStudioRecordingBehaviour; mainWindowRecordingStartBehaviour?: MainWindowRecordingStartBehaviour; custom_cursor_capture2?: boolean; serverUrl?: string; recordingCountdown?: number | null; enableNativeCameraPreview: boolean; autoZoomOnClicks?: boolean; captureKeyboardEvents?: boolean; postDeletionBehaviour?: PostDeletionBehaviour; excludedWindows?: WindowExclusion[]; deleteInstantRecordingsAfterUpload?: boolean; instantModeMaxResolution?: number; defaultProjectNameTemplate?: string | null; crashRecoveryRecording?: boolean; maxFps?: number; transcriptionHints?: string[]; editorPreviewQuality?: EditorPreviewQuality; studioRecordingQuality?: StudioRecordingQuality; mainWindowPosition?: WindowPosition | null; cameraWindowPosition?: WindowPosition | null; cameraWindowPositionsByMonitorName?: { [key in string]: WindowPosition }; hasCompletedOnboarding?: boolean; enableTelemetry?: boolean; outOfProcessMuxer?: boolean; recordingsPath?: string | null;
+/**
+ * App version at which camera background blur was disabled after a crash
+ * was attributed to the blur pipeline; `None` means blur is allowed.
+ * Cleared automatically when the app version changes (one retry per
+ * update, since a new ort/wgpu/driver stack may have fixed the crash).
+ */
+cameraBlurDisabledByCrash?: string | null }
export type GifExportSettings = { fps: number; resolution_base: XY<number>; quality: GifQuality | null }
export type GifQuality = {
/**
@@ -755,7 +811,16 @@ export type PostDeletionBehaviour = "doNothing" | "reopenRecordingWindow"
export type PostStudioRecordingBehaviour = "openEditor" | "showOverlay"
export type Preset = { name: string; config: ProjectConfiguration }
export type PresetsStore = { presets: Preset[]; default: number | null }
-export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: Camera; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline: TimelineConfiguration | null; captions: CaptionsData | null; keyboard: KeyboardData | null; clips: ClipConfiguration[]; annotations: Annotation[]; screenMotionBlur?: number; screenMovementSpring?: ScreenMovementSpring }
+export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: Camera; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline: TimelineConfiguration | null; captions: CaptionsData | null; keyboard: KeyboardData | null; clips: ClipConfiguration[]; annotations: Annotation[]; screenMotionBlur?: number; screenMovementSpring?: ScreenMovementSpring;
+/**
+ * How text segment font sizes are interpreted. 0 (legacy): the renderer
+ * multiplied `font_size` by `size.y / 0.2`, coupling glyph size to the
+ * box. 1: `font_size` alone determines glyph size (1080p-relative);
+ * legacy configs are migrated on load by baking the box factor into
+ * `font_size`. The field-level default keeps old files at 0 while
+ * `Default::default()` produces the current version.
+ */
+textSizeVersion?: number }
export type ProjectRecordingsMeta = { segments: SegmentRecordings[] }
export type RecordingAction = "Started" | "InvalidAuthentication" | "UpgradeRequired"
export type RecordingDeleted = { path: string }
diff --git a/crates/camera-effects/src/lib.rs b/crates/camera-effects/src/lib.rs
index 259adbb05..de5992f11 100644
--- a/crates/camera-effects/src/lib.rs
+++ b/crates/camera-effects/src/lib.rs
@@ -1,13 +1,55 @@
mod blur_pipeline;
mod segmentation;
-use std::sync::Arc;
-use std::sync::atomic::{AtomicU8, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
+use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant};
use blur_pipeline::{BlurPassInputs, BlurPipeline, CompositePipeline};
use segmentation::SegmentationModel;
+static BLUR_DISABLED: AtomicBool = AtomicBool::new(false);
+static BLUR_SESSION_OBSERVER: OnceLock<fn(bool)> = OnceLock::new();
+
+/// Globally disables camera background blur: `BlurProcessor::new` fails fast and
+/// every call site degrades to its unblurred fallback. Set by the desktop app's
+/// crash recovery when a previous session died with the blur pipeline active
+/// (native DirectML/driver crashes never reach a panic handler).
+pub fn set_blur_disabled(disabled: bool) {
+ BLUR_DISABLED.store(disabled, Ordering::Release);
+}
+
+pub fn blur_disabled() -> bool {
+ BLUR_DISABLED.load(Ordering::Acquire)
+}
+
+/// Registers a callback invoked with `true` while any `BlurProcessor` exists
+/// (from just before the ONNX/GPU session is created until drop), so a host can
+/// attribute a hard process death to the blur pipeline. Processes that never
+/// register (cap-exporter, the CLI) get a no-op and unchanged behavior.
+pub fn set_blur_session_observer(observer: fn(bool)) {
+ let _ = BLUR_SESSION_OBSERVER.set(observer);
+}
+
+fn notify_blur_session(active: bool) {
+ if let Some(observer) = BLUR_SESSION_OBSERVER.get() {
+ observer(active);
+ }
+}
+
+/// Pairs the observer's `true` notification with exactly one `false`, whether
+/// init fails, init panics, or the processor is eventually dropped. Declared as
+/// the LAST field of `BlurProcessor` so the disarm runs only after the ONNX
+/// session and GPU resources have finished their own (native, crashable)
+/// teardown.
+struct BlurSessionHandle;
+
+impl Drop for BlurSessionHandle {
+ fn drop(&mut self) {
+ notify_blur_session(false);
+ }
+}
+
const READBACK_PENDING: u8 = 0;
const READBACK_READY_OK: u8 = 1;
const READBACK_READY_ERR: u8 = 2;
@@ -51,6 +93,8 @@ pub struct BlurProcessor {
mask_initialized: bool,
mask_dirty: bool,
output_generation: u64,
+ // Keep last: must drop after every other field (see BlurSessionHandle).
+ _blur_session: BlurSessionHandle,
}
struct DownsamplePipeline {
@@ -149,6 +193,21 @@ struct ProcessorTextures {
impl BlurProcessor {
pub fn new(device: &wgpu::Device, output_format: wgpu::TextureFormat) -> anyhow::Result<Self> {
+ if blur_disabled() {
+ anyhow::bail!("camera background blur disabled by crash recovery");
+ }
+
+ // Armed before the ONNX session is created: model load and the first
+ // GPU work are both native-crash sites we need attributed to blur.
+ notify_blur_session(true);
+ Self::new_inner(device, output_format, BlurSessionHandle)
+ }
+
+ fn new_inner(
+ device: &wgpu::Device,
+ output_format: wgpu::TextureFormat,
+ blur_session: BlurSessionHandle,
+ ) -> anyhow::Result<Self> {
let model = SegmentationModel::new()?;
let blur_pipeline = BlurPipeline::new(device);
let composite_pipeline = CompositePipeline::new(device, output_format);
@@ -203,6 +262,7 @@ impl BlurProcessor {
mask_initialized: false,
mask_dirty: true,
output_generation: 0,
+ _blur_session: blur_session,
})
}
diff --git a/crates/camera-effects/src/segmentation.rs b/crates/camera-effects/src/segmentation.rs
index 82ba2c980..a74ec1bd3 100644
--- a/crates/camera-effects/src/segmentation.rs
+++ b/crates/camera-effects/src/segmentation.rs
@@ -144,12 +144,19 @@ fn onnx_runtime_candidates() -> Vec<PathBuf> {
candidates
}
+// `error_on_failure` is load-bearing in both registrars: without it ort swallows
+// registration failures and returns Ok (it only logs through its own internal
+// logger), so a CPU-only runtime DLL would make the "registered" log a false
+// positive while inference silently runs on CPU.
+
#[cfg(target_os = "macos")]
fn try_register_coreml(
builder: ort::session::builder::SessionBuilder,
) -> ort::session::builder::SessionBuilder {
match builder.with_execution_providers([
- ort::execution_providers::CoreMLExecutionProvider::default().build(),
+ ort::execution_providers::CoreMLExecutionProvider::default()
+ .build()
+ .error_on_failure(),
]) {
Ok(b) => {
tracing::info!("Camera background blur: CoreML execution provider registered");
@@ -167,7 +174,9 @@ fn try_register_directml(
builder: ort::session::builder::SessionBuilder,
) -> ort::session::builder::SessionBuilder {
match builder.with_execution_providers([
- ort::execution_providers::DirectMLExecutionProvider::default().build(),
+ ort::execution_providers::DirectMLExecutionProvider::default()
+ .build()
+ .error_on_failure(),
]) {
Ok(b) => {
tracing::info!("Camera background blur: DirectML execution provider registered");
diff --git a/crates/cap-test/src/suites/performance.rs b/crates/cap-test/src/suites/performance.rs
index 543846f41..d7ac1a74c 100644
--- a/crates/cap-test/src/suites/performance.rs
+++ b/crates/cap-test/src/suites/performance.rs
@@ -418,7 +418,12 @@ async fn benchmark_playback(
.segments
.iter()
.map(|segment_media| {
- ZoomTransformTimeline::from_project(&context.project, &segment_media.cursor, duration)
+ ZoomTransformTimeline::from_project(
+ &context.project,
+ &segment_media.cursor,
+ duration,
+ context.render_constants.options.screen_size,
+ )
})
.collect();
@@ -667,8 +672,12 @@ async fn render_single_frame(context: &FixtureContext) -> Result<()> {
.get_frames_initial(0.0, !context.project.camera.hide, true, clip_offsets)
.await
.ok_or_else(|| anyhow::anyhow!("Initial frame decode returned no frame"))?;
- let mut zoom_timeline =
- ZoomTransformTimeline::from_project(&context.project, &segment_media.cursor, duration);
+ let mut zoom_timeline = ZoomTransformTimeline::from_project(
+ &context.project,
+ &segment_media.cursor,
+ duration,
+ context.render_constants.options.screen_size,
+ );
zoom_timeline.ensure_precomputed_until(1.0 / PLAYBACK_FPS as f32);
let uniforms = ProjectUniforms::new(
&context.render_constants,
diff --git a/crates/editor/examples/playback-pipeline-benchmark.rs b/crates/editor/examples/playback-pipeline-benchmark.rs
index 6d0c58d5e..00d9c16f7 100644
--- a/crates/editor/examples/playback-pipeline-benchmark.rs
+++ b/crates/editor/examples/playback-pipeline-benchmark.rs
@@ -487,7 +487,12 @@ async fn run_full_pipeline_benchmark(
let mut zoom_timelines: Vec<ZoomTransformTimeline> = segments
.iter()
.map(|segment_media| {
- ZoomTransformTimeline::from_project(project, &segment_media.cursor, duration)
+ ZoomTransformTimeline::from_project(
+ project,
+ &segment_media.cursor,
+ duration,
+ render_constants.options.screen_size,
+ )
})
.collect();
@@ -683,7 +688,12 @@ async fn run_scrubbing_benchmark(
let mut zoom_timelines: Vec<ZoomTransformTimeline> = segments
.iter()
.map(|segment_media| {
- ZoomTransformTimeline::from_project(project, &segment_media.cursor, duration)
+ ZoomTransformTimeline::from_project(
+ project,
+ &segment_media.cursor,
+ duration,
+ render_constants.options.screen_size,
+ )
})
.collect();
diff --git a/crates/editor/src/audio.rs b/crates/editor/src/audio.rs
index 29b8d299d..82e9a41d5 100644
--- a/crates/editor/src/audio.rs
+++ b/crates/editor/src/audio.rs
@@ -1313,11 +1313,11 @@ mod tests {
clips: vec![
ClipConfiguration {
index: 0,
- offsets: Default::default(),
+ ..Default::default()
},
ClipConfiguration {
index: 1,
- offsets: Default::default(),
+ ..Default::default()
},
],
..Default::default()
@@ -1440,7 +1440,7 @@ mod tests {
}),
clips: vec![ClipConfiguration {
index: 0,
- offsets: Default::default(),
+ ..Default::default()
}],
..Default::default()
};
@@ -1530,7 +1530,7 @@ mod tests {
}),
clips: vec![ClipConfiguration {
index: 0,
- offsets: Default::default(),
+ ..Default::default()
}],
..Default::default()
};
@@ -1568,7 +1568,7 @@ mod tests {
}),
clips: vec![ClipConfiguration {
index: 0,
- offsets: Default::default(),
+ ..Default::default()
}],
..Default::default()
};
@@ -1707,7 +1707,7 @@ mod tests {
}),
clips: vec![ClipConfiguration {
index: 0,
- offsets: Default::default(),
+ ..Default::default()
}],
..Default::default()
}
diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rs
index 3e9bdc945..2ba08c018 100644
--- a/crates/editor/src/editor_instance.rs
+++ b/crates/editor/src/editor_instance.rs
@@ -245,6 +245,7 @@ impl EditorInstance {
index: i as u32,
offsets: segment
.calculate_audio_offsets_with_calibration(calibration_offset),
+ offsets_auto_calculated: true,
}
})
.collect();
@@ -253,6 +254,7 @@ impl EditorInstance {
project.clips = vec![cap_project::ClipConfiguration {
index: 0,
offsets: cap_project::ClipOffsets::default(),
+ offsets_auto_calculated: false,
}];
}
}
@@ -619,6 +621,7 @@ impl EditorInstance {
&project,
&segment_medias.cursor,
total_duration,
+ self.render_constants.options.screen_size,
);
zoom_timeline
.ensure_precomputed_until((frame_number as f32 + 1.0) / fps as f32);
diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rs
index 422f5899c..e3b77f9ff 100644
--- a/crates/editor/src/playback.rs
+++ b/crates/editor/src/playback.rs
@@ -581,7 +581,12 @@ impl Playback {
self.segment_medias
.iter()
.map(|seg| {
- ZoomTransformTimeline::from_project(project, &seg.cursor, duration)
+ ZoomTransformTimeline::from_project(
+ project,
+ &seg.cursor,
+ duration,
+ self.render_constants.options.screen_size,
+ )
})
.collect()
};
@@ -618,6 +623,7 @@ impl Playback {
&segment_media.cursor,
cached_project.screen_movement_spring,
duration,
+ None,
);
&empty_timeline
}
@@ -1032,6 +1038,7 @@ impl Playback {
&segment_media.cursor,
cached_project.screen_movement_spring,
duration,
+ None,
);
&empty_timeline
}
diff --git a/crates/export/src/preview.rs b/crates/export/src/preview.rs
index a9327b638..a9b1e3fb7 100644
--- a/crates/export/src/preview.rs
+++ b/crates/export/src/preview.rs
@@ -98,6 +98,7 @@ async fn render_preview_with_base(
&exporter_base.project_config,
&segment_media.cursor,
total_duration,
+ exporter_base.render_constants.options.screen_size,
);
zoom_timeline.ensure_precomputed_until((frame_number as f32 + 1.0) / settings.fps as f32);
diff --git a/crates/export/tests/real_recording_regression.rs b/crates/export/tests/real_recording_regression.rs
index e0c8fd2ef..9cba28eb7 100644
--- a/crates/export/tests/real_recording_regression.rs
+++ b/crates/export/tests/real_recording_regression.rs
@@ -205,6 +205,7 @@ async fn export_sequence_render_matches_editor_reference_for_real_recording()
&project_config,
&segment.cursor,
total_duration,
+ render_constants.options.screen_size,
)
})
.collect();
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index 06c317ec5..202e49de9 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -228,6 +228,66 @@ pub struct BorderConfiguration {
pub opacity: f32,
}
+/// Decorative frame drawn around the screen recording (browser window,
+/// macOS window, MacBook bezel, ...). The video is inset inside the frame's
+/// chrome; the framed card as a whole follows padding / position / zoom
+/// exactly like the bare video does today.
+#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum FrameStyle {
+ /// No frame: the video renders bare, exactly as before this feature.
+ #[default]
+ None,
+ /// A macOS window title bar with traffic-light buttons.
+ MacOS,
+ /// A Windows 11 window title bar with minimize/maximize/close controls.
+ Windows,
+ /// A browser toolbar: traffic lights plus a centered URL pill.
+ Browser,
+ /// A MacBook mockup: black bezel, aluminum body and deck.
+ Macbook,
+}
+
+#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum FrameTheme {
+ #[default]
+ Dark,
+ Light,
+}
+
+#[derive(Type, Serialize, Deserialize, Clone, Debug, PartialEq)]
+#[serde(rename_all = "camelCase", default)]
+pub struct FrameConfiguration {
+ pub style: FrameStyle,
+ pub theme: FrameTheme,
+ /// Text shown in the browser style's URL pill.
+ pub url: String,
+ /// Text shown in the macOS window style's title bar.
+ pub title: String,
+}
+
+impl Default for FrameConfiguration {
+ fn default() -> Self {
+ Self {
+ style: FrameStyle::None,
+ theme: FrameTheme::default(),
+ url: "Cap.so".to_string(),
+ title: String::new(),
+ }
+ }
+}
+
+impl FrameConfiguration {
+ pub fn active_style(config: Option<&FrameConfiguration>) -> FrameStyle {
+ config.map(|f| f.style).unwrap_or(FrameStyle::None)
+ }
+
+ pub fn is_active(&self) -> bool {
+ self.style != FrameStyle::None
+ }
+}
+
#[derive(Type, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase", default)]
pub struct BackgroundConfiguration {
@@ -239,11 +299,15 @@ pub struct BackgroundConfiguration {
pub inset: u32,
pub crop: Option<Crop>,
/// Normalized (0-1) center of the display rect in output-frame space.
- /// `None` keeps the display centered.
+ /// `None` keeps the display centered. When a frame is active this is the
+ /// center of the framed card (chrome included), not the bare video.
pub display_position: Option<XY<f64>>,
pub shadow: f32,
pub advanced_shadow: Option<ShadowConfiguration>,
pub border: Option<BorderConfiguration>,
+ /// Decorative frame around the recording. `None` (or `FrameStyle::None`)
+ /// renders the bare video exactly as before the feature existed.
+ pub frame: Option<FrameConfiguration>,
}
impl Default for BorderConfiguration {
@@ -271,6 +335,7 @@ impl Default for BackgroundConfiguration {
shadow: 73.6,
advanced_shadow: Some(ShadowConfiguration::default()),
border: None, // Border is disabled by default for backwards compatibility
+ frame: None, // No decorative frame by default
}
}
}
@@ -1195,6 +1260,11 @@ pub struct ClipOffsets {
pub struct ClipConfiguration {
pub index: u32,
pub offsets: ClipOffsets,
+ /// Whether `offsets` were computed automatically (recording start-time
+ /// alignment + device sync calibration) rather than entered by the user.
+ /// Cleared by the editor UI once the user edits an offset.
+ #[serde(default)]
+ pub offsets_auto_calculated: bool,
}
#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug, PartialEq)]
@@ -1338,8 +1408,18 @@ pub struct ProjectConfiguration {
pub screen_motion_blur: f32,
#[serde(default)]
pub screen_movement_spring: ScreenMovementSpring,
+ /// How text segment font sizes are interpreted. 0 (legacy): the renderer
+ /// multiplied `font_size` by `size.y / 0.2`, coupling glyph size to the
+ /// box. 1: `font_size` alone determines glyph size (1080p-relative);
+ /// legacy configs are migrated on load by baking the box factor into
+ /// `font_size`. The field-level default keeps old files at 0 while
+ /// `Default::default()` produces the current version.
+ #[serde(default)]
+ pub text_size_version: u32,
}
+pub const TEXT_SIZE_VERSION: u32 = 1;
+
fn camera_config_needs_migration(value: &Value) -> bool {
value
.get("camera")
@@ -1368,6 +1448,7 @@ impl Default for ProjectConfiguration {
hidden_text_segments: Default::default(),
screen_motion_blur: Self::default_screen_motion_blur(),
screen_movement_spring: Default::default(),
+ text_size_version: TEXT_SIZE_VERSION,
}
}
}
@@ -1414,11 +1495,34 @@ impl ProjectConfiguration {
} else {
config.screen_motion_blur = screen_motion_blur;
}
+
+ // Legacy text configs coupled glyph size to the box: the renderer
+ // multiplied font_size by size.y / 0.2. Bake that factor into
+ // font_size so the new decoupled law renders them identically.
+ let mut needs_text_size_migration = false;
+ if config.text_size_version == 0 {
+ if let Some(timeline) = config.timeline.as_mut() {
+ for segment in &mut timeline.text_segments {
+ let scale = (segment.size.y / 0.2).clamp(0.25, 4.0) as f32;
+ let migrated = (segment.font_size * scale).clamp(1.0, 480.0);
+ if (migrated - segment.font_size).abs() > f32::EPSILON {
+ segment.font_size = migrated;
+ needs_text_size_migration = true;
+ }
+ }
+ }
+ config.text_size_version = TEXT_SIZE_VERSION;
+ }
+
config
.validate()
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
- if needs_camera_migration || needs_motion_blur_clamp || needs_screen_motion_blur_migration {
+ if needs_camera_migration
+ || needs_motion_blur_clamp
+ || needs_screen_motion_blur_migration
+ || needs_text_size_migration
+ {
match config.write(project_path) {
Ok(_) => {
eprintln!("Updated project-config.json migrated settings");
@@ -1589,6 +1693,98 @@ mod tests {
assert_eq!(loaded.background.display_position, Some(XY::new(0.5, 0.4)));
}
+ fn write_config_with_text_segment(
+ project_path: &std::path::Path,
+ font_size: f32,
+ size_y: f64,
+ text_size_version: Option<u32>,
+ ) {
+ let config = ProjectConfiguration {
+ timeline: Some(TimelineConfiguration {
+ segments: Vec::new(),
+ zoom_segments: Vec::new(),
+ scene_segments: Vec::new(),
+ mask_segments: Vec::new(),
+ text_segments: vec![TextSegment {
+ start: 0.0,
+ end: 1.0,
+ track: 0,
+ enabled: true,
+ content: "Text".to_string(),
+ center: XY::new(0.5, 0.5),
+ size: XY::new(0.35, size_y),
+ font_family: "sans-serif".to_string(),
+ font_size,
+ font_weight: 700.0,
+ italic: false,
+ color: "#ffffff".to_string(),
+ fade_duration: 0.15,
+ }],
+ caption_segments: Vec::new(),
+ keyboard_segments: Vec::new(),
+ audio_segments: Vec::new(),
+ }),
+ ..Default::default()
+ };
+
+ let mut value = serde_json::to_value(&config).unwrap();
+ let object = value.as_object_mut().unwrap();
+ match text_size_version {
+ Some(version) => {
+ object.insert("textSizeVersion".to_string(), Value::from(version));
+ }
+ None => {
+ object.remove("textSizeVersion");
+ }
+ }
+ std::fs::write(
+ project_path.join("project-config.json"),
+ serde_json::to_string(&value).unwrap(),
+ )
+ .unwrap();
+ }
+
+ #[test]
+ fn legacy_text_segment_bakes_box_scale_into_font_size() {
+ let dir = tempfile::tempdir().unwrap();
+ // Legacy renderer drew this at 96 * (0.4 / 0.2) = 2x glyph scale.
+ write_config_with_text_segment(dir.path(), 96.0, 0.4, None);
+
+ let config = ProjectConfiguration::load(dir.path()).unwrap();
+
+ let segment = &config.timeline.as_ref().unwrap().text_segments[0];
+ assert_eq!(segment.font_size, 192.0);
+ assert_eq!(config.text_size_version, TEXT_SIZE_VERSION);
+
+ // The migration must persist so it never runs twice.
+ let reloaded = ProjectConfiguration::load(dir.path()).unwrap();
+ let segment = &reloaded.timeline.as_ref().unwrap().text_segments[0];
+ assert_eq!(segment.font_size, 192.0);
+ }
+
+ #[test]
+ fn legacy_text_segment_at_base_height_is_unchanged() {
+ let dir = tempfile::tempdir().unwrap();
+ write_config_with_text_segment(dir.path(), 48.0, 0.2, None);
+
+ let config = ProjectConfiguration::load(dir.path()).unwrap();
+
+ let segment = &config.timeline.as_ref().unwrap().text_segments[0];
+ assert_eq!(segment.font_size, 48.0);
+ assert_eq!(config.text_size_version, TEXT_SIZE_VERSION);
+ }
+
+ #[test]
+ fn current_text_config_is_not_rebaked() {
+ let dir = tempfile::tempdir().unwrap();
+ write_config_with_text_segment(dir.path(), 96.0, 0.4, Some(TEXT_SIZE_VERSION));
+
+ let config = ProjectConfiguration::load(dir.path()).unwrap();
+
+ let segment = &config.timeline.as_ref().unwrap().text_segments[0];
+ assert_eq!(segment.font_size, 96.0);
+ }
+
#[test]
fn legacy_config_without_motion_rework_fields_resolves_defaults() {
let dir = tempfile::tempdir().unwrap();
diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs
index a735afdf0..9c0ddb705 100644
--- a/crates/recording/src/studio_recording.rs
+++ b/crates/recording/src/studio_recording.rs
@@ -1133,6 +1133,7 @@ async fn stop_recording(
.map(|(i, segment)| ClipConfiguration {
index: i as u32,
offsets: segment.calculate_audio_offsets(),
+ offsets_auto_calculated: true,
})
.collect::<Vec<_>>()
});
diff --git a/crates/rendering/src/composite_frame.rs b/crates/rendering/src/composite_frame.rs
index d9be39967..8a56e705f 100644
--- a/crates/rendering/src/composite_frame.rs
+++ b/crates/rendering/src/composite_frame.rs
@@ -87,6 +87,11 @@ pub struct CompositeVideoFrameUniforms {
pub preserve_source_alpha: f32,
pub _padding1: [f32; 3],
pub border_color: [f32; 4],
+ /// Per-corner multipliers on `rounding_px` (top-left, top-right,
+ /// bottom-left, bottom-right). All 1s = uniform rounding; the display
+ /// squares its top corners against decorative frame chrome with
+ /// `[0, 0, 1, 1]`.
+ pub corner_radii: [f32; 4],
}
impl Default for CompositeVideoFrameUniforms {
@@ -113,6 +118,7 @@ impl Default for CompositeVideoFrameUniforms {
preserve_source_alpha: 0.0,
_padding1: [0.0; 3],
border_color: [0.0, 0.0, 0.0, 0.0],
+ corner_radii: [1.0; 4],
}
}
}
diff --git a/crates/rendering/src/frame_chrome.rs b/crates/rendering/src/frame_chrome.rs
new file mode 100644
index 000000000..83ad67aa1
--- /dev/null
+++ b/crates/rendering/src/frame_chrome.rs
@@ -0,0 +1,710 @@
+//! Decorative frame ("chrome") rendering for the display layer.
+//!
+//! A frame wraps the screen recording in synthetic window chrome — a macOS
+//! title bar, a browser toolbar or a MacBook body. The chrome is rasterized
+//! on the CPU from a parameterized SVG (same technique as SVG cursors) into
+//! an RGBA texture that the frame layer composites with the shared
+//! composite-video-frame pipeline, so it inherits rounded corners, shadows,
+//! borders and motion blur from the exact same shader as the video itself.
+//!
+//! Geometry model: the *outer card* (video + chrome) is what padding,
+//! `display_position` and zoom apply to; the video sits inside it offset by
+//! [`ChromeInsets`]. Insets are expressed as fractions of the video content
+//! height so the chrome keeps its proportions at any recording size.
+
+use crate::composite_frame::CompositeVideoFrameUniforms;
+use cap_project::{FrameStyle, FrameTheme, XY};
+use std::sync::{Arc, OnceLock};
+
+/// Everything the frame layer needs to draw the chrome for one frame:
+/// composite uniforms for the shared pipeline (bounds/rounding/shadow/motion
+/// blur; `frame_size`/`crop_bounds` are filled in by the layer once the
+/// texture size is known) plus the parameters that drive rasterization.
+#[derive(Clone, Debug)]
+pub struct FrameChromeUniforms {
+ pub composite: CompositeVideoFrameUniforms,
+ pub style: FrameStyle,
+ pub theme: FrameTheme,
+ pub url: String,
+ pub title: String,
+ /// Unzoomed outer card size in output px — the rasterization base size.
+ pub raster_size: XY<f64>,
+ /// Unzoomed video content height in output px (chrome proportions basis).
+ pub content_height: f64,
+}
+
+/// Content insets of a frame style, as fractions of the video content height.
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct ChromeInsets {
+ pub top: f64,
+ pub right: f64,
+ pub bottom: f64,
+ pub left: f64,
+}
+
+/// macOS window title bar height.
+const MACOS_BAR_FRAC: f64 = 0.055;
+/// Windows 11 window title bar height.
+const WINDOWS_BAR_FRAC: f64 = 0.05;
+/// Browser toolbar height.
+const BROWSER_BAR_FRAC: f64 = 0.075;
+/// MacBook screen bezel thickness (all four sides of the panel).
+const MACBOOK_BEZEL_FRAC: f64 = 0.028;
+/// MacBook deck (keyboard base) height below the panel.
+const MACBOOK_DECK_FRAC: f64 = 0.045;
+/// How far the deck overhangs the panel on each side.
+const MACBOOK_OVERHANG_FRAC: f64 = 0.10;
+/// Room reserved under the deck for its baked soft shadow.
+const MACBOOK_SHADOW_ROOM_FRAC: f64 = 0.035;
+
+/// Supersampling factor for the rasterized chrome texture, so it stays crisp
+/// when zoom segments scale the card up.
+const CHROME_SUPERSAMPLE: f64 = 2.0;
+/// Hard cap on either texture dimension.
+const CHROME_MAX_TEXTURE_DIM: f64 = 4096.0;
+
+pub fn chrome_insets(style: FrameStyle) -> ChromeInsets {
+ match style {
+ FrameStyle::None => ChromeInsets::default(),
+ FrameStyle::MacOS => ChromeInsets {
+ top: MACOS_BAR_FRAC,
+ ..Default::default()
+ },
+ FrameStyle::Windows => ChromeInsets {
+ top: WINDOWS_BAR_FRAC,
+ ..Default::default()
+ },
+ FrameStyle::Browser => ChromeInsets {
+ top: BROWSER_BAR_FRAC,
+ ..Default::default()
+ },
+ FrameStyle::Macbook => ChromeInsets {
+ top: MACBOOK_BEZEL_FRAC,
+ right: MACBOOK_BEZEL_FRAC + MACBOOK_OVERHANG_FRAC,
+ bottom: MACBOOK_BEZEL_FRAC + MACBOOK_DECK_FRAC + MACBOOK_SHADOW_ROOM_FRAC,
+ left: MACBOOK_BEZEL_FRAC + MACBOOK_OVERHANG_FRAC,
+ },
+ }
+}
+
+/// Whether the shader-side shadow/border decoration applies to this style.
+/// The MacBook silhouette is not a rectangle, so it bakes its own shadow into
+/// the SVG instead of using the rect-SDF shadow.
+pub fn style_uses_card_decoration(style: FrameStyle) -> bool {
+ matches!(
+ style,
+ FrameStyle::MacOS | FrameStyle::Windows | FrameStyle::Browser
+ )
+}
+
+/// Texture size for a chrome card whose unzoomed on-screen size is `w`×`h`
+/// output pixels.
+pub fn chrome_texture_size(w: f64, h: f64) -> (u32, u32) {
+ let scale = (CHROME_MAX_TEXTURE_DIM / w.max(1.0))
+ .min(CHROME_MAX_TEXTURE_DIM / h.max(1.0))
+ .min(CHROME_SUPERSAMPLE);
+ let tw = ((w * scale).round() as u32).clamp(16, CHROME_MAX_TEXTURE_DIM as u32);
+ let th = ((h * scale).round() as u32).clamp(16, CHROME_MAX_TEXTURE_DIM as u32);
+ (tw, th)
+}
+
+fn escape_xml(text: &str) -> String {
+ text.replace('&', "&amp;")
+ .replace('<', "&lt;")
+ .replace('>', "&gt;")
+ .replace('"', "&quot;")
+ .replace('\'', "&apos;")
+}
+
+struct Palette {
+ bar: &'static str,
+ bar_top_highlight: &'static str,
+ hairline: &'static str,
+ title_text: &'static str,
+ icon: &'static str,
+ pill_fill: &'static str,
+ pill_stroke: &'static str,
+ pill_text: &'static str,
+}
+
+fn palette(theme: FrameTheme) -> Palette {
+ match theme {
+ FrameTheme::Light => Palette {
+ bar: "#ECEBEA",
+ bar_top_highlight: "rgba(255,255,255,0.55)",
+ hairline: "rgba(0,0,0,0.12)",
+ title_text: "#4B4B4E",
+ icon: "#87868B",
+ pill_fill: "#FFFFFF",
+ pill_stroke: "rgba(0,0,0,0.07)",
+ pill_text: "#414145",
+ },
+ FrameTheme::Dark => Palette {
+ bar: "#2E2E31",
+ bar_top_highlight: "rgba(255,255,255,0.07)",
+ hairline: "rgba(0,0,0,0.55)",
+ title_text: "#C9C9CE",
+ icon: "#9A9AA1",
+ pill_fill: "#3C3C41",
+ pill_stroke: "rgba(255,255,255,0.06)",
+ pill_text: "#C9C9CE",
+ },
+ }
+}
+
+/// The three traffic-light buttons, positioned in a bar of height `bar_h`
+/// whose vertical center is `cy`.
+fn traffic_lights(bar_h: f64, cy: f64) -> String {
+ let r = bar_h * 0.135;
+ let first_cx = bar_h * 0.45;
+ let gap = r * 3.0;
+ format!(
+ concat!(
+ r##"<circle cx="{x0}" cy="{cy}" r="{r}" fill="#FF5F57"/>"##,
+ r##"<circle cx="{x1}" cy="{cy}" r="{r}" fill="#FEBC2E"/>"##,
+ r##"<circle cx="{x2}" cy="{cy}" r="{r}" fill="#28C840"/>"##,
+ ),
+ x0 = first_cx,
+ x1 = first_cx + gap,
+ x2 = first_cx + gap * 2.0,
+ cy = cy,
+ r = r,
+ )
+}
+
+/// Font stack used for chrome text. Resolved against the system font
+/// database; if nothing matches, resvg simply skips the text node and the
+/// chrome renders without labels.
+const CHROME_FONTS: &str = "Helvetica Neue, Helvetica, Segoe UI, Arial, sans-serif";
+
+/// The bar fill extends slightly below the bar so no background seam can show
+/// between the chrome and the video's (square) top edge.
+fn bar_fill_height(bar_h: f64) -> f64 {
+ bar_h + (bar_h * 0.04).max(1.5)
+}
+
+fn macos_svg(w: f64, h: f64, bar_h: f64, theme: FrameTheme, title: &str) -> String {
+ let p = palette(theme);
+ let title_el = if title.trim().is_empty() {
+ String::new()
+ } else {
+ format!(
+ r##"<text x="{x}" y="{y}" font-family="{fonts}" font-size="{size}" font-weight="600" fill="{fill}" text-anchor="middle">{title}</text>"##,
+ x = w * 0.5,
+ y = bar_h * 0.5 + bar_h * 0.155,
+ fonts = CHROME_FONTS,
+ size = bar_h * 0.42,
+ fill = p.title_text,
+ title = escape_xml(title),
+ )
+ };
+
+ format!(
+ concat!(
+ r##"<svg width="{w}" height="{h}" viewBox="0 0 {w} {h}" xmlns="http://www.w3.org/2000/svg">"##,
+ r##"<rect width="{w}" height="{bar_fill}" fill="{bar}"/>"##,
+ r##"<rect width="{w}" height="{hl_h}" fill="{highlight}"/>"##,
+ r##"<rect y="{hair_y}" width="{w}" height="{hair_h}" fill="{hairline}"/>"##,
+ "{lights}",
+ "{title_el}",
+ "</svg>"
+ ),
+ w = w,
+ h = h,
+ bar_fill = bar_fill_height(bar_h),
+ bar = p.bar,
+ hl_h = (bar_h * 0.045).max(1.0),
+ highlight = p.bar_top_highlight,
+ hair_y = bar_h - (bar_h * 0.03).max(1.0),
+ hair_h = (bar_h * 0.03).max(1.0),
+ hairline = p.hairline,
+ lights = traffic_lights(bar_h, bar_h * 0.5),
+ title_el = title_el,
+ )
+}
+
+/// Windows 11 title bar: left-aligned title, right-aligned minimize /
+/// maximize / close caption controls.
+fn windows_svg(w: f64, h: f64, bar_h: f64, theme: FrameTheme, title: &str) -> String {
+ let p = palette(theme);
+ let cy = bar_h * 0.5;
+ let g = bar_h * 0.145;
+ let stroke = format!(
+ r##"stroke="{icon}" stroke-width="{sw}" stroke-linecap="round" fill="none""##,
+ icon = p.icon,
+ sw = (bar_h * 0.038).max(1.2),
+ );
+ // Caption controls, right to left: close, maximize, minimize.
+ let zone = bar_h * 1.30;
+ let close_cx = w - zone * 0.5;
+ let max_cx = w - zone * 1.5;
+ let min_cx = w - zone * 2.5;
+ let controls = format!(
+ concat!(
+ r##"<path d="M {min0} {cy} H {min1}" {stroke}/>"##,
+ r##"<rect x="{mx}" y="{my}" width="{ms}" height="{ms}" rx="{mr}" {stroke}/>"##,
+ r##"<path d="M {cx0} {cy0} L {cx1} {cy1} M {cx0} {cy1} L {cx1} {cy0}" {stroke}/>"##,
+ ),
+ min0 = min_cx - g,
+ min1 = min_cx + g,
+ cy = cy,
+ mx = max_cx - g,
+ my = cy - g,
+ ms = g * 2.0,
+ mr = g * 0.30,
+ cx0 = close_cx - g,
+ cx1 = close_cx + g,
+ cy0 = cy - g,
+ cy1 = cy + g,
+ stroke = stroke,
+ );
+
+ let title_el = if title.trim().is_empty() {
+ String::new()
+ } else {
+ format!(
+ r##"<text x="{x}" y="{y}" font-family="{fonts}" font-size="{size}" fill="{fill}" text-anchor="start">{title}</text>"##,
+ x = bar_h * 0.55,
+ y = cy + bar_h * 0.14,
+ fonts = CHROME_FONTS,
+ size = bar_h * 0.38,
+ fill = p.title_text,
+ title = escape_xml(title),
+ )
+ };
+
+ format!(
+ concat!(
+ r##"<svg width="{w}" height="{h}" viewBox="0 0 {w} {h}" xmlns="http://www.w3.org/2000/svg">"##,
+ r##"<rect width="{w}" height="{bar_fill}" fill="{bar}"/>"##,
+ r##"<rect y="{hair_y}" width="{w}" height="{hair_h}" fill="{hairline}"/>"##,
+ "{title_el}",
+ "{controls}",
+ "</svg>"
+ ),
+ w = w,
+ h = h,
+ bar_fill = bar_fill_height(bar_h),
+ bar = p.bar,
+ hair_y = bar_h - (bar_h * 0.028).max(1.0),
+ hair_h = (bar_h * 0.028).max(1.0),
+ hairline = p.hairline,
+ title_el = title_el,
+ controls = controls,
+ )
+}
+
+fn browser_svg(w: f64, h: f64, bar_h: f64, theme: FrameTheme, url: &str) -> String {
+ let p = palette(theme);
+ let cy = bar_h * 0.5;
+
+ // Navigation glyphs (back / forward chevrons, reload arc) to the right of
+ // the traffic lights.
+ let lights_end = bar_h * 0.45 + bar_h * 0.135 * 3.0 * 2.0 + bar_h * 0.135;
+ let glyph = bar_h * 0.14;
+ let nav_stroke = format!(
+ r##"stroke="{icon}" stroke-width="{sw}" stroke-linecap="round" stroke-linejoin="round" fill="none""##,
+ icon = p.icon,
+ sw = (bar_h * 0.032).max(1.2),
+ );
+ let back_x = lights_end + bar_h * 0.42;
+ let fwd_x = back_x + bar_h * 0.62;
+ let reload_x = fwd_x + bar_h * 0.62;
+ // Reload: clockwise arc with the gap at the top-right and a solid arrow
+ // head at the arc's end pointing clockwise into the gap, like the
+ // standard material/Chrome refresh glyph. Angles are in y-down screen
+ // space, where increasing angle travels clockwise.
+ let reload = {
+ let r = glyph * 1.05;
+ let point = |deg: f64| {
+ let rad = deg.to_radians();
+ (reload_x + r * rad.cos(), cy + r * rad.sin())
+ };
+ let start_deg = -15.0; // just below the gap, ~2 o'clock
+ let end_deg = 300.0; // upper end of the gap, ~1 o'clock
+ let (sx, sy) = point(start_deg);
+ let (ex, ey) = point(end_deg);
+ // Tangent of clockwise travel at the arc end; the arrow head points
+ // along it.
+ let trad = end_deg.to_radians();
+ let (tx, ty) = (-trad.sin(), trad.cos());
+ let (nx, ny) = (-ty, tx);
+ let head = glyph * 0.85;
+ format!(
+ concat!(
+ r##"<path d="M {sx} {sy} A {r} {r} 0 1 1 {ex} {ey}" {stroke}/>"##,
+ r##"<path d="M {tipx} {tipy} L {b0x} {b0y} L {b1x} {b1y} Z" fill="{icon}"/>"##,
+ ),
+ sx = sx,
+ sy = sy,
+ r = r,
+ ex = ex,
+ ey = ey,
+ stroke = nav_stroke,
+ tipx = ex + tx * head,
+ tipy = ey + ty * head,
+ b0x = ex - tx * head * 0.25 + nx * head * 0.75,
+ b0y = ey - ty * head * 0.25 + ny * head * 0.75,
+ b1x = ex - tx * head * 0.25 - nx * head * 0.75,
+ b1y = ey - ty * head * 0.25 - ny * head * 0.75,
+ icon = p.icon,
+ )
+ };
+ let nav = format!(
+ concat!(
+ r##"<path d="M {bx1} {ty} L {bx0} {cy} L {bx1} {by}" {stroke}/>"##,
+ r##"<path d="M {fx0} {ty} L {fx1} {cy} L {fx0} {by}" {stroke}/>"##,
+ "{reload}",
+ ),
+ bx0 = back_x - glyph * 0.55,
+ bx1 = back_x + glyph * 0.55,
+ fx0 = fwd_x - glyph * 0.55,
+ fx1 = fwd_x + glyph * 0.55,
+ ty = cy - glyph,
+ by = cy + glyph,
+ cy = cy,
+ stroke = nav_stroke,
+ reload = reload,
+ );
+
+ // Centered URL pill; the padlock and address text are left-aligned inside
+ // it at fixed positions (like Chrome/Arc), so they stay perfectly aligned
+ // to each other no matter how the text renders.
+ let pill_h = bar_h * 0.60;
+ let pill_w = (w * 0.42).max(pill_h * 4.0).min(w * 0.8);
+ let pill_x = (w - pill_w) * 0.5;
+ let pill_y = cy - pill_h * 0.5;
+ let text = escape_xml(url.trim());
+ let font_size = bar_h * 0.30;
+ // Padlock: shackle arc over a rounded body, vertically centered on the
+ // text's optical middle.
+ let lock_x = pill_x + pill_h * 0.60;
+ let body_w = font_size * 0.74;
+ let body_h = font_size * 0.56;
+ let body_y = cy - font_size * 0.05;
+ let shackle_r = body_w * 0.30;
+ let lock = format!(
+ concat!(
+ r##"<path d="M {shx0} {shy} v {leg} a {sr} {sr} 0 0 1 {sdia} 0 v {leg_down}" stroke="{icon}" stroke-width="{ssw}" fill="none"/>"##,
+ r##"<rect x="{bx}" y="{by}" width="{bw}" height="{bh}" rx="{brx}" fill="{icon}"/>"##,
+ ),
+ shx0 = lock_x + body_w * 0.5 - shackle_r,
+ shy = body_y,
+ leg = -font_size * 0.14,
+ sr = shackle_r,
+ sdia = shackle_r * 2.0,
+ leg_down = font_size * 0.14,
+ ssw = (font_size * 0.16).max(1.0),
+ bx = lock_x,
+ by = body_y,
+ bw = body_w,
+ bh = body_h,
+ brx = body_w * 0.18,
+ icon = p.icon,
+ );
+ let url_el = if text.is_empty() {
+ String::new()
+ } else {
+ format!(
+ concat!(
+ "{lock}",
+ r##"<text x="{tx}" y="{ty}" font-family="{fonts}" font-size="{size}" fill="{fill}" text-anchor="start">{text}</text>"##,
+ ),
+ lock = lock,
+ tx = lock_x + body_w + font_size * 0.42,
+ ty = cy + font_size * 0.36,
+ fonts = CHROME_FONTS,
+ size = font_size,
+ fill = p.pill_text,
+ text = text,
+ )
+ };
+
+ format!(
+ concat!(
+ r##"<svg width="{w}" height="{h}" viewBox="0 0 {w} {h}" xmlns="http://www.w3.org/2000/svg">"##,
+ r##"<rect width="{w}" height="{bar_fill}" fill="{bar}"/>"##,
+ r##"<rect width="{w}" height="{hl_h}" fill="{highlight}"/>"##,
+ r##"<rect y="{hair_y}" width="{w}" height="{hair_h}" fill="{hairline}"/>"##,
+ "{lights}",
+ "{nav}",
+ r##"<rect x="{px}" y="{py}" width="{pw}" height="{ph}" rx="{pr}" fill="{pill}" stroke="{pill_stroke}" stroke-width="1"/>"##,
+ "{url_el}",
+ "</svg>"
+ ),
+ w = w,
+ h = h,
+ bar_fill = bar_fill_height(bar_h),
+ bar = p.bar,
+ hl_h = (bar_h * 0.03).max(1.0),
+ highlight = p.bar_top_highlight,
+ hair_y = bar_h - (bar_h * 0.022).max(1.0),
+ hair_h = (bar_h * 0.022).max(1.0),
+ hairline = p.hairline,
+ lights = traffic_lights(bar_h, cy),
+ nav = nav,
+ px = pill_x,
+ py = pill_y,
+ pw = pill_w,
+ ph = pill_h,
+ pr = pill_h * 0.5,
+ pill = p.pill_fill,
+ pill_stroke = p.pill_stroke,
+ url_el = url_el,
+ )
+}
+
+/// MacBook mockup: black panel bezel around the screen, aluminum deck with a
+/// thumb scoop, camera dot, and a baked soft shadow (its silhouette is not a
+/// rectangle, so the shader's rect shadow stays off for this style).
+fn macbook_svg(w: f64, h: f64, content_h: f64, theme: FrameTheme) -> String {
+ let bezel = content_h * MACBOOK_BEZEL_FRAC;
+ let deck_h = content_h * MACBOOK_DECK_FRAC;
+ let overhang = content_h * MACBOOK_OVERHANG_FRAC;
+ let shadow_room = content_h * MACBOOK_SHADOW_ROOM_FRAC;
+
+ // Panel (screen + bezel) block.
+ let panel_x = overhang;
+ let panel_w = w - overhang * 2.0;
+ let panel_h = h - deck_h - shadow_room;
+ let panel_radius = bezel * 1.35;
+
+ let deck_y = panel_h;
+ let deck_radius = deck_h * 0.42;
+ let scoop_w = w * 0.14;
+ let scoop_h = deck_h * 0.52;
+
+ let (alu_top, alu_bottom, alu_edge, panel_fill, scoop_top, scoop_bottom) = match theme {
+ FrameTheme::Light => (
+ "#E6E7E9", "#ADAFB4", "#8E9094", "#0E0E11", "#C4C6CA", "#9EA0A5",
+ ),
+ FrameTheme::Dark => (
+ "#3E3F43", "#232427", "#151619", "#0E0E11", "#2A2B2F", "#1B1C1F",
+ ),
+ };
+
+ format!(
+ concat!(
+ r##"<svg width="{w}" height="{h}" viewBox="0 0 {w} {h}" xmlns="http://www.w3.org/2000/svg">"##,
+ "<defs>",
+ r##"<linearGradient id="alu" x1="0" y1="0" x2="0" y2="1">"##,
+ r##"<stop offset="0" stop-color="{alu_top}"/><stop offset="1" stop-color="{alu_bottom}"/>"##,
+ "</linearGradient>",
+ r##"<linearGradient id="scoop" x1="0" y1="0" x2="0" y2="1">"##,
+ r##"<stop offset="0" stop-color="{scoop_top}"/><stop offset="1" stop-color="{scoop_bottom}"/>"##,
+ "</linearGradient>",
+ r##"<filter id="soft" x="-30%" y="-30%" width="160%" height="160%">"##,
+ r##"<feGaussianBlur stdDeviation="{shadow_blur}"/>"##,
+ "</filter>",
+ "</defs>",
+ // Baked ground shadow under the deck.
+ r##"<ellipse cx="{sh_cx}" cy="{sh_cy}" rx="{sh_rx}" ry="{sh_ry}" fill="rgba(0,0,0,0.42)" filter="url(#soft)"/>"##,
+ // Panel with bezel; the video sits inset by the bezel.
+ r##"<rect x="{panel_x}" y="0" width="{panel_w}" height="{panel_h}" rx="{panel_radius}" fill="{panel_fill}"/>"##,
+ // Camera dot centered in the top bezel.
+ r##"<circle cx="{cam_cx}" cy="{cam_cy}" r="{cam_r}" fill="#17181C"/>"##,
+ r##"<circle cx="{cam_cx}" cy="{cam_cy}" r="{cam_r_inner}" fill="#2A3138"/>"##,
+ // Deck with rounded bottom corners and the thumb scoop.
+ r##"<path d="M 0 {deck_y} H {w} V {deck_bot_edge} Q {w} {deck_bot} {deck_right_in} {deck_bot} H {deck_left_in} Q 0 {deck_bot} 0 {deck_bot_edge} Z" fill="url(#alu)"/>"##,
+ r##"<rect x="0" y="{deck_y}" width="{w}" height="{edge_h}" fill="{alu_edge}" fill-opacity="0.35"/>"##,
+ r##"<path d="M {scoop_left} {deck_y} h {scoop_w} v {scoop_body} a {scoop_r} {scoop_r} 0 0 1 -{scoop_r} {scoop_r} h -{scoop_flat} a {scoop_r} {scoop_r} 0 0 1 -{scoop_r} -{scoop_r} Z" fill="url(#scoop)"/>"##,
+ // Bottom edge line of the deck for definition.
+ r##"<rect x="{deck_left_in}" y="{deck_edge_y}" width="{deck_edge_w}" height="{deck_edge_h}" fill="{alu_edge}" fill-opacity="0.6"/>"##,
+ "</svg>"
+ ),
+ w = w,
+ h = h,
+ alu_top = alu_top,
+ alu_bottom = alu_bottom,
+ scoop_top = scoop_top,
+ scoop_bottom = scoop_bottom,
+ shadow_blur = deck_h * 0.55,
+ sh_cx = w * 0.5,
+ sh_cy = deck_y + deck_h * 0.9,
+ sh_rx = w * 0.46,
+ sh_ry = deck_h * 0.55,
+ panel_x = panel_x,
+ panel_w = panel_w,
+ panel_h = panel_h,
+ panel_radius = panel_radius,
+ panel_fill = panel_fill,
+ cam_cx = w * 0.5,
+ cam_cy = bezel * 0.5,
+ cam_r = (bezel * 0.16).max(1.5),
+ cam_r_inner = (bezel * 0.07).max(0.8),
+ deck_y = deck_y,
+ deck_bot = deck_y + deck_h,
+ deck_bot_edge = deck_y + deck_h - deck_radius,
+ deck_right_in = w - deck_radius,
+ deck_left_in = deck_radius,
+ edge_h = (deck_h * 0.06).max(1.0),
+ scoop_left = (w - scoop_w) * 0.5,
+ scoop_w = scoop_w,
+ scoop_body = scoop_h - scoop_h * 0.5,
+ scoop_r = scoop_h * 0.5,
+ scoop_flat = scoop_w - scoop_h,
+ deck_edge_y = deck_y + deck_h - (deck_h * 0.08).max(1.0),
+ deck_edge_w = w - deck_radius * 2.0,
+ deck_edge_h = (deck_h * 0.08).max(1.0),
+ alu_edge = alu_edge,
+ )
+}
+
+/// Build the SVG for a chrome card of `w`×`h` texture pixels wrapping a video
+/// content area of height `content_h` texture pixels.
+pub fn chrome_svg(
+ style: FrameStyle,
+ theme: FrameTheme,
+ url: &str,
+ title: &str,
+ w: f64,
+ h: f64,
+ content_h: f64,
+) -> Option<String> {
+ match style {
+ FrameStyle::None => None,
+ FrameStyle::MacOS => Some(macos_svg(w, h, content_h * MACOS_BAR_FRAC, theme, title)),
+ FrameStyle::Windows => Some(windows_svg(
+ w,
+ h,
+ content_h * WINDOWS_BAR_FRAC,
+ theme,
+ title,
+ )),
+ FrameStyle::Browser => Some(browser_svg(w, h, content_h * BROWSER_BAR_FRAC, theme, url)),
+ FrameStyle::Macbook => Some(macbook_svg(w, h, content_h, theme)),
+ }
+}
+
+fn chrome_fontdb() -> Arc<resvg::usvg::fontdb::Database> {
+ static FONTDB: OnceLock<Arc<resvg::usvg::fontdb::Database>> = OnceLock::new();
+ FONTDB
+ .get_or_init(|| {
+ let mut db = resvg::usvg::fontdb::Database::new();
+ db.load_system_fonts();
+ Arc::new(db)
+ })
+ .clone()
+}
+
+/// Rasterize a chrome card to RGBA8 (non-premultiplied). Returns `None` for
+/// [`FrameStyle::None`] or if rasterization fails (the frame layer then skips
+/// drawing rather than erroring the whole frame).
+pub fn rasterize_chrome(
+ style: FrameStyle,
+ theme: FrameTheme,
+ url: &str,
+ title: &str,
+ tex_w: u32,
+ tex_h: u32,
+ content_h_px: f64,
+) -> Option<Vec<u8>> {
+ let svg = chrome_svg(
+ style,
+ theme,
+ url,
+ title,
+ tex_w as f64,
+ tex_h as f64,
+ content_h_px,
+ )?;
+
+ let options = resvg::usvg::Options {
+ fontdb: chrome_fontdb(),
+ ..Default::default()
+ };
+
+ let tree = match resvg::usvg::Tree::from_str(&svg, &options) {
+ Ok(tree) => tree,
+ Err(error) => {
+ tracing::warn!("Failed to parse frame chrome SVG: {error}");
+ return None;
+ }
+ };
+
+ let mut pixmap = tiny_skia::Pixmap::new(tex_w, tex_h)?;
+ resvg::render(
+ &tree,
+ tiny_skia::Transform::identity(),
+ &mut pixmap.as_mut(),
+ );
+
+ Some(
+ pixmap
+ .pixels()
+ .iter()
+ .flat_map(|p| {
+ let c = p.demultiply();
+ [c.red(), c.green(), c.blue(), c.alpha()]
+ })
+ .collect(),
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn no_frame_has_no_insets() {
+ assert_eq!(chrome_insets(FrameStyle::None), ChromeInsets::default());
+ }
+
+ #[test]
+ fn texture_size_respects_max_dim() {
+ let (w, h) = chrome_texture_size(8000.0, 200.0);
+ assert!(w <= 4096 && h <= 4096);
+ let (w, h) = chrome_texture_size(1600.0, 1000.0);
+ assert_eq!((w, h), (3200, 2000));
+ }
+
+ /// Visual iteration helper: dumps every style/theme chrome to PNGs.
+ /// `CAP_CHROME_DUMP_DIR=/tmp/x cargo test -p cap-rendering dump_chrome -- --ignored`
+ #[test]
+ #[ignore]
+ fn dump_chrome_pngs() {
+ let Ok(dir) = std::env::var("CAP_CHROME_DUMP_DIR") else {
+ return;
+ };
+ std::fs::create_dir_all(&dir).unwrap();
+ for style in [
+ FrameStyle::MacOS,
+ FrameStyle::Windows,
+ FrameStyle::Browser,
+ FrameStyle::Macbook,
+ ] {
+ for theme in [FrameTheme::Light, FrameTheme::Dark] {
+ let insets = chrome_insets(style);
+ let content_h = 900.0_f64;
+ let content_w = content_h * 16.0 / 10.0;
+ let w = (content_w + (insets.left + insets.right) * content_h).round() as u32;
+ let h = (content_h * (1.0 + insets.top + insets.bottom)).round() as u32;
+ let rgba =
+ rasterize_chrome(style, theme, "cap.so", "Cap Recording", w, h, content_h)
+ .unwrap();
+ image::RgbaImage::from_raw(w, h, rgba)
+ .unwrap()
+ .save(format!("{dir}/{style:?}-{theme:?}.png"))
+ .unwrap();
+ }
+ }
+ }
+
+ #[test]
+ fn all_styles_rasterize() {
+ for style in [
+ FrameStyle::MacOS,
+ FrameStyle::Windows,
+ FrameStyle::Browser,
+ FrameStyle::Macbook,
+ ] {
+ for theme in [FrameTheme::Light, FrameTheme::Dark] {
+ let rgba = rasterize_chrome(style, theme, "cap.so", "Recording", 640, 420, 360.0);
+ let rgba = rgba.expect("chrome should rasterize");
+ assert_eq!(rgba.len(), 640 * 420 * 4);
+ // Something visible must have been drawn.
+ assert!(rgba.chunks_exact(4).any(|px| px[3] > 0));
+ }
+ }
+ }
+}
diff --git a/crates/rendering/src/layers/cursor.rs b/crates/rendering/src/layers/cursor.rs
index ad0f992bc..ab3c449b4 100644
--- a/crates/rendering/src/layers/cursor.rs
+++ b/crates/rendering/src/layers/cursor.rs
@@ -367,8 +367,13 @@ impl CursorLayer {
return;
};
+ // Out-of-band positions (cursor in a cropped-away region, spring
+ // overshoot past a display edge) still render: the shader's
+ // screen_bounds clip confines the sprite to the display card, so it
+ // slides off the card edge and back instead of popping in and out.
+ // Only non-finite data hides it outright.
let cursor_uv = &interpolated_cursor.position.coord;
- if !(0.0..=1.0).contains(&cursor_uv.x) || !(0.0..=1.0).contains(&cursor_uv.y) {
+ if !cursor_uv.x.is_finite() || !cursor_uv.y.is_finite() {
self.bind_group = None;
return;
}
diff --git a/crates/rendering/src/layers/frame.rs b/crates/rendering/src/layers/frame.rs
new file mode 100644
index 000000000..ce3ff5770
--- /dev/null
+++ b/crates/rendering/src/layers/frame.rs
@@ -0,0 +1,173 @@
+use std::sync::Arc;
+
+use cap_project::{FrameStyle, FrameTheme};
+
+use crate::{
+ ProjectUniforms, RenderVideoConstants,
+ composite_frame::{CompositeVideoFramePipeline, CompositeVideoFrameUniforms},
+ frame_chrome,
+};
+
+/// Inputs that require re-rasterizing the chrome texture. Zoom and card
+/// position are NOT part of the key: the texture is rasterized at the
+/// unzoomed card size (supersampled) and the composite pass scales it, so
+/// animated frames reuse the cached texture.
+#[derive(Clone, PartialEq)]
+struct ChromeCacheKey {
+ style: FrameStyle,
+ theme: FrameTheme,
+ url: String,
+ title: String,
+ tex_size: (u32, u32),
+}
+
+/// Draws decorative frame chrome (macOS window bar, browser toolbar, MacBook
+/// body) behind the display layer, using the shared composite pipeline so the
+/// chrome gets the same rounded corners, shadow, border and motion blur
+/// treatment as the video card itself.
+pub struct FrameLayer {
+ pipeline: Arc<CompositeVideoFramePipeline>,
+ uniforms_buffer: wgpu::Buffer,
+ texture: Option<wgpu::Texture>,
+ texture_view: Option<wgpu::TextureView>,
+ bind_group: Option<wgpu::BindGroup>,
+ cache_key: Option<ChromeCacheKey>,
+ failed_key: Option<ChromeCacheKey>,
+ ready: bool,
+}
+
+impl FrameLayer {
+ pub fn new(device: &wgpu::Device, pipeline: Arc<CompositeVideoFramePipeline>) -> Self {
+ Self {
+ uniforms_buffer: CompositeVideoFrameUniforms::default().to_buffer(device),
+ pipeline,
+ texture: None,
+ texture_view: None,
+ bind_group: None,
+ cache_key: None,
+ failed_key: None,
+ ready: false,
+ }
+ }
+
+ pub fn prepare(&mut self, constants: &RenderVideoConstants, uniforms: &ProjectUniforms) {
+ self.ready = false;
+ let Some(chrome) = uniforms.frame_chrome.as_ref() else {
+ return;
+ };
+ if chrome.composite.opacity <= 0.001 {
+ return;
+ }
+
+ let (tex_w, tex_h) =
+ frame_chrome::chrome_texture_size(chrome.raster_size.x, chrome.raster_size.y);
+ let key = ChromeCacheKey {
+ style: chrome.style,
+ theme: chrome.theme,
+ url: chrome.url.clone(),
+ title: chrome.title.clone(),
+ tex_size: (tex_w, tex_h),
+ };
+
+ if self.failed_key.as_ref() == Some(&key) {
+ return;
+ }
+
+ if self.cache_key.as_ref() != Some(&key) {
+ let scale = tex_w as f64 / chrome.raster_size.x.max(1.0);
+ let content_h_px = chrome.content_height * scale;
+ let Some(rgba) = frame_chrome::rasterize_chrome(
+ chrome.style,
+ chrome.theme,
+ &chrome.url,
+ &chrome.title,
+ tex_w,
+ tex_h,
+ content_h_px,
+ ) else {
+ // Remember the failure so a bad configuration doesn't
+ // re-rasterize every frame; any config change retries.
+ self.failed_key = Some(key);
+ return;
+ };
+
+ if self.texture.as_ref().map(|t| (t.width(), t.height())) != Some((tex_w, tex_h)) {
+ let texture = constants.device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("FrameChrome texture"),
+ size: wgpu::Extent3d {
+ width: tex_w,
+ height: tex_h,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ view_formats: &[],
+ });
+ self.texture_view = Some(texture.create_view(&Default::default()));
+ self.texture = Some(texture);
+ self.bind_group = None;
+ }
+
+ if let Some(texture) = self.texture.as_ref() {
+ constants.queue.write_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ &rgba,
+ wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(4 * tex_w),
+ rows_per_image: None,
+ },
+ wgpu::Extent3d {
+ width: tex_w,
+ height: tex_h,
+ depth_or_array_layers: 1,
+ },
+ );
+ }
+
+ self.failed_key = None;
+ self.cache_key = Some(key);
+ }
+
+ let Some(view) = self.texture_view.as_ref() else {
+ return;
+ };
+ if self.bind_group.is_none() {
+ self.bind_group = Some(self.pipeline.bind_group(
+ &constants.device,
+ &self.uniforms_buffer,
+ view,
+ ));
+ }
+
+ let mut composite = chrome.composite;
+ composite.frame_size = [tex_w as f32, tex_h as f32];
+ composite.crop_bounds = [0.0, 0.0, tex_w as f32, tex_h as f32];
+ composite.write_to_buffer(&constants.queue, &self.uniforms_buffer);
+ self.ready = true;
+ }
+
+ pub fn has_content(&self) -> bool {
+ self.ready
+ }
+
+ pub fn render(&self, pass: &mut wgpu::RenderPass<'_>) {
+ if !self.ready {
+ return;
+ }
+ let Some(bind_group) = self.bind_group.as_ref() else {
+ return;
+ };
+ pass.set_pipeline(&self.pipeline.render_pipeline);
+ pass.set_bind_group(0, bind_group, &[]);
+ pass.draw(0..3, 0..1);
+ }
+}
diff --git a/crates/rendering/src/layers/mod.rs b/crates/rendering/src/layers/mod.rs
index 74748699a..b0e31c08c 100644
--- a/crates/rendering/src/layers/mod.rs
+++ b/crates/rendering/src/layers/mod.rs
@@ -4,6 +4,7 @@ mod camera;
mod captions;
mod cursor;
mod display;
+mod frame;
mod keyboard;
mod mask;
mod text;
@@ -25,7 +26,35 @@ pub(crate) fn new_font_system() -> glyphon::FontSystem {
let (locale, db) = FONT_TEMPLATE.get_or_init(|| {
let font_system = glyphon::FontSystem::new();
- (font_system.locale().to_string(), font_system.db().clone())
+ let mut db = font_system.db().clone();
+ // Pin the generic families to the fonts the editor webview resolves
+ // them to. fontdb's stock defaults (e.g. "Arial") often don't match
+ // any installed face, in which case cosmic-text silently shapes with
+ // an arbitrary fallback font — and canvas overlays measured in the
+ // webview no longer match what the renderer draws.
+ #[cfg(target_os = "macos")]
+ {
+ // WKWebView: sans-serif → Helvetica, serif → Times, monospace →
+ // Courier.
+ db.set_sans_serif_family("Helvetica");
+ db.set_serif_family("Times New Roman");
+ db.set_monospace_family("Courier New");
+ }
+ #[cfg(windows)]
+ {
+ // WebView2 (Chromium): sans-serif → Arial, serif → Times New
+ // Roman, monospace → Consolas.
+ db.set_sans_serif_family("Arial");
+ db.set_serif_family("Times New Roman");
+ db.set_monospace_family("Consolas");
+ }
+ #[cfg(all(unix, not(target_os = "macos")))]
+ {
+ db.set_sans_serif_family("DejaVu Sans");
+ db.set_serif_family("DejaVu Serif");
+ db.set_monospace_family("DejaVu Sans Mono");
+ }
+ (font_system.locale().to_string(), db)
});
glyphon::FontSystem::new_with_locale_and_db(locale.clone(), db.clone())
@@ -37,6 +66,43 @@ pub use camera::*;
pub use captions::*;
pub use cursor::*;
pub use display::*;
+pub use frame::*;
pub use keyboard::*;
pub use mask::*;
pub use text::*;
+
+#[cfg(test)]
+mod font_tests {
+ use super::*;
+
+ /// Text overlays are measured in the editor webview with the CSS generic
+ /// `sans-serif`; the renderer must resolve the same generic to a real
+ /// (and matching) font or boxes and line wrapping diverge from the
+ /// rendered pixels.
+ #[test]
+ fn generic_families_resolve_to_real_fonts() {
+ let font_system = new_font_system();
+ for family in [
+ glyphon::fontdb::Family::SansSerif,
+ glyphon::fontdb::Family::Serif,
+ glyphon::fontdb::Family::Monospace,
+ ] {
+ for weight in [400u16, 700] {
+ let query = glyphon::fontdb::Query {
+ families: &[family],
+ weight: glyphon::fontdb::Weight(weight),
+ ..Default::default()
+ };
+ let id = font_system.db().query(&query);
+ let families = id
+ .and_then(|id| font_system.db().face(id))
+ .map(|face| face.families.clone());
+ println!("{family:?} weight {weight}: {families:?}");
+ assert!(
+ families.is_some(),
+ "{family:?} (weight {weight}) resolved to no font"
+ );
+ }
+ }
+ }
+}
diff --git a/crates/rendering/src/layers/text.rs b/crates/rendering/src/layers/text.rs
index 37a2badee..abb07188d 100644
--- a/crates/rendering/src/layers/text.rs
+++ b/crates/rendering/src/layers/text.rs
@@ -64,9 +64,27 @@ impl TextLayer {
let width = (text.bounds[2] - text.bounds[0]).max(1.0);
let height = (text.bounds[3] - text.bounds[1]).max(1.0);
+ // Shape with a little more width than the editor-measured box:
+ // the webview and cosmic-text can disagree by a few pixels per
+ // line, and without slack a line that fit in the editor wraps in
+ // the render. The room is split evenly so centered lines stay
+ // centered. Boxes already spanning the frame keep their exact
+ // width — there the editor genuinely wrapped too.
+ let output_width = (output_size.0 as f32).max(1.0);
+ let wrap_width = if width < output_width * 0.98 {
+ (width * 1.05 + 4.0).min(output_width.max(width))
+ } else {
+ width
+ };
+ let wrap_dx = (wrap_width - width) / 2.0;
+
let metrics = Metrics::new(text.font_size, text.font_size * 1.2);
let mut buffer = Buffer::new(&mut self.font_system, metrics);
- buffer.set_size(&mut self.font_system, Some(width), Some(height));
+ // The box only constrains wrapping; height is unbounded so every
+ // line is laid out even when the configured box is a little
+ // shorter than the shaped text (e.g. font metric differences
+ // between the editor's measurement and cosmic-text).
+ buffer.set_size(&mut self.font_system, Some(wrap_width), None);
buffer.set_wrap(&mut self.font_system, glyphon::Wrap::Word);
let family = match text.font_family.trim() {
@@ -104,15 +122,22 @@ impl TextLayer {
buffer.shape_until_scroll(&mut self.font_system, false);
+ // Clip horizontally at the (slack-expanded) wrap box, but extend
+ // the bottom to the laid-out text height so descenders and extra
+ // lines never get cut off; glyphon intersects these bounds with
+ // the viewport.
+ let laid_out_height = buffer.layout_runs().count() as f32 * metrics.line_height;
let bounds = TextBounds {
- left: text.bounds[0].floor() as i32,
+ left: (text.bounds[0] - wrap_dx).floor() as i32,
top: text.bounds[1].floor() as i32,
- right: (text.bounds[0] + width).ceil() as i32,
- bottom: (text.bounds[1] + height).ceil() as i32,
+ right: (text.bounds[0] + width + wrap_dx).ceil() as i32,
+ bottom: (text.bounds[1] + height.max(laid_out_height)).ceil() as i32,
};
self.buffers.push(buffer);
- text_area_data.push((bounds, text.bounds[0], text.bounds[1], color));
+ // The buffer origin shifts left by the slack so centered lines
+ // stay centered on the box.
+ text_area_data.push((bounds, text.bounds[0] - wrap_dx, text.bounds[1], color));
}
let text_areas = self
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 763b77788..a99500de9 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -1,8 +1,8 @@
use anyhow::Result;
use cap_project::{
AspectRatio, Camera, CameraShape, CameraXPosition, CameraYPosition, ClipOffsets, CornerStyle,
- Crop, CursorEvents, CursorType, MaskKind, ProjectConfiguration, RecordingMeta, SceneMode,
- StudioRecordingMeta, XY,
+ Crop, CursorEvents, CursorType, FrameConfiguration, FrameStyle, MaskKind, ProjectConfiguration,
+ RecordingMeta, SceneMode, StudioRecordingMeta, XY,
};
use composite_frame::CompositeVideoFrameUniforms;
use core::f64;
@@ -17,7 +17,7 @@ use frame_pipeline::{
use futures::future::OptionFuture;
use layers::{
Background, BackgroundLayer, BlurLayer, CameraLayer, CaptionsLayer, CursorLayer, DisplayLayer,
- KeyboardLayer, MaskLayer, TextLayer,
+ FrameLayer, KeyboardLayer, MaskLayer, TextLayer,
};
use specta::Type;
use spring_mass_damper::SpringMassDamperSimulationConfig;
@@ -35,6 +35,7 @@ mod cursor_interpolation;
#[cfg(target_os = "windows")]
pub mod d3d_texture;
pub mod decoder;
+pub mod frame_chrome;
mod frame_pipeline;
#[cfg(target_os = "macos")]
pub mod iosurface_texture;
@@ -68,7 +69,7 @@ use mask::interpolate_masks;
use scene::*;
use text::{PreparedText, prepare_texts};
use zoom::*;
-pub use zoom_spring::ZoomTransformTimeline;
+pub use zoom_spring::{CursorCropMap, ZoomTransformTimeline};
#[derive(Debug, Clone, serde::Serialize)]
pub struct Nv12RenderStartupBreakdownMs {
@@ -583,7 +584,14 @@ pub async fn render_video_to_channel(
let mut zoom_timelines: Vec<ZoomTransformTimeline> = render_segments
.iter()
- .map(|segment| ZoomTransformTimeline::from_project(project, &segment.cursor, duration))
+ .map(|segment| {
+ ZoomTransformTimeline::from_project(
+ project,
+ &segment.cursor,
+ duration,
+ constants.options.screen_size,
+ )
+ })
.collect();
let mut frame_number = 0;
@@ -920,7 +928,14 @@ pub async fn render_video_to_channel_nv12(
let zoom_build_start = Instant::now();
let mut zoom_timelines: Vec<ZoomTransformTimeline> = render_segments
.iter()
- .map(|segment| ZoomTransformTimeline::from_project(project, &segment.cursor, duration))
+ .map(|segment| {
+ ZoomTransformTimeline::from_project(
+ project,
+ &segment.cursor,
+ duration,
+ constants.options.screen_size,
+ )
+ })
.collect();
for timeline in &mut zoom_timelines {
timeline.precompute();
@@ -1861,6 +1876,12 @@ pub struct ProjectUniforms {
display: CompositeVideoFrameUniforms,
camera: Option<CompositeVideoFrameUniforms>,
camera_only: Option<CompositeVideoFrameUniforms>,
+ /// Decorative frame chrome around the display; `None` when no frame style
+ /// is active.
+ pub frame_chrome: Option<frame_chrome::FrameChromeUniforms>,
+ /// Final placement of the outer display card (chrome included) in output
+ /// px. Equals `display.target_bounds` when no frame is active.
+ display_outer_bounds: [f32; 4],
interpolated_cursor: Option<InterpolatedCursorPosition>,
pub prev_cursor: Option<InterpolatedCursorPosition>,
pub project: ProjectConfiguration,
@@ -2241,7 +2262,9 @@ impl MotionBlurDescriptor {
/// Final rendered placement of the display and camera layers in output-frame
/// pixels ([x0, y0, x1, y1]), used by the editor preview for hit-testing the
-/// on-canvas move/resize overlays.
+/// on-canvas move/resize overlays. `display` is the outer card — chrome
+/// included when a decorative frame is active — so the overlay handles glue
+/// to what the user actually sees.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FrameLayout {
pub display: [f32; 4],
@@ -2249,10 +2272,20 @@ pub struct FrameLayout {
pub output_size: [u32; 2],
}
+/// Unzoomed placement of the display card in output-frame pixels. Without a
+/// decorative frame, outer == content.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub(crate) struct DisplayLayout {
+ pub outer_offset: XY<f64>,
+ pub outer_size: XY<f64>,
+ pub content_offset: XY<f64>,
+ pub content_size: XY<f64>,
+}
+
impl ProjectUniforms {
pub fn frame_layout(&self) -> FrameLayout {
FrameLayout {
- display: self.display.target_bounds,
+ display: self.display_outer_bounds,
camera: self.camera.as_ref().map(|c| c.target_bounds),
output_size: [self.output_size.0, self.output_size.1],
}
@@ -2355,22 +2388,73 @@ impl ProjectUniforms {
project: &ProjectConfiguration,
resolution_base: XY<u32>,
) -> Coord<FrameSpace> {
- let base = Self::display_base_offset(options, project, resolution_base);
+ Coord::new(Self::display_layout(options, project, resolution_base).content_offset)
+ }
+
+ /// Placement of the display card in output-frame pixels.
+ ///
+ /// Without a decorative frame the outer card IS the video, so the two
+ /// rects are identical and every value matches the pre-frames math
+ /// exactly. With a frame active, the outer card (video + chrome insets)
+ /// is what fits the padded box, is centered / positioned by
+ /// `display_position`, and is scaled by zoom; the video content rect sits
+ /// inside it. Cursor and zoom math flow through the content rect via
+ /// [`Self::display_offset`] / [`Self::display_size`].
+ pub(crate) fn display_layout(
+ options: &RenderOptions,
+ project: &ProjectConfiguration,
+ resolution_base: XY<u32>,
+ ) -> DisplayLayout {
+ let base = Self::display_base_offset(options, project, resolution_base).coord;
+ let output_size = Self::get_output_size(options, project, resolution_base);
+ let output_size = XY::new(output_size.0 as f64, output_size.1 as f64);
+ // Same op order as the legacy display_size (end - offset - offset) so
+ // the no-frame path stays bit-exact.
+ let box_size = (output_size - base) - base;
- let Some(position) = project.background.display_position else {
- return base;
+ let style = FrameConfiguration::active_style(project.background.frame.as_ref());
+ let (outer_offset, outer_size, content_offset, content_size) = if style == FrameStyle::None
+ {
+ (base, box_size, base, box_size)
+ } else {
+ let insets = frame_chrome::chrome_insets(style);
+ let crop = Self::get_crop(options, project);
+ let aspect = (crop.size.x as f64 / f64::from(crop.size.y.max(1))).max(f64::EPSILON);
+ // Insets are fractions of the content height; solve for the
+ // largest content that keeps the outer card inside the box.
+ let outer_w_per_h = aspect + insets.left + insets.right;
+ let outer_h_per_h = 1.0 + insets.top + insets.bottom;
+ let content_h = (box_size.x / outer_w_per_h)
+ .min(box_size.y / outer_h_per_h)
+ .max(1.0);
+ let content_size = XY::new(content_h * aspect, content_h);
+ let outer_size = XY::new(content_h * outer_w_per_h, content_h * outer_h_per_h);
+ let outer_offset = base + (box_size - outer_size) / 2.0;
+ let content_offset =
+ outer_offset + XY::new(insets.left * content_h, insets.top * content_h);
+ (outer_offset, outer_size, content_offset, content_size)
};
- let output_size = Self::get_output_size(options, project, resolution_base);
// The center may sit anywhere in-frame, so the display can overhang
// the edges (revealing background) but can never be dragged fully
// out of view.
- let delta = XY::new(
- (position.x.clamp(0.0, 1.0) - 0.5) * output_size.0 as f64,
- (position.y.clamp(0.0, 1.0) - 0.5) * output_size.1 as f64,
- );
+ let delta = project
+ .background
+ .display_position
+ .map(|position| {
+ XY::new(
+ (position.x.clamp(0.0, 1.0) - 0.5) * output_size.x,
+ (position.y.clamp(0.0, 1.0) - 0.5) * output_size.y,
+ )
+ })
+ .unwrap_or(XY::new(0.0, 0.0));
- Coord::new(base.coord + delta)
+ DisplayLayout {
+ outer_offset: outer_offset + delta,
+ outer_size,
+ content_offset: content_offset + delta,
+ content_size,
+ }
}
fn display_base_offset(
@@ -2453,14 +2537,7 @@ impl ProjectUniforms {
project: &ProjectConfiguration,
resolution_base: XY<u32>,
) -> Coord<FrameSpace> {
- let output_size = Self::get_output_size(options, project, resolution_base);
- let output_size = XY::new(output_size.0 as f64, output_size.1 as f64);
-
- let display_offset = Self::display_base_offset(options, project, resolution_base);
-
- let end = Coord::new(output_size) - display_offset;
-
- end - display_offset
+ Coord::new(Self::display_layout(options, project, resolution_base).content_size)
}
fn display_bounds(
@@ -2932,7 +3009,7 @@ impl ProjectUniforms {
None
};
- let (display, display_motion_parent) = {
+ let (display, display_motion_parent, frame_chrome, display_outer_bounds) = {
let output_size = XY::new(output_size.0 as f64, output_size.1 as f64);
let size = [options.screen_size.x as f32, options.screen_size.y as f32];
@@ -2945,8 +3022,10 @@ impl ProjectUniforms {
(crop.position.y + crop.size.y) as f64,
));
- let display_offset = Self::display_offset(options, project, resolution_base);
- let display_size = Self::display_size(options, project, resolution_base);
+ let layout = Self::display_layout(options, project, resolution_base);
+ let display_offset = Coord::<FrameSpace>::new(layout.content_offset);
+ let display_size = Coord::<FrameSpace>::new(layout.content_size);
+ let frame_config = project.background.frame.clone().filter(|f| f.is_active());
let (start, end) = Self::display_bounds(&zoom, display_offset, display_size);
let (prev_start, prev_end) =
@@ -3010,6 +3089,132 @@ impl ProjectUniforms {
];
let final_min_axis = final_target_size[0].min(final_target_size[1]) as f64;
+ let display_rounding_px =
+ (project.background.rounding / 100.0 * 0.5 * final_min_axis) as f32 * split_fade
+ + floating_rounding_px * floating_t;
+ let frame_active = frame_config.is_some();
+ // With a frame active the card decoration (shadow/border) moves to
+ // the chrome pass; the video keeps only the floating-card shadow
+ // that appears as a Floating scene morphs in (the chrome itself
+ // fades out with any split, so nothing double-draws).
+ let display_decoration_fade = if frame_active {
+ floating_t
+ } else {
+ chrome_fade
+ };
+ // Top-bar frame styles butt the video flush under the chrome bar,
+ // so the video's top corners go square (bottom corners keep the
+ // card rounding). As a split/floating scene morphs in the chrome
+ // fades out, so the multipliers relax back to uniform rounding.
+ let display_corner_radii = match frame_config.as_ref().map(|f| f.style) {
+ Some(FrameStyle::MacOS | FrameStyle::Windows | FrameStyle::Browser) => {
+ [split_t, split_t, 1.0, 1.0]
+ }
+ _ => [1.0; 4],
+ };
+ let border_color = if let Some(b) = project.background.border.as_ref() {
+ [
+ b.color[0] as f32 / 255.0,
+ b.color[1] as f32 / 255.0,
+ b.color[2] as f32 / 255.0,
+ (b.opacity / 100.0).clamp(0.0, 1.0),
+ ]
+ } else {
+ [0.0, 0.0, 0.0, 0.0]
+ };
+ let border_on = project
+ .background
+ .border
+ .as_ref()
+ .is_some_and(|b| b.enabled);
+
+ let frame_chrome = frame_config.map(|frame| {
+ // The chrome rect is the outer card pushed through the exact
+ // same zoom transform as the video content rect.
+ let zoom_scale = zoom.bounds.bottom_right - zoom.bounds.top_left;
+ let zoomed = |p: XY<f64>| start.coord + (p - layout.content_offset) * zoom_scale;
+ let outer_start = zoomed(layout.outer_offset);
+ let outer_end = zoomed(layout.outer_offset + layout.outer_size);
+ let base_outer_bounds = [
+ outer_start.x as f32,
+ outer_start.y as f32,
+ outer_end.x as f32,
+ outer_end.y as f32,
+ ];
+ // Follow the same split morph as the video so the chrome hugs
+ // the card while it fades out.
+ let chrome_bounds = split_layout.as_ref().map_or(base_outer_bounds, |s| {
+ lerp_bounds(base_outer_bounds, s.screen.target, split_t)
+ });
+ let chrome_size = [
+ chrome_bounds[2] - chrome_bounds[0],
+ chrome_bounds[3] - chrome_bounds[1],
+ ];
+ let decorated = frame_chrome::style_uses_card_decoration(frame.style);
+
+ frame_chrome::FrameChromeUniforms {
+ composite: CompositeVideoFrameUniforms {
+ output_size: [output_size.x as f32, output_size.y as f32],
+ // frame_size/crop_bounds are texture-dependent; the
+ // frame layer fills them once the texture exists.
+ frame_size: [1.0, 1.0],
+ crop_bounds: [0.0, 0.0, 1.0, 1.0],
+ target_bounds: chrome_bounds,
+ target_size: chrome_size,
+ rounding_px: if decorated { display_rounding_px } else { 0.0 },
+ rounding_type: rounding_type_value(project.background.rounding_type),
+ mirror_x: 0.0,
+ motion_blur_vector: descriptor.movement_vector_uv,
+ motion_blur_zoom_center: descriptor.zoom_center_uv,
+ motion_blur_params: [
+ descriptor.mode.as_f32(),
+ descriptor.strength,
+ descriptor.zoom_amount,
+ 0.0,
+ ],
+ shadow: if decorated {
+ project.background.shadow * split_fade
+ } else {
+ 0.0
+ },
+ shadow_size: project
+ .background
+ .advanced_shadow
+ .as_ref()
+ .map_or(50.0, |s| s.size),
+ shadow_opacity: project
+ .background
+ .advanced_shadow
+ .as_ref()
+ .map_or(18.0, |s| s.opacity)
+ * split_fade,
+ shadow_blur: project
+ .background
+ .advanced_shadow
+ .as_ref()
+ .map_or(50.0, |s| s.blur),
+ opacity: scene.screen_opacity as f32 * split_fade,
+ border_enabled: if decorated && border_on { 1.0 } else { 0.0 },
+ border_width: project.background.border.as_ref().map_or(5.0, |b| b.width),
+ preserve_source_alpha: 1.0,
+ _padding1: [0.0; 3],
+ border_color,
+ corner_radii: [1.0; 4],
+ },
+ style: frame.style,
+ theme: frame.theme,
+ url: frame.url,
+ title: frame.title,
+ raster_size: layout.outer_size,
+ content_height: layout.content_size.y,
+ }
+ });
+
+ let display_outer_bounds = frame_chrome
+ .as_ref()
+ .map(|f| f.composite.target_bounds)
+ .unwrap_or(final_target_bounds);
+
(
CompositeVideoFrameUniforms {
output_size: [output_size.x as f32, output_size.y as f32],
@@ -3017,10 +3222,7 @@ impl ProjectUniforms {
crop_bounds: final_crop_bounds,
target_bounds: final_target_bounds,
target_size: final_target_size,
- rounding_px: (project.background.rounding / 100.0 * 0.5 * final_min_axis)
- as f32
- * split_fade
- + floating_rounding_px * floating_t,
+ rounding_px: display_rounding_px,
rounding_type: rounding_type_value(project.background.rounding_type),
mirror_x: 0.0,
motion_blur_vector: descriptor.movement_vector_uv,
@@ -3031,7 +3233,7 @@ impl ProjectUniforms {
descriptor.zoom_amount,
0.0,
],
- shadow: project.background.shadow * chrome_fade,
+ shadow: project.background.shadow * display_decoration_fade,
shadow_size: project
.background
.advanced_shadow
@@ -3042,23 +3244,14 @@ impl ProjectUniforms {
.advanced_shadow
.as_ref()
.map_or(18.0, |s| s.opacity)
- * chrome_fade,
+ * display_decoration_fade,
shadow_blur: project
.background
.advanced_shadow
.as_ref()
.map_or(50.0, |s| s.blur),
opacity: scene.screen_opacity as f32,
- border_enabled: if project
- .background
- .border
- .as_ref()
- .is_some_and(|b| b.enabled)
- {
- 1.0
- } else {
- 0.0
- },
+ border_enabled: if border_on && !frame_active { 1.0 } else { 0.0 },
border_width: project.background.border.as_ref().map_or(5.0, |b| b.width),
preserve_source_alpha: if options.preserve_screen_alpha {
1.0
@@ -3066,18 +3259,12 @@ impl ProjectUniforms {
0.0
},
_padding1: [0.0; 3],
- border_color: if let Some(b) = project.background.border.as_ref() {
- [
- b.color[0] as f32 / 255.0,
- b.color[1] as f32 / 255.0,
- b.color[2] as f32 / 255.0,
- (b.opacity / 100.0).clamp(0.0, 1.0),
- ]
- } else {
- [0.0, 0.0, 0.0, 0.0]
- },
+ border_color,
+ corner_radii: display_corner_radii,
},
display_parent_motion_px,
+ frame_chrome,
+ display_outer_bounds,
)
};
@@ -3273,6 +3460,7 @@ impl ProjectUniforms {
preserve_source_alpha: 0.0,
_padding1: [0.0; 3],
border_color: [0.0, 0.0, 0.0, 0.0],
+ corner_radii: [1.0; 4],
}
});
@@ -3365,6 +3553,7 @@ impl ProjectUniforms {
preserve_source_alpha: 0.0,
_padding1: [0.0; 3],
border_color: [0.0, 0.0, 0.0, 0.0],
+ corner_radii: [1.0; 4],
}
});
@@ -3401,6 +3590,8 @@ impl ProjectUniforms {
display,
camera,
camera_only,
+ frame_chrome,
+ display_outer_bounds,
project: project.clone(),
zoom,
scene,
@@ -3551,6 +3742,80 @@ mod tests {
assert_eq!(size.coord, XY::new(1920.0, 1080.0));
}
+ #[test]
+ fn frame_none_layout_has_identical_outer_and_content_rects() {
+ let options = render_options(1920, 1080);
+ let mut project = ProjectConfiguration::default();
+ project.background.padding = 25.0;
+
+ let layout = ProjectUniforms::display_layout(&options, &project, XY::new(2688, 1512));
+
+ assert_eq!(layout.outer_offset, layout.content_offset);
+ assert_eq!(layout.outer_size, layout.content_size);
+ }
+
+ #[test]
+ fn frame_chrome_insets_video_within_centered_outer_card() {
+ let options = render_options(1920, 1080);
+ let mut project = ProjectConfiguration::default();
+ project.background.padding = 10.0;
+ project.background.frame = Some(cap_project::FrameConfiguration {
+ style: FrameStyle::Browser,
+ ..Default::default()
+ });
+
+ let resolution_base = XY::new(2112, 1188);
+ let (out_w, out_h) = ProjectUniforms::get_output_size(&options, &project, resolution_base);
+ let layout = ProjectUniforms::display_layout(&options, &project, resolution_base);
+ let insets = frame_chrome::chrome_insets(FrameStyle::Browser);
+
+ // The video keeps the recording's aspect ratio.
+ let content_aspect = layout.content_size.x / layout.content_size.y;
+ assert!((content_aspect - 1920.0 / 1080.0).abs() < 1e-9);
+
+ // The browser toolbar insets the video from the outer card's top.
+ assert!(
+ (layout.content_offset.y
+ - (layout.outer_offset.y + insets.top * layout.content_size.y))
+ .abs()
+ < 1e-9
+ );
+ assert_eq!(layout.content_offset.x, layout.outer_offset.x);
+
+ // The outer card (not the video) is centered in the output.
+ let outer_center_x = layout.outer_offset.x + layout.outer_size.x / 2.0;
+ let outer_center_y = layout.outer_offset.y + layout.outer_size.y / 2.0;
+ assert!((outer_center_x - out_w as f64 / 2.0).abs() < 1.0);
+ assert!((outer_center_y - out_h as f64 / 2.0).abs() < 1.0);
+
+ // And it stays inside the frame.
+ assert!(layout.outer_offset.x >= 0.0 && layout.outer_offset.y >= 0.0);
+ assert!(layout.outer_offset.x + layout.outer_size.x <= out_w as f64 + 1e-6);
+ assert!(layout.outer_offset.y + layout.outer_size.y <= out_h as f64 + 1e-6);
+ }
+
+ #[test]
+ fn frame_display_position_shifts_outer_and_content_together() {
+ let options = render_options(1920, 1080);
+ let mut project = ProjectConfiguration::default();
+ project.background.padding = 20.0;
+ project.background.frame = Some(cap_project::FrameConfiguration {
+ style: FrameStyle::MacOS,
+ ..Default::default()
+ });
+
+ let resolution_base = XY::new(2304, 1296);
+ let centered = ProjectUniforms::display_layout(&options, &project, resolution_base);
+ project.background.display_position = Some(XY::new(0.25, 0.75));
+ let moved = ProjectUniforms::display_layout(&options, &project, resolution_base);
+
+ let outer_delta = moved.outer_offset - centered.outer_offset;
+ let content_delta = moved.content_offset - centered.content_offset;
+ assert_eq!(outer_delta, content_delta);
+ assert_eq!(moved.outer_size, centered.outer_size);
+ assert_eq!(moved.content_size, centered.content_size);
+ }
+
#[test]
fn display_position_center_matches_legacy_centered_layout() {
let options = render_options(1920, 1080);
@@ -4165,6 +4430,7 @@ impl<'a> FrameRenderer<'a> {
pub struct RendererLayers {
background: BackgroundLayer,
background_blur: BlurLayer,
+ frame: FrameLayer,
display: DisplayLayer,
cursor: CursorLayer,
camera: CameraLayer,
@@ -4194,6 +4460,7 @@ impl RendererLayers {
Self {
background: BackgroundLayer::new(device),
background_blur: BlurLayer::new(device),
+ frame: FrameLayer::new(device, shared_composite_pipeline.clone()),
display: DisplayLayer::new_with_all_shared_pipelines(
device,
shared_yuv_pipelines.clone(),
@@ -4356,6 +4623,7 @@ impl RendererLayers {
}
if render_display {
+ self.frame.prepare(constants, uniforms);
self.display.prepare(
&constants.device,
&constants.queue,
@@ -4497,6 +4765,7 @@ impl RendererLayers {
let start = Instant::now();
if render_display {
+ self.frame.prepare(constants, uniforms);
let display_ready = self.display.prepare_with_encoder(
&constants.device,
&constants.queue,
@@ -4673,6 +4942,11 @@ impl RendererLayers {
true
};
+ if should_render_screen && self.frame.has_content() {
+ let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
+ self.frame.render(&mut pass);
+ }
+
if should_render_screen {
let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
self.display.render(&mut pass);
diff --git a/crates/rendering/src/shaders/composite-video-frame.wgsl b/crates/rendering/src/shaders/composite-video-frame.wgsl
index b792a7703..524f281c0 100644
--- a/crates/rendering/src/shaders/composite-video-frame.wgsl
+++ b/crates/rendering/src/shaders/composite-video-frame.wgsl
@@ -22,6 +22,10 @@ struct Uniforms {
_padding1b: f32,
_padding1c: f32,
border_color: vec4<f32>,
+ // Per-corner multipliers on rounding_px: (tl, tr, bl, br). All 1s keeps
+ // the uniform rounding; the display squares its top corners against
+ // decorative frame chrome with (0, 0, 1, 1).
+ corner_radii: vec4<f32>,
};
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@@ -62,6 +66,16 @@ fn rounded_corner_norm(p: vec2<f32>, rounding_type: f32) -> f32 {
return superellipse_norm(p, power);
}
+// Radius for the corner of the quadrant `p` (center-relative) falls in.
+fn corner_radius_for(p: vec2<f32>) -> f32 {
+ let multiplier = select(
+ select(uniforms.corner_radii.w, uniforms.corner_radii.z, p.x < 0.0),
+ select(uniforms.corner_radii.y, uniforms.corner_radii.x, p.x < 0.0),
+ p.y < 0.0
+ );
+ return uniforms.rounding_px * multiplier;
+}
+
fn sdf_rounded_rect(p: vec2<f32>, b: vec2<f32>, r: f32, rounding_type: f32) -> f32 {
let q = abs(p) - b + vec2<f32>(r);
let outside = max(q, vec2<f32>(0.0));
@@ -127,7 +141,7 @@ fn fs_main(@builtin(position) frag_coord: vec4<f32>) -> @location(0) vec4<f32> {
let center = (uniforms.target_bounds.xy + uniforms.target_bounds.zw) * 0.5;
let size = (uniforms.target_bounds.zw - uniforms.target_bounds.xy) * 0.5;
- let dist = sdf_rounded_rect(p - center, size, uniforms.rounding_px, uniforms.rounding_type);
+ let dist = sdf_rounded_rect(p - center, size, corner_radius_for(p - center), uniforms.rounding_type);
let min_frame_size = min(size.x, size.y);
let shadow_enabled = uniforms.shadow > 0.0;
@@ -177,13 +191,13 @@ fn fs_main(@builtin(position) frag_coord: vec4<f32>) -> @location(0) vec4<f32> {
let border_outer_coverage = rounded_rect_coverage(
p - center,
size + vec2<f32>(uniforms.border_width),
- uniforms.rounding_px + uniforms.border_width,
+ corner_radius_for(p - center) + uniforms.border_width,
uniforms.rounding_type
);
let border_inner_coverage = rounded_rect_coverage(
p - center,
size,
- uniforms.rounding_px,
+ corner_radius_for(p - center),
uniforms.rounding_type
);
let border_coverage = clamp(border_outer_coverage - border_inner_coverage, 0.0, 1.0);
@@ -200,7 +214,7 @@ fn fs_main(@builtin(position) frag_coord: vec4<f32>) -> @location(0) vec4<f32> {
let shape_coverage = rounded_rect_coverage(
p - center,
size,
- uniforms.rounding_px,
+ corner_radius_for(p - center),
uniforms.rounding_type
);
@@ -393,7 +407,7 @@ fn apply_rounded_corners(current_color: vec4<f32>, target_uv: vec2<f32>) -> vec4
let coverage = rounded_rect_coverage(
centered_uv,
half_size,
- uniforms.rounding_px,
+ corner_radius_for(centered_uv),
uniforms.rounding_type
);
diff --git a/crates/rendering/src/shaders/cursor.wgsl b/crates/rendering/src/shaders/cursor.wgsl
index b9fc6d60e..aefd09b86 100644
--- a/crates/rendering/src/shaders/cursor.wgsl
+++ b/crates/rendering/src/shaders/cursor.wgsl
@@ -98,11 +98,24 @@ fn sample_cursor(uv: vec2<f32>) -> vec4<f32> {
return textureSample(t_cursor, s_cursor, uv);
}
+// Confine the sprite to the display card (screen_bounds is the card's
+// content rect in output px): a cursor whose source position is outside the
+// visible crop slides off the card edge instead of floating over the
+// background. Feathered ~1px to match the card's antialiased edge.
+fn screen_bounds_mask(frag_pos: vec2<f32>) -> f32 {
+ let b = uniforms.screen_bounds;
+ let inside = min(
+ min(frag_pos.x - b.x, b.z - frag_pos.x),
+ min(frag_pos.y - b.y, b.w - frag_pos.y),
+ );
+ return clamp(inside + 0.5, 0.0, 1.0);
+}
+
@fragment
fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> {
let velocity_uv = cursor_velocity_uv();
let blur_strength = uniforms.motion_vector_strength.z;
- let opacity = uniforms.motion_vector_strength.w;
+ let opacity = uniforms.motion_vector_strength.w * screen_bounds_mask(input.position.xy);
let base_color = sample_cursor(input.uv);
if (length(velocity_uv) < 0.005 || blur_strength < 0.001) {
diff --git a/crates/rendering/src/text.rs b/crates/rendering/src/text.rs
index 661eabee5..5fb66bd61 100644
--- a/crates/rendering/src/text.rs
+++ b/crates/rendering/src/text.rs
@@ -1,7 +1,13 @@
use cap_project::{TextSegment, XY};
-const BASE_TEXT_HEIGHT: f64 = 0.2;
-const MAX_FONT_SIZE_PX: f32 = 256.0;
+/// Text font sizes are authored against a 1080p-tall reference frame and
+/// scaled to the output height, so a project renders identically at every
+/// export resolution. `size` only positions and wraps the text — it never
+/// affects glyph size (that coupling is baked away by the config migration
+/// in cap_project).
+const REFERENCE_HEIGHT: f32 = 1080.0;
+pub const MIN_FONT_SIZE: f32 = 8.0;
+pub const MAX_FONT_SIZE: f32 = 480.0;
#[derive(Debug, Clone)]
pub struct PreparedText {
@@ -40,7 +46,7 @@ pub fn prepare_texts(
let height_scale = if output_size.y == 0 {
1.0
} else {
- output_size.y as f32 / 1080.0
+ output_size.y as f32 / REFERENCE_HEIGHT
};
for (i, segment) in segments.iter().enumerate() {
@@ -60,17 +66,16 @@ pub fn prepare_texts(
segment.size.x.clamp(0.01, 2.0),
segment.size.y.clamp(0.01, 2.0),
);
- let size_scale = (size.y / BASE_TEXT_HEIGHT).clamp(0.25, 4.0) as f32;
let width = (size.x * output_size.x as f64).max(1.0) as f32;
let height = (size.y * output_size.y as f64).max(1.0) as f32;
- let half_w = width / 2.0;
- let half_h = height / 2.0;
- let left = (center.x as f32 * output_size.x as f32 - half_w).max(0.0);
- let top = (center.y as f32 * output_size.y as f32 - half_h).max(0.0);
- let right = (left + width).min(output_size.x as f32);
- let bottom = (top + height).min(output_size.y as f32);
+ // The box may overhang frame edges (the editor allows dragging up to
+ // half the box outside); glyphon culls anything past the viewport.
+ let left = center.x as f32 * output_size.x as f32 - width / 2.0;
+ let top = center.y as f32 * output_size.y as f32 - height / 2.0;
+ let right = left + width;
+ let bottom = top + height;
let fade_duration = segment.fade_duration.max(0.0);
let opacity = if fade_duration > 0.0 {
@@ -90,8 +95,7 @@ pub fn prepare_texts(
bounds: [left, top, right, bottom],
color: parse_color(&segment.color),
font_family: segment.font_family.clone(),
- font_size: ((segment.font_size * size_scale).max(1.0) * height_scale)
- .min(MAX_FONT_SIZE_PX),
+ font_size: segment.font_size.clamp(MIN_FONT_SIZE, MAX_FONT_SIZE) * height_scale,
font_weight: segment.font_weight,
italic: segment.italic,
opacity,
diff --git a/crates/rendering/src/zoom_spring.rs b/crates/rendering/src/zoom_spring.rs
index 34f9d2af2..fc093d92a 100644
--- a/crates/rendering/src/zoom_spring.rs
+++ b/crates/rendering/src/zoom_spring.rs
@@ -27,8 +27,8 @@
//! export matches playback by construction.
use cap_project::{
- CursorEvents, ProjectConfiguration, ScreenMovementSpring, TimelineConfiguration, XY, ZoomMode,
- ZoomSegment,
+ Crop, CursorEvents, ProjectConfiguration, ScreenMovementSpring, TimelineConfiguration, XY,
+ ZoomMode, ZoomSegment,
};
use crate::{
@@ -52,6 +52,59 @@ const CLUSTER_HEIGHT_RATIO: f64 = 0.7;
/// Fallback focus when a segment has no usable cursor data.
const FALLBACK_FOCUS: (f64, f64) = (0.5, 0.5);
+/// Maps raw display-UV cursor coordinates into cropped-content UV space.
+///
+/// Cursor events are normalized to the FULL recorded display, but zoom
+/// centers ([`SegmentBounds::from_amount_center`]) are proportions of the
+/// rendered (cropped) content. Without this remap a cropped recording aims
+/// its auto zoom at the wrong spot — and clustering dead-zone distances are
+/// measured in the wrong scale. Identity when the recording is uncropped.
+#[derive(Clone, Copy, Debug)]
+pub struct CursorCropMap {
+ /// Crop top-left in raw display UV.
+ offset: XY<f64>,
+ /// Crop size in raw display UV.
+ scale: XY<f64>,
+}
+
+impl CursorCropMap {
+ /// `None` when the crop covers the whole screen (identity) or when the
+ /// inputs are degenerate.
+ pub fn from_crop(crop: &Crop, screen_size: XY<u32>) -> Option<Self> {
+ if screen_size.x == 0 || screen_size.y == 0 || crop.size.x == 0 || crop.size.y == 0 {
+ return None;
+ }
+ if crop.position.x == 0
+ && crop.position.y == 0
+ && crop.size.x >= screen_size.x
+ && crop.size.y >= screen_size.y
+ {
+ return None;
+ }
+ let screen = XY::new(f64::from(screen_size.x), f64::from(screen_size.y));
+ Some(Self {
+ offset: XY::new(
+ f64::from(crop.position.x) / screen.x,
+ f64::from(crop.position.y) / screen.y,
+ ),
+ scale: XY::new(
+ f64::from(crop.size.x) / screen.x,
+ f64::from(crop.size.y) / screen.y,
+ ),
+ })
+ }
+
+ /// Raw display UV -> content UV. Positions outside the crop map outside
+ /// [0, 1]; consumers clamp at the point of use so movement into a
+ /// cropped-away strip still aims the camera at that content edge.
+ fn map(&self, x: f64, y: f64) -> (f64, f64) {
+ (
+ (x - self.offset.x) / self.scale.x,
+ (y - self.offset.y) / self.scale.y,
+ )
+ }
+}
+
#[derive(Debug)]
pub(crate) struct ClickCluster {
min_x: f64,
@@ -108,11 +161,16 @@ pub(crate) fn build_clusters(
segment_start_secs: f64,
segment_end_secs: f64,
zoom_amount: f64,
+ crop: Option<CursorCropMap>,
) -> Vec<ClickCluster> {
let start_ms = segment_start_secs * 1000.0;
let end_ms = segment_end_secs * 1000.0;
let cluster_w = CLUSTER_WIDTH_RATIO / zoom_amount.max(1.0);
let cluster_h = CLUSTER_HEIGHT_RATIO / zoom_amount.max(1.0);
+ // Clustering happens in CONTENT UV space: dead-zone box limits are
+ // fractions of the visible (cropped) viewport, so raw display UVs must be
+ // remapped before distances mean what the constants say they mean.
+ let map_uv = |x: f64, y: f64| crop.map_or((x, y), |c| c.map(x, y));
// Non-finite coordinates (corrupted files, synthetic event generators)
// must never reach the cluster math: NaN propagates through min/max and
@@ -144,21 +202,24 @@ pub(crate) fn build_clusters(
});
if let Some(evt) = fallback {
- return vec![ClickCluster::new(evt.x, evt.y, evt.time_ms)];
+ let (x, y) = map_uv(evt.x, evt.y);
+ return vec![ClickCluster::new(x, y, evt.time_ms)];
}
return vec![];
}
let mut clusters = Vec::new();
let first = events_in_range[0];
- let mut current = ClickCluster::new(first.x, first.y, first.time_ms);
+ let (first_x, first_y) = map_uv(first.x, first.y);
+ let mut current = ClickCluster::new(first_x, first_y, first.time_ms);
for evt in &events_in_range[1..] {
- if current.can_add(evt.x, evt.y, cluster_w, cluster_h) {
- current.add(evt.x, evt.y, evt.time_ms);
+ let (x, y) = map_uv(evt.x, evt.y);
+ if current.can_add(x, y, cluster_w, cluster_h) {
+ current.add(x, y, evt.time_ms);
} else {
clusters.push(current);
- current = ClickCluster::new(evt.x, evt.y, evt.time_ms);
+ current = ClickCluster::new(x, y, evt.time_ms);
}
}
clusters.push(current);
@@ -288,6 +349,7 @@ impl ZoomTransformTimeline {
cursor_events: &CursorEvents,
spring: ScreenMovementSpring,
duration_secs: f64,
+ crop: Option<CursorCropMap>,
) -> Self {
let mut zoom_segments = zoom_segments.to_vec();
zoom_segments.sort_by(|a, b| a.start.total_cmp(&b.start).then(a.end.total_cmp(&b.end)));
@@ -305,6 +367,7 @@ impl ZoomTransformTimeline {
recording_start,
recording_end,
segment.amount,
+ crop,
))
}
ZoomMode::Manual { .. } => None,
@@ -365,13 +428,22 @@ impl ZoomTransformTimeline {
timeline
}
- /// Convenience constructor pulling zoom segments, edit mapping and spring
- /// config out of a [`ProjectConfiguration`].
+ /// Convenience constructor pulling zoom segments, edit mapping, spring
+ /// config and crop mapping out of a [`ProjectConfiguration`].
+ /// `screen_size` is the raw recorded display size in px
+ /// (`RenderOptions::screen_size`), needed to normalize the project's
+ /// pixel-space crop into cursor UV space.
pub fn from_project(
project: &ProjectConfiguration,
cursor_events: &CursorEvents,
duration_secs: f64,
+ screen_size: XY<u32>,
) -> Self {
+ let crop = project
+ .background
+ .crop
+ .as_ref()
+ .and_then(|crop| CursorCropMap::from_crop(crop, screen_size));
Self::new(
project
.timeline
@@ -382,6 +454,7 @@ impl ZoomTransformTimeline {
cursor_events,
project.screen_movement_spring,
duration_secs,
+ crop,
)
}
@@ -639,6 +712,7 @@ mod tests {
cursor,
ScreenMovementSpring::default(),
duration,
+ None,
)
}
@@ -1201,6 +1275,7 @@ mod tests {
&cursor,
ScreenMovementSpring::default(),
10.0,
+ None,
);
timeline.precompute();
@@ -1220,4 +1295,104 @@ mod tests {
settled.bounds
);
}
+
+ #[test]
+ fn crop_map_identity_cases() {
+ let screen = XY::new(1000u32, 1000u32);
+ // Full-screen crop is the identity: no map.
+ let full = Crop {
+ position: XY::new(0, 0),
+ size: XY::new(1000, 1000),
+ };
+ assert!(CursorCropMap::from_crop(&full, screen).is_none());
+ // Degenerate inputs never produce a map.
+ let degenerate = Crop {
+ position: XY::new(0, 0),
+ size: XY::new(0, 500),
+ };
+ assert!(CursorCropMap::from_crop(&degenerate, screen).is_none());
+ assert!(CursorCropMap::from_crop(&full, XY::new(0, 0)).is_none());
+ }
+
+ #[test]
+ fn crop_remaps_auto_zoom_focus_into_content_space() {
+ // Screen 1000x1000 cropped to the bottom half: content = y 500..1000.
+ let crop = Crop {
+ position: XY::new(0, 500),
+ size: XY::new(1000, 500),
+ };
+ let map = CursorCropMap::from_crop(&crop, XY::new(1000, 1000)).unwrap();
+
+ // Cursor parked at raw (0.5, 0.75) = the exact CENTER of the visible
+ // content. Uncropped this raw y would edge-snap to a bottom-flush
+ // framing; content-space it must settle centered.
+ let cursor = CursorEvents {
+ moves: vec![move_event(0.0, 0.5, 0.75), move_event(8_000.0, 0.5, 0.75)],
+ clicks: vec![],
+ };
+ let segments = vec![auto_segment(0.5, 8.0, 2.0)];
+ let mut with_crop = ZoomTransformTimeline::new(
+ &segments,
+ None,
+ &cursor,
+ ScreenMovementSpring::default(),
+ 10.0,
+ Some(map),
+ );
+ with_crop.precompute();
+
+ let settled = with_crop.sample(6.0);
+ let centered = SegmentBounds::from_amount_center(2.0, XY::new(0.5, 0.5));
+ assert!(
+ (settled.bounds.top_left.y - centered.top_left.y).abs() < 1e-2,
+ "expected centered framing {:?}, got {:?}",
+ centered,
+ settled.bounds
+ );
+
+ let mut without_crop = timeline_for(&segments, &cursor, 10.0);
+ without_crop.precompute();
+ let raw_settled = without_crop.sample(6.0);
+ assert!(
+ (raw_settled.bounds.top_left.y - centered.top_left.y).abs() > 0.2,
+ "control: uncropped framing should NOT be centered, got {:?}",
+ raw_settled.bounds
+ );
+ }
+
+ #[test]
+ fn cursor_in_cropped_away_region_aims_at_content_edge() {
+ // Bottom-half crop; the cursor hovers in the removed TOP strip
+ // (raw y = 0.05 -> content y < 0). The framing must clamp to a
+ // top-flush viewport, not wander or blow up.
+ let crop = Crop {
+ position: XY::new(0, 500),
+ size: XY::new(1000, 500),
+ };
+ let map = CursorCropMap::from_crop(&crop, XY::new(1000, 1000)).unwrap();
+
+ let cursor = CursorEvents {
+ moves: vec![move_event(0.0, 0.5, 0.05), move_event(8_000.0, 0.5, 0.05)],
+ clicks: vec![],
+ };
+ let segments = vec![auto_segment(0.5, 8.0, 2.0)];
+ let mut timeline = ZoomTransformTimeline::new(
+ &segments,
+ None,
+ &cursor,
+ ScreenMovementSpring::default(),
+ 10.0,
+ Some(map),
+ );
+ timeline.precompute();
+
+ let settled = timeline.sample(6.0);
+ let top_flush = SegmentBounds::from_amount_center(2.0, XY::new(0.5, 0.0));
+ assert!(
+ (settled.bounds.top_left.y - top_flush.top_left.y).abs() < 1e-2,
+ "expected top-flush framing {:?}, got {:?}",
+ top_flush,
+ settled.bounds
+ );
+ }
}