Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: reconcile desktop editor and recording improvements

Richie McIlroyae19682d9f1b
diff --cc Cargo.lock
index 138b03df8,6f98ac0d9..c395bf647
--- a/Cargo.lock
+++ b/Cargo.lock
@@@ -1247,6 -1247,6 +1247,7 @@@ dependencies =
"tokio-util",
"toml_edit 0.23.10+spec-1.0.0",
"tracing",
++ "tracing-appender",
"tracing-subscriber",
"url",
"uuid",
@@@ -1458,6 -1457,6 +1459,7 @@@ dependencies =
"async-stream",
"axum",
"base64 0.22.1",
++ "block2 0.6.1",
"bytemuck",
"bytes",
"cap-audio",
@@@ -1586,6 -1585,6 +1588,7 @@@ dependencies =
"cap-media-info",
"cap-project",
"cap-rendering",
++ "cap-utils",
"cpal 0.15.3 (git+https://github.com/CapSoftware/cpal?rev=6013cb5f8bd3)",
"ffmpeg-next",
"flume",
@@@ -2038,6 -2036,6 +2041,7 @@@ dependencies =
"tempfile",
"tokio",
"tracing",
++ "tracing-appender",
"uuid",
"windows 0.58.0",
"windows-sys 0.52.0",
diff --cc apps/cli/Cargo.toml
index 73f5de61d,73f5de61d..b66b0c7ae
--- a/apps/cli/Cargo.toml
+++ b/apps/cli/Cargo.toml
@@@ -42,6 -42,6 +42,7 @@@ toml_edit = "0.23.7
url = "2.5.7"
tracing.workspace = true
tracing-subscriber = "0.3.19"
++tracing-appender = "0.2.3"
cpal = { workspace = true }
winit = "0.30"
softbuffer = "0.4"
diff --cc apps/cli/build.rs
index b99bd3ea5,b99bd3ea5..77ca169f7
--- a/apps/cli/build.rs
+++ b/apps/cli/build.rs
@@@ -1,3 -1,3 +1,6 @@@
++#[path = "../../scripts/diagnostic-build.rs"]
++mod diagnostic_build;
++
use std::path::Path;
// The cap-demo skill directory is embedded wholesale into the `cap` binary via
@@@ -9,6 -9,6 +12,7 @@@
// including playwright-core — bloating the shipped CLI and making builds
// non-reproducible. Guard against that here, loudly, at build time.
fn main() {
++ diagnostic_build::emit();
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set");
let node_modules = Path::new(&manifest_dir)
.join("skill")
diff --cc apps/cli/src/main.rs
index 8c0a790f7,8c0a790f7..00f1635d1
--- a/apps/cli/src/main.rs
+++ b/apps/cli/src/main.rs
@@@ -484,6 -484,6 +484,30 @@@ fn main()
)
.init();
++ let _diagnostic_guard = if std::env::var_os("CAP_DIAGNOSTIC_PARENT").is_some() {
++ let (writer, guard) = tracing_appender::non_blocking(std::io::stderr());
++ let queue_errors = writer.error_counter();
++ cap_utils::operation_diagnostics::install_queue_loss_counter(move || {
++ queue_errors.dropped_lines()
++ });
++ cap_utils::operation_diagnostics::install_sink(
++ cap_utils::operation_diagnostics::AppInfo {
++ flavor: "export_worker",
++ version: env!("CARGO_PKG_VERSION"),
++ source_revision: option_env!("CAP_BUILD_REVISION"),
++ debug_build: cfg!(debug_assertions),
++ source_dirty: option_env!("CAP_BUILD_DIRTY").map(|value| value == "true"),
++ },
++ move |bytes| {
++ use std::io::Write;
++ let _ = writer.clone().write_all(bytes);
++ },
++ );
++ Some(guard)
++ } else {
++ None
++ };
++
let exit_after_success = cli.exit_after_success();
// The self-test opens a window, which AppKit requires to live on the real
@@@ -516,7 -516,7 +540,11 @@@
.build()
.map_err(|e| format!("Failed to build Tokio runtime: {e}"))?;
++ if _diagnostic_guard.is_some() {
++ drop(runtime.spawn(cap_utils::operation_diagnostics::run_checkpoints()));
++ }
let result = runtime.block_on(run(cli));
++ drop(_diagnostic_guard);
if exit_after_success && result.is_ok() {
// Successful export/preview workers have already written their output by here.
// Exiting directly avoids Windows GPU/MediaFoundation teardown crashes in the
diff --cc apps/desktop-gpui/Cargo.lock
index 45b260128,504a5feea..d36888cc5
--- a/apps/desktop-gpui/Cargo.lock
+++ b/apps/desktop-gpui/Cargo.lock
@@@ -1610,6 -1608,6 +1610,7 @@@ dependencies =
"cap-media-info",
"cap-project",
"cap-rendering",
++ "cap-utils",
"cpal 0.15.3 (git+https://github.com/CapSoftware/cpal?rev=6013cb5f8bd3)",
"ffmpeg-next",
"flume 0.11.1",
diff --cc apps/desktop-gpui/build.rs
index 202980b60,202980b60..4faa84b72
--- a/apps/desktop-gpui/build.rs
+++ b/apps/desktop-gpui/build.rs
@@@ -1,4 -1,4 +1,8 @@@
++#[path = "../../scripts/diagnostic-build.rs"]
++mod diagnostic_build;
++
fn main() {
++ diagnostic_build::emit();
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
diff --cc apps/desktop-gpui/src/app_windows.rs
index cd9161e0b,65b0204fc..5665a04bc
--- a/apps/desktop-gpui/src/app_windows.rs
+++ b/apps/desktop-gpui/src/app_windows.rs
@@@ -1032,7 -887,7 +1032,7 @@@ pub fn open_quality_settings(mode: Mode
if defer_window_until_capture_safe(cx) {
return;
}
-- open_settings(Page::General, cx);
++ open_settings(Page::Quality, cx);
if let Some(handle) = cx.global::<AppWindows>().settings {
handle
.update(cx, |view, window, cx| {
diff --cc apps/desktop-gpui/src/assets.rs
index 935e2c591,935e2c591..9b592ca7e
--- a/apps/desktop-gpui/src/assets.rs
+++ b/apps/desktop-gpui/src/assets.rs
@@@ -84,7 -84,7 +84,6 @@@ const ICONS: &[(&str, &[u8])] = assets!
"bg-blur.svg",
"laptop.svg",
"wind.svg",
-- "image-off.svg",
"shuffle.svg",
"gift.svg",
"history.svg",
@@@ -162,27 -162,27 +161,18 @@@
"align-right.svg",
"arrow-left-right.svg",
"download.svg",
-- "ease-curve.svg",
"flip-vertical-2.svg",
-- "grid.svg",
-- "grip.svg",
"italic.svg",
"maximize.svg",
-- "moon.svg",
"mouse-pointer-2.svg",
-- "mouse-pointer-click.svg",
"move.svg",
"move-right.svg",
"palette.svg",
-- "rabbit.svg",
"ratio.svg",
"refresh-cw.svg",
"rotate-ccw.svg",
"rotate-cw.svg",
-- "sliders-horizontal.svg",
-- "sparkles.svg",
"timer.svg",
-- "volume-2.svg",
"volume-x.svg",
"diamond.svg",
"x-mark.svg",
@@@ -239,22 -239,22 +229,6 @@@ const IMAGES: &[(&str, &[u8])] = assets
"dark.jpg",
);
--/// The background-source tiles' fallback art, copied from
--/// `apps/desktop/src/assets/illustrations/`. Full-colour, so `img()` not
--/// `svg()`, and webp because that is what the app ships -- 4 KB for the pair,
--/// against 25 MB if the wallpapers themselves were embedded (see the README).
--///
--/// **Two of `BACKGROUND_ICONS`' four are dead in the shipping app.**
--/// `renderBackgroundSourceIcon` returns a live swatch for `color` and a live
--/// gradient for `gradient` before it ever reaches the map
--/// (`ConfigSidebar.tsx:2076-2089`), so `colorBg` and `gradientBg` are imported
--/// and never drawn; only `imageBg` (desktop and wallpaper) and
--/// `transparentBg` (image) are.
--const ILLUSTRATIONS: &[(&str, &[u8])] = assets!("illustrations":
-- "image.webp",
-- "transparent.webp",
--);
--
const ONBOARDING: &[(&str, &[u8])] = &[
("onboarding/cloud-1.png", include_bytes!("../../desktop/src/assets/illustrations/cloud-1.png")),
("onboarding/cloud-2.png", include_bytes!("../../desktop/src/assets/illustrations/cloud-2.png")),
@@@ -276,7 -276,7 +250,6 @@@ impl Assets
.iter()
.chain(ICONS.iter())
.chain(IMAGES.iter())
-- .chain(ILLUSTRATIONS.iter())
.chain(ONBOARDING.iter())
}
}
@@@ -333,6 -333,6 +306,7 @@@ mod tests
include_str!("teleprompter_window.rs"),
include_str!("editor_window.rs"),
include_str!("editor_window/frame.rs"),
++ include_str!("editor_window/scenes.rs"),
// The timeline's nine track glyphs and its scene-mode icons are named
// in the strip's own module, not in the window that hosts it.
include_str!("editor_timeline.rs"),
@@@ -453,42 -453,42 +427,6 @@@
);
}
-- /// And for the background-source tiles' art, which resolves through the
-- /// same `AssetSource` and fails just as silently.
-- #[test]
-- fn every_referenced_illustration_is_embedded_and_vice_versa() {
-- let source = ICON_SOURCES.concat();
-- let source = source.as_str();
--
-- let referenced: Vec<&str> = source
-- .match_indices("\"illustrations/")
-- .filter_map(|(start, _)| source[start + 1..].split('"').next())
-- .collect();
-- assert!(
-- !referenced.is_empty(),
-- "found no illustration references to check"
-- );
--
-- let missing: Vec<&str> = referenced
-- .into_iter()
-- .filter(|path| Assets.load(path).unwrap().is_none())
-- .collect();
-- assert!(
-- missing.is_empty(),
-- "illustrations referenced but not embedded: {missing:?}"
-- );
--
-- let unused: Vec<&str> = ILLUSTRATIONS
-- .iter()
-- .map(|(path, _)| *path)
-- .filter(|path| !source.contains(path))
-- .collect();
-- assert!(
-- unused.is_empty(),
-- "illustrations embedded but never drawn: {unused:?}"
-- );
-- }
--
#[test]
fn fonts_and_icons_resolve() {
assert!(Assets.load("fonts/Geist.ttf").unwrap().is_some());
@@@ -498,10 -498,10 +436,5 @@@
assert_eq!(Assets.list("fonts").unwrap().len(), FONTS.len());
assert_eq!(Assets.list("icons").unwrap().len(), ICONS.len());
assert_eq!(Assets.list("images").unwrap().len(), IMAGES.len());
-- assert!(Assets.load("illustrations/image.webp").unwrap().is_some());
-- assert_eq!(
-- Assets.list("illustrations").unwrap().len(),
-- ILLUSTRATIONS.len()
-- );
}
}
diff --cc apps/desktop-gpui/src/auth.rs
index a40220a8d,a40220a8d..072cdab5c
--- a/apps/desktop-gpui/src/auth.rs
+++ b/apps/desktop-gpui/src/auth.rs
@@@ -9,6 -9,6 +9,8 @@@ use serde_json::{Value, json}
use crate::store::{self, DEFAULT_SERVER_URL};
++pub const PRICING_URL: &str = "https://cap.so/pricing?ref=desktop";
++
const CALLBACK_HTML: &str = r#"<!DOCTYPE html>
<html lang="en">
<head>
diff --cc apps/desktop-gpui/src/dev_restore.rs
index 3cd18b1ef,3cd18b1ef..2c1c2bd88
--- a/apps/desktop-gpui/src/dev_restore.rs
+++ b/apps/desktop-gpui/src/dev_restore.rs
@@@ -13,7 -13,7 +13,7 @@@
use std::path::{Path, PathBuf};
use std::time::Duration;
--use gpui::{App, Window};
++use gpui::{App, Bounds, Pixels, Point, Size, Window, point, px};
use serde::{Deserialize, Serialize};
use crate::app_windows::{self, AppWindows};
@@@ -74,26 -74,26 +74,86 @@@ fn state_path() -> Option<PathBuf>
.map(PathBuf::from)
}
--pub fn init(cx: &mut App) {
-- let Some(path) = state_path() else {
-- return;
-- };
-- match std::fs::read_to_string(&path) {
++pub struct DevRestore {
++ path: PathBuf,
++ state: Option<DevState>,
++}
++
++pub fn load() -> Option<DevRestore> {
++ let path = state_path()?;
++ let state = match std::fs::read_to_string(&path) {
Ok(raw) => match serde_json::from_str::<DevState>(&raw) {
-- Ok(state) => restore(state, cx),
++ Ok(state) => Some(state),
Err(error) => {
tracing::warn!(%error, "dev-restore state unreadable; starting fresh");
++ None
}
},
-- Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
-- Err(error) => tracing::warn!(%error, "dev-restore state unreadable; starting fresh"),
++ Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
++ Err(error) => {
++ tracing::warn!(%error, "dev-restore state unreadable; starting fresh");
++ None
++ }
++ };
++ Some(DevRestore { path, state })
++}
++
++impl DevRestore {
++ /// Where the main window opens: the saved origin under the app's own
++ /// collapsed size, so it never moves after its first frame.
++ ///
++ /// Only the origin is restored. The size is the app's to decide, and
++ /// re-asserting a saved frame over it once shrank the window under its
++ /// content (a 396pt frame from an older layout against the 432pt
++ /// collapsed size): the body scrolled, and the poller kept re-saving the
++ /// shrunken frame, so every relaunch inherited it. Bottom-left anchoring
++ /// matches `setContentSize:`, which is what `window.resize` uses on
++ /// macOS, so an expanded restore grows back into the exact saved frame.
++ pub fn main_window_bounds(&self, size: Size<Pixels>, cx: &App) -> Option<Bounds<Pixels>> {
++ let (x, y, width, height) = self.state.as_ref()?.main.frame?;
++ if !platform::frame_is_on_screen(x, y, width, height) {
++ tracing::info!(
++ x,
++ y,
++ width,
++ height,
++ "saved main window frame is off every connected display; opening centred"
++ );
++ return None;
++ }
++ let primary_height = cx.primary_display()?.bounds().size.height;
++ Some(Bounds {
++ origin: opening_origin((x, y), size, primary_height),
++ size,
++ })
++ }
++
++ pub fn init(self, cx: &mut App) {
++ if let Some(state) = self.state {
++ restore(state, cx);
++ }
++ spawn_poller(self.path, cx);
}
-- spawn_poller(path, cx);
++}
++
++/// gpui's macOS open path takes a top-left origin measured down from the top
++/// of the primary display (`MacWindow::open` adds the primary display height
++/// and calls `setFrameTopLeftPoint:`); an AppKit frame origin is the
++/// bottom-left, measured up from that display's bottom.
++fn opening_origin(
++ appkit_origin: (f64, f64),
++ size: Size<Pixels>,
++ primary_height: Pixels,
++) -> Point<Pixels> {
++ let (x, y) = appkit_origin;
++ let top = px(y as f32) + size.height;
++ point(px(x as f32), primary_height - top)
}
fn restore(state: DevState, cx: &mut App) {
tracing::info!(
expanded = state.main.expanded,
++ main_frame = ?state.main.frame,
settings = state.settings.as_ref().map(|s| s.page.as_str()),
editors = state.editors.len(),
teleprompter = state.teleprompter,
@@@ -131,8 -131,8 +191,8 @@@
}
cx.spawn(async move |cx| {
-- // Let the centred first frames and the expand animation land before
-- // the frames are re-asserted.
++ // Let the first frames and the expand animation land before the
++ // frames are re-asserted.
cx.background_executor()
.timer(Duration::from_millis(600))
.await;
@@@ -155,11 -155,11 +215,13 @@@
}
};
cx.update(|cx| {
++ // The main window already opened at its saved origin
++ // (`DevRestore::main_window_bounds`); only its ordering is left.
collect(
main.update(cx, |_, window, _| platform::native_window(window))
.ok()
.flatten(),
-- state.main.frame,
++ None,
state.main.visible,
);
if let (Some(handle), Some(saved)) = (settings, &state.settings) {
@@@ -351,3 -351,3 +413,23 @@@ fn write_atomic(path: &Path, contents:
}
result.is_ok()
}
++
++#[cfg(test)]
++mod tests {
++ use super::opening_origin;
++ use gpui::{point, px, size};
++
++ #[test]
++ fn saved_origin_is_kept_under_the_current_collapsed_size() {
++ let origin = opening_origin((1035., 857.), size(px(330.), px(432.)), px(1440.));
++ assert_eq!(origin, point(px(1035.), px(151.)));
++ }
++
++ #[test]
++ fn expanded_frame_restores_to_the_same_bottom_left() {
++ let collapsed = opening_origin((1035., 857.), size(px(330.), px(432.)), px(1440.));
++ let expanded = opening_origin((1035., 857.), size(px(600.), px(672.)), px(1440.));
++ assert_eq!(collapsed.x, expanded.x);
++ assert_eq!(collapsed.y - expanded.y, px(672. - 432.));
++ }
++}
diff --cc apps/desktop-gpui/src/diagnostics.rs
index f4bfb11f8,f4bfb11f8..9636fdfcb
--- a/apps/desktop-gpui/src/diagnostics.rs
+++ b/apps/desktop-gpui/src/diagnostics.rs
@@@ -38,7 -38,7 +38,6 @@@ use crate::{permissions, store}
pub const LOG_FILE_PREFIX: &str = "cap-gpui.log";
/// `MAX_SIZE` in `src-tauri/src/logging.rs`.
--const MAX_LOG_UPLOAD_BYTES: usize = 1024 * 1024;
/// How much of the self-test's stderr is kept for a failure message.
const STDERR_TAIL_BYTES: usize = 8 * 1024;
@@@ -92,70 -92,70 +91,8 @@@ pub fn logs_dir() -> PathBuf
}
}
--/// `get_latest_log_file` in `src-tauri/src/logging.rs`: the daily appender
--/// names files `<prefix>.<date>`, so the newest by modification time is the
--/// one being written right now.
--fn latest_log_file(dir: &Path) -> Option<PathBuf> {
-- let mut files: Vec<_> = std::fs::read_dir(dir)
-- .ok()?
-- .filter_map(|entry| {
-- let entry = entry.ok()?;
-- let path = entry.path();
-- if !path.is_file() || !path.file_name()?.to_str()?.contains(LOG_FILE_PREFIX) {
-- return None;
-- }
-- let modified = std::fs::metadata(&path).ok()?.modified().ok()?;
-- Some((path, modified))
-- })
-- .collect();
-- files.sort_by_key(|(_, modified)| std::cmp::Reverse(*modified));
-- files.into_iter().next().map(|(path, _)| path)
--}
--
--/// The last ~1MB of the newest log file, with the Tauri app's truncation
--/// header. Split out from the IO so the byte arithmetic is testable.
--fn log_tail_from(content: &str, file_size: u64, max_bytes: usize) -> String {
-- if file_size as usize <= max_bytes {
-- return content.to_string();
-- }
-- let header =
-- format!("⚠️ Log file truncated (original size: {file_size} bytes, showing last ~1MB)\n\n");
-- let Some(max_content) = max_bytes.checked_sub(header.len()) else {
-- return header;
-- };
-- if content.len() <= max_content {
-- return content.to_string();
-- }
--
-- let mut start = content.len() - max_content;
-- // The cut lands at an arbitrary byte; walk forward to a char boundary
-- // before slicing, then forward again to the next line so the upload never
-- // opens mid-record.
-- while start < content.len() && !content.is_char_boundary(start) {
-- start += 1;
-- }
-- let start = match content[start..].find('\n') {
-- Some(offset) => start + offset + 1,
-- None => start,
-- };
-- format!("{header}{}", &content[start..])
--}
--
--/// The log text to upload. A missing log file is not an error: the upload is
--/// still worth making for its diagnostics, so a placeholder goes up instead.
--pub fn log_tail() -> String {
-- let dir = logs_dir();
-- let Some(path) = latest_log_file(&dir) else {
-- return format!(
-- "No log file was found in {}. This build may not have written one yet.",
-- dir.display()
-- );
-- };
-- let size = std::fs::metadata(&path).map(|meta| meta.len()).unwrap_or(0);
-- match std::fs::read_to_string(&path) {
-- Ok(content) => log_tail_from(&content, size, MAX_LOG_UPLOAD_BYTES),
-- Err(error) => format!("Failed to read {}: {error}", path.display()),
-- }
++pub fn log_tail() -> cap_utils::log_upload::LogBundle {
++ cap_utils::log_upload::collect(&logs_dir(), LOG_FILE_PREFIX)
}
// ---------------------------------------------------------------------------
@@@ -917,25 -917,25 +854,49 @@@ fn write_report_into(dir: &Path, report
pub async fn upload_report(
server_url: String,
token: Option<String>,
-- log: String,
++ log: cap_utils::log_upload::LogBundle,
report: Option<String>,
diagnostics: Option<String>,
) -> Result<(), String> {
++ let context = serde_json::json!({
++ "schemaVersion": 1,
++ "app": {
++ "flavor": "gpui",
++ "version": env!("CARGO_PKG_VERSION"),
++ "os": std::env::consts::OS,
++ "binaryArchitecture": std::env::consts::ARCH,
++ "debugBuild": cfg!(debug_assertions),
++ "sourceRevision": option_env!("CAP_BUILD_REVISION"),
++ "sourceDirty": option_env!("CAP_BUILD_DIRTY").and_then(|value| value.parse::<bool>().ok()),
++ },
++ "operations": cap_utils::operation_diagnostics::snapshot(),
++ "logCoverage": &log,
++ "environmentCollectedAt": "upload_time",
++ "mediaIncluded": false,
++ });
// Everything leaving the machine goes through the redactor. Logs record
// whole URLs on failure (reqwest's Display and Debug both append the URL),
// and an upload failure logs a presigned S3 PUT, whose query string is a
// live write credential for up to an hour.
use cap_recording::log_redaction::scrub_log_text;
++ let upload = cap_utils::log_upload::prepare_upload(
++ log,
++ context,
++ diagnostics.as_deref(),
++ report.as_deref(),
++ scrub_log_text,
++ );
let mut form = reqwest::multipart::Form::new()
-- .text("log", scrub_log_text(&log))
++ .text("log", upload.log)
.text("os", std::env::consts::OS)
-- .text("version", env!("CARGO_PKG_VERSION"));
-- if let Some(report) = report {
-- form = form.text("report", scrub_log_text(&report));
++ .text("version", env!("CARGO_PKG_VERSION"))
++ .text("context", upload.context);
++ if let Some(report) = upload.report {
++ form = form.text("report", report);
}
-- if let Some(diagnostics) = diagnostics {
-- form = form.text("diagnostics", scrub_log_text(&diagnostics));
++ if let Some(diagnostics) = upload.diagnostics {
++ form = form.text("diagnostics", diagnostics);
}
let mut request = reqwest::Client::new()
@@@ -1285,37 -1285,37 +1246,6 @@@ mod tests
std::fs::remove_dir_all(&dir).ok();
}
-- #[test]
-- fn a_short_log_is_uploaded_whole() {
-- let content = "line one\nline two\n";
-- assert_eq!(log_tail_from(content, content.len() as u64, 1024), content);
-- }
--
-- /// Over the cap, the tail keeps the header, stays under it, and opens on a
-- /// record boundary rather than mid-line.
-- #[test]
-- fn a_long_log_is_truncated_to_its_tail_on_a_line_boundary() {
-- let content: String = (0..500).map(|index| format!("line {index}\n")).collect();
-- let tail = log_tail_from(&content, content.len() as u64, 200);
--
-- assert!(tail.starts_with("⚠️ Log file truncated (original size:"));
-- assert!(tail.len() <= 200, "tail was {} bytes", tail.len());
-- assert!(tail.ends_with("line 499\n"));
-- let body = tail.split("\n\n").nth(1).unwrap();
-- assert!(
-- body.starts_with("line "),
-- "the tail opened mid-record: {body:?}"
-- );
-- }
--
-- /// A multi-byte character straddling the cut must not panic the slice.
-- #[test]
-- fn truncation_survives_a_cut_inside_a_character() {
-- let content: String = (0..200).map(|index| format!("café {index} ✅\n")).collect();
-- let tail = log_tail_from(&content, content.len() as u64, 300);
-- assert!(tail.ends_with("✅\n"));
-- }
--
#[test]
fn stage_labels_read_as_sentences() {
assert_eq!(
diff --cc apps/desktop-gpui/src/editor_canvas.rs
index a2f3f99ae,88d6876cc..eaa364b54
--- a/apps/desktop-gpui/src/editor_canvas.rs
+++ b/apps/desktop-gpui/src/editor_canvas.rs
@@@ -44,7 -44,7 +44,7 @@@ use std::cell::Cell
use std::rc::Rc;
use crate::{editor_timeline::TrackKind, editor_window::EditorWindow};
--use cap_project::{CameraXPosition, CameraYPosition, SceneMode, XY};
++use cap_project::{CameraXPosition, CameraYPosition, OverlayTrackKind, SceneMode, XY};
use cap_rendering::FrameLayout;
use gpui::{
AnyElement, Bounds, Context, CursorStyle, FontWeight, Hsla, InteractiveElement, IntoElement,
@@@ -1305,7 -1132,7 +1305,7 @@@ impl EditorWindow
.h(player.frame.size.height)
.overflow_hidden();
-- if self.canvas_selection.is_some() {
++ if self.canvas_selection.is_some() || self.selection.is_some() {
layer = layer.child(
div()
.id("canvas-deselect")
@@@ -1314,6 -1141,6 +1314,7 @@@
.on_mouse_down(
MouseButton::Left,
cx.listener(|this, _, window, cx| {
++ this.set_selection(None, cx);
this.canvas_selection = None;
cx.notify();
window.refresh();
@@@ -1335,38 -1162,23 +1336,70 @@@
layer.child(self.render_element_box(CanvasSelection::Camera, rect, (cw, ch), cx));
}
let time = self.preview_or_playhead();
++ let overlay_order = self.project.overlay_tracks();
if let Some(timeline) = self.project.timeline.as_ref() {
-- for (index, segment) in timeline.mask_segments.iter().enumerate() {
-- if !(time >= segment.start && time < segment.end) {
-- continue;
-- }
-- let element = CanvasSelection::Mask(index);
-- if let Some(rect) = self.element_rect(element) {
-- layer = layer.child(self.render_element_box(element, rect, (cw, ch), cx));
-- }
-- }
-- for (index, segment) in timeline.text_segments.iter().enumerate() {
-- if !(time >= segment.start && time < segment.end && segment.enabled) {
-- continue;
-- }
-- let element = CanvasSelection::Text(index);
-- if let Some(rect) = self.element_rect(element) {
-- layer = layer.child(self.render_element_box(element, rect, (cw, ch), cx));
- }
- }
- }
-
- if let Some(timeline) = self.project.timeline.as_ref() {
- let mut images: Vec<_> = timeline
- .image_segments
- .iter()
- .enumerate()
- .filter(|(_, segment)| segment.is_active_at(time) && segment.opacity > 0.)
- .collect();
- images.sort_by_key(|(index, segment)| (segment.track, *index));
- for (index, _) in images {
- if let Some(rect) = self.element_rect(CanvasSelection::Image(index)) {
- layer = layer.child(self.render_image_box(index, rect, (cw, ch), cx));
++ for track in overlay_order.iter().rev() {
++ match track.kind {
++ OverlayTrackKind::Mask => {
++ for (index, segment) in timeline
++ .mask_segments
++ .iter()
++ .enumerate()
++ .filter(|(_, segment)| segment.track == track.track)
++ {
++ if !(segment.enabled && time >= segment.start && time < segment.end) {
++ continue;
++ }
++ let element = CanvasSelection::Mask(index);
++ if let Some(rect) = self.element_rect(element) {
++ layer = layer.child(self.render_element_box(
++ element,
++ rect,
++ (cw, ch),
++ cx,
++ ));
++ }
++ }
++ }
++ OverlayTrackKind::Image => {
++ for (index, _) in
++ timeline
++ .image_segments
++ .iter()
++ .enumerate()
++ .filter(|(_, segment)| {
++ segment.track == track.track
++ && segment.is_active_at(time)
++ && segment.opacity > 0.
++ })
++ {
++ if let Some(rect) = self.element_rect(CanvasSelection::Image(index)) {
++ layer =
++ layer.child(self.render_image_box(index, rect, (cw, ch), cx));
++ }
++ }
++ }
++ OverlayTrackKind::Text => {
++ for (index, segment) in timeline
++ .text_segments
++ .iter()
++ .enumerate()
++ .filter(|(_, segment)| segment.track == track.track)
++ {
++ if !(time >= segment.start && time < segment.end && segment.enabled) {
++ continue;
++ }
++ let element = CanvasSelection::Text(index);
++ if let Some(rect) = self.element_rect(element) {
++ layer = layer.child(self.render_element_box(
++ element,
++ rect,
++ (cw, ch),
++ cx,
++ ));
++ }
++ }
++ }
}
}
}
diff --cc apps/desktop-gpui/src/editor_clips.rs
index 9ae9a2710,1f16e2946..814c372b1
--- a/apps/desktop-gpui/src/editor_clips.rs
+++ b/apps/desktop-gpui/src/editor_clips.rs
@@@ -228,9 -242,6 +242,8 @@@ pub(crate) fn move_clip
timeline
.transitions
.retain(|candidate| candidate.segment_index != transition.segment_index);
- // The source ripples these seven tracks and no others (`:672-682`).
+ ripple_track(&mut timeline.style_segments, boundary, effective.duration);
+ ripple_track(&mut timeline.image_segments, boundary, effective.duration);
ripple_track(&mut timeline.zoom_segments, boundary, effective.duration);
ripple_track(&mut timeline.scene_segments, boundary, effective.duration);
ripple_track(&mut timeline.mask_segments, boundary, effective.duration);
@@@ -401,19 -412,19 +414,17 @@@ impl EditorWindow
/// The Clips toggle (`Header.tsx:173-187`): `Button variant={open ?
/// "white" : "gray"}` at `flex gap-1.5 justify-center h-[40px]`, clearing
/// the timeline selection on every press.
-- pub(crate) fn render_clips_pill(&self, cx: &mut Context<Self>) -> impl IntoElement {
-- let variant = if self.clips.open {
-- ui::ButtonVariant::White
-- } else {
-- ui::ButtonVariant::Gray
-- };
-- ui::Button::plain(&self.theme, "clips-pill", variant, ui::ButtonSize::Md)
-- .icon("icons/clapperboard.svg")
-- .label("Clips")
++ pub(crate) fn render_clips_pill(
++ &self,
++ compact: bool,
++ cx: &mut Context<Self>,
++ ) -> impl IntoElement {
++ ui::EditorButton::plain(&self.theme, "clips-pill")
++ .left_icon("icons/clapperboard.svg")
++ .when(!compact, |button| button.label("Clips"))
++ .tooltip(&self.theme, "Clips")
++ .pressed(self.clips.open)
.disabled(!self.project_ready())
-- .height(px(40.))
-- .radius(px(12.))
-- .font_weight(FontWeight::MEDIUM)
.on_click(cx.listener(|this, _, window, cx| this.toggle_clips(window, cx)))
}
@@@ -716,21 -727,21 +727,16 @@@
// -- The sidebar ------------------------------------------------------------
/// The whole clips column, drawn in the config sidebar's slot while the
-- /// mode is open. Same `ml-2 w-104` wrapper the config sidebar carries
-- /// (`Editor.tsx:728`); the card itself is `flex flex-col flex-1 min-h-0
-- /// rounded-xl border bg-gray-1 dark:bg-gray-2 border-gray-3
-- /// overflow-hidden` (`ClipsSidebar.tsx:791-797`).
++ /// mode is open. Same `ml-2 w-104` wrapper the config sidebar carries, and
++ /// the same card.
pub(crate) fn render_clips_sidebar(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
self.request_clip_thumbnails(cx);
-- let theme = self.theme;
div()
-- .ml(px(8.))
.w(px(crate::editor_window::SIDEBAR_WIDTH))
.flex_none()
.flex()
.min_h_0()
-- .overflow_hidden()
.child(
div()
.flex()
@@@ -740,8 -751,8 +746,9 @@@
.overflow_hidden()
.rounded(px(12.))
.border_1()
-- .border_color(Hsla::from(theme.gray_3))
++ .border_color(self.card_line())
.bg(self.panel_bg())
++ .shadow(self.theme.editor.card_shadow())
.child(self.render_clips_back_header(cx))
.child(self.render_clips_body(cx)),
)
@@@ -758,22 -769,22 +765,23 @@@
.flex_row()
.items_center()
.gap(px(8.))
-- .px(px(16.))
++ .px(px(12.))
.w_full()
-- .h(px(64.))
++ .h(px(crate::editor_window::SIDEBAR_TAB_BAR_HEIGHT))
.rounded_t(px(11.))
.border_b_1()
-- .border_color(Hsla::from(theme.gray_3))
-- .text_size(px(14.))
++ .border_color(Hsla::from(theme.editor.line))
++ .text_size(px(13.))
.font_weight(FontWeight::MEDIUM)
-- .text_color(Hsla::from(theme.gray_12))
-- .hover(move |style| style.bg(Hsla::from(theme.gray_3)))
++ .text_color(Hsla::from(theme.editor.text_1))
++ .cursor_pointer()
++ .hover(move |style| style.bg(Hsla::from(theme.editor.ctl)))
.child(
svg()
.path("icons/move-left.svg")
.size(px(16.))
.flex_shrink_0()
-- .text_color(Hsla::from(theme.gray_11)),
++ .text_color(Hsla::from(theme.editor.text_2)),
)
.child("Back to editor")
.on_click(cx.listener(|this, _, window, cx| this.close_clips(window, cx)))
@@@ -3807,31 -3804,57 +3815,76 @@@ mod tests
edge_snap_ratio: 0.25,
}];
+ config.style_segments.push(cap_project::StyleSegment {
+ start: 15.,
+ end: 18.,
+ ..Default::default()
+ });
+ config.image_segments.push(cap_project::ImageSegment {
+ start: 15.,
+ end: 18.,
+ path: "content/images/retained.png".into(),
+ ..Default::default()
+ });
+ config.text_segments = serde_json::from_value(serde_json::json!([{
+ "start": 10.0,
+ "end": 12.0,
+ "track": 0,
+ "content": "Hold",
+ "layout": "fullscreen"
+ }]))
+ .unwrap();
+ config.keyboard_segments = serde_json::from_value(serde_json::json!([
+ {
+ "id": "before-boundary",
+ "start": 11.0,
+ "end": 12.0,
+ "displayText": "a",
+ "keys": [{ "key": "a", "timeOffset": 500.0 }]
+ },
+ {
+ "id": "spanning-boundary",
+ "start": 11.0,
+ "end": 13.0,
+ "displayText": "bc",
+ "keys": [
+ { "key": "b", "timeOffset": 500.0 },
+ { "key": "c", "timeOffset": 1500.0 }
+ ]
+ }
+ ]))
+ .unwrap();
// Moving clip 0 to the end separates the 0|1 pair, dropping the 1s
// transition whose boundary sat at offset(1) + 1.0 = 10.0.
assert!(move_clip(&mut config, 0, 3));
assert!(config.transitions.is_empty());
assert_eq!(config.zoom_segments[0].start, 16.0);
assert_eq!(config.zoom_segments[0].end, 19.0);
+ assert_eq!(
+ (config.style_segments[0].start, config.style_segments[0].end),
+ (16., 19.)
+ );
+ assert_eq!(
+ (config.image_segments[0].start, config.image_segments[0].end),
+ (16., 19.)
+ );
+ assert_eq!(
+ (
+ config.keyboard_segments[0].start,
+ config.keyboard_segments[0].end,
+ config.keyboard_segments[0].keys[0].time_offset,
+ ),
+ (11.0, 12.0, 500.0)
+ );
+ assert_eq!(
+ (
+ config.keyboard_segments[1].start,
+ config.keyboard_segments[1].end,
+ ),
+ (11.0, 14.0)
+ );
+ assert_eq!(config.keyboard_segments[1].keys[0].time_offset, 500.0);
+ assert_eq!(config.keyboard_segments[1].keys[1].time_offset, 2500.0);
}
/// `computeDropIndex` (`:692-703`): the insertion point is after every
diff --cc apps/desktop-gpui/src/editor_color.rs
index 60a7525eb,60a7525eb..13393aee3
--- a/apps/desktop-gpui/src/editor_color.rs
+++ b/apps/desktop-gpui/src/editor_color.rs
@@@ -41,7 -41,7 +41,7 @@@ use cap_project::{ColorCorrection, Proj
use gpui::{
AnyElement, Context, FontWeight, Hsla, InteractiveElement, IntoElement, ParentElement,
RenderImage, SharedString, StatefulInteractiveElement, Styled, StyledImage, Window, div, img,
-- prelude::FluentBuilder, px, svg,
++ prelude::FluentBuilder, px,
};
use crate::{editor_window::EditorWindow, ui};
@@@ -827,38 -827,38 +827,29 @@@ impl EditorWindow
let mut section = div()
.flex()
.flex_col()
-- .gap(px(24.))
-- .child(
-- ui::Field::plain(&theme, "Color Correction")
-- .icon("icons/sliders-horizontal.svg")
-- .child(tiles),
-- )
-- .child(
-- ui::Field::plain(&theme, "Grain")
-- .icon("icons/grip.svg")
-- .child(self.slider(
-- crate::editor_sidebar::SliderKey::Grade(target, GradeSlider::Grain),
-- "%",
-- cx,
-- )),
-- );
++ .gap(px(14.))
++ .child(ui::Field::section(&theme, "Color Correction").child(tiles))
++ .child(self.slider_field(
++ "Grain",
++ crate::editor_sidebar::SliderKey::Grade(target, GradeSlider::Grain),
++ "%",
++ cx,
++ ));
// `<Show when={props.target === "screen"}>` (`:151`).
if target == GradeTarget::Screen {
let grade_cursor = self.project.color_correction.grade_cursor;
section = section.child(
-- ui::Field::plain(&theme, "Apply to cursor")
-- .icon("icons/mouse-pointer-2.svg")
-- .value(
-- ui::Toggle::plain(&theme, "grade-cursor", grade_cursor)
-- .on_click(cx.listener(move |this, _, window, cx| {
-- this.edit_project("grade-cursor", window, cx, |project| {
-- project.color_correction.grade_cursor = !grade_cursor;
-- true
-- });
-- }))
-- .into_any_element(),
-- ),
++ ui::Field::inline(&theme, "Apply to cursor").value(
++ ui::Toggle::plain(&theme, "grade-cursor", grade_cursor)
++ .on_click(cx.listener(move |this, _, window, cx| {
++ this.edit_project("grade-cursor", window, cx, |project| {
++ project.color_correction.grade_cursor = !grade_cursor;
++ true
++ });
++ }))
++ .into_any_element(),
++ ),
);
}
@@@ -869,53 -869,53 +860,32 @@@
.w_full()
.flex()
.flex_col()
-- .child(
-- div()
-- .id(SharedString::from(format!("grade-adjust-{}", target.key())))
-- .flex()
-- .flex_row()
-- .gap(px(4.))
-- .items_center()
-- .w_full()
-- .text_size(px(14.))
-- .font_weight(FontWeight::MEDIUM)
-- .text_color(Hsla::from(theme.gray_12))
-- .cursor_pointer()
-- .child("Fine-tune colors")
-- .child(
-- // `group-data-expanded:rotate-180` -- no
-- // rotation in this rev, so the glyph swaps.
-- svg()
-- .path(if open.is_open() {
-- "icons/chevron-down.svg"
-- } else {
-- "icons/chevron-right.svg"
-- })
-- .size(px(20.))
-- .text_color(Hsla::from(theme.gray_12)),
-- )
-- .on_click(cx.listener(move |this, _, window, cx| {
-- let next = !this.sidebar.grade_open(target).is_open();
-- this.sidebar.set_grade_open(target, next);
-- this.animate_collapsibles(window, cx);
-- })),
-- )
++ .child(crate::editor_sidebar::disclosure_row(
++ &theme,
++ SharedString::from(format!("grade-adjust-{}", target.key())),
++ "Fine-tune colors",
++ open.is_open(),
++ cx.listener(move |this, _, window, cx| {
++ let next = !this.sidebar.grade_open(target).is_open();
++ this.sidebar.set_grade_open(target, next);
++ this.animate_collapsibles(window, cx);
++ }),
++ ))
.child(crate::editor_sidebar::collapsible(
open,
div()
.flex()
.flex_col()
-- .gap(px(24.))
// `mt-4 space-y-6`
-- .pt(px(16.))
++ .pt(px(4.))
.children(GradeSlider::ADJUST.map(|slider| {
-- ui::Field::plain(&theme, slider.label())
-- .child(self.slider(
-- crate::editor_sidebar::SliderKey::Grade(target, slider),
-- "%",
-- cx,
-- ))
-- .into_any_element()
++ self.slider_field(
++ slider.label(),
++ crate::editor_sidebar::SliderKey::Grade(target, slider),
++ "%",
++ cx,
++ )
++ .into_any_element()
}))
.into_any_element(),
)),
diff --cc apps/desktop-gpui/src/editor_crop.rs
index 797348ff1,553de486f..84b8ff276
--- a/apps/desktop-gpui/src/editor_crop.rs
+++ b/apps/desktop-gpui/src/editor_crop.rs
@@@ -2711,7 -2653,7 +2711,7 @@@ impl EditorWindow
Some(frame) => Some(
gpui::canvas(
|bounds, _window, _cx| bounds,
-- move |_, bounds, window, _cx| frame.paint(bounds, window),
++ move |_, bounds, window, _cx| frame.paint(bounds, px(0.), window),
)
.w(px(fitted_w))
.h(px(fitted_h))
@@@ -2759,7 -2701,7 +2759,7 @@@
let menu = state.menu.as_ref()?;
let items = crop_menu_items(state.aspect, self.crop_snap_to_ratio);
Some(
-- ui::Menu::plain(&self.theme, "crop-menu", items, menu)
++ ui::Menu::editor(&self.theme, "crop-menu", items, menu)
.on_select(cx.listener(|this, index: &usize, window, cx| {
this.choose_crop_menu(*index, window, cx);
}))
diff --cc apps/desktop-gpui/src/editor_edits.rs
index 87a5ddf43,5cf07c933..ca9f0c598
--- a/apps/desktop-gpui/src/editor_edits.rs
+++ b/apps/desktop-gpui/src/editor_edits.rs
@@@ -28,8 -28,8 +28,8 @@@
use cap_project::{
AudioTrackSegment, Camera3DProperties, Camera3DSegment, CaptionTrackSegment,
ClipSpeedAudioMode, CursorClickEvent, GlideDirection, KeyboardTrackSegment, MaskKind,
-- MaskSegment, ProjectConfiguration, SceneMode, SceneSegment, TextSegment, TimelineConfiguration,
-- TimelineSegment, XY, ZoomMode, ZoomSegment, mask_effect_contract,
++ MaskSegment, OverlayTrack, ProjectConfiguration, SceneMode, SceneSegment, TextSegment,
++ TimelineConfiguration, TimelineSegment, XY, ZoomMode, ZoomSegment, mask_effect_contract,
};
use crate::editor_timeline::{self, Segment, TrackKind};
@@@ -829,8 -812,8 +828,8 @@@ pub fn move_segment
})
}
--/// `delete*Segments(indices)` for the eight non-clip tracks. The three
--/// multi-lane ones renormalise their lanes afterwards; the others do not
++/// `delete*Segments(indices)` for the eight non-clip tracks. Style and audio
++/// renormalise their lanes afterwards; the others do not
/// (`ED/context.ts:781-799` vs `:623-639`).
pub fn delete_segments(
timeline: &mut TimelineConfiguration,
@@@ -838,34 -821,20 +837,16 @@@
indices: &[usize],
) -> bool {
match kind {
- TrackKind::Image => {
- let deleted = delete_indices(&mut timeline.image_segments, indices);
- normalize_track(&mut timeline.image_segments, |segment, lane| {
- TrackKind::Mask => {
- let deleted = delete_indices(&mut timeline.mask_segments, indices);
- normalize_track(&mut timeline.mask_segments, |segment, lane| {
-- segment.track = lane
-- });
-- deleted
-- }
- TrackKind::Text => {
- let deleted = delete_indices(&mut timeline.text_segments, indices);
- normalize_track(&mut timeline.text_segments, |segment, lane| {
++ TrackKind::Image => delete_indices(&mut timeline.image_segments, indices),
+ TrackKind::Style => {
+ let deleted = delete_indices(&mut timeline.style_segments, indices);
+ normalize_track(&mut timeline.style_segments, |segment, lane| {
segment.track = lane
});
deleted
}
- TrackKind::Mask => {
- let deleted = delete_indices(&mut timeline.mask_segments, indices);
- normalize_track(&mut timeline.mask_segments, |segment, lane| {
- segment.track = lane
- });
- deleted
- }
- TrackKind::Text => {
- let deleted = delete_indices(&mut timeline.text_segments, indices);
- normalize_track(&mut timeline.text_segments, |segment, lane| {
- segment.track = lane
- });
- deleted
- }
++ TrackKind::Mask => delete_indices(&mut timeline.mask_segments, indices),
++ TrackKind::Text => delete_indices(&mut timeline.text_segments, indices),
TrackKind::Audio => {
let deleted = delete_indices(&mut timeline.audio_segments, indices);
normalize_track(&mut timeline.audio_segments, |segment, lane| {
@@@ -938,6 -895,6 +919,107 @@@ pub fn delete_track_lane(timeline: &mu
}
}
++pub fn delete_track_lane_and_order(
++ project: &mut ProjectConfiguration,
++ available: &[OverlayTrack],
++ kind: TrackKind,
++ lane: u32,
++) -> bool {
++ let next_order = kind.overlay_track(lane).map(|deleted| {
++ project
++ .resolved_overlay_order(available)
++ .into_iter()
++ .filter(|track| *track != deleted)
++ .map(|mut track| {
++ if track.kind == deleted.kind && track.track > deleted.track {
++ track.track -= 1;
++ }
++ track
++ })
++ .collect::<Vec<_>>()
++ });
++ let timeline_changed = project
++ .timeline
++ .as_mut()
++ .is_some_and(|timeline| delete_track_lane(timeline, kind, lane));
++ let order_changed = next_order.is_some_and(|order| {
++ if project.overlay_order == order {
++ false
++ } else {
++ project.overlay_order = order;
++ true
++ }
++ });
++ timeline_changed || order_changed
++}
++
++pub fn reorder_overlay_track(
++ project: &mut ProjectConfiguration,
++ available: &[OverlayTrack],
++ from: OverlayTrack,
++ target_index: usize,
++) -> bool {
++ let mut order = project.resolved_overlay_order(available);
++ let Some(from_index) = order.iter().position(|track| *track == from) else {
++ return false;
++ };
++ let moved = order.remove(from_index);
++ let target_index = target_index.min(order.len());
++ order.insert(target_index, moved);
++ if order == project.resolved_overlay_order(available) {
++ return false;
++ }
++ project.overlay_order = order;
++ true
++}
++
++pub fn reorder_track_lane(
++ timeline: &mut TimelineConfiguration,
++ kind: TrackKind,
++ from: u32,
++ to: u32,
++) -> bool {
++ if from == to {
++ return false;
++ }
++
++ fn apply<T: TrackSegmentOps>(
++ segments: &mut [T],
++ from: u32,
++ to: u32,
++ set: impl Fn(&mut T, u32),
++ ) -> bool {
++ let mut changed = false;
++ for segment in segments {
++ let lane = segment.lane();
++ let next = if lane == from {
++ to
++ } else if from < to && lane > from && lane <= to {
++ lane - 1
++ } else if from > to && lane >= to && lane < from {
++ lane + 1
++ } else {
++ lane
++ };
++ if next != lane {
++ set(segment, next);
++ changed = true;
++ }
++ }
++ changed
++ }
++
++ match kind {
++ TrackKind::Style => apply(&mut timeline.style_segments, from, to, |segment, lane| {
++ segment.track = lane
++ }),
++ TrackKind::Audio => apply(&mut timeline.audio_segments, from, to, |segment, lane| {
++ segment.track = lane
++ }),
++ _ => false,
++ }
++}
++
/// `deleteClipSegment` (`ED/context.ts:581-600`), including the guard that
/// makes it the one track a selection cannot empty: **the last clip cannot be
/// deleted**. The Delete binding sorts descending and deletes one at a time
@@@ -967,6 -950,329 +1075,331 @@@ pub fn delete_clip_segments(timeline: &
deleted
}
+ pub(crate) fn effective_to_output_end(holds: &[(f64, f64)], effective: f64) -> f64 {
+ let mut output = effective;
+ for (start, finish) in holds {
+ if output > *start {
+ output += finish - start;
+ } else {
+ break;
+ }
+ }
+ output
+ }
+
+ pub(crate) fn effective_to_output(holds: &[(f64, f64)], effective: f64) -> f64 {
+ let mut output = effective;
+ for (start, finish) in holds {
+ if output >= *start {
+ output += finish - start;
+ } else {
+ break;
+ }
+ }
+ output
+ }
+
+ fn ripple_delete_track<T: TrackSegmentOps>(
+ segments: &mut Vec<T>,
+ cut_start: f64,
+ cut_end: f64,
+ shift: f64,
+ ) {
+ segments.retain_mut(|segment| {
+ let Some((start, end)) =
+ ripple_deleted_bounds(segment.start(), segment.end(), cut_start, cut_end, shift)
+ else {
+ return false;
+ };
+ segment.set_start(start);
+ segment.set_end(end);
+ true
+ });
+ }
+
+ fn ripple_deleted_bounds(
+ start: f64,
+ end: f64,
+ cut_start: f64,
+ cut_end: f64,
+ shift: f64,
+ ) -> Option<(f64, f64)> {
+ let (start, end) = if end <= cut_start {
+ (start, end)
+ } else if start >= cut_start && end <= cut_end {
+ return None;
+ } else if start >= cut_end {
+ (start - shift, end - shift)
+ } else if start < cut_start && end > cut_end {
+ (start, end - shift)
+ } else if start < cut_start {
+ (start, cut_start)
+ } else {
+ let start = cut_end - shift;
+ (start, (end - shift).max(start))
+ };
+ (end > start).then_some((start, end))
+ }
+
+ fn ripple_relative_keyframes<T>(
+ keyframes: &mut Vec<T>,
+ old_start: f64,
+ new_start: f64,
+ new_end: f64,
+ cut_start: f64,
+ cut_end: f64,
+ shift: f64,
+ time: impl for<'a> Fn(&'a mut T) -> &'a mut f64,
+ ) {
+ keyframes.retain_mut(|keyframe| {
+ let value = time(keyframe);
+ let absolute = old_start + *value;
+ if absolute >= cut_start && absolute < cut_end {
+ return false;
+ }
+ let mapped = if absolute >= cut_end {
+ absolute - shift
+ } else {
+ absolute
+ };
+ *value = (mapped - new_start).clamp(0.0, new_end - new_start);
+ true
+ });
+ }
+
+ fn ripple_delete_mask_track(
+ segments: &mut Vec<MaskSegment>,
+ cut_start: f64,
+ cut_end: f64,
+ shift: f64,
+ ) {
+ segments.retain_mut(|segment| {
+ let old_start = segment.start;
+ let Some((new_start, new_end)) =
+ ripple_deleted_bounds(old_start, segment.end, cut_start, cut_end, shift)
+ else {
+ return false;
+ };
+ ripple_relative_keyframes(
+ &mut segment.keyframes.position,
+ old_start,
+ new_start,
+ new_end,
+ cut_start,
+ cut_end,
+ shift,
+ |keyframe| &mut keyframe.time,
+ );
+ ripple_relative_keyframes(
+ &mut segment.keyframes.size,
+ old_start,
+ new_start,
+ new_end,
+ cut_start,
+ cut_end,
+ shift,
+ |keyframe| &mut keyframe.time,
+ );
+ ripple_relative_keyframes(
+ &mut segment.keyframes.intensity,
+ old_start,
+ new_start,
+ new_end,
+ cut_start,
+ cut_end,
+ shift,
+ |keyframe| &mut keyframe.time,
+ );
+ segment.start = new_start;
+ segment.end = new_end;
+ true
+ });
+ }
+
+ fn ripple_delete_camera3d_track(
+ segments: &mut Vec<Camera3DSegment>,
+ cut_start: f64,
+ cut_end: f64,
+ shift: f64,
+ ) {
+ segments.retain_mut(|segment| {
+ let old_start = segment.start;
+ let old_end = segment.end;
+ if old_end <= cut_start {
+ return true;
+ }
+ if old_start >= cut_end {
+ segment.start -= shift;
+ segment.end -= shift;
+ return true;
+ }
+ if old_start >= cut_start && old_end <= cut_end {
+ return false;
+ }
+ let Some((new_start, new_end)) =
+ ripple_deleted_bounds(old_start, old_end, cut_start, cut_end, shift)
+ else {
+ return false;
+ };
+ let retains_left = old_start < cut_start;
+ let retains_right = old_end > cut_end;
+ let ripple = Camera3DRipple {
+ old_start,
+ new_start,
+ cut_start,
+ cut_end,
+ shift,
+ retains_left,
+ retains_right,
+ };
+ for track in segment.tracks.all_tracks_mut() {
+ ripple_camera3d_keyframes(track, ripple);
+ }
+ if retains_left && !retains_right {
+ segment.transition_out = 0.0;
+ } else if !retains_left && retains_right {
+ segment.transition_in = 0.0;
+ }
+ segment.start = new_start;
+ segment.end = new_end;
+ true
+ });
+ }
+
+ #[derive(Clone, Copy)]
+ struct Camera3DRipple {
+ old_start: f64,
+ new_start: f64,
+ cut_start: f64,
+ cut_end: f64,
+ shift: f64,
+ retains_left: bool,
+ retains_right: bool,
+ }
+
+ fn ripple_camera3d_keyframes(
+ keyframes: &mut Vec<cap_project::Camera3DKeyframe>,
+ ripple: Camera3DRipple,
+ ) {
+ if keyframes.is_empty() {
+ return;
+ }
+ let mut old = std::mem::take(keyframes);
+ old.sort_by(|left, right| left.time.total_cmp(&right.time));
+ let cut_start_local = ripple.cut_start - ripple.old_start;
+ let cut_end_local = ripple.cut_end - ripple.old_start;
+ let boundary = |time: f64, left: bool| {
+ let previous = old.iter().rev().find(|keyframe| keyframe.time <= time);
+ let next = old.iter().find(|keyframe| keyframe.time >= time);
+ cap_project::Camera3DKeyframe {
+ time,
+ value: cap_rendering::camera3d::sample_track(0.0, &old, time),
+ out_easing: if left {
+ None
+ } else {
+ previous.and_then(|keyframe| keyframe.out_easing)
+ },
+ in_easing: if left {
+ next.and_then(|keyframe| keyframe.in_easing)
+ } else {
+ None
+ },
+ }
+ };
+
+ keyframes.extend(
+ old.iter()
+ .filter(|keyframe| ripple.old_start + keyframe.time < ripple.cut_start)
+ .cloned(),
+ );
+ if ripple.retains_left {
+ let mut keyframe = boundary(cut_start_local, true);
+ keyframe.time = ripple.cut_start - ripple.new_start;
+ keyframes.push(keyframe);
+ }
+ if ripple.retains_right {
+ let mut keyframe = boundary(cut_end_local, false);
+ keyframe.time = ripple.cut_end - ripple.shift - ripple.new_start;
+ keyframes.push(keyframe);
+ }
+ keyframes.extend(
+ old.into_iter()
+ .filter(|keyframe| ripple.old_start + keyframe.time > ripple.cut_end)
+ .map(|mut keyframe| {
+ keyframe.time = ripple.old_start + keyframe.time - ripple.shift - ripple.new_start;
+ keyframe
+ }),
+ );
+ keyframes.sort_by(|left, right| left.time.total_cmp(&right.time));
+ }
+
+ fn ripple_delete_audio_track(
+ segments: &mut Vec<AudioTrackSegment>,
+ cut_start: f64,
+ cut_end: f64,
+ shift: f64,
+ ) {
+ let mut next = Vec::with_capacity(segments.len());
+ for mut segment in std::mem::take(segments) {
+ if segment.end <= cut_start {
+ next.push(segment);
+ } else if segment.start >= cut_start && segment.end <= cut_end {
+ continue;
+ } else if segment.start >= cut_end {
+ segment.start -= shift;
+ segment.end -= shift;
+ next.push(segment);
+ } else if segment.start < cut_start && segment.end > cut_end {
+ let mut tail = segment.clone();
+ let old_start = tail.start;
+ segment.end = cut_start;
+ segment.fade_out = 0.0;
+ tail.start = cut_end - shift;
+ tail.end -= shift;
+ tail.trim_start += cut_end - old_start;
+ tail.fade_in = 0.0;
+ next.push(segment);
+ if tail.end > tail.start {
+ next.push(tail);
+ }
+ } else if segment.start < cut_start {
+ segment.end = cut_start;
+ segment.fade_out = 0.0;
+ next.push(segment);
+ } else {
+ let old_start = segment.start;
+ segment.start = cut_end - shift;
+ segment.end = (segment.end - shift).max(segment.start);
+ segment.trim_start += cut_end - old_start;
+ segment.fade_in = 0.0;
+ if segment.end > segment.start {
+ next.push(segment);
+ }
+ }
+ }
+ *segments = next;
+ }
+
+ fn ripple_delete_output_tracks(
+ timeline: &mut TimelineConfiguration,
+ cut_start: f64,
+ cut_end: f64,
+ shift: f64,
+ ) {
++ ripple_delete_track(&mut timeline.style_segments, cut_start, cut_end, shift);
++ ripple_delete_track(&mut timeline.image_segments, cut_start, cut_end, shift);
+ ripple_delete_track(&mut timeline.zoom_segments, cut_start, cut_end, shift);
+ ripple_delete_track(&mut timeline.scene_segments, cut_start, cut_end, shift);
+ ripple_delete_camera3d_track(&mut timeline.camera3d_segments, cut_start, cut_end, shift);
+ ripple_delete_mask_track(&mut timeline.mask_segments, cut_start, cut_end, shift);
+ ripple_delete_track(&mut timeline.text_segments, cut_start, cut_end, shift);
+ ripple_delete_track(&mut timeline.caption_segments, cut_start, cut_end, shift);
+ timeline
+ .keyboard_segments
+ .retain_mut(|segment| segment.ripple_delete(cut_start, cut_end, shift));
+ ripple_delete_audio_track(&mut timeline.audio_segments, cut_start, cut_end, shift);
+ }
+
/// The seven plain splits. 3D is **not** among them: `splitCamera3DSegment`
/// rebuilds both halves' pose tracks around the pose the segment held at the
/// cut (`ED/context.ts:640-676`), which needs the keyframe evaluator; see the
@@@ -2753,7 -3338,7 +3487,7 @@@ mod tests
}
}));
let timeline = config.timeline.as_mut().unwrap();
-- assert!(delete_segments(timeline, TrackKind::Mask, &[0]));
++ assert!(delete_track_lane(timeline, TrackKind::Mask, 0));
assert_eq!(timeline.mask_segments.len(), 1);
assert_eq!(
timeline.mask_segments[0].track, 0,
@@@ -2875,204 -3475,3 +3624,309 @@@
));
}
}
+
+pub fn insert_style_segment(
+ timeline: &mut TimelineConfiguration,
+ segment: cap_project::StyleSegment,
+) -> usize {
+ let start = segment.start;
+ let track = segment.track;
+ timeline.style_segments.push(segment);
+ sort_lane_segments(&mut timeline.style_segments);
+ timeline
+ .style_segments
+ .iter()
+ .rposition(|item| item.start == start && item.track == track)
+ .unwrap_or(0)
+}
+
+pub fn insert_image_segment(
+ timeline: &mut TimelineConfiguration,
+ segment: cap_project::ImageSegment,
+) -> usize {
+ let start = segment.start;
+ let track = segment.track;
+ timeline.image_segments.push(segment);
+ sort_lane_segments(&mut timeline.image_segments);
+ timeline
+ .image_segments
+ .iter()
+ .rposition(|item| item.start == start && item.track == track)
+ .unwrap_or(0)
+}
+
+#[cfg(test)]
+mod style_image_tests {
+ use super::*;
+
+ fn project() -> ProjectConfiguration {
+ serde_json::from_value(serde_json::json!({"timeline": {"zoomSegments":[],
+ "segments": [{"start":0,"end":20,"timescale":1}],
+ "styleSegments": [{"start":2,"end":8,"track":0,"name":"First"}, {"start":1,"end":6,"track":1,"name":"Second"}],
+ "imageSegments": [{"start":2,"end":8,"track":0,"path":"content/images/retained.png","rotation":35,"flipX":true}]
+ }})).unwrap()
+ }
+
+ #[test]
+ fn style_image_edit_split_delete_and_history_preserve_assets_and_overrides() {
+ let mut project = project();
+ let mut history = ProjectHistory::new(project.clone());
+ history.pause();
+ for kind in [TrackKind::Style, TrackKind::Image] {
+ let timeline = project.timeline.as_mut().unwrap();
+ assert!(move_segment(timeline, kind, 0, 3., 9.));
+ assert!(set_segment_start(timeline, kind, 0, 4.));
+ assert!(set_segment_end(timeline, kind, 0, 10.));
+ history.record(&project);
+ }
+ history.resume(&project);
+ assert_eq!(history.depth(), 2);
+ assert_eq!(
+ history
+ .undo()
+ .unwrap()
+ .timeline
+ .as_ref()
+ .unwrap()
+ .image_segments[0]
+ .start,
+ 2.
+ );
+ project = history.redo().unwrap().clone();
+ let timeline = project.timeline.as_mut().unwrap();
+ for kind in [TrackKind::Style, TrackKind::Image] {
+ assert!(split_segment(timeline, kind, 0, 3.));
+ assert!(!split_segment(timeline, kind, 0, 0.1));
+ }
+ assert_eq!(timeline.style_segments[1].end, 10.);
+ assert_eq!(timeline.style_segments[2].name, "Second");
+ assert!(timeline.style_segments[0].overrides.background.is_none());
+ assert_eq!(
+ timeline.image_segments[1].path,
+ "content/images/retained.png"
+ );
+ assert_eq!(timeline.image_segments[1].rotation, 35.);
+ assert!(timeline.image_segments[1].flip_x);
+ history.record(&project);
+ assert!(delete_segments(
+ project.timeline.as_mut().unwrap(),
+ TrackKind::Image,
+ &[0, 1]
+ ));
+ history.record(&project);
+ let restored = history.undo().unwrap().timeline.as_ref().unwrap();
+ assert_eq!(restored.image_segments.len(), 2);
+ assert_eq!(
+ restored.image_segments[0].path,
+ "content/images/retained.png"
+ );
+ }
+
+ #[test]
+ fn style_image_trim_keeps_unsorted_loaded_indices_and_delete_normalizes_lanes() {
+ let mut project = project();
+ let timeline = project.timeline.as_mut().unwrap();
+ timeline.style_segments.swap(0, 1);
+ assert!(set_segment_start(timeline, TrackKind::Style, 0, 1.5));
+ assert_eq!(timeline.style_segments[0].name, "Second");
+ assert!(delete_track_lane(timeline, TrackKind::Style, 0));
+ assert_eq!(timeline.style_segments[0].track, 0);
+ assert_eq!(timeline.style_segments[0].name, "Second");
+ }
+
++ #[test]
++ fn lane_reorder_moves_segments_without_changing_config_indices() {
++ let mut project = project();
++ let timeline = project.timeline.as_mut().unwrap();
++ timeline.style_segments.push(cap_project::StyleSegment {
++ start: 0.,
++ end: 10.,
++ track: 2,
++ ..Default::default()
++ });
++ let names = timeline
++ .style_segments
++ .iter()
++ .map(|segment| segment.name.clone())
++ .collect::<Vec<_>>();
++
++ assert!(reorder_track_lane(timeline, TrackKind::Style, 2, 0));
++ assert_eq!(
++ timeline
++ .style_segments
++ .iter()
++ .map(|segment| segment.track)
++ .collect::<Vec<_>>(),
++ vec![1, 2, 0]
++ );
++ assert_eq!(
++ timeline
++ .style_segments
++ .iter()
++ .map(|segment| segment.name.clone())
++ .collect::<Vec<_>>(),
++ names
++ );
++ }
++
++ #[test]
++ fn lane_reorder_from_empty_lane_still_reports_sibling_shift() {
++ let mut project = project();
++ let timeline = project.timeline.as_mut().unwrap();
++
++ assert!(reorder_track_lane(timeline, TrackKind::Style, 2, 0));
++ assert_eq!(
++ timeline
++ .style_segments
++ .iter()
++ .map(|segment| segment.track)
++ .collect::<Vec<_>>(),
++ vec![1, 2]
++ );
++ }
++
++ #[test]
++ fn visual_segment_delete_preserves_lane_identity() {
++ let mut project = project();
++ let timeline = project.timeline.as_mut().unwrap();
++ let mut second = timeline.image_segments[0].clone();
++ second.track = 2;
++ timeline.image_segments.push(second);
++ assert!(delete_segments(timeline, TrackKind::Image, &[0]));
++ assert_eq!(timeline.image_segments[0].track, 2);
++ }
++
++ #[test]
++ fn overlay_reorder_and_lane_delete_update_only_saved_order() {
++ let mut project = project();
++ let text = cap_project::OverlayTrack {
++ kind: cap_project::OverlayTrackKind::Text,
++ track: 0,
++ };
++ let image = cap_project::OverlayTrack {
++ kind: cap_project::OverlayTrackKind::Image,
++ track: 2,
++ };
++ let mask = cap_project::OverlayTrack {
++ kind: cap_project::OverlayTrackKind::Mask,
++ track: 0,
++ };
++ let available = [text, image, mask];
++ project.timeline.as_mut().unwrap().image_segments[0].track = 2;
++
++ assert!(reorder_overlay_track(&mut project, &available, image, 0));
++ assert_eq!(project.overlay_order, [image, text, mask]);
++ assert!(delete_track_lane_and_order(
++ &mut project,
++ &available,
++ TrackKind::Image,
++ 1,
++ ));
++ assert_eq!(
++ project.timeline.as_ref().unwrap().image_segments[0].track,
++ 1
++ );
++ assert_eq!(
++ project.overlay_order,
++ [
++ cap_project::OverlayTrack {
++ kind: cap_project::OverlayTrackKind::Image,
++ track: 1,
++ },
++ text,
++ mask
++ ]
++ );
++ }
++
+ #[test]
+ fn style_image_speed_ripple_and_serialization_keep_both_tracks() {
+ let mut project = project();
+ let timeline = project.timeline.as_mut().unwrap();
+ assert!(set_clip_segment_timescale(timeline, 0, 2.));
+ assert_eq!(
+ (
+ timeline.style_segments[0].start,
+ timeline.style_segments[0].end
+ ),
+ (1., 4.)
+ );
+ assert_eq!(
+ (
+ timeline.image_segments[0].start,
+ timeline.image_segments[0].end
+ ),
+ (1., 4.)
+ );
+ let json = serde_json::to_value(&project).unwrap();
+ assert!(json["timeline"]["styleSegments"][0]["overrides"]["cameraOnlyPadding"].is_null());
+ assert_eq!(json["timeline"]["imageSegments"][0]["lockAspect"], true);
+ let restored: ProjectConfiguration = serde_json::from_value(json).unwrap();
+ assert_eq!(
+ restored.timeline.unwrap().image_segments[0].path,
+ "content/images/retained.png"
+ );
+ }
+}
+
+pub(crate) fn replace_image_asset(
+ project: &mut ProjectConfiguration,
+ index: usize,
+ fingerprint: &str,
+ path: String,
+ name: String,
+) -> bool {
+ let Some(segment) = project
+ .timeline
+ .as_mut()
+ .and_then(|timeline| timeline.image_segments.get_mut(index))
+ else {
+ return false;
+ };
+ if serde_json::to_string(segment).ok().as_deref() != Some(fingerprint) {
+ return false;
+ }
+ segment.path = path;
+ segment.name = name;
+ true
+}
+
+#[cfg(test)]
+mod style_image_replacement_tests {
+ use super::*;
+ #[test]
+ fn style_image_replace_preserves_geometry_and_history_rejects_stale_target() {
+ let mut project: ProjectConfiguration = serde_json::from_value(serde_json::json!({"timeline":{"zoomSegments":[],"segments":[],"imageSegments":[{"start":2,"end":8,"track":3,"path":"content/images/old.png","name":"Old","center":{"x":0.3,"y":0.7},"size":{"x":0.2,"y":0.4},"rotation":35,"flipX":true,"opacity":0.6}]}})).unwrap();
+ let before = serde_json::to_value(&project).unwrap();
+ let mut history = ProjectHistory::new(project.clone());
+ let fingerprint =
+ serde_json::to_string(&project.timeline.as_ref().unwrap().image_segments[0]).unwrap();
+ assert!(replace_image_asset(
+ &mut project,
+ 0,
+ &fingerprint,
+ "content/images/new.gif".into(),
+ "New".into()
+ ));
+ history.record(&project);
+ let mut expected = before.clone();
+ expected["timeline"]["imageSegments"][0]["path"] = "content/images/new.gif".into();
+ expected["timeline"]["imageSegments"][0]["name"] = "New".into();
+ assert_eq!(serde_json::to_value(&project).unwrap(), expected);
+ assert!(!replace_image_asset(
+ &mut project,
+ 0,
+ &fingerprint,
+ "stale.png".into(),
+ "Stale".into()
+ ));
+ assert_eq!(
+ serde_json::to_value(history.undo().unwrap()).unwrap(),
+ before
+ );
+ assert_eq!(
+ serde_json::to_value(history.redo().unwrap()).unwrap(),
+ expected
+ );
+ }
+}
diff --cc apps/desktop-gpui/src/editor_export.rs
index ab14d6128,908904dd8..29c0c5a4a
--- a/apps/desktop-gpui/src/editor_export.rs
+++ b/apps/desktop-gpui/src/editor_export.rs
@@@ -591,15 -590,12 +591,24 @@@ impl EditorWindow
"mp4"
};
let default = format!("{pretty_name}.{ext}");
- let chosen = match std::env::var_os("CAP_GPUI_AUTO_EXPORT") {
- Some(path) => Some(PathBuf::from(path)),
- None => platform::save_file_panel_async(&default, &[ext], cx).await,
- let chosen = std::env::var_os("CAP_GPUI_AUTO_EXPORT")
- .map(PathBuf::from)
- .or_else(|| platform::save_file_panel(&default, &[ext]));
- if chosen.is_none() {
++ let chosen: Result<Option<PathBuf>, String> = match std::env::var_os("CAP_GPUI_AUTO_EXPORT") {
++ Some(path) => Ok(Some(PathBuf::from(path))),
++ None => {
++ #[cfg(target_os = "macos")]
++ {
++ platform::try_save_file_panel(&default, &[ext])
++ }
++ #[cfg(not(target_os = "macos"))]
++ {
++ Ok(platform::save_file_panel_async(&default, &[ext], cx).await)
++ }
++ }
+ };
- if chosen.is_none() {
++ if matches!(chosen, Ok(None)) {
let _ = this.update(cx, |this, cx| {
- if let Some(ui) = this.export.as_mut() {
+ if let Some(ui) = this.export.as_mut()
+ && Arc::ptr_eq(&ui.cancel, &cancel)
+ {
ui.phase = ExportPhase::Idle;
}
cx.notify();
@@@ -609,7 -605,7 +618,13 @@@
});
return;
}
-- chosen
++ match chosen {
++ Ok(path) => path,
++ Err(error) => {
++ tracing::warn!(error, "Save dialog unavailable; keeping the export in its project output folder");
++ None
++ }
++ }
} else {
None
};
@@@ -827,7 -820,7 +842,7 @@@
let upgraded = store::auth_snapshot().is_upgraded();
if !upgraded && duration >= 300.0 {
-- cx.open_url(&format!("{}/pricing", crate::auth::server_url()));
++ cx.open_url(crate::auth::PRICING_URL);
return;
}
@@@ -990,7 -983,7 +1005,7 @@@
cx.notify();
});
let _ = this.update(cx, |_, cx| {
-- cx.open_url(&format!("{}/pricing", crate::auth::server_url()));
++ cx.open_url(crate::auth::PRICING_URL);
});
platform::alert_dialog(
"Upgrade required",
diff --cc apps/desktop-gpui/src/editor_panels.rs
index 73874c555,abafeb5b1..71a3951cb
--- a/apps/desktop-gpui/src/editor_panels.rs
+++ b/apps/desktop-gpui/src/editor_panels.rs
@@@ -3242,9 -3103,9 +3242,11 @@@ impl EditorWindow
.min_h_0()
.overflow_y_scroll()
.track_scroll(&self.sidebar.scroll)
-- .p(px(16.))
-- .gap(px(16.))
-- .text_size(px(14.))
++ .pt(px(14.))
++ .px(px(16.))
++ .pb(px(16.))
++ .gap(px(14.))
++ .text_size(px(13.))
.child(body)
.into_any_element()
}
@@@ -3274,7 -3135,7 +3276,7 @@@
.p(px(16.))
.rounded(px(8.))
.border_1()
-- .border_color(Hsla::from(self.theme.gray_200_legacy))
++ .border_color(Hsla::from(self.theme.editor.line))
.child(content)
.into_any_element()
}
@@@ -3319,32 -3180,32 +3321,29 @@@
div()
.flex()
.flex_col()
-- .gap(px(24.))
-- .child(
-- ui::Field::plain(&theme, SharedString::from(format!("Zoom {}", index + 1)))
-- .icon("icons/search.svg")
-- .child(self.slider(SliderKey::Panel(PanelSlider::ZoomAmount, index), "x", cx)),
-- )
++ .gap(px(14.))
++ .child(self.slider_field(
++ SharedString::from(format!("Zoom {}", index + 1)),
++ SliderKey::Panel(PanelSlider::ZoomAmount, index),
++ "x",
++ cx,
++ ))
.child(
-- ui::Field::plain(&theme, "Zoom Mode")
-- .icon("icons/settings.svg")
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(24.))
-- .child(self.zoom_mode_tabs(
-- manual,
-- cx,
-- move |this, want_manual, window, cx| {
-- this.set_zoom_mode(index, want_manual, window, cx);
-- },
-- ))
-- .child(self.zoom_mode_helper(manual, cx))
-- .children(
-- manual.then(|| self.render_pad(PadKey::ZoomManual(index), cx)),
-- ),
-- ),
++ ui::Field::section(&theme, "Zoom Mode").child(
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(14.))
++ .child(self.zoom_mode_tabs(
++ manual,
++ cx,
++ move |this, want_manual, window, cx| {
++ this.set_zoom_mode(index, want_manual, window, cx);
++ },
++ ))
++ .child(self.zoom_mode_helper(manual, cx))
++ .children(manual.then(|| self.render_pad(PadKey::ZoomManual(index), cx))),
++ ),
)
.into_any_element()
}
@@@ -3412,61 -3273,61 +3411,56 @@@
div()
.flex()
.flex_col()
-- .gap(px(24.))
++ .gap(px(14.))
.p(px(16.))
.rounded(px(8.))
.border_1()
-- .border_color(Hsla::from(theme.gray_200_legacy))
++ .border_color(Hsla::from(theme.editor.line))
.child({
-- let mut field = ui::Field::plain(&theme, "Zoom Amount")
-- .icon("icons/search.svg")
-- .child(self.slider(
-- SliderKey::Panel(PanelSlider::ZoomAmountAll, 0),
-- "x",
-- cx,
-- ));
++ let mut field = self.slider_field(
++ "Zoom Amount",
++ SliderKey::Panel(PanelSlider::ZoomAmountAll, 0),
++ "x",
++ cx,
++ );
if mixed_amount {
field = field.value(mixed_badge("Mixed"));
}
field
})
.child({
-- let mut field = ui::Field::plain(&theme, "Zoom Mode")
-- .icon("icons/settings.svg")
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(16.))
-- .child(self.zoom_mode_tabs(
-- manual && !mixed_mode,
-- cx,
-- |this, want_manual, window, cx| {
-- this.set_all_zoom_modes(want_manual, window, cx);
-- },
-- ))
-- .children(
-- (!mixed_mode).then(|| self.zoom_mode_helper(manual, cx)),
-- )
-- .children((manual && !mixed_mode).then(|| {
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(6.))
-- .child(self.render_pad(PadKey::ZoomMulti, cx))
-- .children(positions_mixed.then(|| {
-- div()
-- .text_size(px(12.))
-- .text_color(Hsla::from(theme.gray_10))
-- .child(
-- "Segments zoom into different spots. Drag \
++ let mut field = ui::Field::section(&theme, "Zoom Mode").child(
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(16.))
++ .child(self.zoom_mode_tabs(
++ manual && !mixed_mode,
++ cx,
++ |this, want_manual, window, cx| {
++ this.set_all_zoom_modes(want_manual, window, cx);
++ },
++ ))
++ .children((!mixed_mode).then(|| self.zoom_mode_helper(manual, cx)))
++ .children((manual && !mixed_mode).then(|| {
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(6.))
++ .child(self.render_pad(PadKey::ZoomMulti, cx))
++ .children(positions_mixed.then(|| {
++ div()
++ .text_size(px(12.))
++ .text_color(Hsla::from(theme.gray_10))
++ .child(
++ "Segments zoom into different spots. Drag \
to move them all to the same one.",
-- )
-- .into_any_element()
-- }))
-- .into_any_element()
-- })),
-- );
++ )
++ .into_any_element()
++ }))
++ .into_any_element()
++ })),
++ );
if mixed_mode {
field = field.value(mixed_badge("Mixed"));
}
@@@ -3838,7 -3699,7 +3832,7 @@@ impl EditorWindow
.height(px(36.))
.text_size(px(14.))
.bg(Hsla::from(theme.gray_2))
-- .border(Hsla::from(theme.gray_3)),
++ .border(Hsla::from(theme.editor.line)),
),
);
}
@@@ -3858,7 -3719,7 +3852,7 @@@
.padding_x(px(12.))
.text_size(px(14.))
.bg(Hsla::from(theme.gray_2))
-- .border(Hsla::from(theme.gray_3));
++ .border(Hsla::from(theme.editor.line));
// A `<textarea>` measures its own height; a single-line box is `h-9`.
field = match height {
// `min-h-[80px]` / `min-h-[96px]` on the two textareas.
@@@ -4059,8 -3920,8 +4053,7 @@@ impl EditorWindow
.flex_col()
.gap(px(16.))
.child(
-- ui::Field::plain(&theme, SharedString::from(format!("Text {}", index + 1)))
-- .icon("icons/type.svg")
++ ui::Field::section(&theme, SharedString::from(format!("Text {}", index + 1)))
.child(
div()
.flex()
@@@ -4106,361 -3967,361 +4099,337 @@@
),
)
.child(
-- ui::Field::plain(&theme, "Layout")
-- .icon("icons/box-select.svg")
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(12.))
-- .child(
-- self.icon_toggle_row(
-- SharedString::from(format!("text-layout-{index}")),
-- TEXT_LAYOUTS
-- .iter()
-- .map(|(value, label, icon)| {
-- (*icon, Some(*label), *value == layout)
-- })
-- .collect(),
-- cx.listener(move |this, choice: &usize, window, cx| {
-- let Some((value, ..)) = TEXT_LAYOUTS.get(*choice) else {
-- return;
-- };
-- let value = *value;
-- this.edit_text_segment(
-- "text-layout",
-- index,
-- window,
-- cx,
-- move |segment| {
-- if segment.layout == value {
-- return false;
-- }
-- segment.layout = value;
-- // A takeover layout implies where
-- // the text belongs (`:3672-3677`).
-- if value == TextLayout::Fullscreen {
-- segment.center = XY::new(0.5, 0.5);
-- }
-- true
-- },
-- );
-- }),
-- ),
-- )
-- .children((layout == TextLayout::Fullscreen).then(|| {
-- div()
-- .text_size(px(12.))
-- .text_color(Hsla::from(theme.gray_10))
-- .child(
-- "Pauses the video while the text is shown, then resumes \
-- where it left off.",
-- )
-- .into_any_element()
-- }))
-- .children((layout != TextLayout::Overlay).then(|| {
-- self.labelled_small(
-- "Screen transition",
-- self.slider(
-- SliderKey::Panel(PanelSlider::TextLayoutTransition, index),
-- "s",
++ ui::Field::section(&theme, "Layout").child(
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(12.))
++ .child(
++ self.icon_toggle_row(
++ SharedString::from(format!("text-layout-{index}")),
++ TEXT_LAYOUTS
++ .iter()
++ .map(|(value, label, icon)| {
++ (*icon, Some(*label), *value == layout)
++ })
++ .collect(),
++ cx.listener(move |this, choice: &usize, window, cx| {
++ let Some((value, ..)) = TEXT_LAYOUTS.get(*choice) else {
++ return;
++ };
++ let value = *value;
++ this.edit_text_segment(
++ "text-layout",
++ index,
++ window,
cx,
-- )
-- .into_any_element(),
++ move |segment| {
++ if segment.layout == value {
++ return false;
++ }
++ segment.layout = value;
++ // A takeover layout implies where
++ // the text belongs (`:3672-3677`).
++ if value == TextLayout::Fullscreen {
++ segment.center = XY::new(0.5, 0.5);
++ }
++ true
++ },
++ );
++ }),
++ ),
++ )
++ .children((layout == TextLayout::Fullscreen).then(|| {
++ div()
++ .text_size(px(12.))
++ .text_color(Hsla::from(theme.gray_10))
++ .child(
++ "Pauses the video while the text is shown, then resumes \
++ where it left off.",
)
-- })),
-- ),
++ .into_any_element()
++ }))
++ .children((layout != TextLayout::Overlay).then(|| {
++ self.labelled_small(
++ "Screen transition",
++ self.slider(
++ SliderKey::Panel(PanelSlider::TextLayoutTransition, index),
++ "s",
++ cx,
++ )
++ .into_any_element(),
++ )
++ })),
++ ),
)
// `Templates` (`:3746-3762`): eight `TextPresetCard`s in a
// `grid-cols-2`, each drawing its sample in the preset's own family,
// weight and tracking.
.child(
-- ui::Field::plain(&theme, "Templates")
-- .icon("icons/sparkles.svg")
-- .child(self.render_text_presets(index, cx)),
++ ui::Field::stacked(&theme, "Templates").child(self.render_text_presets(index, cx)),
)
.child(
-- ui::Field::plain(&theme, "Font")
-- .icon("icons/type.svg")
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(8.))
-- // `<FontPicker />` (`:3764-3771`).
-- .child(self.menu_select_owned(
-- SidebarMenu::TextFontFamily(index),
-- SharedString::from(format!("text-font-{index}")),
-- SharedString::from(font_family_label(&family)),
-- cx,
-- ))
-- .child(
-- div()
-- .flex()
-- .items_center()
-- .gap(px(8.))
-- .child(div().flex_1().min_w_0().child(self.menu_select(
-- SidebarMenu::TextWeight(index),
-- "text-weight",
-- weight_label,
-- cx,
-- )))
-- .child(
-- div()
-- .id(SharedString::from(format!("text-italic-{index}")))
-- .flex()
-- .justify_center()
-- .items_center()
-- .size(px(36.))
-- .flex_none()
-- .rounded(px(6.))
-- .border_1()
-- .border_color(if italic {
-- Hsla::from(theme.blue_9)
-- } else {
-- Hsla::from(theme.gray_3)
-- })
-- .when(italic, |this| {
-- this.bg(crate::editor_sidebar::with_alpha(
-- theme.blue_9,
-- 0.1,
-- ))
-- })
-- .when(!italic, |this| this.bg(Hsla::from(theme.gray_2)))
-- .child(
-- svg()
-- .path("icons/italic.svg")
-- .size(px(16.))
-- .text_color(if italic {
-- Hsla::from(theme.blue_9)
-- } else {
-- Hsla::from(theme.gray_11)
-- }),
-- )
-- .on_click(cx.listener(move |this, _, window, cx| {
-- this.edit_text_segment(
-- "text-italic",
-- index,
-- window,
-- cx,
-- move |segment| {
-- segment.italic = !italic;
-- true
-- },
-- );
-- })),
-- ),
-- )
-- .child(
-- self.labelled_small(
-- "Size",
-- self.slider(
-- SliderKey::Panel(PanelSlider::TextFontSize, index),
-- "",
-- cx,
-- )
-- .into_any_element(),
++ ui::Field::stacked(&theme, "Font").child(
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(8.))
++ // `<FontPicker />` (`:3764-3771`).
++ .child(self.menu_select_owned(
++ SidebarMenu::TextFontFamily(index),
++ SharedString::from(format!("text-font-{index}")),
++ SharedString::from(font_family_label(&family)),
++ cx,
++ ))
++ .child(
++ div()
++ .flex()
++ .items_center()
++ .gap(px(8.))
++ .child(div().flex_1().min_w_0().child(self.menu_select(
++ SidebarMenu::TextWeight(index),
++ "text-weight",
++ weight_label,
++ cx,
++ )))
++ .child(
++ div()
++ .id(SharedString::from(format!("text-italic-{index}")))
++ .flex()
++ .justify_center()
++ .items_center()
++ .size(px(36.))
++ .flex_none()
++ .rounded(px(6.))
++ .border_1()
++ .border_color(if italic {
++ Hsla::from(theme.blue_9)
++ } else {
++ Hsla::from(theme.gray_3)
++ })
++ .when(italic, |this| {
++ this.bg(crate::editor_sidebar::with_alpha(
++ theme.blue_9,
++ 0.1,
++ ))
++ })
++ .when(!italic, |this| this.bg(Hsla::from(theme.gray_2)))
++ .child(
++ svg()
++ .path("icons/italic.svg")
++ .size(px(16.))
++ .text_color(if italic {
++ Hsla::from(theme.blue_9)
++ } else {
++ Hsla::from(theme.gray_11)
++ }),
++ )
++ .on_click(cx.listener(move |this, _, window, cx| {
++ this.edit_text_segment(
++ "text-italic",
++ index,
++ window,
++ cx,
++ move |segment| {
++ segment.italic = !italic;
++ true
++ },
++ );
++ })),
),
++ )
++ .child(
++ self.labelled_small(
++ "Size",
++ self.slider(
++ SliderKey::Panel(PanelSlider::TextFontSize, index),
++ "",
++ cx,
++ )
++ .into_any_element(),
),
-- ),
++ ),
++ ),
)
.child(
-- ui::Field::plain(&theme, "Layout")
-- .icon("icons/align-center.svg")
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(12.))
-- .child(
-- self.icon_toggle_row(
-- SharedString::from(format!("text-align-{index}")),
-- TEXT_ALIGNS
-- .iter()
-- .map(|(value, icon)| (*icon, None, *value == align))
-- .collect(),
-- cx.listener(move |this, choice: &usize, window, cx| {
-- let Some((value, _)) = TEXT_ALIGNS.get(*choice) else {
-- return;
-- };
-- let value = *value;
-- this.edit_text_segment(
-- "text-align",
-- index,
-- window,
-- cx,
-- move |segment| {
-- segment.align = value;
-- true
-- },
-- );
-- }),
-- ),
-- )
-- .child(
-- self.labelled_small(
-- "Line height",
-- self.slider(
-- SliderKey::Panel(PanelSlider::TextLineHeight, index),
-- "",
-- cx,
-- )
-- .into_any_element(),
-- ),
-- )
-- .child(
-- self.labelled_small(
-- "Letter spacing",
-- self.slider(
-- SliderKey::Panel(PanelSlider::TextLetterSpacing, index),
-- "px",
++ ui::Field::section(&theme, "Layout").child(
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(12.))
++ .child(
++ self.icon_toggle_row(
++ SharedString::from(format!("text-align-{index}")),
++ TEXT_ALIGNS
++ .iter()
++ .map(|(value, icon)| (*icon, None, *value == align))
++ .collect(),
++ cx.listener(move |this, choice: &usize, window, cx| {
++ let Some((value, _)) = TEXT_ALIGNS.get(*choice) else {
++ return;
++ };
++ let value = *value;
++ this.edit_text_segment(
++ "text-align",
++ index,
++ window,
cx,
-- )
-- .into_any_element(),
-- ),
++ move |segment| {
++ segment.align = value;
++ true
++ },
++ );
++ }),
),
-- ),
++ )
++ .child(
++ self.labelled_small(
++ "Line height",
++ self.slider(
++ SliderKey::Panel(PanelSlider::TextLineHeight, index),
++ "",
++ cx,
++ )
++ .into_any_element(),
++ ),
++ )
++ .child(
++ self.labelled_small(
++ "Letter spacing",
++ self.slider(
++ SliderKey::Panel(PanelSlider::TextLetterSpacing, index),
++ "px",
++ cx,
++ )
++ .into_any_element(),
++ ),
++ ),
++ ),
)
.child(
-- ui::Field::plain(&theme, "Color")
-- .icon("icons/palette.svg")
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(12.))
-- .child(self.render_color_input(
-- ColorTarget::TextColor(index),
-- &color,
++ ui::Field::section(&theme, "Color").child(
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(12.))
++ .child(self.render_color_input(ColorTarget::TextColor(index), &color, cx))
++ .child(
++ self.labelled_small(
++ "Background",
++ ui::Toggle::plain(
++ &theme,
++ SharedString::from(format!("text-background-enabled-{index}")),
++ background_enabled,
++ )
++ .on_click(cx.listener(move |this, _, window, cx| {
++ this.edit_text_segment(
++ "text-background",
++ index,
++ window,
++ cx,
++ move |segment| {
++ segment.background_color = if background_enabled {
++ None
++ } else {
++ Some("#000000".to_string())
++ };
++ true
++ },
++ );
++ }))
++ .into_any_element(),
++ ),
++ )
++ .when_some(background_color, |this, background_color| {
++ this.child(self.render_color_input(
++ ColorTarget::TextBackground(index),
++ &background_color,
cx,
))
-- .child(
-- self.labelled_small(
-- "Background",
-- ui::Toggle::plain(
-- &theme,
-- SharedString::from(format!(
-- "text-background-enabled-{index}"
-- )),
-- background_enabled,
-- )
-- .on_click(cx.listener(move |this, _, window, cx| {
-- this.edit_text_segment(
-- "text-background",
-- index,
-- window,
-- cx,
-- move |segment| {
-- segment.background_color = if background_enabled {
-- None
-- } else {
-- Some("#000000".to_string())
-- };
-- true
-- },
-- );
-- }))
-- .into_any_element(),
-- ),
-- )
-- .when_some(background_color, |this, background_color| {
-- this.child(self.render_color_input(
-- ColorTarget::TextBackground(index),
-- &background_color,
++ })
++ .child(
++ self.labelled_small(
++ "Opacity",
++ self.slider(
++ SliderKey::Panel(PanelSlider::TextOpacity, index),
++ "",
++ cx,
++ )
++ .into_any_element(),
++ ),
++ )
++ .child(
++ self.labelled_small(
++ "Shadow",
++ self.slider(
++ SliderKey::Panel(PanelSlider::TextShadow, index),
++ "",
++ cx,
++ )
++ .into_any_element(),
++ ),
++ ),
++ ),
++ )
++ .child(
++ ui::Field::section(&theme, "Animation").child(
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(12.))
++ .child(
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(8.))
++ .child(
++ div()
++ .text_size(px(12.))
++ .text_color(Hsla::from(theme.gray_11))
++ .child("In"),
++ )
++ .child(self.menu_select(
++ SidebarMenu::TextAnimationIn(index),
++ "text-anim-in",
++ in_label,
cx,
))
-- })
-- .child(
-- self.labelled_small(
-- "Opacity",
++ .children((animation_in != TextAnimation::None).then(|| {
self.slider(
-- SliderKey::Panel(PanelSlider::TextOpacity, index),
-- "",
++ SliderKey::Panel(PanelSlider::TextAnimInDuration, index),
++ "s",
cx,
)
-- .into_any_element(),
-- ),
-- )
-- .child(
-- self.labelled_small(
-- "Shadow",
++ .into_any_element()
++ })),
++ )
++ .child(
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(8.))
++ .child(
++ div()
++ .text_size(px(12.))
++ .text_color(Hsla::from(theme.gray_11))
++ .child("Out"),
++ )
++ .child(self.menu_select(
++ SidebarMenu::TextAnimationOut(index),
++ "text-anim-out",
++ out_label,
++ cx,
++ ))
++ .children((animation_out != TextAnimation::None).then(|| {
self.slider(
-- SliderKey::Panel(PanelSlider::TextShadow, index),
-- "",
-- cx,
-- )
-- .into_any_element(),
-- ),
-- ),
-- ),
-- )
-- .child(
-- ui::Field::plain(&theme, "Animation")
-- .icon("icons/timer.svg")
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(12.))
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(8.))
-- .child(
-- div()
-- .text_size(px(12.))
-- .text_color(Hsla::from(theme.gray_11))
-- .child("In"),
-- )
-- .child(self.menu_select(
-- SidebarMenu::TextAnimationIn(index),
-- "text-anim-in",
-- in_label,
++ SliderKey::Panel(PanelSlider::TextAnimOutDuration, index),
++ "s",
cx,
-- ))
-- .children((animation_in != TextAnimation::None).then(|| {
-- self.slider(
-- SliderKey::Panel(
-- PanelSlider::TextAnimInDuration,
-- index,
-- ),
-- "s",
-- cx,
-- )
-- .into_any_element()
-- })),
-- )
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(8.))
-- .child(
-- div()
-- .text_size(px(12.))
-- .text_color(Hsla::from(theme.gray_11))
-- .child("Out"),
)
-- .child(self.menu_select(
-- SidebarMenu::TextAnimationOut(index),
-- "text-anim-out",
-- out_label,
-- cx,
-- ))
-- .children((animation_out != TextAnimation::None).then(|| {
-- self.slider(
-- SliderKey::Panel(
-- PanelSlider::TextAnimOutDuration,
-- index,
-- ),
-- "s",
-- cx,
-- )
-- .into_any_element()
-- })),
-- ),
-- ),
++ .into_any_element()
++ })),
++ ),
++ ),
)
.into_any_element()
}
@@@ -4483,7 -4344,7 +4452,7 @@@
.p(px(4.))
.rounded(px(8.))
.border_1()
-- .border_color(Hsla::from(theme.gray_3))
++ .border_color(Hsla::from(theme.editor.line))
.bg(Hsla::from(theme.gray_2))
.children(
items
@@@ -4540,8 -4401,8 +4509,7 @@@
.flex_col()
.gap(px(16.))
.child(
-- ui::Field::plain(&theme, SharedString::from(format!("Caption {}", index + 1)))
-- .icon("icons/message-bubble.svg")
++ ui::Field::section(&theme, SharedString::from(format!("Caption {}", index + 1)))
.child(self.render_field_input(FieldKey::CaptionText(index), Some(96.))),
)
.child(self.timing_field(
@@@ -4570,11 -4431,11 +4538,10 @@@
.flex_col()
.gap(px(16.))
.child(
-- ui::Field::plain(
++ ui::Field::section(
&theme,
SharedString::from(format!("Keyboard {}", index + 1)),
)
-- .icon("icons/keyboard.svg")
.child(self.render_field_input(FieldKey::KeyboardText(index), None)),
)
.child(self.timing_field(
@@@ -4584,11 -4445,11 +4551,12 @@@
end,
cx,
))
-- .child(
-- ui::Field::plain(&theme, "Fade Duration")
-- .icon("icons/timer.svg")
-- .child(self.slider(SliderKey::Panel(PanelSlider::KeyboardFade, index), "", cx)),
-- )
++ .child(self.slider_field(
++ "Fade Duration",
++ SliderKey::Panel(PanelSlider::KeyboardFade, index),
++ "",
++ cx,
++ ))
.into_any_element()
}
@@@ -4613,7 -4474,7 +4581,7 @@@
.p(px(10.))
.rounded(px(8.))
.border_1()
-- .border_color(Hsla::from(theme.gray_3))
++ .border_color(Hsla::from(theme.editor.line))
.bg(crate::editor_sidebar::with_alpha(theme.gray_1, 0.8))
.child(
div()
@@@ -4629,8 -4490,8 +4597,7 @@@
.child(self.render_field_input(key, None))
};
-- ui::Field::plain(&theme, "Timing")
-- .icon("icons/timer.svg")
++ ui::Field::section(&theme, "Timing")
.child(
div()
.flex()
@@@ -4639,7 -4500,7 +4606,7 @@@
.p(px(12.))
.rounded(px(12.))
.border_1()
-- .border_color(Hsla::from(theme.gray_3))
++ .border_color(Hsla::from(theme.editor.line))
.bg(crate::editor_sidebar::with_alpha(theme.gray_2, 0.7))
.child(
div()
@@@ -4706,8 -4567,8 +4673,7 @@@
.flex_col()
.gap(px(16.))
.child(
-- ui::Field::plain(&theme, SharedString::from(format!("Audio {}", index + 1)))
-- .icon("icons/music.svg")
++ ui::Field::section(&theme, SharedString::from(format!("Audio {}", index + 1)))
.child(
div()
.flex()
@@@ -4727,7 -4588,7 +4693,7 @@@
.w_full()
.rounded(px(12.))
.border_1()
-- .border_color(Hsla::from(theme.gray_3))
++ .border_color(Hsla::from(theme.editor.line))
.bg(Hsla::from(theme.gray_2))
.cursor_pointer()
.tab_index(0)
@@@ -4773,7 -4634,7 +4739,7 @@@
.flex_none()
.rounded(px(8.))
.border_1()
-- .border_color(Hsla::from(theme.gray_3))
++ .border_color(Hsla::from(theme.editor.line))
.bg(Hsla::from(theme.gray_1))
.text_size(px(12.))
.font_weight(FontWeight::MEDIUM)
@@@ -4836,29 -4697,29 +4802,24 @@@
),
),
)
-- .child(
-- ui::Field::plain(&theme, "Volume")
-- .icon("icons/volume-2.svg")
-- .child(self.slider(
-- SliderKey::Panel(PanelSlider::AudioVolume, index),
-- "db",
-- cx,
-- )),
-- )
-- .child(
-- ui::Field::plain(&theme, "Fade In")
-- .icon("icons/timer.svg")
-- .child(self.slider(SliderKey::Panel(PanelSlider::AudioFadeIn, index), "s", cx)),
-- )
-- .child(
-- ui::Field::plain(&theme, "Fade Out")
-- .icon("icons/timer.svg")
-- .child(self.slider(
-- SliderKey::Panel(PanelSlider::AudioFadeOut, index),
-- "s",
-- cx,
-- )),
-- )
++ .child(self.slider_field(
++ "Volume",
++ SliderKey::Panel(PanelSlider::AudioVolume, index),
++ "db",
++ cx,
++ ))
++ .child(self.slider_field(
++ "Fade In",
++ SliderKey::Panel(PanelSlider::AudioFadeIn, index),
++ "s",
++ cx,
++ ))
++ .child(self.slider_field(
++ "Fade Out",
++ SliderKey::Panel(PanelSlider::AudioFadeOut, index),
++ "s",
++ cx,
++ ))
.into_any_element()
}
@@@ -4876,155 -4737,155 +4837,127 @@@
let effect = mask_effect(segment);
let mut panel = div().flex().flex_col().gap(px(16.)).child(
-- ui::Field::plain(&theme, SharedString::from(format!("Mask {}", index + 1)))
-- .icon("icons/box-select.svg")
-- .child(
-- div()
-- .flex()
-- .flex_row()
-- .items_center()
-- .justify_between()
-- .gap(px(16.))
-- .child(div().flex_1().min_w_0().child(self.radio_row(
-- SharedString::from(format!("mask-kind-{index}")),
-- vec![("Sensitive", sensitive), ("Highlight", !sensitive)],
-- cx.listener(move |this, choice: &usize, window, cx| {
-- let want_sensitive = *choice == 0;
-- this.edit_mask_segment(
-- "mask-kind",
-- index,
-- window,
-- cx,
-- move |segment| {
-- segment.mask_type = if want_sensitive {
-- MaskKind::Sensitive
-- } else {
-- MaskKind::Highlight
-- };
-- // The two kinds seed different
-- // defaults (`:4408-4416`).
-- if want_sensitive {
-- segment.feather = 0.1;
-- segment.fade_duration = 0.;
-- } else {
-- segment.feather = 0.;
-- segment.opacity = 1.;
-- }
-- true
-- },
-- );
-- }),
-- )))
-- .child(
-- div()
-- .flex()
-- .flex_row()
-- .items_center()
-- .gap(px(8.))
-- .child(
-- div()
-- .text_size(px(12.))
-- .text_color(Hsla::from(theme.gray_11))
-- .child("Enabled"),
++ ui::Field::section(&theme, SharedString::from(format!("Mask {}", index + 1))).child(
++ div()
++ .flex()
++ .flex_row()
++ .items_center()
++ .justify_between()
++ .gap(px(16.))
++ .child(div().flex_1().min_w_0().child(self.radio_row(
++ SharedString::from(format!("mask-kind-{index}")),
++ vec![("Sensitive", sensitive), ("Highlight", !sensitive)],
++ cx.listener(move |this, choice: &usize, window, cx| {
++ let want_sensitive = *choice == 0;
++ this.edit_mask_segment(
++ "mask-kind",
++ index,
++ window,
++ cx,
++ move |segment| {
++ segment.mask_type = if want_sensitive {
++ MaskKind::Sensitive
++ } else {
++ MaskKind::Highlight
++ };
++ // The two kinds seed different
++ // defaults (`:4408-4416`).
++ if want_sensitive {
++ segment.feather = 0.1;
++ segment.fade_duration = 0.;
++ } else {
++ segment.feather = 0.;
++ segment.opacity = 1.;
++ }
++ true
++ },
++ );
++ }),
++ )))
++ .child(
++ div()
++ .flex()
++ .flex_row()
++ .items_center()
++ .gap(px(8.))
++ .child(
++ div()
++ .text_size(px(12.))
++ .text_color(Hsla::from(theme.gray_11))
++ .child("Enabled"),
++ )
++ .child(
++ ui::Toggle::plain(
++ &theme,
++ SharedString::from(format!("mask-enabled-{index}")),
++ enabled,
)
-- .child(
-- ui::Toggle::plain(
-- &theme,
-- SharedString::from(format!("mask-enabled-{index}")),
-- enabled,
-- )
-- .on_click(cx.listener(
-- move |this, _, window, cx| {
-- this.edit_mask_segment(
-- "mask-enabled",
-- index,
-- window,
-- cx,
-- move |segment| {
-- segment.enabled = !enabled;
-- true
-- },
-- );
-- },
-- )),
-- ),
-- ),
-- ),
++ .on_click(cx.listener(
++ move |this, _, window, cx| {
++ this.edit_mask_segment(
++ "mask-enabled",
++ index,
++ window,
++ cx,
++ move |segment| {
++ segment.enabled = !enabled;
++ true
++ },
++ );
++ },
++ )),
++ ),
++ ),
++ ),
);
if sensitive {
panel = panel
-- .child(
-- ui::Field::plain(&theme, "Effect")
-- .icon("icons/eye-off.svg")
-- .child(self.radio_row(
-- SharedString::from(format!("mask-effect-{index}")),
-- vec![
-- ("Blur", effect == MaskEffect::Blur),
-- ("Pixelate", effect == MaskEffect::Pixelate),
-- ],
-- cx.listener(move |this, choice: &usize, window, cx| {
-- let next = if *choice == 0 {
-- MaskEffect::Blur
-- } else {
-- MaskEffect::Pixelate
-- };
-- this.edit_mask_segment(
-- "mask-effect",
-- index,
-- window,
-- cx,
-- move |segment| {
-- let amount = mask_effect_amount(segment);
-- segment.pixelation = encode_mask_effect(next, amount);
-- segment.opacity = 1.;
-- segment.keyframes.intensity.clear();
-- true
-- },
-- );
-- }),
-- )),
-- )
-- .child(
-- ui::Field::plain(
-- &theme,
-- if effect == MaskEffect::Blur {
-- "Blur"
++ .child(ui::Field::section(&theme, "Effect").child(self.radio_row(
++ SharedString::from(format!("mask-effect-{index}")),
++ vec![
++ ("Blur", effect == MaskEffect::Blur),
++ ("Pixelate", effect == MaskEffect::Pixelate),
++ ],
++ cx.listener(move |this, choice: &usize, window, cx| {
++ let next = if *choice == 0 {
++ MaskEffect::Blur
} else {
-- "Pixel Size"
-- },
-- )
-- .icon(if effect == MaskEffect::Blur {
-- "icons/wind.svg"
++ MaskEffect::Pixelate
++ };
++ this.edit_mask_segment("mask-effect", index, window, cx, move |segment| {
++ let amount = mask_effect_amount(segment);
++ segment.pixelation = encode_mask_effect(next, amount);
++ segment.opacity = 1.;
++ segment.keyframes.intensity.clear();
++ true
++ });
++ }),
++ )))
++ .child(self.slider_field(
++ if effect == MaskEffect::Blur {
++ "Blur"
} else {
-- "icons/grid.svg"
-- })
-- .child(self.slider(
-- SliderKey::Panel(PanelSlider::MaskAmount, index),
-- "px",
-- cx,
-- )),
-- );
++ "Pixel Size"
++ },
++ SliderKey::Panel(PanelSlider::MaskAmount, index),
++ "px",
++ cx,
++ ));
} else {
panel = panel
-- .child(
-- ui::Field::plain(&theme, "Outside Darkness")
-- .icon("icons/moon.svg")
-- .child(self.slider(
-- SliderKey::Panel(PanelSlider::MaskDarkness, index),
-- "",
-- cx,
-- )),
-- )
-- .child(
-- ui::Field::plain(&theme, "Fade Duration")
-- .icon("icons/timer.svg")
-- .child(self.slider(
-- SliderKey::Panel(PanelSlider::MaskFade, index),
-- "s",
-- cx,
-- )),
-- );
++ .child(self.slider_field(
++ "Outside Darkness",
++ SliderKey::Panel(PanelSlider::MaskDarkness, index),
++ "",
++ cx,
++ ))
++ .child(self.slider_field(
++ "Fade Duration",
++ SliderKey::Panel(PanelSlider::MaskFade, index),
++ "s",
++ cx,
++ ));
}
panel.into_any_element()
@@@ -5144,156 -5005,156 +5077,140 @@@ impl EditorWindow
cx.listener(|this, _, _window, cx| this.set_selection(None, cx)),
),
)
- .child(
- ui::EditorButton::plain(&theme, "scene-delete")
- .danger(&theme)
- .left_icon("icons/trash.svg")
- .label("Delete")
- .on_click(cx.listener(|this, _, window, cx| {
- this.delete_selected_segments(window, cx)
- })),
- ),
- )
- .child(
- ui::Field::plain(&theme, "Camera Layout")
- .icon("icons/layout.svg")
- .child(
- div()
- .flex()
- .flex_col()
- .gap(px(12.))
- // `grid grid-cols-2 gap-2`
- .child(div().flex().flex_row().flex_wrap().gap(px(8.)).children(
- SCENE_MODES.iter().enumerate().map(
- |(choice, (value, label, icon, _))| {
- let selected = std::mem::discriminant(value)
- == std::mem::discriminant(&mode);
- // Split and Floating need a camera.
- let disabled = !has_camera
- && matches!(
- value,
- SceneMode::SplitScreen | SceneMode::Floating
- );
- div()
- .id(SharedString::from(format!("scene-mode-{choice}")))
- .w(px(187.))
- .flex()
- .flex_row()
- .gap(px(6.))
- .justify_center()
- .items_center()
- .py(px(10.))
- .px(px(8.))
- .rounded(px(10.))
- .border_1()
- .border_color(if selected {
- Hsla::from(theme.gray_3)
- } else {
- gpui::transparent_black()
- })
- .when(selected, |this| {
- this.bg(Hsla::from(theme.gray_3))
- })
- .when(disabled, |this| this.opacity(0.4))
- .text_size(px(12.))
- .text_color(if selected {
+ .child(
+ ui::EditorButton::plain(&theme, "scene-delete")
+ .danger(&theme)
+ .left_icon("icons/trash.svg")
+ .label("Delete")
+ .on_click(cx.listener(|this, _, window, cx| {
+ this.delete_selected_segments(window, cx)
+ })),
+ ),
+ )
+ .child(
- ui::Field::plain(&theme, "Camera Layout")
- .icon("icons/layout.svg")
- .child(
- div()
- .flex()
- .flex_col()
- .gap(px(12.))
- // `grid grid-cols-2 gap-2`
- .child(div().flex().flex_row().flex_wrap().gap(px(8.)).children(
- SCENE_MODES.iter().enumerate().map(
- |(choice, (value, label, icon, _))| {
- let selected = std::mem::discriminant(value)
- == std::mem::discriminant(&mode);
- // Split and Floating need a camera.
- let disabled = !has_camera
- && matches!(
- value,
- SceneMode::SplitScreen | SceneMode::Floating
- );
- div()
- .id(SharedString::from(format!("scene-mode-{choice}")))
- .w(px(187.))
- .flex()
- .flex_row()
- .gap(px(6.))
- .justify_center()
- .items_center()
- .py(px(10.))
- .px(px(8.))
- .rounded(px(10.))
- .border_1()
- .border_color(if selected {
- Hsla::from(theme.gray_3)
- } else {
- gpui::transparent_black()
- })
- .when(selected, |this| {
- this.bg(Hsla::from(theme.gray_3))
- })
- .when(disabled, |this| this.opacity(0.4))
- .text_size(px(12.))
- .text_color(if selected {
++ ui::Field::section(&theme, "Camera Layout").child(
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(12.))
++ // `grid grid-cols-2 gap-2`
++ .child(div().flex().flex_row().flex_wrap().gap(px(8.)).children(
++ SCENE_MODES.iter().enumerate().map(
++ |(choice, (value, label, icon, _))| {
++ let selected = std::mem::discriminant(value)
++ == std::mem::discriminant(&mode);
++ // Split and Floating need a camera.
++ let disabled = !has_camera
++ && matches!(
++ value,
++ SceneMode::SplitScreen | SceneMode::Floating
++ );
++ div()
++ .id(SharedString::from(format!("scene-mode-{choice}")))
++ .w(px(187.))
++ .flex()
++ .flex_row()
++ .gap(px(6.))
++ .justify_center()
++ .items_center()
++ .py(px(10.))
++ .px(px(8.))
++ .rounded(px(10.))
++ .border_1()
++ .border_color(if selected {
++ Hsla::from(theme.gray_3)
++ } else {
++ gpui::transparent_black()
++ })
++ .when(selected, |this| this.bg(Hsla::from(theme.gray_3)))
++ .when(disabled, |this| this.opacity(0.4))
++ .text_size(px(12.))
++ .text_color(if selected {
++ Hsla::from(theme.gray_12)
++ } else {
++ Hsla::from(theme.gray_11)
++ })
++ .child(svg().path(*icon).size(px(14.)).text_color(
++ if selected {
Hsla::from(theme.gray_12)
} else {
Hsla::from(theme.gray_11)
-- })
-- .child(svg().path(*icon).size(px(14.)).text_color(
-- if selected {
-- Hsla::from(theme.gray_12)
-- } else {
-- Hsla::from(theme.gray_11)
++ },
++ ))
++ .child(*label)
++ .when(!disabled, |this| {
++ this.on_click(cx.listener(
++ move |this, _, window, cx| {
++ this.set_scene_mode(index, choice, window, cx);
},
))
-- .child(*label)
-- .when(!disabled, |this| {
-- this.on_click(cx.listener(
-- move |this, _, window, cx| {
-- this.set_scene_mode(
-- index, choice, window, cx,
-- );
-- },
-- ))
-- })
-- },
-- ),
-- ))
-- .child(
-- div()
-- .p(px(10.))
-- .rounded(px(6.))
-- .bg(Hsla::from(theme.gray_2))
-- .border_1()
-- .border_color(Hsla::from(theme.gray_3))
-- .child(
-- div()
-- .w_full()
-- .text_size(px(12.))
-- .text_center()
-- .text_color(Hsla::from(theme.gray_11))
-- .child(description),
-- ),
++ })
++ },
),
-- ),
++ ))
++ .child(
++ div()
++ .p(px(10.))
++ .rounded(px(6.))
++ .bg(Hsla::from(theme.gray_2))
++ .border_1()
++ .border_color(Hsla::from(theme.editor.line))
++ .child(
++ div()
++ .w_full()
++ .text_size(px(12.))
++ .text_center()
++ .text_color(Hsla::from(theme.gray_11))
++ .child(description),
++ ),
++ ),
++ ),
)
.child(
-- ui::Field::plain(&theme, "Transition")
-- .icon("icons/timer.svg")
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(12.))
-- .child(ui::Subfield::plain(&theme, "In").child(
-- div().flex_1().min_w_0().ml(px(16.)).child(self.slider_flex(
-- SliderKey::Panel(PanelSlider::SceneTransitionIn, index),
-- "s2",
-- cx,
-- )),
-- ))
-- .child(ui::Subfield::plain(&theme, "Out").child(
-- div().flex_1().min_w_0().ml(px(16.)).child(self.slider_flex(
-- SliderKey::Panel(PanelSlider::SceneTransitionOut, index),
-- "s2",
-- cx,
-- )),
++ ui::Field::section(&theme, "Transition").child(
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(12.))
++ .child(ui::Subfield::plain(&theme, "In").child(
++ div().flex_1().min_w_0().ml(px(16.)).child(self.slider_flex(
++ SliderKey::Panel(PanelSlider::SceneTransitionIn, index),
++ "s2",
++ cx,
)),
-- ),
++ ))
++ .child(ui::Subfield::plain(&theme, "Out").child(
++ div().flex_1().min_w_0().ml(px(16.)).child(self.slider_flex(
++ SliderKey::Panel(PanelSlider::SceneTransitionOut, index),
++ "s2",
++ cx,
++ )),
++ )),
++ ),
);
if split_mode {
panel = panel
-- .child(dashed_divider(Hsla::from(theme.gray_5)))
-- .child(
-- ui::Field::plain(&theme, "Screen Zoom")
-- .icon("icons/enlarge.svg")
-- .child(self.slider(
-- SliderKey::Panel(PanelSlider::SceneScreenZoom, index),
-- "",
-- cx,
-- )),
-- )
++ .child(dashed_divider(Hsla::from(theme.editor.line)))
++ .child(self.slider_field(
++ "Screen Zoom",
++ SliderKey::Panel(PanelSlider::SceneScreenZoom, index),
++ "",
++ cx,
++ ))
.child(
-- ui::Field::plain(&theme, "Screen Position")
-- .icon("icons/move.svg")
++ ui::Field::stacked(&theme, "Screen Position")
.child(self.render_pad(PadKey::SceneScreen(index), cx)),
)
-- .child(dashed_divider(Hsla::from(theme.gray_5)))
-- .child(
-- ui::Field::plain(&theme, "Camera Zoom")
-- .icon("icons/enlarge.svg")
-- .child(self.slider(
-- SliderKey::Panel(PanelSlider::SceneCameraZoom, index),
-- "",
-- cx,
-- )),
-- )
++ .child(dashed_divider(Hsla::from(theme.editor.line)))
++ .child(self.slider_field(
++ "Camera Zoom",
++ SliderKey::Panel(PanelSlider::SceneCameraZoom, index),
++ "",
++ cx,
++ ))
.child(
-- ui::Field::plain(&theme, "Camera Position")
-- .icon("icons/move.svg")
++ ui::Field::stacked(&theme, "Camera Position")
.child(self.render_pad(PadKey::SceneCamera(index), cx)),
);
}
@@@ -5725,17 -5586,17 +5642,8 @@@
.flex()
.flex_col()
.gap(px(16.))
-- // `Templates` (`:5091-5170`). Scenes lead: one click lays a whole
-- // chained sequence over this segment's range, where the two rows
-- // below author a single shot.
- .child(
- ui::Field::plain(&theme, "Templates")
- .icon("icons/rotate-3d.svg")
- .child(templates),
- )
.child(
- ui::Field::plain(&theme, "Templates")
- .icon("icons/rotate-3d.svg")
- .child(templates),
- )
- .child(
-- ui::Field::plain(&theme, "Motion")
-- .icon("icons/move-right.svg")
++ ui::Field::section(&theme, "Motion")
.child(
div()
.flex()
@@@ -5785,8 -5646,8 +5693,7 @@@
.text_size(px(11.))
.text_color(Hsla::from(theme.gray_10))
.child(
-- "Pick a template or edit the end pose to add \
-- motion",
++ "Open Customize camera to choose a move or adjust the end pose",
)
.into_any_element()
} else {
@@@ -5808,7 -5669,7 +5715,7 @@@
self.camera3d_section(
Camera3DSection {
id: "camera3d-camera",
-- name: "Camera",
++ name: "Customize camera",
icon: "icons/video.svg",
summary: Some(if editing_end {
"End pose"
@@@ -5822,6 -5683,6 +5729,7 @@@
.flex()
.flex_col()
.gap(px(12.))
++ .child(ui::Field::stacked(&theme, "Templates").child(templates))
.children(CAMERA3D_POSE_SLIDERS.map(|(property, label, unit, icon)| {
div()
.flex()
@@@ -6806,338 -6648,3 +6714,357 @@@ mod tests
assert_eq!(font_family_label("Georgia"), "Georgia");
}
}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum ImageProperty {
- X,
- Y,
- Width,
- Height,
+ Opacity,
+ Rotation,
+ Rounding,
+}
+
+impl ImageProperty {
+ fn label(self) -> &'static str {
+ match self {
- Self::X => "Position X",
- Self::Y => "Position Y",
- Self::Width => "Width",
- Self::Height => "Height",
+ Self::Opacity => "Opacity",
+ Self::Rotation => "Rotation",
+ Self::Rounding => "Rounding",
+ }
+ }
+ fn limits(self) -> (f32, f32, f32) {
+ match self {
- Self::X | Self::Y => (-50., 150., 1.),
- Self::Width | Self::Height => (1., 200., 1.),
+ Self::Rotation => (-180., 180., 1.),
+ _ => (0., 100., 1.),
+ }
+ }
+ fn read(self, segment: &cap_project::ImageSegment) -> f32 {
+ match self {
- Self::X => (segment.center.x * 100.) as f32,
- Self::Y => (segment.center.y * 100.) as f32,
- Self::Width => (segment.size.x * 100.) as f32,
- Self::Height => (segment.size.y * 100.) as f32,
+ Self::Opacity => segment.opacity * 100.,
+ Self::Rotation => segment.rotation,
+ Self::Rounding => segment.rounding,
+ }
+ }
+ fn write(self, segment: &mut cap_project::ImageSegment, value: f32) {
+ if !value.is_finite() {
+ return;
+ }
+ let (min, max, _) = self.limits();
+ let value = value.clamp(min, max);
+ match self {
- Self::X => segment.center.x = f64::from(value) / 100.,
- Self::Y => segment.center.y = f64::from(value) / 100.,
- Self::Width => {
- let width = f64::from(value) / 100.;
- if segment.lock_aspect && segment.size.x > 0. {
- segment.size.y *= width / segment.size.x;
- }
- segment.size.x = width;
- }
- Self::Height => {
- let height = f64::from(value) / 100.;
- if segment.lock_aspect && segment.size.y > 0. {
- segment.size.x *= height / segment.size.y;
- }
- segment.size.y = height;
- }
+ Self::Opacity => segment.opacity = value / 100.,
+ Self::Rotation => segment.rotation = value,
+ Self::Rounding => segment.rounding = value,
+ }
+ }
+}
+
+impl EditorWindow {
+ fn render_image_panel(&self, index: usize, cx: &mut Context<Self>) -> AnyElement {
+ let Some(segment) = self
+ .timeline()
+ .and_then(|timeline| timeline.image_segments.get(index))
+ else {
+ return div().into_any_element();
+ };
+ let mut panel = div()
+ .flex()
+ .flex_col()
+ .gap(px(16.))
+ .child(self.labelled_small(
+ "Name",
+ self.render_field_input(FieldKey::ImageName(index), None),
+ ));
+ panel = panel
+ .child(
+ div()
- .text_size(px(12.))
- .child("Drag the image in the canvas to move it. Drag a corner to resize."),
++ .flex()
++ .flex_col()
++ .gap(px(8.))
++ .rounded(px(8.))
++ .border_1()
++ .border_color(Hsla::from(self.theme.gray_4))
++ .bg(Hsla::from(self.theme.gray_2))
++ .p(px(12.))
++ .child(
++ div()
++ .flex()
++ .flex_row()
++ .items_center()
++ .gap(px(8.))
++ .text_size(px(12.))
++ .font_weight(FontWeight::MEDIUM)
++ .child(svg().path("icons/move.svg").size(px(16.)))
++ .child("Arrange on canvas"),
++ )
++ .child(
++ div()
++ .text_size(px(12.))
++ .text_color(Hsla::from(self.theme.gray_10))
++ .child("Drag the image to move it. Pull a corner to resize, or use the rotation control below to turn it."),
++ )
++ .child(
++ ui::Button::plain(
++ &self.theme,
++ SharedString::from(format!("center-image-{index}")),
++ ui::ButtonVariant::Gray,
++ ui::ButtonSize::Sm,
++ )
++ .icon("icons/move.svg")
++ .label("Center on canvas")
++ .on_click(cx.listener(move |this, _, window, cx| {
++ this.edit_image_segment(
++ "image-center",
++ index,
++ window,
++ cx,
++ |segment| {
++ segment.center = XY::new(0.5, 0.5);
++ true
++ },
++ );
++ })),
++ ),
+ )
+ .child(
+ ui::Button::plain(
+ &self.theme,
+ SharedString::from(format!("replace-image-{index}")),
+ ui::ButtonVariant::Gray,
+ ui::ButtonSize::Md,
+ )
+ .label("Replace image")
+ .disabled(self.sidebar.picking_image)
+ .on_click(cx.listener(move |this, _, window, cx| {
+ this.replace_timeline_image(index, window, cx)
+ })),
+ );
+ if self
+ .sidebar
+ .image_asset_status
+ .as_ref()
+ .is_some_and(|(path, present)| path == &segment.path && !present)
+ {
+ panel = panel.child(div().text_size(px(12.)).child("Image file is missing. Replace it to restore this segment while keeping its timing and transforms."));
+ }
+ if let Some(error) = &self.sidebar.image_import_error {
+ panel = panel.child(div().text_size(px(12.)).child(error.clone()));
+ }
+ for (key, label, value) in [
+ (0, "Enabled", segment.enabled),
+ (1, "Lock aspect ratio", segment.lock_aspect),
+ (2, "Flip horizontally", segment.flip_x),
+ (3, "Flip vertically", segment.flip_y),
+ ] {
+ panel = panel.child(
+ ui::Subfield::plain(&self.theme, label).child(
+ ui::Toggle::plain(
+ &self.theme,
+ SharedString::from(format!("image-{index}-{key}")),
+ value,
+ )
+ .on_click(cx.listener(move |this, _, window, cx| {
+ this.edit_image_segment("image-toggle", index, window, cx, move |segment| {
+ match key {
+ 0 => segment.enabled = !value,
+ 1 => segment.lock_aspect = !value,
+ 2 => segment.flip_x = !value,
+ _ => segment.flip_y = !value,
+ };
+ true
+ })
+ })),
+ ),
+ );
+ }
+ for property in [
- ImageProperty::X,
- ImageProperty::Y,
- ImageProperty::Width,
- ImageProperty::Height,
+ ImageProperty::Rotation,
+ ImageProperty::Rounding,
+ ImageProperty::Opacity,
+ ] {
+ panel = panel.child(
+ self.labelled_small(
+ property.label(),
+ self.slider(
+ SliderKey::Panel(PanelSlider::Image(property), index),
+ if property == ImageProperty::Rotation {
+ "°"
+ } else {
+ "%"
+ },
+ cx,
+ )
+ .into_any_element(),
+ ),
+ );
+ }
+ panel.into_any_element()
+ }
+
+ fn render_style_panel(&self, index: usize, cx: &mut Context<Self>) -> AnyElement {
+ use crate::editor_sidebar::StyleGroup;
+ let Some(segment) = self
+ .timeline()
+ .and_then(|timeline| timeline.style_segments.get(index))
+ else {
+ return div().into_any_element();
+ };
+ let enabled = segment.enabled;
+ let mut panel = div().flex().flex_col().gap(px(16.))
+ .child(div().text_size(px(12.)).child("Overrides apply only during this segment. Enable a group to copy its global settings."))
+ .child(self.labelled_small("Name", self.render_field_input(FieldKey::StyleName(index), None)))
+ .child(ui::Subfield::plain(&self.theme,"Enabled").child(ui::Toggle::plain(&self.theme,SharedString::from(format!("style-enabled-{index}")),enabled).on_click(cx.listener(move |this,_,window,cx| this.edit_style_segment("style-enabled",index,window,cx,move |segment| { segment.enabled = !enabled; true })))));
+ for (group, active) in [
+ (
+ StyleGroup::Background,
+ segment.overrides.background.is_some(),
+ ),
+ (StyleGroup::Camera, segment.overrides.camera.is_some()),
+ (StyleGroup::Cursor, segment.overrides.cursor.is_some()),
+ ] {
+ panel = panel.child(
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(8.))
+ .child(
+ ui::Subfield::plain(&self.theme, group.label()).child(
+ ui::Toggle::plain(
+ &self.theme,
+ SharedString::from(format!("style-{index}-{group:?}")),
+ active,
+ )
+ .on_click(cx.listener(
+ move |this, _, window, cx| {
+ this.edit_project(
+ "style-override",
+ window,
+ cx,
+ move |project| {
+ let Some(segment) =
+ project.timeline.as_mut().and_then(|timeline| {
+ timeline.style_segments.get_mut(index)
+ })
+ else {
+ return false;
+ };
+ match group {
+ StyleGroup::Background => {
+ segment.overrides.background = (!active)
+ .then(|| project.background.clone())
+ }
+ StyleGroup::Camera => {
+ segment.overrides.camera =
+ (!active).then(|| project.camera.clone())
+ }
+ StyleGroup::Cursor => {
+ segment.overrides.cursor =
+ (!active).then(|| project.cursor.clone())
+ }
+ }
+ true
+ },
+ );
+ },
+ )),
+ ),
+ )
+ .children(active.then(|| {
+ div()
+ .id(SharedString::from(format!("style-edit-{index}-{group:?}")))
+ .cursor_pointer()
+ .px(px(12.))
+ .py(px(8.))
+ .rounded(px(6.))
+ .bg(Hsla::from(self.theme.gray_3))
- .child(format!("Edit {}", group.label()))
++ .child(
++ div()
++ .flex()
++ .flex_row()
++ .items_center()
++ .gap(px(6.))
++ .child(svg().path(group.icon()).size(px(14.)))
++ .child(format!("Edit {}", group.label())),
++ )
+ .on_click(cx.listener(move |this, _, window, cx| {
+ this.open_style_group(index, group, window, cx)
+ }))
+ })),
+ );
+ }
+ if segment.overrides.background.is_some() {
+ let mut crop = div().flex().flex_col().gap(px(8.)).child(
+ div()
+ .text_size(px(12.))
+ .child("Screen crop (source pixels)"),
+ );
+ for (axis, label) in [(0, "Left"), (1, "Top"), (2, "Width"), (3, "Height")] {
+ crop = crop.child(self.labelled_small(
+ label,
+ self.render_number_field(FieldKey::StyleCrop(index, axis), "px", 80.),
+ ));
+ }
+ crop = crop.child(
+ div()
+ .id(SharedString::from(format!("style-crop-reset-{index}")))
+ .cursor_pointer()
+ .child("Reset crop")
+ .on_click(cx.listener(move |this, _, window, cx| {
+ this.edit_style_segment(
+ "style-crop-reset",
+ index,
+ window,
+ cx,
+ move |segment| {
+ if let Some(background) = segment.overrides.background.as_mut() {
+ background.crop = None;
+ true
+ } else {
+ false
+ }
+ },
+ )
+ })),
+ );
+ panel = panel.child(crop);
+ }
+ let padding = segment.overrides.camera_only_padding.is_some();
+ panel = panel.child(
+ ui::Subfield::plain(&self.theme, "Camera Only background").child(
+ ui::Toggle::plain(
+ &self.theme,
+ SharedString::from(format!("style-camera-only-{index}")),
+ padding,
+ )
+ .on_click(cx.listener(move |this, _, window, cx| {
+ this.edit_style_segment(
+ "camera-only-background",
+ index,
+ window,
+ cx,
+ move |segment| {
+ segment.overrides.camera_only_padding = (!padding).then_some(10.);
+ true
+ },
+ )
+ })),
+ ),
+ );
+ if padding {
+ panel = panel
+ .child(
+ self.labelled_small(
+ "Camera Only padding",
+ self.slider(
+ SliderKey::Panel(PanelSlider::StyleCameraOnlyPadding, index),
+ "%",
+ cx,
+ )
+ .into_any_element(),
+ ),
+ )
+ .child(div().text_size(px(11.)).child(
+ "Use a Camera Only scene. Padding reveals the background around the camera.",
+ ));
+ }
+ panel.into_any_element()
+ }
+}
diff --cc apps/desktop-gpui/src/editor_sidebar.rs
index 322750fab,3d2ac8a3b..64bdcfee2
--- a/apps/desktop-gpui/src/editor_sidebar.rs
+++ b/apps/desktop-gpui/src/editor_sidebar.rs
@@@ -296,10 -296,10 +296,15 @@@ pub enum SourceTab
}
impl SourceTab {
-- /// `BACKGROUND_SOURCES_ROW_ONE` / `_TWO` (`:236-246`).
-- pub const ROWS: [[SourceTab; 3]; 2] = [
-- [Self::Desktop, Self::Wallpaper, Self::Image],
-- [Self::Color, Self::Gradient, Self::AnimatedGradient],
++ /// `BACKGROUND_SOURCES_ROW_ONE` / `_TWO` (`:236-246`), now one segmented
++ /// row. `None` is not in it: it is the section header's own action.
++ pub const PICKER: [SourceTab; 6] = [
++ Self::Desktop,
++ Self::Wallpaper,
++ Self::Image,
++ Self::Color,
++ Self::Gradient,
++ Self::AnimatedGradient,
];
pub fn label(self) -> &'static str {
@@@ -2428,9 -2399,9 +2433,10 @@@ impl EditorWindow
/// The sidebar card's inner content width: 416 minus its 1px borders minus the
/// panel's `p-4`. Fixed, because the column is `w-104 min-w-104 flex-none`.
const CONTENT_WIDTH: f32 = 416. - 2. - 32.;
--/// `grid grid-cols-7 gap-2`.
--const WALLPAPER_COLUMNS: f32 = 7.;
--const WALLPAPER_GAP: f32 = 8.;
++/// Six 34px-tall tiles across the pane.
++const WALLPAPER_COLUMNS: f32 = 6.;
++const WALLPAPER_GAP: f32 = 6.;
++const WALLPAPER_TILE_HEIGHT: f32 = 34.;
/// The gradient preview: `h-28` over the panel's full content width.
const GRADIENT_PREVIEW_WIDTH: f32 = CONTENT_WIDTH;
const GRADIENT_PREVIEW_HEIGHT: f32 = 112.;
@@@ -2456,6 -2427,6 +2462,7 @@@ impl EditorWindow
// the indicator is hidden (`:586-592, 667-677`).
ui::TabRailItem::new(
tab.icon(),
++ tab.label(),
selection.is_none() && tab == selected_tab,
disabled,
)
@@@ -2469,14 -2440,14 +2476,12 @@@
}));
div()
-- .ml(px(8.))
.w(px(crate::editor_window::SIDEBAR_WIDTH))
.h_full()
.flex()
.flex_col()
.flex_none()
.min_h_0()
-- .overflow_hidden()
.child(
div()
.flex()
@@@ -2488,23 -2459,9 +2493,24 @@@
.rounded(px(12.))
.bg(self.panel_bg())
.border_1()
-- .border_color(Hsla::from(theme.gray_3))
++ .border_color(self.card_line())
++ .shadow(theme.editor.card_shadow())
.child(rail)
- .child(if self.audio_picker.is_some() {
+ .children(self.sidebar.image_import_error.as_ref().map(|error| {
+ div()
+ .p(px(12.))
+ .text_size(px(12.))
- .text_color(Hsla::from(theme.gray_12))
++ .text_color(Hsla::from(theme.editor.text_1))
+ .child(error.clone())
+ }))
+ .children(
+ self.sidebar
+ .picking_image
+ .then(|| div().p(px(12.)).child("Importing image…")),
+ )
+ .child(if let Some((index, group)) = self.sidebar.style_target {
+ self.render_style_group(index, group, cx)
+ } else if self.audio_picker.is_some() {
self.render_audio_library(cx)
} else if self.camera3d_setup.is_some() {
self.render_camera3d_setup(cx)
@@@ -2539,13 -2496,13 +2545,15 @@@
.overflow_x_hidden()
.overflow_y_scroll()
.track_scroll(&self.sidebar.scroll)
-- .text_size(px(14.))
++ .text_size(px(13.))
.child(
div()
.flex()
.flex_col()
-- .gap(px(24.))
-- .p(px(16.))
++ .gap(px(14.))
++ .pt(px(14.))
++ .px(px(16.))
++ .pb(px(16.))
.child(content),
)
.into_any_element()
@@@ -2579,38 -2536,38 +2587,48 @@@ impl EditorWindow
div()
.flex()
.flex_col()
-- .gap(px(24.))
++ .gap(px(14.))
.child(self.render_source_field(cx))
++ .child(dashed_divider(Hsla::from(theme.editor.line)))
.child(
-- ui::Field::plain(&theme, "Background Blur")
-- .icon("icons/bg-blur.svg")
-- .child(self.slider(SliderKey::Bg(BgSlider::Blur), "%", cx)),
-- )
-- // `<div class="w-full border-t border-gray-300 border-dashed" />`
-- .child(dashed_divider(Hsla::from(theme.gray_300_legacy)))
-- .child(
-- ui::Field::plain(&theme, "Padding")
-- .icon("icons/padding.svg")
-- .child(self.slider(SliderKey::Bg(BgSlider::Padding), "%", cx))
-- // The custom screen position row, shown only once the
-- // display has been dragged on the canvas (`:2656-2667`).
-- .children(background.display_position.map(|_| {
-- div()
-- .flex()
-- .flex_row()
-- .justify_between()
-- .items_center()
-- .mt(px(12.))
-- .child(
-- div()
-- .text_size(px(12.))
-- .text_color(Hsla::from(theme.gray_11))
-- .child("Custom screen position (dragged on canvas)"),
-- )
-- .child(
-- ui::EditorButton::plain(&theme, "reset-display-position")
-- .label("Reset")
-- .on_click(cx.listener(|this, _, window, cx| {
++ ui::Field::section(&theme, "Layout").child(
++ div()
++ .flex()
++ .flex_col()
++ .child(self.slider_field(
++ "Background Blur",
++ SliderKey::Bg(BgSlider::Blur),
++ "%",
++ cx,
++ ))
++ .child(self.slider_field(
++ "Padding",
++ SliderKey::Bg(BgSlider::Padding),
++ "%",
++ cx,
++ ))
++ // The custom screen position row, shown only once the
++ // display has been dragged on the canvas (`:2656-2667`).
++ .children(background.display_position.map(|_| {
++ div()
++ .flex()
++ .flex_row()
++ .justify_between()
++ .items_center()
++ .h(px(34.))
++ .child(
++ div()
++ .text_size(px(12.))
++ .text_color(Hsla::from(theme.editor.text_2))
++ .child("Custom screen position (dragged on canvas)"),
++ )
++ .child(section_action(
++ &theme,
++ "reset-display-position",
++ "Reset",
++ None,
++ false,
++ cx.listener(|this, _, window, cx| {
this.edit_background(
"display-position",
|project| {
@@@ -2620,38 -2577,33 +2638,41 @@@
window,
cx,
);
-- })),
++ }),
++ ))
++ .into_any_element()
++ }))
++ .child(self.slider_field(
++ "Rounded Corners",
++ SliderKey::Bg(BgSlider::Rounding),
++ "%",
++ cx,
++ ))
++ .child(self.render_corner_style(cx))
++ .children(self.sidebar.style_target.is_none().then(|| {
++ self.slider_field(
++ "Motion Blur",
++ SliderKey::Bg(BgSlider::MotionBlur),
++ "x100%",
++ cx,
)
.into_any_element()
-- })),
-- )
-- .child(
-- ui::Field::plain(&theme, "Rounded Corners")
-- .icon("icons/corners.svg")
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(12.))
-- .child(self.slider(SliderKey::Bg(BgSlider::Rounding), "%", cx))
-- .child(self.render_corner_style(cx)),
-- ),
- )
- .child(
- ui::Field::plain(&theme, "Motion Blur")
- .icon("icons/wind.svg")
- .child(self.slider(SliderKey::Bg(BgSlider::MotionBlur), "x100%", cx)),
++ })),
++ ),
)
- .children(self.sidebar.style_target.is_none().then(|| {
- ui::Field::plain(&theme, "Motion Blur")
- .icon("icons/wind.svg")
- .child(self.slider(SliderKey::Bg(BgSlider::MotionBlur), "x100%", cx))
- }))
++ .child(dashed_divider(Hsla::from(theme.editor.line)))
.child(self.render_border_field(cx))
++ .child(dashed_divider(Hsla::from(theme.editor.line)))
.child(self.render_notch_field(cx))
++ .child(dashed_divider(Hsla::from(theme.editor.line)))
.child(self.render_shadow_field(cx))
// `<ColorCorrectionSection target="screen" />` (`:2962`).
- .child(self.render_color_correction(GradeTarget::Screen, cx))
+ .children(
+ self.sidebar
+ .style_target
+ .is_none()
+ .then(|| self.render_color_correction(GradeTarget::Screen, cx)),
+ )
}
// -- Source ------------------------------------------------------------
@@@ -2660,171 -2612,171 +2681,45 @@@
let theme = self.theme;
let tab = self.sidebar.source_tab;
-- let rows = SourceTab::ROWS.map(|row| {
-- div()
-- .flex()
-- .flex_row()
-- .items_center()
-- .gap(px(8.))
-- .children(
-- row.into_iter()
-- .map(|item| self.render_source_trigger(item, cx).into_any_element()),
-- )
-- .into_any_element()
-- });
++ let options = SourceTab::PICKER
++ .into_iter()
++ .map(|item| ui::SegmentOption::new(item.label(), tab == item))
++ .collect();
-- ui::Field::plain(&theme, "Background Image")
-- .icon("icons/image.svg")
++ ui::Field::section(&theme, "Background")
++ .value(section_action(
++ &theme,
++ "source-none",
++ SourceTab::None.label(),
++ Some("icons/x.svg"),
++ tab == SourceTab::None,
++ cx.listener(|this, _, window, cx| {
++ this.select_source_tab(SourceTab::None, window, cx);
++ }),
++ ))
.child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(8.))
-- .children(rows)
-- .child(self.render_source_trigger(SourceTab::None, cx))
-- // `my-5 w-full border-t border-dashed border-gray-5`
-- .child(
-- div()
-- .my(px(20.))
-- .child(dashed_divider(Hsla::from(theme.gray_5))),
-- )
-- .child(match tab {
-- SourceTab::Desktop => self.render_desktop_pane(cx).into_any_element(),
-- SourceTab::Wallpaper => self.render_wallpaper_pane(cx).into_any_element(),
-- SourceTab::Image => self.render_image_pane(cx).into_any_element(),
-- SourceTab::Color => self.render_color_pane(cx).into_any_element(),
-- SourceTab::Gradient => self.render_gradient_pane(cx).into_any_element(),
-- SourceTab::AnimatedGradient => {
-- self.render_animated_gradient_pane(cx).into_any_element()
++ ui::SegmentedControl::editor(&theme, "background-source", options)
++ .stretch()
++ .item_height(px(26.))
++ .item_padding(px(4.), px(0.))
++ .text_size(px(11.5))
++ .on_select(cx.listener(|this, index: &usize, window, cx| {
++ if let Some(item) = ui::option_at(&SourceTab::PICKER, *index) {
++ this.select_source_tab(item, window, cx);
}
-- SourceTab::None => div().into_any_element(),
-- }),
++ })),
)
-- }
--
-- /// `BackgroundSourceTrigger` (`:2116-2130`): `py-2.5 px-2 text-xs
-- /// rounded-[10px] border` with a live `size-3.5` preview of what the tile
-- /// would select.
-- fn render_source_trigger(&self, item: SourceTab, cx: &mut Context<Self>) -> impl IntoElement {
-- let theme = self.theme;
-- let selected = self.sidebar.source_tab == item;
--
-- div()
-- .id(SharedString::from(format!("source-{}", item.label())))
-- .flex()
-- .flex_1()
-- .justify_center()
-- .items_center()
-- .gap(px(6.))
-- .py(px(10.))
-- .px(px(8.))
-- .rounded(px(10.))
-- .border_1()
-- .text_size(px(12.))
-- .when(selected, |this| {
-- this.border_color(Hsla::from(theme.gray_3))
-- .bg(Hsla::from(theme.gray_3))
-- .text_color(Hsla::from(theme.gray_12))
-- })
-- .when(!selected, |this| {
-- this.border_color(if item == SourceTab::None {
-- Hsla::from(theme.gray_5)
-- } else {
-- gpui::transparent_black()
-- })
-- .text_color(Hsla::from(theme.gray_11))
-- .cursor_pointer()
-- .hover(|this| this.border_color(Hsla::from(theme.gray_7)))
-- })
-- .child(self.render_source_icon(item))
-- .child(item.label())
-- .on_click(cx.listener(move |this, _, window, cx| {
-- this.select_source_tab(item, window, cx);
-- }))
-- }
--
-- /// `renderBackgroundSourceIcon` (`:2054-2114`). Every tile previews the
-- /// thing it would select: the colour tile is the colour, the gradient tile
-- /// is the gradient at its current angle, and the three image tiles are the
-- /// selected file where there is one and the shipped illustration where
-- /// there is not.
-- fn render_source_icon(&self, item: SourceTab) -> AnyElement {
-- let source = &self.project.background.source;
-- match item {
-- SourceTab::None => svg()
-- .path("icons/image-off.svg")
-- .size(px(14.))
-- .text_color(Hsla::from(self.theme.gray_11))
-- .into_any_element(),
-- SourceTab::Gradient => {
-- let (from, to, angle) = match source {
-- BackgroundSource::Gradient {
-- from, to, angle, ..
-- } => (*from, *to, f32::from(*angle)),
-- _ => (DEFAULT_GRADIENT_FROM, DEFAULT_GRADIENT_TO, 90.),
-- };
-- div()
-- .size(px(14.))
-- .rounded(px(2.))
-- .bg(linear_gradient(
-- angle,
-- linear_color_stop(color_to_hsla(from), 0.),
-- linear_color_stop(color_to_hsla(to), 1.),
-- ))
-- .into_any_element()
-- }
-- SourceTab::AnimatedGradient => self.render_animated_gradient_icon(),
-- SourceTab::Color => {
-- let value = match source {
-- BackgroundSource::Color { value, .. } => *value,
-- // `hexToRgb(BACKGROUND_COLORS[9])` -- dodger blue.
-- _ => [71, 133, 255],
-- };
-- div()
-- .size(px(14.))
-- .rounded(px(5.))
-- .bg(color_to_hsla(value))
-- .into_any_element()
-- }
-- SourceTab::Image | SourceTab::Wallpaper | SourceTab::Desktop => {
-- let thumbnail = match item {
-- SourceTab::Image => match source {
-- BackgroundSource::Image { path: Some(path) } => self.tile_image(path),
-- _ => None,
-- },
-- SourceTab::Desktop => self
-- .sidebar
-- .desktop_background
-- .as_ref()
-- .and_then(|path| self.tile_image(&path.to_string_lossy())),
-- _ => match source {
-- BackgroundSource::Wallpaper { path: Some(path) }
-- if !is_current_desktop_background_path(Some(path)) =>
-- {
-- wallpaper_id_for_path(path)
-- .and_then(|id| self.sidebar.wallpapers.get(id).cloned())
-- }
-- _ => None,
-- },
-- };
-- match thumbnail {
-- Some(image) => img(image)
-- .size(px(14.))
-- .rounded(px(2.))
-- .object_fit(gpui::ObjectFit::Cover)
-- .into_any_element(),
-- None => img(match item {
-- // `imageBg` for both the desktop and wallpaper tiles,
-- // `transparentBg` for image (`:229-234, 2088-2089`).
-- SourceTab::Image => "illustrations/transparent.webp",
-- _ => "illustrations/image.webp",
-- })
-- .size(px(14.))
-- .rounded(px(2.))
-- .into_any_element(),
++ .child(match tab {
++ SourceTab::Desktop => self.render_desktop_pane(cx).into_any_element(),
++ SourceTab::Wallpaper => self.render_wallpaper_pane(cx).into_any_element(),
++ SourceTab::Image => self.render_image_pane(cx).into_any_element(),
++ SourceTab::Color => self.render_color_pane(cx).into_any_element(),
++ SourceTab::Gradient => self.render_gradient_pane(cx).into_any_element(),
++ SourceTab::AnimatedGradient => {
++ self.render_animated_gradient_pane(cx).into_any_element()
}
-- }
-- }
++ SourceTab::None => div().into_any_element(),
++ })
}
/// The decoded preview for a path, if it is the one already decoded.
@@@ -2857,18 -2809,18 +2752,18 @@@
.p(px(24.))
.w_full()
.rounded(px(8.))
-- .border_dashed_1(Hsla::from(theme.gray_5))
-- .bg(Hsla::from(theme.gray_2))
++ .border_dashed_1(Hsla::from(theme.editor.line_strong))
++ .bg(Hsla::from(theme.editor.ctl))
.child(
svg()
.path("icons/monitor-outline.svg")
.size(px(24.))
-- .text_color(Hsla::from(theme.gray_11)),
++ .text_color(Hsla::from(theme.editor.text_2)),
)
.child(
div()
.text_size(px(13.))
-- .text_color(Hsla::from(theme.gray_12))
++ .text_color(Hsla::from(theme.editor.text_1))
.child("Use the wallpaper from your desktop"),
)
.child(
@@@ -2905,9 -2857,9 +2800,11 @@@
.border_1()
.when(selected, |this| this.border_color(Hsla::from(theme.blue_9)))
.when(!selected, |this| {
-- this.border_color(Hsla::from(theme.gray_5))
++ this.border_color(Hsla::from(theme.editor.line_strong))
.cursor_pointer()
-- .hover(|this| this.border_color(Hsla::from(theme.gray_7)))
++ .hover(|this| {
++ this.border_color(Hsla::from(theme.editor.accent))
++ })
})
.children(preview.map(|image| {
img(image)
@@@ -2958,7 -2910,7 +2855,11 @@@
_ => None,
};
let ids = wallpapers_for_theme(BACKGROUND_THEMES[selected_theme].0);
-- let cell = (CONTENT_WIDTH - WALLPAPER_GAP * (WALLPAPER_COLUMNS - 1.)) / WALLPAPER_COLUMNS;
++ // Floored, with a pixel to spare: a cell that divides the pane exactly
++ // wraps the last tile onto its own row.
++ let cell = ((CONTENT_WIDTH - WALLPAPER_GAP * (WALLPAPER_COLUMNS - 1.)) / WALLPAPER_COLUMNS)
++ .floor()
++ - 1.;
div()
.flex()
@@@ -2973,8 -2925,8 +2874,8 @@@
.flex()
.flex_row()
.items_center()
-- .gap(px(8.))
-- .mb(px(12.))
++ .gap(px(4.))
++ .mb(px(10.))
.text_size(px(12.))
.overflow_x_scroll()
.children(
@@@ -2989,22 -2941,22 +2890,18 @@@
.flex_1()
.justify_center()
.items_center()
-- .px(px(16.))
-- .py(px(8.))
-- .rounded(px(8.))
-- .border_1()
++ .h(px(24.))
++ .px(px(8.))
++ .rounded(px(6.))
++ .font_weight(FontWeight::MEDIUM)
.when(selected, |this| {
-- this.bg(Hsla::from(theme.gray_3))
-- .border_color(Hsla::from(theme.gray_3))
-- .text_color(Hsla::from(theme.gray_12))
++ this.bg(Hsla::from(theme.editor.ctl_hover))
++ .text_color(Hsla::from(theme.editor.text_1))
})
.when(!selected, |this| {
-- this.border_color(gpui::transparent_black())
-- .text_color(Hsla::from(theme.gray_11))
++ this.text_color(Hsla::from(theme.editor.text_2))
.cursor_pointer()
-- .hover(|this| {
-- this.border_color(Hsla::from(theme.gray_7))
-- })
++ .hover(|this| this.bg(Hsla::from(theme.editor.ctl)))
})
.child(*label)
.on_click(cx.listener(move |this, _, window, cx| {
@@@ -3016,9 -2968,9 +2913,6 @@@
),
)
.child(
-- // `grid grid-cols-7 gap-2 h-auto`, each item `aspect-square
-- // rounded-lg`, selected `ring-2 ring-gray-500 ring-offset-2
-- // ring-offset-gray-200`.
div()
.flex()
.flex_row()
@@@ -3030,33 -2982,33 +2924,26 @@@
div()
.id(SharedString::from(format!("wallpaper-{id}")))
.w(px(cell))
-- .h(px(cell))
++ .h(px(WALLPAPER_TILE_HEIGHT + 2. * (RING_WIDTH + RING_GAP)))
.rounded(px(8.))
-- .overflow_hidden()
-- .bg(Hsla::from(theme.gray_3))
.cursor_pointer()
-- .when(selected, |this| {
-- // The ring: 2px of `gray-500` outside a 2px
-- // `gray-200` offset. gpui has no outside
-- // border, so the offset is drawn as the tile's
-- // own 2px `gray-200` ring and the selection
-- // colour as the 2px border over it.
-- this.border_2()
-- .border_color(Hsla::from(theme.gray_500_legacy))
-- })
-- .when(!selected, |this| {
-- this.hover(|this| {
-- this.border_1().border_color(Hsla::from(theme.gray_7))
-- })
-- })
-- .children(image.map(|image| {
-- // `overflow_hidden` clips to the rect, not the
-- // radius, so the picture needs its own corners.
-- img(image)
++ .selection_ring(self.panel_bg(), theme.editor.accent, selected)
++ .child(
++ div()
.size_full()
-- .object_fit(gpui::ObjectFit::Cover)
-- .rounded(px(8.))
-- }))
++ .rounded(px(6.))
++ .overflow_hidden()
++ .bg(Hsla::from(theme.editor.ctl_hover))
++ .children(image.map(|image| {
++ // `overflow_hidden` clips to the rect,
++ // not the radius, so the picture needs
++ // its own corners.
++ img(image)
++ .size_full()
++ .object_fit(gpui::ObjectFit::Cover)
++ .rounded(px(6.))
++ })),
++ )
.on_click(cx.listener(move |this, _, window, cx| {
let Some(path) = wallpaper_path(id) else {
tracing::error!(id, "wallpaper file not found");
@@@ -3095,20 -3047,20 +2982,20 @@@
.p(px(24.))
.w_full()
.rounded(px(8.))
-- .bg(Hsla::from(theme.gray_2))
-- .border_dashed_1(Hsla::from(theme.gray_5))
++ .bg(Hsla::from(theme.editor.ctl))
++ .border_dashed_1(Hsla::from(theme.editor.line_strong))
.text_size(px(13.))
.cursor_pointer()
-- .hover(|this| this.bg(Hsla::from(theme.gray_3)))
++ .hover(|this| this.bg(Hsla::from(theme.editor.ctl_hover)))
.child(
svg()
.path("icons/image.svg")
.size(px(24.))
-- .text_color(Hsla::from(theme.gray_11)),
++ .text_color(Hsla::from(theme.editor.text_2)),
)
.child(
div()
-- .text_color(Hsla::from(theme.gray_12))
++ .text_color(Hsla::from(theme.editor.text_1))
.child("Click to select or drag and drop image"),
)
.on_click(cx.listener(|this, _, window, cx| {
@@@ -3122,7 -3074,7 +3009,7 @@@
.rounded(px(6.))
.overflow_hidden()
.border_1()
-- .border_color(Hsla::from(theme.gray_3))
++ .border_color(Hsla::from(theme.editor.line))
.children(self.tile_image(&path).map(|image| {
img(image)
.size_full()
@@@ -3194,16 -3146,16 +3081,18 @@@
.size(px(32.))
.rounded(px(8.))
.cursor_pointer()
-- .when(transparent, |this| {
-- // `CHECKERED_BUTTON_BACKGROUND` (`:6500`): an
-- // 8px `#a0a0a0` checker.
-- this.bg(gpui::checkerboard(gpui::rgb(0xa0a0a0), 8.))
-- })
-- .when(!transparent, |this| this.bg(color_to_hsla(color)))
-- .when(selected, |this| {
-- this.border_2()
-- .border_color(Hsla::from(theme.gray_500_legacy))
-- })
++ .selection_ring(self.panel_bg(), theme.editor.accent, selected)
++ .child(
++ div()
++ .size_full()
++ .rounded(px(6.))
++ .when(transparent, |this| {
++ // `CHECKERED_BUTTON_BACKGROUND`
++ // (`:6500`): an 8px `#a0a0a0` checker.
++ this.bg(gpui::checkerboard(gpui::rgb(0xa0a0a0), 8.))
++ })
++ .when(!transparent, |this| this.bg(color_to_hsla(color))),
++ )
.on_click(cx.listener(move |this, _, window, cx| {
this.edit_background(
"color-preset",
@@@ -3275,11 -3227,11 +3164,10 @@@
.padding_x(px(6.))
.padding_y(px(6.))
.height(px(30.))
-- .radius(px(8.))
-- .bg(Hsla::from(theme.gray_1))
-- .border(Hsla::from(theme.gray_12))
++ .radius(px(7.))
++ .bg(Hsla::from(theme.editor.ctl))
.text_size(px(13.))
-- .text_color(Hsla::from(theme.gray_12))
++ .text_color(Hsla::from(theme.editor.text_1))
}))
}
@@@ -3329,7 -3281,7 +3217,7 @@@
.overflow_hidden()
.rounded(px(12.))
.border_1()
-- .border_color(Hsla::from(theme.gray_5))
++ .border_color(Hsla::from(theme.editor.line_strong))
.bg(linear_gradient(
angle,
linear_color_stop(color_to_hsla(from), 0.),
@@@ -3365,58 -3317,58 +3253,35 @@@
cx,
)),
)
++ .child(dashed_divider(Hsla::from(theme.editor.line)))
.child(
div()
-- .my(px(4.))
-- .child(dashed_divider(Hsla::from(theme.gray_5))),
-- )
-- // Angle: the slider plus the redundant `w-12 text-right
-- // tabular-nums` readout the source draws beside it.
-- .child(
-- ui::Subfield::plain(&theme, "Angle").gap(px(16.)).child(
-- div()
-- .flex()
-- .flex_1()
-- .flex_row()
-- .items_center()
-- .gap(px(12.))
-- .child(self.slider_flex(SliderKey::Bg(BgSlider::GradientAngle), "deg", cx))
-- .child(
-- div()
-- .w(px(48.))
-- .text_size(px(12.))
-- .text_color(Hsla::from(theme.gray_11))
-- .child(format!("{}\u{b0}", angle.round() as i32)),
-- ),
-- ),
-- )
-- .child(
-- div()
-- .my(px(4.))
-- .child(dashed_divider(Hsla::from(theme.gray_5))),
-- )
-- .child(ui::Subfield::plain(&theme, "Noise").child(
-- div().w(px(120.)).child(self.slider(
-- SliderKey::Bg(BgSlider::GradientNoise),
-- "%",
-- cx,
-- )),
-- ))
-- // Grain Scale appears only while noise is on (`:204-221`).
-- .children((noise > 0.).then(|| {
-- ui::Subfield::plain(&theme, "Grain Scale")
-- .child(div().w(px(120.)).child(self.slider(
-- SliderKey::Bg(BgSlider::GradientGrain),
++ .flex()
++ .flex_col()
++ .child(self.slider_field(
++ "Angle",
++ SliderKey::Bg(BgSlider::GradientAngle),
++ "deg",
++ cx,
++ ))
++ .child(self.slider_field(
++ "Noise",
++ SliderKey::Bg(BgSlider::GradientNoise),
"%",
cx,
-- )))
-- .into_any_element()
-- }))
-- .child(
-- div()
-- .my(px(4.))
-- .child(dashed_divider(Hsla::from(theme.gray_5))),
++ ))
++ // Grain Scale appears only while noise is on (`:204-221`).
++ .children((noise > 0.).then(|| {
++ self.slider_field(
++ "Grain Scale",
++ SliderKey::Bg(BgSlider::GradientGrain),
++ "%",
++ cx,
++ )
++ .into_any_element()
++ })),
)
++ .child(dashed_divider(Hsla::from(theme.editor.line)))
// Randomize, then the 18 presets -- which rotate live with the
// angle, because each swatch draws the same gradient the preview
// does (`:255-282`).
@@@ -3434,15 -3386,15 +3299,15 @@@
.justify_center()
.size(px(32.))
.rounded(px(8.))
-- .bg(Hsla::from(theme.gray_2))
-- .border_dashed_1(Hsla::from(theme.gray_8))
-- .text_color(Hsla::from(theme.gray_10))
++ .bg(Hsla::from(theme.editor.ctl))
++ .border_dashed_1(Hsla::from(theme.editor.line_strong))
++ .text_color(Hsla::from(theme.editor.text_3))
.cursor_pointer()
.child(
svg()
.path("icons/shuffle.svg")
.size(px(14.))
-- .text_color(Hsla::from(theme.gray_10)),
++ .text_color(Hsla::from(theme.editor.text_3)),
)
.on_click(cx.listener(|this, _, window, cx| {
// `Math.floor(Math.random() * 256)` per
@@@ -3489,15 -3441,15 +3354,16 @@@
.size(px(32.))
.rounded(px(8.))
.cursor_pointer()
-- .bg(linear_gradient(
++ .selection_ring(
++ self.panel_bg(),
++ theme.editor.accent,
++ preset == Some(index),
++ )
++ .child(div().size_full().rounded(px(6.)).bg(linear_gradient(
angle,
linear_color_stop(color_to_hsla(preset_from), 0.),
linear_color_stop(color_to_hsla(preset_to), 1.),
-- ))
-- .when(preset == Some(index), |this| {
-- this.border_2()
-- .border_color(Hsla::from(theme.gray_500_legacy))
-- })
++ )))
.on_click(cx.listener(move |this, _, window, cx| {
this.edit_background(
"gradient-preset",
@@@ -3538,7 -3490,7 +3404,7 @@@
div()
.mb(px(4.))
.text_size(px(11.))
-- .text_color(Hsla::from(theme.gray_10))
++ .text_color(Hsla::from(theme.editor.text_3))
.child(label),
)
.child(self.render_rgb_input(id, target, value, cx))
@@@ -3556,22 -3508,22 +3422,12 @@@
CornerStyle::Rounded => "Rounded",
};
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(6.))
-- .child(
-- div()
-- .text_size(px(10.4))
-- .text_color(Hsla::from(theme.gray_11))
-- .child("CORNER STYLE"),
-- )
-- .child(self.menu_select(
-- crate::editor_tabs::SidebarMenu::BackgroundCornerStyle,
-- "corner-style",
-- label,
-- cx,
-- ))
++ ui::Field::inline(&theme, "Corner Style").child(div().w(px(150.)).child(self.menu_select(
++ crate::editor_tabs::SidebarMenu::BackgroundCornerStyle,
++ "corner-style",
++ label,
++ cx,
++ )))
}
fn render_border_field(&self, cx: &mut Context<Self>) -> impl IntoElement {
@@@ -3583,65 -3535,65 +3439,60 @@@
div()
.flex()
.flex_col()
-- .gap(px(24.))
.child(
-- ui::Field::plain(&theme, "Border")
-- .icon("icons/settings.svg")
-- .value(
-- ui::Toggle::plain(&theme, "border-enabled", enabled)
-- .on_click(cx.listener(move |this, _, window, cx| {
-- let next = !enabled;
-- this.sidebar.border_open.set_open(next);
-- // gpui renders on invalidation only, so the
-- // height transition needs someone to ask for
-- // the frames.
-- this.animate_collapsibles(window, cx);
-- this.edit_background(
-- "border-enabled",
-- |project| {
-- let mut border = project
-- .background
-- .border
-- .clone()
-- .unwrap_or(UI_BORDER_FALLBACK);
-- border.enabled = next;
-- project.background.border = Some(border);
-- true
-- },
-- window,
-- cx,
-- );
-- }))
-- .into_any_element(),
-- ),
++ ui::Field::inline(&theme, "Border").value(
++ ui::Toggle::plain(&theme, "border-enabled", enabled)
++ .on_click(cx.listener(move |this, _, window, cx| {
++ let next = !enabled;
++ this.sidebar.border_open.set_open(next);
++ // gpui renders on invalidation only, so the
++ // height transition needs someone to ask for
++ // the frames.
++ this.animate_collapsibles(window, cx);
++ this.edit_background(
++ "border-enabled",
++ |project| {
++ let mut border = project
++ .background
++ .border
++ .clone()
++ .unwrap_or(UI_BORDER_FALLBACK);
++ border.enabled = next;
++ project.background.border = Some(border);
++ true
++ },
++ window,
++ cx,
++ );
++ }))
++ .into_any_element(),
++ ),
)
.child(collapsible(
&self.sidebar.border_open,
div()
.flex()
.flex_col()
-- .gap(px(24.))
-- .pb(px(24.))
-- .child(
-- ui::Field::plain(&theme, "Border Width")
-- .icon("icons/enlarge.svg")
-- .child(self.slider(SliderKey::Bg(BgSlider::BorderWidth), "px", cx)),
-- )
-- .child(
-- ui::Field::plain(&theme, "Border Color")
-- .icon("icons/image.svg")
-- .child(self.render_rgb_input(
-- "border-color",
-- ColorTarget::BorderColor,
-- color,
-- cx,
-- )),
-- )
++ .child(self.slider_field(
++ "Border Width",
++ SliderKey::Bg(BgSlider::BorderWidth),
++ "px",
++ cx,
++ ))
.child(
-- ui::Field::plain(&theme, "Border Opacity")
-- .icon("icons/shadow.svg")
-- .child(self.slider(SliderKey::Bg(BgSlider::BorderOpacity), "%", cx)),
++ ui::Field::stacked(&theme, "Border Color").child(self.render_rgb_input(
++ "border-color",
++ ColorTarget::BorderColor,
++ color,
++ cx,
++ )),
)
++ .child(self.slider_field(
++ "Border Opacity",
++ SliderKey::Bg(BgSlider::BorderOpacity),
++ "%",
++ cx,
++ ))
.into_any_element(),
))
}
@@@ -3658,67 -3610,67 +3509,68 @@@
div()
.flex()
.flex_col()
-- .gap(px(24.))
.child(
-- ui::Field::plain(&theme, "MacBook notch")
-- .icon("icons/laptop.svg")
-- .value(
-- ui::Toggle::plain(&theme, "notch-enabled", enabled)
-- .on_click(cx.listener(move |this, _, window, cx| {
-- let next = !enabled;
-- this.sidebar.notch_open.set_open(next);
-- // gpui renders on invalidation only, so the
-- // height transition needs someone to ask for
-- // the frames.
-- this.animate_collapsibles(window, cx);
-- this.edit_background(
-- "notch-enabled",
-- |project| {
-- let mut notch =
-- project.background.notch.unwrap_or(UNPLACED_NOTCH);
-- notch.enabled = next;
-- project.background.notch = Some(notch);
-- true
-- },
-- window,
-- cx,
-- );
-- }))
-- .into_any_element(),
-- ),
++ ui::Field::inline(&theme, "MacBook notch").value(
++ ui::Toggle::plain(&theme, "notch-enabled", enabled)
++ .on_click(cx.listener(move |this, _, window, cx| {
++ let next = !enabled;
++ this.sidebar.notch_open.set_open(next);
++ // gpui renders on invalidation only, so the
++ // height transition needs someone to ask for
++ // the frames.
++ this.animate_collapsibles(window, cx);
++ this.edit_background(
++ "notch-enabled",
++ |project| {
++ let mut notch =
++ project.background.notch.unwrap_or(UNPLACED_NOTCH);
++ notch.enabled = next;
++ project.background.notch = Some(notch);
++ true
++ },
++ window,
++ cx,
++ );
++ }))
++ .into_any_element(),
++ ),
)
.child(collapsible(
&self.sidebar.notch_open,
div()
.flex()
.flex_col()
-- .gap(px(24.))
-- .pb(px(24.))
++ .gap(px(4.))
++ .pb(px(8.))
.child(
div()
++ .pt(px(4.))
.text_size(px(12.))
-- .text_color(Hsla::from(theme.gray_11))
++ .text_color(Hsla::from(theme.editor.text_2))
.child(
"Draws a MacBook notch over the recording. Recordings made \
on a Mac with a notch use their own measurements; \
otherwise start from the size below and adjust to match.",
),
)
-- .child(
-- ui::Field::plain(&theme, "Notch Width")
-- .icon("icons/enlarge.svg")
-- .child(self.slider(SliderKey::Bg(BgSlider::NotchWidth), "pct", cx)),
-- )
-- .child(
-- ui::Field::plain(&theme, "Notch Height")
-- .icon("icons/enlarge.svg")
-- .child(self.slider(SliderKey::Bg(BgSlider::NotchHeight), "pct", cx)),
-- )
-- .child(
-- ui::Field::plain(&theme, "Notch Position")
-- .icon("icons/enlarge.svg")
-- .child(self.slider(SliderKey::Bg(BgSlider::NotchX), "pct", cx)),
-- )
++ .child(self.slider_field(
++ "Notch Width",
++ SliderKey::Bg(BgSlider::NotchWidth),
++ "pct",
++ cx,
++ ))
++ .child(self.slider_field(
++ "Notch Height",
++ SliderKey::Bg(BgSlider::NotchHeight),
++ "pct",
++ cx,
++ ))
++ .child(self.slider_field(
++ "Notch Position",
++ SliderKey::Bg(BgSlider::NotchX),
++ "pct",
++ cx,
++ ))
.into_any_element(),
))
}
@@@ -3727,67 -3679,67 +3579,49 @@@
let theme = self.theme;
let open = self.sidebar.shadow_open.is_open();
-- ui::Field::plain(&theme, "Shadow")
-- .icon("icons/shadow.svg")
-- .child(self.slider(SliderKey::Bg(BgSlider::Shadow), "%", cx))
++ div()
++ .flex()
++ .flex_col()
++ .child(self.slider_field("Shadow", SliderKey::Bg(BgSlider::Shadow), "%", cx))
// `ShadowSettings` (`ShadowSettings.tsx:37-86`): its own trigger
// row with a rotating chevron, over three sliders.
.child(
div()
.flex()
.flex_col()
-- .child(
-- div()
-- .id("shadow-advanced")
-- .flex()
-- .flex_row()
-- .items_center()
-- .gap(px(4.))
-- .font_weight(FontWeight::MEDIUM)
-- .text_color(Hsla::from(theme.gray_12))
-- .cursor_pointer()
-- .child(div().text_size(px(14.)).child("Advanced shadow settings"))
-- .child(
-- // `rotate-180` when open. There is no rotation
-- // in this gpui rev, so the glyph swaps rather
-- // than turns -- the same substitution the
-- // settings window's reveal makes.
-- svg()
-- .path(if open {
-- "icons/chevron-down.svg"
-- } else {
-- "icons/chevron-right.svg"
-- })
-- .size(px(20.))
-- .text_color(Hsla::from(theme.gray_12)),
-- )
-- .on_click(cx.listener(|this, _, window, cx| {
-- this.sidebar.shadow_open.toggle();
-- this.animate_collapsibles(window, cx);
-- })),
-- )
++ .child(disclosure_row(
++ &theme,
++ "shadow-advanced",
++ "Advanced shadow settings",
++ open,
++ cx.listener(|this, _, window, cx| {
++ this.sidebar.shadow_open.toggle();
++ this.animate_collapsibles(window, cx);
++ }),
++ ))
.child(collapsible(
&self.sidebar.shadow_open,
div()
.flex()
.flex_col()
-- .gap(px(24.))
-- .mt(px(16.))
-- .child(ui::Field::plain(&theme, "Size").child(self.slider(
++ .child(self.slider_field(
++ "Size",
SliderKey::Bg(BgSlider::ShadowSize),
"",
cx,
-- )))
-- .child(ui::Field::plain(&theme, "Opacity").child(self.slider(
++ ))
++ .child(self.slider_field(
++ "Opacity",
SliderKey::Bg(BgSlider::ShadowOpacity),
"",
cx,
-- )))
-- .child(ui::Field::plain(&theme, "Blur").child(self.slider(
++ ))
++ .child(self.slider_field(
++ "Blur",
SliderKey::Bg(BgSlider::ShadowBlur),
"",
cx,
-- )))
++ ))
.into_any_element(),
)),
)
@@@ -3847,18 -3799,18 +3681,32 @@@
self.slider_sized(slider, unit, true, cx)
}
-- /// `<Slider disabled>`: Kobalte stops the pointer reaching the track and
-- /// the fill repaints `data-disabled:bg-gray-8` (`editor/ui.tsx:118`). The
-- /// two audio volumes are the sidebar's only disabled sliders, and both are
-- /// disabled by `project.audio.mute` (`:786, :804`).
-- pub(crate) fn slider_disabled(
++ /// The inline row every single-slider setting is: label, track, readout.
++ /// The readout is the value the source only showed in the slider's own
++ /// tooltip, which the tooltip still carries.
++ pub(crate) fn slider_field(
+ &self,
++ name: impl Into<SharedString>,
++ slider: SliderKey,
++ unit: &'static str,
++ cx: &mut Context<Self>,
++ ) -> ui::Field {
++ self.slider_field_disabled(name, slider, unit, false, cx)
++ }
++
++ pub(crate) fn slider_field_disabled(
+ &self,
++ name: impl Into<SharedString>,
slider: SliderKey,
unit: &'static str,
disabled: bool,
cx: &mut Context<Self>,
-- ) -> impl IntoElement {
-- self.slider_sized_state(slider, unit, false, disabled, cx)
++ ) -> ui::Field {
++ let value = format_slider_value(self.slider_value(slider), unit);
++ ui::Field::inline(&self.theme, name)
++ .disabled(disabled)
++ .value_text(value)
++ .child(self.slider_sized_state(slider, unit, true, disabled, cx))
}
fn slider_sized(
@@@ -3907,24 -3859,24 +3755,19 @@@
track,
)
.flex()
-- .row_height(px(32.))
-- // `h-[0.3rem] bg-gray-4 rounded-full`
-- .track(px(4.8), Hsla::from(theme.gray_4))
++ .row_height(px(28.))
++ .track(px(3.), Hsla::from(theme.editor.ctl_active))
.fill(Hsla::from(if disabled {
-- theme.gray_8
++ theme.editor.text_3
} else {
-- theme.blue_9
++ theme.editor.accent
}))
-- // `bg-gray-1 dark:bg-gray-12 border border-gray-6 size-4`
.thumb(
-- px(16.),
-- Hsla::from(if theme.is_dark() {
-- theme.gray_12
-- } else {
-- theme.gray_1
-- }),
-- Some(Hsla::from(theme.gray_6)),
++ px(14.),
++ Hsla::from(theme.editor.thumb),
++ Some(gpui::hsla(0., 0., 0., 0.12)),
)
++ .thumb_shadow()
.when(!disabled, |this| {
this.on_drag_start(cx.listener(
move |this, event: &MouseDownEvent, window, cx| {
@@@ -3953,30 -3905,30 +3796,106 @@@ pub(crate) fn format_slider_value(value
}
}
--/// The dashed dividers. gpui has no dashed border, so the dashes are painted:
--/// 4px on, 4px off, one pixel tall.
++/// The section dividers: a solid hairline, not the source's dashes.
pub(crate) fn dashed_divider(color: Hsla) -> impl IntoElement {
-- div().w_full().h(px(1.)).child(
-- canvas(
-- |_, _, _| {},
-- move |bounds: Bounds<Pixels>, _, window: &mut Window, _| {
-- let mut x = f32::from(bounds.origin.x);
-- let right = x + f32::from(bounds.size.width);
-- while x < right {
-- let width = 4_f32.min(right - x);
-- window.paint_quad(gpui::fill(
-- Bounds {
-- origin: gpui::point(px(x), bounds.origin.y),
-- size: gpui::size(px(width), px(1.)),
-- },
-- color,
-- ));
-- x += 8.;
-- }
-- },
++ div().w_full().h(px(1.)).bg(color)
++}
++
++/// A section header that is also a disclosure trigger: same 12px/500 `text_2`
++/// as [`ui::Field::section`]'s label, with a chevron.
++pub(crate) fn disclosure_row(
++ theme: &crate::theme::Theme,
++ id: impl Into<gpui::ElementId>,
++ label: impl Into<SharedString>,
++ open: bool,
++ handler: impl Fn(&gpui::ClickEvent, &mut Window, &mut gpui::App) + 'static,
++) -> AnyElement {
++ let id = id.into();
++ let group: SharedString = SharedString::from(format!("dr-{id:?}"));
++ let rest = Hsla::from(theme.editor.text_2);
++ let hover = Hsla::from(theme.editor.text_1);
++
++ div()
++ .id(id)
++ .group(group.clone())
++ .flex()
++ .flex_row()
++ .items_center()
++ .gap(px(4.))
++ .min_h(px(22.))
++ .text_size(px(12.))
++ .font_weight(FontWeight::MEDIUM)
++ .text_color(rest)
++ .cursor_pointer()
++ .hover(move |this| this.text_color(hover))
++ .child(label.into())
++ .child(
++ // `rotate-180` when open. There is no rotation in this gpui rev,
++ // so the glyph swaps rather than turns.
++ svg()
++ .path(if open {
++ "icons/chevron-down.svg"
++ } else {
++ "icons/chevron-right.svg"
++ })
++ .size(px(12.))
++ .flex_shrink_0()
++ .text_color(Hsla::from(theme.editor.text_3))
++ .group_hover(group, move |style| style.text_color(hover)),
)
-- .size_full(),
-- )
++ .on_click(handler)
++ .into_any_element()
++}
++
++/// The 22px ghost that sits on a section header's own row (`None`, `Save`,
++/// `Reset`). `EditorButton` is the 28px ghost the header rows are too short
++/// for, and its height is shared with the player toolbar.
++pub(crate) fn section_action(
++ theme: &crate::theme::Theme,
++ id: impl Into<gpui::ElementId>,
++ label: impl Into<SharedString>,
++ icon: Option<&'static str>,
++ active: bool,
++ handler: impl Fn(&gpui::ClickEvent, &mut Window, &mut gpui::App) + 'static,
++) -> AnyElement {
++ let id = id.into();
++ let group: SharedString = SharedString::from(format!("sa-{id:?}"));
++ let rest = Hsla::from(theme.editor.text_2);
++ let hover = Hsla::from(theme.editor.text_1);
++ let foreground = if active { hover } else { rest };
++
++ div()
++ .id(id)
++ .group(group.clone())
++ .flex()
++ .flex_row()
++ .items_center()
++ .gap(px(4.))
++ .h(px(22.))
++ .px(px(6.))
++ .rounded(px(6.))
++ .flex_shrink_0()
++ .text_size(px(12.))
++ .font_weight(FontWeight::MEDIUM)
++ .text_color(foreground)
++ .when(active, |this| this.bg(Hsla::from(theme.editor.ctl_hover)))
++ .cursor_pointer()
++ .hover(move |this| {
++ this.bg(Hsla::from(theme.editor.ctl_hover))
++ .text_color(hover)
++ })
++ .active(move |this| this.bg(Hsla::from(theme.editor.ctl_active)))
++ .children(icon.map(|icon| {
++ svg()
++ .path(icon)
++ .size(px(12.))
++ .flex_shrink_0()
++ .text_color(foreground)
++ .group_hover(group, move |style| style.text_color(hover))
++ }))
++ .child(label.into())
++ .on_click(handler)
++ .into_any_element()
}
/// The clipped, animating container. Mounted while open *and* while animating
@@@ -4007,6 -3959,6 +3926,24 @@@ trait DashedBorder
fn border_dashed_1(self, color: Hsla) -> Self;
}
++/// The selected-tile ring: a 2px accent border with a 2px gap of the card
++/// colour inside it, painted on every tile so selecting one never moves the
++/// grid.
++pub(crate) const RING_WIDTH: f32 = 2.;
++pub(crate) const RING_GAP: f32 = 2.;
++
++pub(crate) trait SelectionRing {
++ fn selection_ring(self, gap: Hsla, accent: impl Into<Hsla>, selected: bool) -> Self;
++}
++
++fn ring_colors(gap: Hsla, accent: impl Into<Hsla>, selected: bool) -> (Hsla, Hsla) {
++ if selected {
++ (gap, accent.into())
++ } else {
++ (gpui::transparent_black(), gpui::transparent_black())
++ }
++}
++
impl DashedBorder for gpui::Div {
fn border_dashed_1(self, color: Hsla) -> Self {
self.border_1().border_color(color)
@@@ -4019,6 -3971,6 +3956,26 @@@ impl DashedBorder for gpui::Stateful<gp
}
}
++impl SelectionRing for gpui::Div {
++ fn selection_ring(self, gap: Hsla, accent: impl Into<Hsla>, selected: bool) -> Self {
++ let (fill, border) = ring_colors(gap, accent, selected);
++ self.bg(fill)
++ .p(px(RING_GAP))
++ .border(px(RING_WIDTH))
++ .border_color(border)
++ }
++}
++
++impl SelectionRing for gpui::Stateful<gpui::Div> {
++ fn selection_ring(self, gap: Hsla, accent: impl Into<Hsla>, selected: bool) -> Self {
++ let (fill, border) = ring_colors(gap, accent, selected);
++ self.bg(fill)
++ .p(px(RING_GAP))
++ .border(px(RING_WIDTH))
++ .border_color(border)
++ }
++}
++
// ---------------------------------------------------------------------------
// Verification hooks
// ---------------------------------------------------------------------------
@@@ -4116,13 -4066,13 +4073,8 @@@ mod tests
};
assert_eq!(source_tab_for(&source), SourceTab::AnimatedGradient);
assert_eq!(SourceTab::AnimatedGradient.label(), "Animated");
-- assert!(SourceTab::ROWS[1].contains(&SourceTab::AnimatedGradient));
-- assert!(
-- !SourceTab::ROWS
-- .iter()
-- .flatten()
-- .any(|tab| *tab == SourceTab::None)
-- );
++ assert!(SourceTab::PICKER.contains(&SourceTab::AnimatedGradient));
++ assert!(!SourceTab::PICKER.contains(&SourceTab::None));
assert!(!ColorTarget::AnimatedGradientStop(0).is_hex_string());
}
@@@ -4308,304 -4258,3 +4260,329 @@@
assert_eq!((rgba.r * 255.).round() as u8, 209);
}
}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum StyleGroup {
+ Background,
+ Camera,
+ Cursor,
+}
+
+impl StyleGroup {
+ pub(crate) fn label(self) -> &'static str {
+ match self {
+ Self::Background => "Background & frame",
+ Self::Camera => "Camera",
+ Self::Cursor => "Cursor",
+ }
+ }
++
++ pub(crate) fn icon(self) -> &'static str {
++ match self {
++ Self::Background => "icons/monitor-outline.svg",
++ Self::Camera => "icons/camera.svg",
++ Self::Cursor => "icons/cursor.svg",
++ }
++ }
+}
+
+pub(crate) fn apply_style_control_change(
+ project: &mut ProjectConfiguration,
+ index: usize,
+ group: StyleGroup,
+ change: impl FnOnce(&mut ProjectConfiguration) -> bool,
+) -> bool {
+ let Some(segment) = project
+ .timeline
+ .as_ref()
+ .and_then(|timeline| timeline.style_segments.get(index))
+ else {
+ return false;
+ };
+ let mut scoped = project.clone();
+ match group {
+ StyleGroup::Background => {
+ let Some(value) = &segment.overrides.background else {
+ return false;
+ };
+ scoped.background = value.clone();
+ }
+ StyleGroup::Camera => {
+ let Some(value) = &segment.overrides.camera else {
+ return false;
+ };
+ scoped.camera = value.clone();
+ }
+ StyleGroup::Cursor => {
+ let Some(value) = &segment.overrides.cursor else {
+ return false;
+ };
+ scoped.cursor = value.clone();
+ }
+ }
+ if !change(&mut scoped) {
+ return false;
+ }
+ let Some(segment) = project
+ .timeline
+ .as_mut()
+ .and_then(|timeline| timeline.style_segments.get_mut(index))
+ else {
+ return false;
+ };
+ match group {
+ StyleGroup::Background => segment.overrides.background = Some(scoped.background),
+ StyleGroup::Camera => segment.overrides.camera = Some(scoped.camera),
+ StyleGroup::Cursor => segment.overrides.cursor = Some(scoped.cursor),
+ }
+ true
+}
+
+impl EditorWindow {
+ pub(crate) fn style_background(&self) -> &cap_project::BackgroundConfiguration {
+ self.sidebar
+ .style_target
+ .filter(|(_, group)| *group == StyleGroup::Background)
+ .and_then(|(index, _)| {
+ self.project
+ .timeline
+ .as_ref()?
+ .style_segments
+ .get(index)?
+ .overrides
+ .background
+ .as_ref()
+ })
+ .unwrap_or(&self.project.background)
+ }
+
+ pub(crate) fn style_control_project(&self) -> std::borrow::Cow<'_, ProjectConfiguration> {
+ let Some((index, group)) = self.sidebar.style_target else {
+ return std::borrow::Cow::Borrowed(&self.project);
+ };
+ let Some(segment) = self
+ .project
+ .timeline
+ .as_ref()
+ .and_then(|timeline| timeline.style_segments.get(index))
+ else {
+ return std::borrow::Cow::Borrowed(&self.project);
+ };
+ let mut project = self.project.clone();
+ match group {
+ StyleGroup::Background => {
+ if let Some(value) = &segment.overrides.background {
+ project.background = value.clone();
+ }
+ }
+ StyleGroup::Camera => {
+ if let Some(value) = &segment.overrides.camera {
+ project.camera = value.clone();
+ }
+ }
+ StyleGroup::Cursor => {
+ if let Some(value) = &segment.overrides.cursor {
+ project.cursor = value.clone();
+ }
+ }
+ }
+ std::borrow::Cow::Owned(project)
+ }
+
+ pub(crate) fn with_style_controls<R>(&mut self, render: impl FnOnce(&mut Self) -> R) -> R {
+ let std::borrow::Cow::Owned(scoped) = self.style_control_project() else {
+ return render(self);
+ };
+ // Existing controls read the project while building their elements. Restore the base before any event can publish or save it.
+ let base = std::mem::replace(&mut self.project, scoped);
+ let result = render(self);
+ self.project = base;
+ result
+ }
+
+ fn apply_control_change(
+ &mut self,
+ change: impl FnOnce(&mut ProjectConfiguration) -> bool,
+ ) -> bool {
+ match self.sidebar.style_target {
+ Some((index, group)) => {
+ apply_style_control_change(&mut self.project, index, group, change)
+ }
+ None => change(&mut self.project),
+ }
+ }
+
+ pub(crate) fn open_style_group(
+ &mut self,
+ index: usize,
+ group: StyleGroup,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.dismiss_frame_controls(cx);
+ self.end_field_edit(cx);
+ self.close_color_picker(cx);
+ self.sidebar.menu = None;
+ self.sidebar.style_target = Some((index, group));
+ self.sidebar.tab = match group {
+ StyleGroup::Background => SidebarTab::Background,
+ StyleGroup::Camera => SidebarTab::Camera,
+ StyleGroup::Cursor => SidebarTab::Cursor,
+ };
+ let ripple_enabled = self.style_control_project().cursor.ripple.enabled;
+ self.sidebar.cursor_ripple_open.set_open(ripple_enabled);
+ self.sidebar.source_tab = initial_source_tab(&self.style_control_project());
+ self.sidebar.scroll.set_offset(gpui::point(px(0.), px(0.)));
+ cx.notify();
+ window.refresh();
+ }
+
+ fn render_style_group(
+ &self,
+ index: usize,
+ group: StyleGroup,
+ cx: &mut Context<Self>,
+ ) -> AnyElement {
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_h_0()
+ .child(
+ div()
+ .p(px(12.))
+ .flex()
+ .flex_col()
+ .gap(px(6.))
- .child(format!("Style {} · {}", index + 1, group.label()))
++ .child(
++ div()
++ .flex()
++ .flex_row()
++ .items_center()
++ .gap(px(8.))
++ .font_weight(gpui::FontWeight::MEDIUM)
++ .child(svg().path(group.icon()).size(px(16.)))
++ .child(format!("Style {} · {}", index + 1, group.label())),
++ )
+ .child(
+ div()
+ .text_size(px(11.))
+ .child("Editing this segment only. Global settings are unchanged."),
+ )
+ .child(
+ div()
+ .id("style-back")
+ .cursor_pointer()
+ .text_size(px(12.))
- .child("← Back to Style")
++ .child(
++ div()
++ .flex()
++ .flex_row()
++ .items_center()
++ .gap(px(4.))
++ .child(svg().path("icons/arrow-left.svg").size(px(14.)))
++ .child("Back to Style"),
++ )
+ .on_click(cx.listener(|this, _, window, cx| {
+ this.end_field_edit(cx);
+ this.close_color_picker(cx);
+ this.sidebar.menu = None;
+ this.sidebar.style_target = None;
+ cx.notify();
+ window.refresh();
+ })),
+ ),
+ )
+ .child(self.render_tab_body(cx))
+ .into_any_element()
+ }
+}
+
+impl EditorWindow {
+ fn style_target_fingerprint(&self) -> Option<String> {
+ let index = self.sidebar.style_target?.0;
+ serde_json::to_string(self.project.timeline.as_ref()?.style_segments.get(index)?).ok()
+ }
+
+ pub(crate) fn selected_style_index(&self) -> Option<usize> {
+ self.sidebar
+ .style_target
+ .map(|target| target.0)
+ .or_else(|| {
+ self.selection()
+ .filter(|selection| {
+ selection.track == TrackKind::Style && selection.indices.len() == 1
+ })
+ .map(|selection| selection.indices[0])
+ })
+ }
+}
+
+#[cfg(test)]
+mod style_image_tests {
+ use super::*;
+
+ #[test]
+ fn style_image_group_changes_preserve_globals_and_require_opt_in() {
+ let mut project: ProjectConfiguration = serde_json::from_value(
+ serde_json::json!({"timeline":{"zoomSegments":[],"segments":[],"styleSegments":[{"start":1,"end":5}]}}),
+ )
+ .unwrap();
+ let base = serde_json::to_value(&project).unwrap();
+ assert!(!apply_style_control_change(
+ &mut project,
+ 0,
+ StyleGroup::Background,
+ |project| {
+ project.background.padding = 30.;
+ true
+ }
+ ));
+ assert_eq!(serde_json::to_value(&project).unwrap(), base);
+ let background = project.background.clone();
+ let camera = project.camera.clone();
+ let cursor = project.cursor.clone();
+ let segment = &mut project.timeline.as_mut().unwrap().style_segments[0];
+ segment.overrides.background = Some(background);
+ segment.overrides.camera = Some(camera);
+ segment.overrides.cursor = Some(cursor);
+ assert!(apply_style_control_change(
+ &mut project,
+ 0,
+ StyleGroup::Background,
+ |project| {
+ project.background.padding = 30.;
+ project.camera.hide = true;
+ true
+ }
+ ));
+ assert!(apply_style_control_change(
+ &mut project,
+ 0,
+ StyleGroup::Camera,
+ |project| {
+ project.camera.hide = true;
+ true
+ }
+ ));
+ for enabled in [true, false] {
+ assert!(apply_style_control_change(
+ &mut project,
+ 0,
+ StyleGroup::Cursor,
+ |project| {
+ project.cursor.ripple.enabled = enabled;
+ true
+ }
+ ));
+ }
+ let after = serde_json::to_value(&project).unwrap();
+ for group in ["background", "camera", "cursor"] {
+ assert_eq!(after[group], base[group]);
+ }
+ let segment = &project.timeline.as_ref().unwrap().style_segments[0];
+ assert_eq!(segment.overrides.background.as_ref().unwrap().padding, 30.);
+ assert!(segment.overrides.camera.as_ref().unwrap().hide);
+ assert!(!segment.overrides.cursor.as_ref().unwrap().ripple.enabled);
+ }
+}
diff --cc apps/desktop-gpui/src/editor_sidebar/animated_gradient.rs
index 937c8aa3b,ffda5323b..a450e8603
--- a/apps/desktop-gpui/src/editor_sidebar/animated_gradient.rs
+++ b/apps/desktop-gpui/src/editor_sidebar/animated_gradient.rs
@@@ -313,35 -313,35 +313,37 @@@ fn header_button
) -> gpui::Stateful<gpui::Div> {
let theme = *theme;
let foreground = Hsla::from(if pressed {
-- theme.gray_12
++ theme.editor.text_1
} else {
-- theme.gray_11
++ theme.editor.text_2
});
div()
.id(id)
.flex()
.items_center()
.gap(px(4.))
-- .h(px(28.))
-- .px(px(8.))
++ .h(px(22.))
++ .px(px(6.))
.rounded(px(6.))
.text_size(px(12.))
++ .font_weight(FontWeight::MEDIUM)
.text_color(foreground)
-- .when(pressed, |this| this.bg(Hsla::from(theme.gray_3)))
++ .when(pressed, |this| this.bg(Hsla::from(theme.editor.ctl_hover)))
.when(disabled, |this| this.opacity(0.4))
.when(!disabled, |this| {
this.cursor_pointer()
.hover(|this| {
-- this.bg(Hsla::from(theme.gray_3))
-- .text_color(Hsla::from(theme.gray_12))
++ this.bg(Hsla::from(theme.editor.ctl_hover))
++ .text_color(Hsla::from(theme.editor.text_1))
})
++ .active(|this| this.bg(Hsla::from(theme.editor.ctl_active)))
.on_click(on_click)
})
.tooltip(move |_window, cx| ui::Tooltip::new(&theme, tooltip).view(cx))
.child(
svg()
.path(icon)
-- .size(px(14.))
++ .size(px(12.))
.flex_shrink_0()
.text_color(foreground),
)
@@@ -362,15 -362,15 +364,15 @@@ fn icon_button
.flex()
.items_center()
.justify_center()
-- .size(px(26.))
++ .size(px(22.))
.rounded(px(6.))
-- .text_color(Hsla::from(theme.gray_10))
++ .text_color(Hsla::from(theme.editor.text_2))
.when(disabled, |this| this.opacity(0.3))
.when(!disabled, |this| {
this.cursor_pointer()
.hover(|this| {
-- this.bg(Hsla::from(theme.gray_3))
-- .text_color(Hsla::from(theme.gray_12))
++ this.bg(Hsla::from(theme.editor.ctl_hover))
++ .text_color(Hsla::from(theme.editor.text_1))
})
.on_click(on_click)
})
@@@ -378,8 -378,8 +380,8 @@@
.child(
svg()
.path(icon)
-- .size(px(14.))
-- .text_color(Hsla::from(theme.gray_10)),
++ .size(px(12.))
++ .text_color(Hsla::from(theme.editor.text_2)),
)
}
@@@ -718,14 -718,14 +720,6 @@@ impl EditorWindow
cx.notify();
}
-- pub(super) fn render_animated_gradient_icon(&self) -> AnyElement {
-- let config = self.animated_gradient_config().cloned().unwrap_or_default();
-- div()
-- .size(px(14.))
-- .child(palette(&config, px(3.)))
-- .into_any_element()
-- }
--
pub(super) fn render_animated_gradient_pane(&self, cx: &mut Context<Self>) -> AnyElement {
let Some(config) = self.animated_gradient_config() else {
return div().into_any_element();
@@@ -749,11 -749,11 +743,11 @@@
.child(error)
}))
.child(self.render_animated_gradient_presets(cx))
-- .child(dashed_divider(Hsla::from(theme.gray_5)))
++ .child(dashed_divider(Hsla::from(theme.editor.line)))
.child(self.render_animated_gradient_colours(config, cx))
-- .child(dashed_divider(Hsla::from(theme.gray_5)))
++ .child(dashed_divider(Hsla::from(theme.editor.line)))
.child(self.render_animated_gradient_motion(config, cx))
-- .child(dashed_divider(Hsla::from(theme.gray_5)))
++ .child(dashed_divider(Hsla::from(theme.editor.line)))
.child(self.render_animated_gradient_fine_tune(config, cx))
.into_any_element()
}
@@@ -772,18 -772,18 +766,18 @@@
.justify_center()
.size(px(cell))
.rounded(px(8.))
-- .bg(Hsla::from(theme.gray_2))
++ .bg(Hsla::from(theme.editor.ctl))
.border_1()
-- .border_color(Hsla::from(theme.gray_8))
-- .text_color(Hsla::from(theme.gray_10))
++ .border_color(Hsla::from(theme.editor.line_strong))
++ .text_color(Hsla::from(theme.editor.text_3))
.cursor_pointer()
-- .hover(|this| this.opacity(0.8))
++ .hover(|this| this.bg(Hsla::from(theme.editor.ctl_hover)))
.tooltip(move |_window, cx| ui::Tooltip::new(&theme, "Randomize").view(cx))
.child(
svg()
.path("icons/shuffle.svg")
-- .size(px(16.))
-- .text_color(Hsla::from(theme.gray_10)),
++ .size(px(14.))
++ .text_color(Hsla::from(theme.editor.text_3)),
)
.on_click(cx.listener(|this, _, window, cx| {
this.select_animated_gradient(AnimatedGradientConfig::random(), window, cx);
@@@ -855,7 -855,7 +849,7 @@@
.into_any_element()
});
-- ui::Field::plain(&theme, "Presets")
++ ui::Field::section(&theme, "Presets")
.value(
header_button(
&theme,
@@@ -887,7 -887,7 +881,7 @@@
this.child(
div()
.text_size(px(11.))
-- .text_color(Hsla::from(theme.gray_10))
++ .text_color(Hsla::from(theme.editor.text_3))
.child("Saved"),
)
.child(swatch_rows(saved))
@@@ -913,12 -913,12 +907,9 @@@
.size_full()
.rounded(px(8.))
.cursor_pointer()
-- .when(selected, |this| {
-- this.border_2()
-- .border_color(Hsla::from(theme.gray_500_legacy))
-- })
++ .selection_ring(Hsla::from(theme.editor.card), theme.editor.accent, selected)
.when(!selected, |this| this.hover(|this| this.opacity(0.8)))
-- .child(palette(&config, px(if selected { 6. } else { 8. })))
++ .child(palette(&config, px(6.)))
.tooltip(move |_window, cx| ui::Tooltip::new(&theme, name.clone()).view(cx))
.on_click(cx.listener(move |this, _, window, cx| {
this.select_animated_gradient(config.clone(), window, cx);
@@@ -1036,7 -1036,7 +1027,7 @@@
.inset_0()
.rounded(px(8.))
.border_1()
-- .border_color(Hsla::from(theme.gray_5))
++ .border_color(Hsla::from(theme.editor.line))
.child(
canvas(
move |bounds, _window, _cx| {
@@@ -1089,7 -1089,7 +1080,7 @@@
))
});
-- ui::Field::plain(&theme, "Colours")
++ ui::Field::section(&theme, "Colours")
.value(
header_button(
&theme,
@@@ -1124,30 -1124,30 +1115,13 @@@
let theme = self.theme;
let control = AnimatedGradientParameter::MotionSpeed.control();
let value = AnimatedGradientParameter::MotionSpeed.get(config);
-- ui::Subfield::plain(&theme, "Motion")
-- .gap(px(16.))
-- .child(
-- div()
-- .flex()
-- .flex_1()
-- .min_w_0()
-- .items_center()
-- .gap(px(12.))
-- .child(self.slider_flex(
-- SliderKey::AnimatedGradient(AnimatedGradientParameter::MotionSpeed),
-- slider_unit(AnimatedGradientParameter::MotionSpeed),
-- cx,
-- ))
-- .child(
-- div()
-- .w(px(40.))
-- .flex_shrink_0()
-- .text_right()
-- .text_size(px(12.))
-- .text_color(Hsla::from(theme.gray_11))
-- .child(format_control_value(&control, value)),
-- ),
-- )
++ ui::Field::inline(&theme, "Motion")
++ .value_text(format_control_value(&control, value))
++ .child(self.slider_flex(
++ SliderKey::AnimatedGradient(AnimatedGradientParameter::MotionSpeed),
++ slider_unit(AnimatedGradientParameter::MotionSpeed),
++ cx,
++ ))
.into_any_element()
}
@@@ -1184,33 -1184,33 +1158,13 @@@
.iter()
.map(|control| {
let value = control.key.get(config);
-- div()
-- .flex()
-- .items_center()
-- .gap(px(12.))
-- .child(
-- div()
-- .w(px(96.))
-- .flex_shrink_0()
-- .truncate()
-- .text_size(px(12.))
-- .text_color(Hsla::from(theme.gray_11))
-- .child(control.label.clone()),
-- )
++ ui::Field::inline(&theme, control.label.clone())
++ .value_text(format_control_value(control, value))
.child(self.slider_flex(
SliderKey::AnimatedGradient(control.key),
slider_unit(control.key),
cx,
))
-- .child(
-- div()
-- .w(px(40.))
-- .flex_shrink_0()
-- .text_right()
-- .text_size(px(12.))
-- .text_color(Hsla::from(theme.gray_11))
-- .child(format_control_value(control, value)),
-- )
.into_any_element()
})
.collect::<Vec<_>>();
@@@ -1222,33 -1222,33 +1176,16 @@@
div()
.flex()
.items_center()
-- .child(
-- div()
-- .id("animated-gradient-fine-tune")
-- .flex()
-- .flex_1()
-- .items_center()
-- .gap(px(6.))
-- .text_size(px(14.))
-- .font_weight(FontWeight::MEDIUM)
-- .text_color(Hsla::from(theme.gray_12))
-- .cursor_pointer()
-- .child("Fine-tune")
-- .child(
-- svg()
-- .path(if open {
-- "icons/chevron-up.svg"
-- } else {
-- "icons/chevron-down.svg"
-- })
-- .size(px(14.))
-- .text_color(Hsla::from(theme.gray_10)),
-- )
-- .on_click(cx.listener(|this, _, window, cx| {
-- this.sidebar.animated_gradient.fine_tune_open.toggle();
-- this.animate_collapsibles(window, cx);
-- })),
-- )
++ .child(div().flex().flex_1().child(disclosure_row(
++ &theme,
++ "animated-gradient-fine-tune",
++ "Fine-tune",
++ open,
++ cx.listener(|this, _, window, cx| {
++ this.sidebar.animated_gradient.fine_tune_open.toggle();
++ this.animate_collapsibles(window, cx);
++ }),
++ )))
.when(open, |this| {
this.child(header_button(
&theme,
diff --cc apps/desktop-gpui/src/editor_sidebar/cursor.rs
index 151c63492,b7bbd66fc..45ed9769b
--- a/apps/desktop-gpui/src/editor_sidebar/cursor.rs
+++ b/apps/desktop-gpui/src/editor_sidebar/cursor.rs
@@@ -304,30 -303,30 +304,27 @@@ impl EditorWindow
.flex()
.flex_col()
.child(
-- ui::Field::plain(&theme, "Click Ripple")
-- .icon("icons/mouse-pointer-click.svg")
-- .value(
-- ui::Toggle::plain(&theme, "cursor-ripple", enabled)
-- .on_click(cx.listener(move |this, _, window, cx| {
- let next = !this.style_control_project().cursor.ripple.enabled;
- let next = !this.project.cursor.ripple.enabled;
-- this.sidebar.cursor_ripple_open.set_open(next);
-- this.animate_collapsibles(window, cx);
-- this.edit_project("cursor-ripple", window, cx, move |project| {
-- project.cursor.ripple.enabled = next;
-- true
-- });
-- }))
-- .into_any_element(),
-- ),
++ ui::Field::inline(&theme, "Click Ripple").value(
++ ui::Toggle::plain(&theme, "cursor-ripple", enabled)
++ .on_click(cx.listener(move |this, _, window, cx| {
++ let next = !this.style_control_project().cursor.ripple.enabled;
++ this.sidebar.cursor_ripple_open.set_open(next);
++ this.animate_collapsibles(window, cx);
++ this.edit_project("cursor-ripple", window, cx, move |project| {
++ project.cursor.ripple.enabled = next;
++ true
++ });
++ }))
++ .into_any_element(),
++ ),
)
.child(collapsible(
&self.sidebar.cursor_ripple_open,
div()
.flex()
.flex_col()
-- .gap(px(16.))
-- .pt(px(16.))
-- .pb(px(24.))
++ .pt(px(4.))
++ .pb(px(8.))
.child(
ui::Subfield::plain(&theme, "Color").child(self.render_rgb_input(
"cursor-ripple-color",
@@@ -336,21 -335,21 +333,24 @@@
cx,
)),
)
-- .child(ui::Field::plain(&theme, "Strength").child(self.slider(
++ .child(self.slider_field(
++ "Strength",
SliderKey::Cursor(CursorSlider::RippleStrength),
"%",
cx,
-- )))
-- .child(ui::Field::plain(&theme, "Size").child(self.slider(
++ ))
++ .child(self.slider_field(
++ "Size",
SliderKey::Cursor(CursorSlider::RippleSize),
"%",
cx,
-- )))
-- .child(ui::Field::plain(&theme, "Duration").child(self.slider(
++ ))
++ .child(self.slider_field(
++ "Duration",
SliderKey::Cursor(CursorSlider::RippleDuration),
"secs",
cx,
-- )))
++ ))
.into_any_element(),
))
.into_any_element()
diff --cc apps/desktop-gpui/src/editor_tabs.rs
index 4d4a81c2d,cd65197d8..1b0c606da
--- a/apps/desktop-gpui/src/editor_tabs.rs
+++ b/apps/desktop-gpui/src/editor_tabs.rs
@@@ -754,7 -763,7 +764,7 @@@ impl EditorWindow
let kind = menu.kind;
let items = self.sidebar_menu_items(kind);
Some(
-- ui::Menu::plain(&self.theme, "sidebar-menu", items, &menu.state)
++ ui::Menu::editor(&self.theme, "sidebar-menu", items, &menu.state)
.on_select(cx.listener(move |this, index: &usize, window, cx| {
this.choose_sidebar_menu(kind, *index, window, cx);
}))
@@@ -1135,20 -1144,20 +1145,18 @@@ impl EditorWindow
/// `flex flex-col gap-2` pair the caption and keyboard tabs stack every
/// row in.
fn labelled(&self, label: &'static str, control: AnyElement) -> AnyElement {
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(8.))
-- .child(
-- div()
-- .text_size(px(14.))
-- .text_color(Hsla::from(self.theme.gray_11))
-- .child(label),
-- )
++ ui::Field::stacked(&self.theme, label)
.child(control)
.into_any_element()
}
++ /// The same pair on one row, for a control that fits beside its label.
++ fn labelled_inline(&self, label: &'static str, control: AnyElement) -> AnyElement {
++ ui::Field::inline(&self.theme, label)
++ .child(div().w(px(180.)).child(control))
++ .into_any_element()
++ }
++
/// The same pair at `text-xs`, which is what the segment panels and the
/// text tab use.
pub(crate) fn labelled_small(&self, label: &'static str, control: AnyElement) -> AnyElement {
@@@ -1159,7 -1168,7 +1167,7 @@@
.child(
div()
.text_size(px(12.))
-- .text_color(Hsla::from(self.theme.gray_11))
++ .text_color(Hsla::from(self.theme.editor.text_2))
.child(label),
)
.child(control)
@@@ -1228,68 -1237,68 +1236,63 @@@
div()
.flex()
.flex_col()
-- .gap(px(24.))
++ .gap(px(14.))
.child(
-- ui::Field::plain(&theme, "Camera")
-- .icon("icons/camera.svg")
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(24.))
-- .child(self.render_camera_position(cx))
-- .child(ui::Subfield::plain(&theme, "Hide Camera").child(
-- ui::Toggle::plain(&theme, "camera-hide", camera.hide).on_click(
-- cx.listener(|this, _, window, cx| {
- let next = !this.style_control_project().camera.hide;
- let next = !this.project.camera.hide;
-- this.edit_project("camera-hide", window, cx, move |p| {
-- p.camera.hide = next;
-- true
-- });
-- }),
-- ),
-- ))
-- .child(ui::Subfield::plain(&theme, "Mirror Camera").child(
-- ui::Toggle::plain(&theme, "camera-mirror", camera.mirror).on_click(
-- cx.listener(|this, _, window, cx| {
- let next = !this.style_control_project().camera.mirror;
- let next = !this.project.camera.mirror;
-- this.edit_project("camera-mirror", window, cx, move |p| {
-- p.camera.mirror = next;
-- true
-- });
-- }),
-- ),
-- ))
-- .child(ui::Subfield::plain(&theme, "Background Blur").child(
-- div().w(px(160.)).child(self.menu_select(
-- SidebarMenu::CameraBlur,
-- "camera-blur",
-- blur_label,
-- cx,
-- )),
-- ))
-- .child(ui::Subfield::plain(&theme, "Shape").child(
-- div().w(px(160.)).child(self.menu_select(
-- SidebarMenu::CameraShape,
-- "camera-shape",
-- shape_label,
-- cx,
-- )),
++ ui::Field::section(&theme, "Camera").child(
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(14.))
++ .child(self.render_camera_position(cx))
++ .child(ui::Subfield::plain(&theme, "Hide Camera").child(
++ ui::Toggle::plain(&theme, "camera-hide", camera.hide).on_click(
++ cx.listener(|this, _, window, cx| {
++ let next = !this.style_control_project().camera.hide;
++ this.edit_project("camera-hide", window, cx, move |p| {
++ p.camera.hide = next;
++ true
++ });
++ }),
++ ),
++ ))
++ .child(ui::Subfield::plain(&theme, "Mirror Camera").child(
++ ui::Toggle::plain(&theme, "camera-mirror", camera.mirror).on_click(
++ cx.listener(|this, _, window, cx| {
++ let next = !this.style_control_project().camera.mirror;
++ this.edit_project("camera-mirror", window, cx, move |p| {
++ p.camera.mirror = next;
++ true
++ });
++ }),
++ ),
++ ))
++ .child(ui::Subfield::plain(&theme, "Background Blur").child(
++ div().w(px(160.)).child(self.menu_select(
++ SidebarMenu::CameraBlur,
++ "camera-blur",
++ blur_label,
++ cx,
)),
-- ),
++ ))
++ .child(ui::Subfield::plain(&theme, "Shape").child(
++ div().w(px(160.)).child(self.menu_select(
++ SidebarMenu::CameraShape,
++ "camera-shape",
++ shape_label,
++ cx,
++ )),
++ )),
++ ),
)
// `<div class="w-full border-t border-dashed border-gray-5" />`
-- .child(dashed_divider(Hsla::from(theme.gray_5)))
-- .child(
-- ui::Field::plain(&theme, "Size")
-- .icon("icons/enlarge.svg")
-- .child(self.slider(SliderKey::Camera(CameraSlider::Size), "%", cx)),
-- )
-- .child(
-- ui::Field::plain(&theme, "Size During Zoom")
-- .icon("icons/enlarge.svg")
-- .child(self.slider(SliderKey::Camera(CameraSlider::ZoomSize), "%", cx)),
-- )
++ .child(dashed_divider(Hsla::from(theme.editor.line)))
++ .child(self.slider_field("Size", SliderKey::Camera(CameraSlider::Size), "%", cx))
++ .child(self.slider_field(
++ "Size During Zoom",
++ SliderKey::Camera(CameraSlider::ZoomSize),
++ "%",
++ cx,
++ ))
.child(
ui::Subfield::plain(&theme, "Keep original size during zoom").child(
ui::Toggle::plain(&theme, "camera-keep-size", camera.scale_during_zoom >= 1.)
@@@ -1309,26 -1318,26 +1312,32 @@@
),
)
.child(
-- ui::Field::plain(&theme, "Rounded Corners")
-- .icon("icons/corners.svg")
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(12.))
-- .child(self.slider(SliderKey::Camera(CameraSlider::Rounding), "%", cx))
-- .child(self.corner_style_select(
-- SidebarMenu::CameraCornerStyle,
-- "camera-corner-style",
-- corner_label,
-- cx,
-- )),
-- ),
++ div()
++ .flex()
++ .flex_col()
++ .child(self.slider_field(
++ "Rounded Corners",
++ SliderKey::Camera(CameraSlider::Rounding),
++ "%",
++ cx,
++ ))
++ .child(self.corner_style_select(
++ SidebarMenu::CameraCornerStyle,
++ "camera-corner-style",
++ corner_label,
++ cx,
++ )),
)
.child(
-- ui::Field::plain(&theme, "Shadow")
-- .icon("icons/shadow.svg")
-- .child(self.slider(SliderKey::Camera(CameraSlider::Shadow), "%", cx))
++ div()
++ .flex()
++ .flex_col()
++ .child(self.slider_field(
++ "Shadow",
++ SliderKey::Camera(CameraSlider::Shadow),
++ "%",
++ cx,
++ ))
.child(self.render_camera_shadow_settings(cx)),
)
// `<ColorCorrectionSection target="camera" />` (`:3324`).
@@@ -1367,8 -1371,8 +1376,7 @@@
.into_any_element()
}
-- /// `CornerStyleSelect` (`:3331-3396`): a `text-[0.65rem] uppercase` label
-- /// over the trigger.
++ /// `CornerStyleSelect` (`:3331-3396`), now an inline row.
fn corner_style_select(
&self,
kind: SidebarMenu,
@@@ -1376,17 -1380,17 +1384,12 @@@
label: &'static str,
cx: &mut Context<Self>,
) -> AnyElement {
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(6.))
++ ui::Field::inline(&self.theme, "Corner Style")
.child(
div()
-- .text_size(px(10.4))
-- .text_color(Hsla::from(self.theme.gray_11))
-- .child("CORNER STYLE"),
++ .w(px(150.))
++ .child(self.menu_select(kind, id, label, cx)),
)
-- .child(self.menu_select(kind, id, label, cx))
.into_any_element()
}
@@@ -1419,7 -1423,7 +1422,7 @@@
.h(px(120.))
.rounded(px(8.))
.border_1()
-- .border_color(Hsla::from(theme.gray_3))
++ .border_color(Hsla::from(theme.editor.line))
.bg(Hsla::from(theme.gray_2));
for (item_x, item_y) in dots {
@@@ -1493,54 -1497,54 +1496,40 @@@
div()
.flex()
.flex_col()
-- .child(
-- div()
-- .id("camera-shadow-advanced")
-- .flex()
-- .flex_row()
-- .items_center()
-- .gap(px(4.))
-- .font_weight(FontWeight::MEDIUM)
-- .text_color(Hsla::from(theme.gray_12))
-- .cursor_pointer()
-- .child(div().text_size(px(14.)).child("Advanced shadow settings"))
-- .child(
-- svg()
-- .path(if open {
-- "icons/chevron-down.svg"
-- } else {
-- "icons/chevron-right.svg"
-- })
-- .size(px(20.))
-- .text_color(Hsla::from(theme.gray_12)),
-- )
-- .on_click(cx.listener(|this, _, window, cx| {
-- this.sidebar.camera_shadow_open.toggle();
-- this.animate_collapsibles(window, cx);
-- })),
-- )
++ .child(crate::editor_sidebar::disclosure_row(
++ &theme,
++ "camera-shadow-advanced",
++ "Advanced shadow settings",
++ open,
++ cx.listener(|this, _, window, cx| {
++ this.sidebar.camera_shadow_open.toggle();
++ this.animate_collapsibles(window, cx);
++ }),
++ ))
.child(collapsible(
&self.sidebar.camera_shadow_open,
div()
.flex()
.flex_col()
-- .gap(px(24.))
-- .mt(px(16.))
-- .child(ui::Field::plain(&theme, "Size").child(self.slider(
++ .pt(px(4.))
++ .child(self.slider_field(
++ "Size",
SliderKey::Camera(CameraSlider::ShadowSize),
"",
cx,
-- )))
-- .child(ui::Field::plain(&theme, "Opacity").child(self.slider(
++ ))
++ .child(self.slider_field(
++ "Opacity",
SliderKey::Camera(CameraSlider::ShadowOpacity),
"",
cx,
-- )))
-- .child(ui::Field::plain(&theme, "Blur").child(self.slider(
++ ))
++ .child(self.slider_field(
++ "Blur",
SliderKey::Camera(CameraSlider::ShadowBlur),
"",
cx,
-- )))
++ ))
.into_any_element(),
))
.into_any_element()
@@@ -1565,63 -1569,63 +1554,57 @@@
div()
.flex()
.flex_col()
-- .gap(px(24.))
++ .gap(px(14.))
.child(
-- ui::Field::plain(&theme, "Audio Controls")
-- .icon("icons/volume-2.svg")
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(16.))
-- .child(ui::Subfield::plain(&theme, "Mute Audio").child(
-- ui::Toggle::plain(&theme, "audio-mute", audio.mute).on_click(
-- cx.listener(|this, _, window, cx| {
-- let next = !this.project.audio.mute;
-- this.edit_project("audio-mute", window, cx, move |p| {
-- p.audio.mute = next;
-- true
-- });
-- }),
-- ),
-- ))
-- // Only a two-channel microphone gets the stereo row
-- // (`:709-711`).
-- .children(stereo_mic.then(|| {
-- ui::Subfield::plain(&theme, "Microphone Stereo Mode")
-- .child(div().w(px(160.)).child(self.menu_select(
-- SidebarMenu::AudioStereo,
-- "audio-stereo",
-- stereo_label,
-- cx,
-- )))
-- .into_any_element()
-- })),
-- ),
++ ui::Field::section(&theme, "Audio Controls").child(
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(16.))
++ .child(ui::Subfield::plain(&theme, "Mute Audio").child(
++ ui::Toggle::plain(&theme, "audio-mute", audio.mute).on_click(
++ cx.listener(|this, _, window, cx| {
++ let next = !this.project.audio.mute;
++ this.edit_project("audio-mute", window, cx, move |p| {
++ p.audio.mute = next;
++ true
++ });
++ }),
++ ),
++ ))
++ // Only a two-channel microphone gets the stereo row
++ // (`:709-711`).
++ .children(stereo_mic.then(|| {
++ ui::Subfield::plain(&theme, "Microphone Stereo Mode")
++ .child(div().w(px(160.)).child(self.menu_select(
++ SidebarMenu::AudioStereo,
++ "audio-stereo",
++ stereo_label,
++ cx,
++ )))
++ .into_any_element()
++ })),
++ ),
)
.children(has_microphone.then(|| {
-- ui::Field::plain(&theme, "Microphone Volume")
-- .icon("icons/microphone.svg")
-- // `disabled={project.audio.mute}` (`:786`).
-- .child(self.slider_disabled(
-- SliderKey::Audio(AudioSlider::MicVolume),
-- "db",
-- muted,
-- cx,
-- ))
-- .into_any_element()
++ self.slider_field_disabled(
++ "Microphone Volume",
++ SliderKey::Audio(AudioSlider::MicVolume),
++ "db",
++ muted,
++ cx,
++ )
++ .into_any_element()
}))
.children(has_system_audio.then(|| {
-- ui::Field::plain(&theme, "System Audio Volume")
-- .icon("icons/monitor-outline.svg")
-- // `disabled={project.audio.mute}` (`:804`).
-- .child(self.slider_disabled(
-- SliderKey::Audio(AudioSlider::SystemVolume),
-- "db",
-- muted,
-- cx,
-- ))
-- .into_any_element()
++ self.slider_field_disabled(
++ "System Audio Volume",
++ SliderKey::Audio(AudioSlider::SystemVolume),
++ "db",
++ muted,
++ cx,
++ )
++ .into_any_element()
}))
.children(self.render_sync_offsets(cx))
.into_any_element()
@@@ -1635,8 -1639,8 +1618,8 @@@
let cursor = &self.project.cursor;
let hidden = cursor.hide;
-- let mut body = div().flex().flex_col().gap(px(24.)).child(
-- ui::Field::plain(&theme, "Show cursor").value(
++ let mut body = div().flex().flex_col().gap(px(14.)).child(
++ ui::Field::inline(&theme, "Show cursor").value(
ui::Toggle::plain(&theme, "cursor-show", !hidden)
.on_click(cx.listener(move |this, _, window, cx| {
this.edit_project("cursor-hide", window, cx, move |p| {
@@@ -1660,34 -1664,34 +1643,23 @@@
body = body
.child(
-- ui::Field::plain(&theme, "Cursor Style")
-- .icon("icons/cursor.svg")
++ ui::Field::stacked(&theme, "Cursor Style")
.child(self.render_cursor_style_picker(cx)),
)
-- .child(
-- ui::Field::plain(&theme, "Size")
-- .icon("icons/enlarge.svg")
-- .child(self.slider(SliderKey::Cursor(CursorSlider::Size), "", cx)),
-- )
-- .child(
-- ui::Field::plain(&theme, "Tilt")
-- .icon("icons/rotate-3d.svg")
-- .child(self.slider(SliderKey::Cursor(CursorSlider::Tilt), "x100%", cx)),
-- )
++ .child(self.slider_field("Size", SliderKey::Cursor(CursorSlider::Size), "", cx))
++ .child(self.slider_field("Tilt", SliderKey::Cursor(CursorSlider::Tilt), "x100%", cx))
.child(self.render_cursor_ripple(cx))
.child(
-- ui::Field::plain(&theme, "Hide When Idle")
-- .icon("icons/timer.svg")
-- .value(
-- ui::Toggle::plain(&theme, "cursor-idle", idle)
-- .on_click(cx.listener(move |this, _, window, cx| {
-- this.edit_project("cursor-idle", window, cx, move |p| {
-- p.cursor.hide_when_idle = !idle;
-- true
-- });
-- }))
-- .into_any_element(),
-- ),
++ ui::Field::inline(&theme, "Hide When Idle").value(
++ ui::Toggle::plain(&theme, "cursor-idle", idle)
++ .on_click(cx.listener(move |this, _, window, cx| {
++ this.edit_project("cursor-idle", window, cx, move |p| {
++ p.cursor.hide_when_idle = !idle;
++ true
++ });
++ }))
++ .into_any_element(),
++ ),
);
if idle {
@@@ -1723,85 -1727,85 +1695,83 @@@
let smooth = !cursor.raw;
let mut body = body
.child(
-- ui::Field::plain(&theme, "Cursor Movement Style")
-- .icon("icons/rabbit.svg")
-- .child(
-- ui::RadioCards::plain(
-- &theme,
-- "cursor-style",
-- CURSOR_STYLES
-- .iter()
-- .map(|(_, label, description)| {
-- ui::RadioCard::new(*label, Some(description))
-- })
-- .collect(),
-- style_index,
-- )
-- .on_select(cx.listener(
-- |this, index: &usize, window, cx| {
-- let Some((style, _, _)) = CURSOR_STYLES.get(*index) else {
-- return;
-- };
-- let style = *style;
-- // `applyCursorStylePreset` (`:551-561`): the style and
-- // its three physics values, in one batch.
-- this.edit_project("cursor-style", window, cx, move |project| {
-- project.cursor.animation_style = style;
-- if let Some(preset) = style.preset() {
-- project.cursor.tension = preset.tension;
-- project.cursor.mass = preset.mass;
-- project.cursor.friction = preset.friction;
-- }
-- true
-- });
-- },
-- )),
-- ),
++ ui::Field::section(&theme, "Cursor Movement Style").child(
++ ui::RadioCards::plain(
++ &theme,
++ "cursor-style",
++ CURSOR_STYLES
++ .iter()
++ .map(|(_, label, description)| {
++ ui::RadioCard::new(*label, Some(description))
++ })
++ .collect(),
++ style_index,
++ )
++ .on_select(cx.listener(
++ |this, index: &usize, window, cx| {
++ let Some((style, _, _)) = CURSOR_STYLES.get(*index) else {
++ return;
++ };
++ let style = *style;
++ // `applyCursorStylePreset` (`:551-561`): the style and
++ // its three physics values, in one batch.
++ this.edit_project("cursor-style", window, cx, move |project| {
++ project.cursor.animation_style = style;
++ if let Some(preset) = style.preset() {
++ project.cursor.tension = preset.tension;
++ project.cursor.mass = preset.mass;
++ project.cursor.friction = preset.friction;
++ }
++ true
++ });
++ },
++ )),
++ ),
)
.child(
div()
.flex()
.flex_col()
.child(
-- ui::Field::plain(&theme, "Smooth Movement")
-- .icon("icons/ease-curve.svg")
-- .value(
-- ui::Toggle::plain(&theme, "cursor-smooth", smooth)
-- .on_click(cx.listener(move |this, _, window, cx| {
-- this.sidebar.cursor_physics_open.set_open(!smooth);
-- this.animate_collapsibles(window, cx);
-- this.edit_project("cursor-raw", window, cx, move |p| {
-- p.cursor.raw = smooth;
-- true
-- });
-- }))
-- .into_any_element(),
-- ),
++ ui::Field::inline(&theme, "Smooth Movement").value(
++ ui::Toggle::plain(&theme, "cursor-smooth", smooth)
++ .on_click(cx.listener(move |this, _, window, cx| {
++ this.sidebar.cursor_physics_open.set_open(!smooth);
++ this.animate_collapsibles(window, cx);
++ this.edit_project("cursor-raw", window, cx, move |p| {
++ p.cursor.raw = smooth;
++ true
++ });
++ }))
++ .into_any_element(),
++ ),
)
.child(collapsible(
&self.sidebar.cursor_physics_open,
div()
.flex()
.flex_col()
-- .gap(px(16.))
// `pt-4 pb-6`
-- .pt(px(16.))
-- .pb(px(24.))
-- .child(ui::Field::plain(&theme, "Tension").child(self.slider(
++ .pt(px(4.))
++ .pb(px(8.))
++ .child(self.slider_field(
++ "Tension",
SliderKey::Cursor(CursorSlider::Tension),
"",
cx,
-- )))
-- .child(ui::Field::plain(&theme, "Friction").child(self.slider(
++ ))
++ .child(self.slider_field(
++ "Friction",
SliderKey::Cursor(CursorSlider::Friction),
"",
cx,
-- )))
-- .child(ui::Field::plain(&theme, "Mass").child(self.slider(
++ ))
++ .child(self.slider_field(
++ "Mass",
SliderKey::Cursor(CursorSlider::Mass),
"",
cx,
-- )))
++ ))
.into_any_element(),
)),
);
@@@ -1810,19 -1814,19 +1780,17 @@@
// showing a setting the renderer is already overriding.
if cursor.cursor_type().family().is_none() {
body = body.child(
-- ui::Field::plain(&theme, "High Quality SVG Cursors")
-- .icon("icons/sparkles.svg")
-- .value(
-- ui::Toggle::plain(&theme, "cursor-svg", cursor.use_svg)
-- .on_click(cx.listener(|this, _, window, cx| {
- let next = !this.style_control_project().cursor.use_svg;
- let next = !this.project.cursor.use_svg;
-- this.edit_project("cursor-svg", window, cx, move |p| {
-- p.cursor.use_svg = next;
-- true
-- });
-- }))
-- .into_any_element(),
-- ),
++ ui::Field::inline(&theme, "High Quality SVG Cursors").value(
++ ui::Toggle::plain(&theme, "cursor-svg", cursor.use_svg)
++ .on_click(cx.listener(|this, _, window, cx| {
++ let next = !this.style_control_project().cursor.use_svg;
++ this.edit_project("cursor-svg", window, cx, move |p| {
++ p.cursor.use_svg = next;
++ true
++ });
++ }))
++ .into_any_element(),
++ ),
);
}
@@@ -1858,191 -1972,188 +1936,169 @@@
.gap(px(16.))
.when(!enabled, |this| this.opacity(0.5))
.child(
-- ui::Field::plain(&theme, "Font Settings")
-- .icon("icons/keyboard.svg")
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(12.))
-- .child(self.labelled(
-- "Font Family",
-- self.menu_select(
-- SidebarMenu::KeyboardFont,
-- "keyboard-font",
-- font_label,
-- cx,
-- ),
-- ))
-- .child(
-- self.labelled(
-- "Size",
-- self.slider(SliderKey::Keyboard(KeyboardSlider::Size), "", cx)
-- .into_any_element(),
-- ),
++ ui::Field::section(&theme, "Font Settings").child(
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(12.))
++ .child(self.labelled_inline(
++ "Font Family",
++ self.menu_select(
++ SidebarMenu::KeyboardFont,
++ "keyboard-font",
++ font_label,
++ cx,
++ ),
++ ))
++ .child(
++ self.slider_field(
++ "Size",
++ SliderKey::Keyboard(KeyboardSlider::Size),
++ "",
++ cx,
)
-- .child(self.labelled(
-- "Text Color",
-- self.render_hex_field(
-- crate::editor_panels::FieldKey::KeyboardColor,
-- &settings.color,
-- cx,
-- ),
-- )),
-- ),
++ .into_any_element(),
++ )
++ .child(self.labelled(
++ "Text Color",
++ self.render_hex_field(
++ crate::editor_panels::FieldKey::KeyboardColor,
++ &settings.color,
++ cx,
++ ),
++ )),
++ ),
)
.child(
-- ui::Field::plain(&theme, "Background Settings")
-- .icon("icons/keyboard.svg")
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(12.))
-- .child(self.labelled(
-- "Background Color",
-- self.render_hex_field(
-- crate::editor_panels::FieldKey::KeyboardBackground,
-- &settings.background_color,
-- cx,
-- ),
-- ))
-- .child(
-- self.labelled(
-- "Background Opacity",
-- self.slider(
-- SliderKey::Keyboard(KeyboardSlider::BackgroundOpacity),
-- "",
-- cx,
-- )
-- .into_any_element(),
-- ),
++ ui::Field::section(&theme, "Background Settings").child(
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(12.))
++ .child(self.labelled(
++ "Background Color",
++ self.render_hex_field(
++ crate::editor_panels::FieldKey::KeyboardBackground,
++ &settings.background_color,
++ cx,
),
-- ),
++ ))
++ .child(
++ self.slider_field(
++ "Background Opacity",
++ SliderKey::Keyboard(KeyboardSlider::BackgroundOpacity),
++ "",
++ cx,
++ )
++ .into_any_element(),
++ ),
++ ),
)
.child(
-- ui::Field::plain(&theme, "Position")
-- .icon("icons/keyboard.svg")
-- .child(self.menu_select(
-- SidebarMenu::KeyboardPosition,
-- "keyboard-position",
-- position_label,
-- cx,
-- )),
++ ui::Field::inline(&theme, "Position").child(self.menu_select(
++ SidebarMenu::KeyboardPosition,
++ "keyboard-position",
++ position_label,
++ cx,
++ )),
)
.child(
-- ui::Field::plain(&theme, "Font Weight")
-- .icon("icons/keyboard.svg")
-- .child(self.menu_select(
-- SidebarMenu::KeyboardWeight,
-- "keyboard-weight",
-- weight_label,
-- cx,
-- )),
++ ui::Field::inline(&theme, "Font Weight").child(self.menu_select(
++ SidebarMenu::KeyboardWeight,
++ "keyboard-weight",
++ weight_label,
++ cx,
++ )),
)
.child(
-- ui::Field::plain(&theme, "Animation")
-- .icon("icons/keyboard.svg")
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(12.))
-- .child(self.labelled_readout(
-- "Fade Duration",
-- SliderKey::Keyboard(KeyboardSlider::FadeDuration),
-- format!("{:.0}ms", settings.fade_duration * 1000.),
-- cx,
-- ))
-- .child(self.labelled_readout(
-- "Linger Duration",
-- SliderKey::Keyboard(KeyboardSlider::LingerDuration),
-- format!("{:.1}s", settings.linger_duration),
-- cx,
-- ))
-- .child(self.labelled_readout(
-- "Grouping Threshold",
-- SliderKey::Keyboard(KeyboardSlider::GroupingThreshold),
-- format!("{:.0}ms", settings.grouping_threshold_ms),
-- cx,
-- )),
-- ),
++ ui::Field::section(&theme, "Animation").child(
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(12.))
++ .child(self.labelled_readout(
++ "Fade Duration",
++ SliderKey::Keyboard(KeyboardSlider::FadeDuration),
++ format!("{:.0}ms", settings.fade_duration * 1000.),
++ cx,
++ ))
++ .child(self.labelled_readout(
++ "Linger Duration",
++ SliderKey::Keyboard(KeyboardSlider::LingerDuration),
++ format!("{:.1}s", settings.linger_duration),
++ cx,
++ ))
++ .child(self.labelled_readout(
++ "Grouping Threshold",
++ SliderKey::Keyboard(KeyboardSlider::GroupingThreshold),
++ format!("{:.0}ms", settings.grouping_threshold_ms),
++ cx,
++ )),
++ ),
)
.child(
-- ui::Field::plain(&theme, "Behavior")
-- .icon("icons/keyboard.svg")
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(12.))
-- .child(
-- ui::Subfield::plain(&theme, "Show Modifiers").child(
-- ui::Toggle::plain(
-- &theme,
-- "keyboard-modifiers",
-- settings.show_modifiers,
-- )
-- .on_click(cx.listener(
-- |this, _, window, cx| {
-- let next =
-- !keyboard_settings(&this.project).show_modifiers;
-- this.set_keyboard_setting(
-- "keyboard-modifiers",
-- window,
-- cx,
-- move |settings| settings.show_modifiers = next,
-- );
-- },
-- )),
-- ),
-- )
-- .child(
-- ui::Subfield::plain(&theme, "Show Special Keys").child(
-- ui::Toggle::plain(
-- &theme,
-- "keyboard-special",
-- settings.show_special_keys,
-- )
-- .on_click(cx.listener(
-- |this, _, window, cx| {
-- let next =
-- !keyboard_settings(&this.project).show_special_keys;
-- this.set_keyboard_setting(
-- "keyboard-special",
-- window,
-- cx,
-- move |settings| settings.show_special_keys = next,
-- );
-- },
-- )),
-- ),
-- )
-- .child(
-- ui::Subfield::plain(&theme, "Uppercase").child(
-- ui::Toggle::plain(
-- &theme,
-- "keyboard-uppercase",
-- settings.uppercase,
-- )
-- .on_click(cx.listener(
-- |this, _, window, cx| {
-- let next = !keyboard_settings(&this.project).uppercase;
-- this.set_keyboard_setting(
-- "keyboard-uppercase",
-- window,
-- cx,
-- move |settings| settings.uppercase = next,
-- );
-- },
-- )),
-- ),
++ ui::Field::section(&theme, "Behavior").child(
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(12.))
++ .child(
++ ui::Subfield::plain(&theme, "Show Modifiers").child(
++ ui::Toggle::plain(
++ &theme,
++ "keyboard-modifiers",
++ settings.show_modifiers,
++ )
++ .on_click(cx.listener(
++ |this, _, window, cx| {
++ let next = !keyboard_settings(&this.project).show_modifiers;
++ this.set_keyboard_setting(
++ "keyboard-modifiers",
++ window,
++ cx,
++ move |settings| settings.show_modifiers = next,
++ );
++ },
++ )),
),
-- ),
++ )
++ .child(
++ ui::Subfield::plain(&theme, "Show Special Keys").child(
++ ui::Toggle::plain(
++ &theme,
++ "keyboard-special",
++ settings.show_special_keys,
++ )
++ .on_click(cx.listener(
++ |this, _, window, cx| {
++ let next =
++ !keyboard_settings(&this.project).show_special_keys;
++ this.set_keyboard_setting(
++ "keyboard-special",
++ window,
++ cx,
++ move |settings| settings.show_special_keys = next,
++ );
++ },
++ )),
++ ),
++ )
++ .child(
++ ui::Subfield::plain(&theme, "Uppercase").child(
++ ui::Toggle::plain(&theme, "keyboard-uppercase", settings.uppercase)
++ .on_click(cx.listener(|this, _, window, cx| {
++ let next = !keyboard_settings(&this.project).uppercase;
++ this.set_keyboard_setting(
++ "keyboard-uppercase",
++ window,
++ cx,
++ move |settings| settings.uppercase = next,
++ );
++ })),
++ ),
++ ),
++ ),
)
- // `Generate Keyboard Segments` -- `commands.generateKeyboardSegments`
- // reads the recording's own key log through a Tauri command this
- // app does not have, so the button renders and says so.
.child(
div().pt(px(8.)).child(
ui::Button::plain(
@@@ -2087,7 -2210,7 +2155,7 @@@
// The whole tab is one `Field` with the master toggle in its header and
// a `Beta` badge (`KeyboardTab.tsx:128-135`).
-- ui::Field::plain(&theme, "Show keyboard")
++ ui::Field::section(&theme, "Show keyboard")
.badge("Beta")
.value(
ui::Toggle::plain(&theme, "keyboard-enabled", enabled)
@@@ -2123,25 -2246,25 +2191,9 @@@
readout: String,
cx: &mut Context<Self>,
) -> AnyElement {
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(8.))
-- .child(
-- div()
-- .text_size(px(14.))
-- .text_color(Hsla::from(self.theme.gray_11))
-- .child(label),
-- )
-- .child(self.slider(slider, "", cx))
-- .child(
-- div()
-- .w_full()
-- .text_size(px(12.))
-- .text_color(Hsla::from(self.theme.gray_11))
-- .text_right()
-- .child(readout),
-- )
++ ui::Field::inline(&self.theme, label)
++ .value_text(readout)
++ .child(self.slider_flex(slider, "", cx))
.into_any_element()
}
@@@ -2236,7 -2359,7 +2288,7 @@@
.rounded(px(8.))
.bg(self.panel_bg())
.border_1()
-- .border_color(Hsla::from(theme.gray_3))
++ .border_color(Hsla::from(theme.editor.line))
.child(
div()
.flex_1()
@@@ -2467,226 -2590,226 +2519,199 @@@
.gap(px(16.))
.when(!has_captions, |this| this.opacity(0.5))
.child(
-- ui::Field::plain(&theme, "Style")
-- .icon("icons/message-bubble.svg")
++ ui::Field::section(&theme, "Style")
.child(self.render_caption_presets(&settings, cx)),
)
.child(
-- ui::Field::plain(&theme, "Font Settings")
-- .icon("icons/message-bubble.svg")
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(12.))
-- .child(self.labelled(
-- "Font Family",
-- self.menu_select(
-- SidebarMenu::CaptionFont,
-- "caption-font",
-- font_label,
-- cx,
-- ),
-- ))
-- .child(
-- self.labelled(
-- "Size",
-- self.slider(SliderKey::Caption(CaptionSlider::Size), "", cx)
-- .into_any_element(),
-- ),
-- )
-- .child(
-- ui::Subfield::plain(&theme, "Uppercase").child(
-- ui::Toggle::plain(
-- &theme,
-- "caption-uppercase",
-- settings.uppercase,
-- )
-- .on_click(cx.listener(
-- |this, _, window, cx| {
-- let next = !caption_settings(&this.project).uppercase;
-- this.set_caption_setting(
-- "caption-uppercase",
-- window,
-- cx,
-- move |settings| settings.uppercase = next,
-- );
-- },
-- )),
-- ),
++ ui::Field::section(&theme, "Font Settings").child(
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(12.))
++ .child(self.labelled_inline(
++ "Font Family",
++ self.menu_select(
++ SidebarMenu::CaptionFont,
++ "caption-font",
++ font_label,
++ cx,
++ ),
++ ))
++ .child(
++ self.slider_field(
++ "Size",
++ SliderKey::Caption(CaptionSlider::Size),
++ "",
++ cx,
)
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(8.))
-- .child(
-- ui::Subfield::plain(&theme, "Active Word Highlight").child(
-- ui::Toggle::plain(
-- &theme,
-- "caption-active-word",
-- settings.active_word_highlight,
-- )
-- .on_click(
-- cx.listener(|this, _, window, cx| {
-- let next = !caption_settings(&this.project)
-- .active_word_highlight;
-- this.set_caption_setting(
-- "caption-active-word",
-- window,
-- cx,
-- move |settings| {
-- settings.active_word_highlight = next
-- },
-- );
-- }),
-- ),
++ .into_any_element(),
++ )
++ .child(
++ ui::Subfield::plain(&theme, "Uppercase").child(
++ ui::Toggle::plain(&theme, "caption-uppercase", settings.uppercase)
++ .on_click(cx.listener(|this, _, window, cx| {
++ let next = !caption_settings(&this.project).uppercase;
++ this.set_caption_setting(
++ "caption-uppercase",
++ window,
++ cx,
++ move |settings| settings.uppercase = next,
++ );
++ })),
++ ),
++ )
++ .child(
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(8.))
++ .child(
++ ui::Subfield::plain(&theme, "Active Word Highlight").child(
++ ui::Toggle::plain(
++ &theme,
++ "caption-active-word",
++ settings.active_word_highlight,
++ )
++ .on_click(
++ cx.listener(|this, _, window, cx| {
++ let next = !caption_settings(&this.project)
++ .active_word_highlight;
++ this.set_caption_setting(
++ "caption-active-word",
++ window,
++ cx,
++ move |settings| {
++ settings.active_word_highlight = next
++ },
++ );
++ }),
),
-- )
-- .child(
-- div()
-- .text_size(px(12.))
-- .text_color(Hsla::from(theme.gray_10))
-- .child(
-- "This is the first version of captions in Cap. \
++ ),
++ )
++ .child(
++ div()
++ .text_size(px(12.))
++ .text_color(Hsla::from(theme.gray_10))
++ .child(
++ "This is the first version of captions in Cap. \
Active word highlighting may be inaccurate in \
some situations. We're working on a fix for this \
and it will be released in upcoming versions.",
-- ),
-- ),
-- )
-- .children(settings.active_word_highlight.then(|| {
-- self.labelled(
-- "Highlight Style",
-- self.menu_select(
-- SidebarMenu::CaptionHighlightStyle,
-- "caption-highlight-style",
-- highlight_label,
-- cx,
-- ),
-- )
-- }))
-- .child(self.labelled(
-- "Text Color",
-- self.render_hex_field(
-- crate::editor_panels::FieldKey::CaptionColor,
-- &settings.color,
++ ),
++ ),
++ )
++ .children(settings.active_word_highlight.then(|| {
++ self.labelled_inline(
++ "Highlight Style",
++ self.menu_select(
++ SidebarMenu::CaptionHighlightStyle,
++ "caption-highlight-style",
++ highlight_label,
cx,
),
-- )),
-- ),
++ )
++ }))
++ .child(self.labelled(
++ "Text Color",
++ self.render_hex_field(
++ crate::editor_panels::FieldKey::CaptionColor,
++ &settings.color,
++ cx,
++ ),
++ )),
++ ),
)
.child(
-- ui::Field::plain(&theme, "Background Settings")
-- .icon("icons/message-bubble.svg")
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(12.))
-- .child(self.labelled(
-- "Background Color",
-- self.render_hex_field(
-- crate::editor_panels::FieldKey::CaptionBackground,
-- &settings.background_color,
-- cx,
-- ),
-- ))
-- .child(
-- self.labelled(
-- "Background Opacity",
-- self.slider(
-- SliderKey::Caption(CaptionSlider::BackgroundOpacity),
-- "",
-- cx,
-- )
-- .into_any_element(),
-- ),
++ ui::Field::section(&theme, "Background Settings").child(
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(12.))
++ .child(self.labelled(
++ "Background Color",
++ self.render_hex_field(
++ crate::editor_panels::FieldKey::CaptionBackground,
++ &settings.background_color,
++ cx,
),
-- ),
++ ))
++ .child(
++ self.slider_field(
++ "Background Opacity",
++ SliderKey::Caption(CaptionSlider::BackgroundOpacity),
++ "",
++ cx,
++ )
++ .into_any_element(),
++ ),
++ ),
)
.child(
-- ui::Field::plain(&theme, "Position")
-- .icon("icons/message-bubble.svg")
-- .child(self.menu_select(
-- SidebarMenu::CaptionPosition,
-- "caption-position",
-- position_label,
-- cx,
-- )),
++ ui::Field::inline(&theme, "Position").child(self.menu_select(
++ SidebarMenu::CaptionPosition,
++ "caption-position",
++ position_label,
++ cx,
++ )),
)
.child(
-- ui::Field::plain(&theme, "Animation")
-- .icon("icons/message-bubble.svg")
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(12.))
-- .child(self.labelled(
-- "Animation Style",
-- self.menu_select(
-- SidebarMenu::CaptionAnimation,
-- "caption-animation",
-- animation_label,
-- cx,
-- ),
-- ))
-- .child(self.labelled(
-- "Highlight Color",
-- self.render_hex_field(
-- crate::editor_panels::FieldKey::CaptionHighlight,
-- &settings.highlight_color,
-- cx,
-- ),
-- ))
-- .child(self.labelled_readout(
-- "Fade Duration",
-- SliderKey::Caption(CaptionSlider::FadeDuration),
-- format!("{:.0}ms", settings.fade_duration * 1000.),
++ ui::Field::section(&theme, "Animation").child(
++ div()
++ .flex()
++ .flex_col()
++ .gap(px(12.))
++ .child(self.labelled_inline(
++ "Animation Style",
++ self.menu_select(
++ SidebarMenu::CaptionAnimation,
++ "caption-animation",
++ animation_label,
cx,
-- )),
-- ),
++ ),
++ ))
++ .child(self.labelled(
++ "Highlight Color",
++ self.render_hex_field(
++ crate::editor_panels::FieldKey::CaptionHighlight,
++ &settings.highlight_color,
++ cx,
++ ),
++ ))
++ .child(self.labelled_readout(
++ "Fade Duration",
++ SliderKey::Caption(CaptionSlider::FadeDuration),
++ format!("{:.0}ms", settings.fade_duration * 1000.),
++ cx,
++ )),
++ ),
)
.child(
-- ui::Field::plain(&theme, "Font Weight")
-- .icon("icons/message-bubble.svg")
-- .child(self.menu_select(
-- SidebarMenu::CaptionWeight,
-- "caption-weight",
-- weight_label,
-- cx,
-- )),
++ ui::Field::inline(&theme, "Font Weight").child(self.menu_select(
++ SidebarMenu::CaptionWeight,
++ "caption-weight",
++ weight_label,
++ cx,
++ )),
)
.child(
-- ui::Field::plain(&theme, "Export Options")
-- .icon("icons/message-bubble.svg")
-- .child(
-- ui::Subfield::plain(&theme, "Export with Subtitles").child(
-- ui::Toggle::plain(
-- &theme,
-- "caption-export",
-- settings.export_with_subtitles,
-- )
-- .on_click(cx.listener(
-- |this, _, window, cx| {
-- let next =
-- !caption_settings(&this.project).export_with_subtitles;
-- this.set_caption_setting(
-- "caption-export",
-- window,
-- cx,
-- move |settings| settings.export_with_subtitles = next,
-- );
-- },
-- )),
-- ),
++ ui::Field::section(&theme, "Export Options").child(
++ ui::Subfield::plain(&theme, "Export with Subtitles").child(
++ ui::Toggle::plain(&theme, "caption-export", settings.export_with_subtitles)
++ .on_click(cx.listener(|this, _, window, cx| {
++ let next = !caption_settings(&this.project).export_with_subtitles;
++ this.set_caption_setting(
++ "caption-export",
++ window,
++ cx,
++ move |settings| settings.export_with_subtitles = next,
++ );
++ })),
),
++ ),
);
// An extra flex ancestor here repeats intrinsic layout while scrolling.
-- ui::Field::plain(&theme, "Captions")
-- .icon("icons/message-bubble.svg")
++ ui::Field::section(&theme, "Captions")
.badge("Beta")
.child(transcription)
.child(style.mt(px(8.)))
@@@ -3067,7 -3190,7 +3092,7 @@@
div()
.flex()
.flex_col()
-- .gap(px(24.))
++ .gap(px(14.))
.child(
div()
.flex()
@@@ -3075,14 -3198,14 +3100,20 @@@
.gap(px(2.))
.child(
div()
++ .text_size(px(12.))
.font_weight(FontWeight::MEDIUM)
-- .text_color(Hsla::from(theme.gray_12))
++ .text_color(Hsla::from(theme.editor.text_2))
.child("Sync"),
)
-- .child(div().text_color(Hsla::from(theme.gray_11)).child(
-- "Fine-tune source offsets if audio or camera drifts out of \
++ .child(
++ div()
++ .text_size(px(12.))
++ .text_color(Hsla::from(theme.editor.text_3))
++ .child(
++ "Fine-tune source offsets if audio or camera drifts out of \
sync with the screen recording.",
-- )),
++ ),
++ ),
)
.children((0..clips).map(|clip| {
let auto = self
@@@ -3094,17 -3217,17 +3125,19 @@@
div()
.flex()
.flex_col()
-- .gap(px(24.))
++ .gap(px(14.))
.children((clips > 1).then(|| {
div()
++ .text_size(px(12.))
.font_weight(FontWeight::MEDIUM)
-- .text_color(Hsla::from(theme.gray_12))
++ .text_color(Hsla::from(theme.editor.text_2))
.child(SharedString::from(format!("Clip {clip}")))
.into_any_element()
}))
.children(auto.then(|| {
div()
-- .text_color(Hsla::from(theme.gray_11))
++ .text_size(px(12.))
++ .text_color(Hsla::from(theme.editor.text_3))
.child(
"Cap calculated these offsets automatically to keep audio in \
sync with the video. Adjust them if anything still sounds \
@@@ -3200,7 -3323,7 +3233,7 @@@ impl EditorWindow
.find(|item| item.index as usize == clip)
.map_or(0., |item| f64::from(kind.read(&item.offsets)));
-- let mut field = ui::Field::plain(&theme, name);
++ let mut field = ui::Field::section(&theme, name);
if auto {
field = field.badge("Auto-synced");
}
@@@ -3233,7 -3356,7 +3266,7 @@@
.py(px(2.))
.rounded(px(2.))
.border_1()
-- .border_color(Hsla::from(theme.gray_3))
++ .border_color(Hsla::from(theme.editor.line))
.bg(Hsla::from(theme.gray_1))
.text_size(px(12.))
.text_color(Hsla::from(theme.gray_11))
diff --cc apps/desktop-gpui/src/editor_timeline.rs
index 8df859275,8bf13e72a..dfb41b990
--- a/apps/desktop-gpui/src/editor_timeline.rs
+++ b/apps/desktop-gpui/src/editor_timeline.rs
@@@ -34,8 -34,8 +34,8 @@@
use std::sync::Arc;
use cap_project::{
-- Camera3DSegment, CaptionTrackSegment, MaskKind, ProjectConfiguration, SceneMode, TextLayout,
-- TimelineConfiguration, ZoomMode,
++ Camera3DSegment, CaptionTrackSegment, MaskKind, OverlayTrack, OverlayTrackKind,
++ ProjectConfiguration, SceneMode, TextLayout, TimelineConfiguration, ZoomMode,
};
use gpui::{
AnyElement, FontWeight, Hsla, InteractiveElement, IntoElement, ParentElement, Pixels,
@@@ -51,31 -51,31 +51,73 @@@ use crate::
// Layout constants (`TL/index.tsx:62-68`)
// ---------------------------------------------------------------------------
--pub const TIMELINE_PADDING: f32 = 16.;
++/// The hairline the root shell's timeline card draws, and the padding the
++/// timeline lays out inside it: the brief's `10px 12px 12px` less that
++/// hairline, which every geometry helper below counts as part of the inset.
++pub const TIMELINE_CARD_BORDER: f32 = 1.;
++pub const TIMELINE_PADDING: f32 = 11.;
++pub const TIMELINE_TOP_PADDING: f32 = 9.;
++pub const TIMELINE_BOTTOM_PADDING: f32 = 11.;
pub const TRACK_GUTTER_GAP: f32 = 8.;
--pub const TRACK_GUTTER: f32 = 112.;
++pub const TRACK_GUTTER: f32 = 104.;
pub const TRACK_ICON_WIDTH: f32 = TRACK_GUTTER - TRACK_GUTTER_GAP;
--pub const TIMELINE_HEADER_HEIGHT: f32 = 32.;
--pub const PLAYHEAD_TOP_OFFSET: f32 = 24.;
++pub const TIMELINE_HEADER_HEIGHT: f32 = 26.;
++/// The playhead hangs from the ruler's baseline, which is the header's bottom
++/// edge measured from the card's padding box.
++pub const PLAYHEAD_TOP_OFFSET: f32 = TIMELINE_TOP_PADDING + TIMELINE_HEADER_HEIGHT;
/// The snap-to-zero zone at the timeline's origin (`TL/index.tsx:68, 826`).
pub const START_SNAP_PX: f64 = 10.;
--/// `px-2` on the timeline slot (`Editor.tsx:781`) -- the container's own left
--/// edge in window coordinates.
++/// `px-2` on the timeline slot (`Editor.tsx:781`) -- the card's own left edge
++/// in window coordinates.
pub const TIMELINE_SLOT_PADDING: f32 = 8.;
--/// `pt-8` on the timeline container (`TL/index.tsx:1149`).
--pub const TIMELINE_TOP_PADDING: f32 = 32.;
/// `pr-1` on the scroll body (`TL/index.tsx:1326`). The clip track -- which is
/// what `timelineBounds` measures -- sits inside it, so every `secsPerPixel` in
/// the timeline is computed over a column four pixels narrower than the ruler's.
pub const SCROLL_BODY_PADDING_RIGHT: f32 = 4.;
--/// `visibleTrackCount() > 2 ? "3rem" : "3.25rem"` (`TL/index.tsx:268-270`).
--pub const TRACK_HEIGHT_COMPACT: f32 = 48.;
--pub const TRACK_HEIGHT_ROOMY: f32 = 52.;
--/// `gap-2` between rows (`TL/index.tsx:1333`) and between gutter and content
--/// (`TL/index.tsx:1516`).
--pub const TRACK_ROW_GAP: f32 = 8.;
++pub const TRACK_HEIGHT: f32 = 44.;
++pub const TRACK_ROW_GAP: f32 = 6.;
++/// The radius of the band a row draws across its gutter and lane.
++pub const TRACK_BAND_RADIUS: f32 = 8.;
++/// The gap between the ruler's baseline and the first track row. It is not the
++/// row gap: the ruler's ticks already hang into their own strip.
++pub const TIMELINE_HEADER_GAP: f32 = 4.;
++
++/// Everything the card spends before the first track row: its hairline, the
++/// padding inside it, the ruler and the gap under the ruler.
++pub const TIMELINE_CHROME_HEIGHT: f32 = TIMELINE_CARD_BORDER * 2.
++ + TIMELINE_TOP_PADDING
++ + TIMELINE_BOTTOM_PADDING
++ + TIMELINE_HEADER_HEIGHT
++ + TIMELINE_HEADER_GAP;
++
++/// The card height that leaves exactly one row visible -- the floor a resize
++/// drag (and the auto height) is allowed to reach.
++pub const MIN_HUG_HEIGHT: f32 = TIMELINE_CHROME_HEIGHT + TRACK_HEIGHT;
++
++/// The card height that exactly hugs `rows` visible track rows, [`build_rows`]
++/// being what decides how many there are.
++pub fn hug_height(rows: usize) -> f32 {
++ let rows = rows.max(1) as f32;
++ TIMELINE_CHROME_HEIGHT + rows * TRACK_HEIGHT + (rows - 1.) * TRACK_ROW_GAP
++}
++
++/// The ruler's ticks hang from the baseline: whole seconds are labelled and
++/// long, half seconds are short.
++const RULER_MAJOR_TICK: f32 = 8.;
++const RULER_MINOR_TICK: f32 = 5.;
++/// The gutter cell: a 22px tile at 4px of left padding, then the label.
++const TRACK_TILE_SIZE: f32 = 22.;
++const TRACK_TILE_INSET: f32 = 4.;
++/// The segment's radius, its left accent bar and the content inset that clears
++/// it (`0 10px 0 13px`).
++const SEGMENT_RADIUS: f32 = 8.;
++const SEGMENT_ACCENT_BAR: f32 = 3.;
++const SEGMENT_PADDING_LEFT: f32 = 13.;
++const SEGMENT_PADDING_RIGHT: f32 = 10.;
++/// The waveform's ceiling inside a row, so it never climbs into the labels.
++const WAVEFORM_MAX_HEIGHT: f32 = 18.;
/// `SEGMENT_RENDER_PADDING` (`TL/context.ts:14`) -- seconds of slack either
/// side of the viewport before a segment stops being rendered at all.
@@@ -106,92 -106,92 +148,91 @@@ pub fn new_segment_min_duration(secs_pe
(MIN_NEW_SEGMENT_PIXEL_WIDTH * secs_per_pixel).max(MIN_NEW_SEGMENT_SECS_WIDTH)
}
--/// The minimap's floor and its 12px strip (`TL/Minimap.tsx:9`, `TL/index.tsx:1209-1216`).
++/// The minimap's chip floor (`TL/Minimap.tsx:9`), the height of its hit strip
++/// and the 4px indicator drawn inside that strip, and the width it is allowed
++/// to take in the card's bottom-right corner.
const MINIMAP_MIN_CHIP_WIDTH: f32 = 20.;
--pub const MINIMAP_HEIGHT: f32 = 12.;
--pub const MINIMAP_TOP: f32 = 2.;
++pub const MINIMAP_HEIGHT: f32 = 10.;
++pub const MINIMAP_BAR_HEIGHT: f32 = 4.;
++pub const MINIMAP_MAX_WIDTH: f32 = 78.;
/// The edge fade (`TL/index.tsx:1103-1106`).
--const FADE_WIDTH: f32 = 32.;
--const FADE_RAMP_PX: f64 = 50.;
// ---------------------------------------------------------------------------
// Colours
// ---------------------------------------------------------------------------
--/// The single source of truth for track colour is nine CSS custom properties
++/// The single source of truth for track colour is eleven CSS custom properties
/// with one definition each -- not per-appearance values -- so they are literal
/// in both themes exactly as they are there
--/// (`apps/desktop/src/styles/theme.css:24-34`):
--///
--/// ```css
--/// --track-clip: #3f8ae0; --track-zoom: #4a4f5c; --track-caption: #6f747d;
--/// --track-keyboard: #d4742c; --track-text: #2898ac; --track-mask: #d2444b;
--/// --track-scene: #975cfa; --track-audio: var(--jade-9); --track-3d: #7c6ff0;
--/// ```
--///
--/// `--jade-9` is `#29a383` in both `jade.css` and `jade-dark.css` (Radix keeps
--/// step 9 constant across the two), so it is a literal here too.
++/// (`apps/desktop/src/styles/theme.css`).
pub mod track_color {
-- pub const CLIP: u32 = 0x3f8ae0;
-- pub const MUTED_CLIP: u32 = 0x5b6c80;
-- pub const ZOOM: u32 = 0x4a4f5c;
-- pub const CAPTION: u32 = 0x6f747d;
-- pub const KEYBOARD: u32 = 0xd4742c;
-- pub const TEXT: u32 = 0x2898ac;
-- pub const MASK: u32 = 0xd2444b;
-- pub const SCENE: u32 = 0x975cfa;
-- /// `var(--jade-9)`.
-- pub const AUDIO: u32 = 0x29a383;
-- pub const THREE_D: u32 = 0x7c6ff0;
++ pub const CLIP: u32 = 0x3b82f6;
++ pub const ZOOM: u32 = 0x64748b;
++ pub const CAPTION: u32 = 0x0ea5e9;
++ pub const KEYBOARD: u32 = 0xf97316;
++ pub const STYLE: u32 = 0xec4899;
++ pub const IMAGE: u32 = 0xf59e0b;
++ pub const TEXT: u32 = 0x14b8a6;
++ pub const MASK: u32 = 0xef4444;
++ pub const SCENE: u32 = 0x8b5cf6;
++ pub const AUDIO: u32 = 0x22c55e;
++ pub const THREE_D: u32 = 0x6366f1;
}
--/// `.cap-track-fill { background: var(--seg-color); border: 1px solid
--/// color-mix(in srgb, var(--seg-color) 58%, black) }` (`TL/styles.css:23-26`).
--pub fn track_fill_border(color: Hsla) -> Hsla {
-- let rgba = gpui::Rgba::from(color);
-- gpui::Rgba {
-- r: rgba.r * 0.58,
-- g: rgba.g * 0.58,
-- b: rgba.b * 0.58,
-- a: rgba.a,
++/// A muted clip keeps the clip lane's shape but drops its hue, so it reads as
++/// the row's own disabled state rather than as a different track.
++fn muted_clip_color(theme: &Theme) -> Hsla {
++ Hsla::from(theme.editor.text_3)
++}
++
++/// The `EditorPalette` mixers work in `Rgba`, which is what the `--ed-*`
++/// tokens are; every track colour in this file is an `Hsla`.
++fn seg_fill(theme: &Theme, color: Hsla, selected: bool) -> Hsla {
++ let color = gpui::Rgba::from(color);
++ if selected {
++ theme.editor.seg_fill_selected(color).into()
++ } else {
++ theme.editor.seg_fill(color).into()
}
-- .into()
}
--/// The playhead's `from-[rgb(226,64,64)]` (`TL/index.tsx:1281`).
--pub fn playhead_color() -> Hsla {
-- gpui::rgb(0xe24040).into()
++fn seg_border(theme: &Theme, color: Hsla, extra_alpha: f32) -> Hsla {
++ let border = theme.editor.seg_border(gpui::Rgba::from(color));
++ Hsla::from(crate::theme::rgba_alpha(
++ border,
++ (border.a + extra_alpha).clamp(0., 1.),
++ ))
}
--/// `bg-linear-to-b to-120% from-<color>`: the gradient runs from the colour at
--/// 0 % to fully transparent at **120 %** of the box, so at the bottom edge it
--/// still carries 1 - 1/1.2 = 1/6 of its alpha. gpui takes two stops, which is
--/// exactly what this needs once the 120 % is folded into the end alpha.
--fn playhead_gradient(color: Hsla) -> gpui::Background {
-- let mut faded = color;
-- faded.a = color.a / 6.;
-- gpui::linear_gradient(
-- 180.,
-- gpui::linear_color_stop(color, 0.),
-- gpui::linear_color_stop(faded, 1.),
-- )
++fn seg_label(theme: &Theme, color: Hsla) -> Hsla {
++ theme.editor.seg_label(gpui::Rgba::from(color)).into()
++}
++
++fn seg_muted(theme: &Theme, color: Hsla) -> Hsla {
++ theme.editor.seg_muted(gpui::Rgba::from(color)).into()
++}
++
++fn seg_handle(theme: &Theme, color: Hsla) -> Hsla {
++ theme.editor.seg_handle(gpui::Rgba::from(color)).into()
++}
++
++pub(crate) fn tile_bg(theme: &Theme, color: Hsla) -> Hsla {
++ theme.editor.tile_bg(gpui::Rgba::from(color)).into()
++}
++
++pub(crate) fn tile_fg(theme: &Theme, color: Hsla) -> Hsla {
++ theme.editor.tile_fg(gpui::Rgba::from(color)).into()
}
fn with_alpha(color: Hsla, alpha: f32) -> Hsla {
Hsla { a: alpha, ..color }
}
--/// `--text-tertiary` (`theme.css:58, 122`), the three empty tracks' copy
--/// colour: `rgba(18, 22, 31, 0.65)` in light, `rgba(255, 255, 255, 0.65)` in
--/// dark. `Theme` carries `--text-primary` but not this one, so it is spelled
--/// out where it is used rather than growing the token set for one caller.
--fn text_tertiary(theme: &Theme) -> Hsla {
-- if theme.is_dark() {
-- with_alpha(gpui::white(), 0.65)
-- } else {
-- with_alpha(gpui::rgb(0x12161f).into(), 0.65)
-- }
++/// Times read as columns of digits, so every one of them is set in the font's
++/// tabular figures.
++fn tabular_numerals() -> gpui::FontFeatures {
++ gpui::FontFeatures(Arc::new(vec![("tnum".to_string(), 1)]))
}
// ---------------------------------------------------------------------------
@@@ -327,11 -327,11 +368,11 @@@ impl Transform
/// `timelineBounds.width`, which every `secsPerPixel` divides by: the window,
/// less the timeline slot's `px-2`, less the container's own 16px padding on
--/// each side, less the scroll body's `pr-1`, less the 112px icon gutter.
++/// each side, less the scroll body's `pr-1`, less the gutter.
pub fn content_width(viewport_width: f32) -> f32 {
(viewport_width
- TIMELINE_SLOT_PADDING * 2.
-- - TIMELINE_PADDING * 2.
++ - (TIMELINE_CARD_BORDER + TIMELINE_PADDING) * 2.
- SCROLL_BODY_PADDING_RIGHT
- TRACK_GUTTER)
.max(1.)
@@@ -343,7 -343,7 +384,11 @@@
/// scaled by the clip track's `secsPerPixel`. Ticks therefore line up with the
/// tracks and the strip simply has four pixels of slack at its right edge.
pub fn ruler_width(viewport_width: f32) -> f32 {
-- (viewport_width - TIMELINE_SLOT_PADDING * 2. - TIMELINE_PADDING * 2. - TRACK_GUTTER).max(1.)
++ (viewport_width
++ - TIMELINE_SLOT_PADDING * 2.
++ - (TIMELINE_CARD_BORDER + TIMELINE_PADDING) * 2.
++ - TRACK_GUTTER)
++ .max(1.)
}
/// The window x of the track content column's left edge --
@@@ -351,7 -351,7 +396,7 @@@
/// (`TL/index.tsx:803-816`), where `rect` is the timeline container, itself
/// inset by the slot's `px-2`.
pub fn content_left() -> f32 {
-- TIMELINE_SLOT_PADDING + TIMELINE_PADDING + TRACK_GUTTER
++ TIMELINE_SLOT_PADDING + TIMELINE_CARD_BORDER + TIMELINE_PADDING + TRACK_GUTTER
}
/// `timelineTimeFromClientX` (`TL/index.tsx:818-828`), verbatim including the
@@@ -629,16 -629,16 +674,10 @@@ pub fn waveform_sample_count(canvas_wid
((canvas_width * WAVEFORM_SAMPLES_PER_PIXEL).ceil() as usize).min(MAX_WAVEFORM_SAMPLES)
}
--/// `drawWaveform`'s two colours (`TL/ClipTrack.tsx:293-302`): the mic in white
--/// at 40 %, system audio in orange at 50 %.
--pub const WAVEFORM_MIC_COLOR: Hsla = Hsla {
-- h: 0.,
-- s: 0.,
-- l: 1.,
-- a: 0.4,
--};
--pub fn waveform_system_color() -> Hsla {
-- with_alpha(gpui::rgb(0xff9600).into(), 0.5)
++/// Both waveforms are the lane's own colour at 55 %: over a tinted segment a
++/// white or orange fill (`TL/ClipTrack.tsx:293-302`) has nothing to sit on.
++pub fn waveform_color(color: Hsla) -> Hsla {
++ with_alpha(color, 0.55)
}
// ---------------------------------------------------------------------------
@@@ -700,8 -694,6 +739,8 @@@ impl TrackKind
pub fn color(self) -> Hsla {
gpui::rgb(match self {
Self::Clip => track_color::CLIP,
- Self::Style => 0xa855f7,
- Self::Image => 0xf59e0b,
++ Self::Style => track_color::STYLE,
++ Self::Image => track_color::IMAGE,
Self::Caption => track_color::CAPTION,
Self::Keyboard => track_color::KEYBOARD,
Self::Text => track_color::TEXT,
@@@ -745,11 -735,8 +784,21 @@@
}
pub fn supports_multiple(self) -> bool {
- matches!(self, Self::Text | Self::Mask | Self::Audio)
+ matches!(
+ self,
+ Self::Text | Self::Mask | Self::Audio | Self::Style | Self::Image
+ )
+ }
++
++ pub fn overlay_track(self, track: u32) -> Option<OverlayTrack> {
++ let kind = match self {
++ Self::Mask => OverlayTrackKind::Mask,
++ Self::Image => OverlayTrackKind::Image,
++ Self::Text => OverlayTrackKind::Text,
++ _ => return None,
++ };
++ Some(OverlayTrack { kind, track })
+ }
}
pub const ADD_TRACK_OPTIONS: &[TrackKind] = &[
@@@ -958,6 -901,6 +1007,20 @@@ pub struct TrackRow
pub lane: u32,
}
++impl TrackRow {
++ pub fn from_overlay_track(track: OverlayTrack) -> Self {
++ let kind = match track.kind {
++ OverlayTrackKind::Mask => TrackKind::Mask,
++ OverlayTrackKind::Image => TrackKind::Image,
++ OverlayTrackKind::Text => TrackKind::Text,
++ };
++ Self {
++ kind,
++ lane: track.track,
++ }
++ }
++}
++
/// Everything the timeline draws, derived once per project-config change.
#[derive(Debug, Clone, Default)]
pub struct TimelineModel {
@@@ -992,14 -933,14 +1055,8 @@@
}
impl TimelineModel {
-- /// `visibleTrackCount()` (`TL/index.tsx:257-267`) -- `rows` already is that
-- /// list, so the count is its length; the two locked tracks are in it.
pub fn track_height(&self) -> f32 {
-- if self.rows.len() > 2 {
-- TRACK_HEIGHT_COMPACT
-- } else {
-- TRACK_HEIGHT_ROOMY
-- }
++ TRACK_HEIGHT
}
fn segments_for(&self, row: TrackRow) -> &[Segment] {
@@@ -1277,16 -1188,14 +1334,37 @@@ fn build_rows
lane: 0,
});
}
++ for lane in (0..lane_count(&model.style).max(lanes.style)).rev() {
++ rows.push(TrackRow {
++ kind: TrackKind::Style,
++ lane,
++ });
++ }
++ let mut overlay_tracks = Vec::new();
for (kind, segments, count) in [
+ (TrackKind::Style, &model.style, lanes.style),
+ (TrackKind::Image, &model.image, lanes.image),
(TrackKind::Text, &model.text, lanes.text),
++ (TrackKind::Image, &model.image, lanes.image),
(TrackKind::Mask, &model.mask, lanes.mask),
-- (TrackKind::Audio, &model.audio, lanes.audio),
] {
-- for lane in 0..lane_count(segments).max(count) {
-- rows.push(TrackRow { kind, lane });
-- }
++ overlay_tracks.extend(
++ (0..lane_count(segments).max(count))
++ .rev()
++ .filter_map(|lane| kind.overlay_track(lane)),
++ );
++ }
++ rows.extend(
++ config
++ .resolved_overlay_order(&overlay_tracks)
++ .into_iter()
++ .map(TrackRow::from_overlay_track),
++ );
++ for lane in (0..lane_count(&model.audio).max(lanes.audio)).rev() {
++ rows.push(TrackRow {
++ kind: TrackKind::Audio,
++ lane,
++ });
}
rows.push(TrackRow {
kind: TrackKind::Zoom,
@@@ -1524,45 -1433,45 +1602,62 @@@ impl SegmentUi<'_>
fn is_hovered(&self, kind: TrackKind, lane: u32, index: usize) -> bool {
self.hovered == Some((kind, lane, index))
}
++
++ fn row_selected(&self, model: &TimelineModel, row: TrackRow) -> bool {
++ self.selection.is_some_and(|selection| {
++ selection.track == row.kind
++ && model
++ .segments_for(row)
++ .iter()
++ .enumerate()
++ .any(|(index, segment)| {
++ segment.lane == row.lane && selection.indices.contains(&index)
++ })
++ })
++ }
}
// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------
--/// The gutter chip: `cap-track-fill` + `relative z-10 w-full h-13 flex flex-col
--/// items-center justify-center gap-0.5 rounded-xl shadow-[...] text-white`
--/// (`TL/TrackManager.tsx:264-281`).
--///
--/// **`h-13` is 52px and deliberately does not follow `--track-height`**, so on
--/// a timeline with more than two rows (48px) the chip overhangs its row. That
--/// is the source's own behaviour, kept.
--pub fn track_chip(kind: TrackKind) -> impl IntoElement {
++/// The gutter cell: a tinted 22px tile carrying the track's glyph, then the
++/// track's name. The saturated pill the source draws
++/// (`TL/TrackManager.tsx:264-281`) is gone.
++pub fn track_chip(theme: &Theme, kind: TrackKind) -> impl IntoElement {
let color = kind.color();
div()
.w_full()
-- .h(px(52.))
++ .h_full()
.flex()
-- .flex_col()
++ .flex_row()
.items_center()
-- .justify_center()
-- .gap(px(2.))
-- .rounded(px(12.))
-- .bg(color)
-- .border_1()
-- .border_color(track_fill_border(color))
-- .text_color(gpui::white())
++ .gap(px(8.))
++ .pl(px(TRACK_TILE_INSET))
++ .pr(px(6.))
.child(
-- svg()
-- .path(kind.icon())
-- .size(px(16.))
++ div()
.flex_none()
-- .text_color(gpui::white()),
++ .size(px(TRACK_TILE_SIZE))
++ .rounded(px(6.))
++ .flex()
++ .items_center()
++ .justify_center()
++ .bg(tile_bg(theme, color))
++ .child(
++ svg()
++ .path(kind.icon())
++ .size(px(12.))
++ .flex_none()
++ .text_color(tile_fg(theme, color)),
++ ),
)
.child(
div()
-- .text_size(px(10.))
-- .line_height(px(10.))
++ .min_w_0()
++ .truncate()
++ .text_size(px(11.))
++ .line_height(px(14.))
.font_weight(FontWeight::MEDIUM)
.child(kind.label()),
)
@@@ -1585,14 -1494,14 +1680,10 @@@ pub fn render_ruler(theme: &Theme, view
let count = (2. + (transform.zoom + 5.) / resolution).ceil().max(0.) as usize;
let offset = transform.position % resolution;
++ let tick = Hsla::from(theme.editor.line_strong);
++ let label = Hsla::from(theme.editor.text_3);
-- let mut body = div()
-- .relative()
-- .flex_1()
-- .h(px(16.))
-- .ml(px(TRACK_GUTTER))
-- .text_size(px(12.))
-- .text_color(Hsla::from(theme.gray_9));
++ let mut body = div().relative().flex_1().h_full().ml(px(TRACK_GUTTER));
// The source renders every mark and hides the negative ones with
// `visibility`, which costs nothing there and would cost an element here.
@@@ -1601,26 -1510,26 +1692,28 @@@
if second < 0. {
continue;
}
-- let x = (second - transform.position) / secs_per_pixel - 1.;
++ let x = (second - transform.position) / secs_per_pixel;
if x > strip_width {
break;
}
-- let show_label = second % 1. == 0.;
++ let major = second % 1. == 0.;
body = body.child(
div()
.absolute()
.left(px(x as f32))
-- .bottom(px(4.))
-- .size(px(4.))
-- .rounded_full()
-- .bg(Hsla::from(theme.gray_9))
-- .when(show_label, |this| {
++ .bottom_0()
++ .w(px(1.))
++ .h(px(if major {
++ RULER_MAJOR_TICK
++ } else {
++ RULER_MINOR_TICK
++ }))
++ .bg(tick)
++ .when(major, |this| {
this.child(
div()
.absolute()
-- // `-top-4.5` = -18px, and the origin's label is
-- // left-anchored (`TL/index.tsx:1591-1594`).
-- .top(px(-18.))
++ .bottom(px(10.))
// `-translate-x-1/2` on every label but the
// origin's, which is left-anchored so it does not
// overhang into the icon gutter
@@@ -1632,9 -1541,9 +1725,10 @@@
.w(px(44.))
.flex()
.when(second != 0., |this| this.justify_center())
-- .text_size(px(12.))
-- .line_height(px(16.))
-- .text_color(Hsla::from(theme.gray_9))
++ .text_size(px(11.))
++ .line_height(px(13.))
++ .font_features(tabular_numerals())
++ .text_color(label)
.child(format_time(second)),
)
}),
@@@ -1650,6 -1559,6 +1744,15 @@@
.into_any_element()
}
++/// The minimap's strip: pinned to the card's inner right edge, at most
++/// [`MINIMAP_MAX_WIDTH`] wide. Returns its window x and its width, which the
++/// drag maths and the drawn bar have to agree on.
++pub fn minimap_bounds(viewport_width: f32) -> (f32, f32) {
++ let strip = ruler_width(viewport_width);
++ let width = MINIMAP_MAX_WIDTH.min(strip);
++ (content_left() + strip - width, width)
++}
++
pub fn minimap_chip(transform: Transform, total_duration: f64, bar_width: f32) -> (f32, f32) {
let total = total_duration.max(0.001);
let bar_width = bar_width.max(1.);
@@@ -1759,12 -1668,12 +1862,10 @@@ pub fn render_minimap
let mut bar = div()
.relative()
.w_full()
-- .h_full()
++ .h(px(MINIMAP_BAR_HEIGHT))
.overflow_hidden()
-- .rounded_full()
-- .border_1()
-- .border_color(Hsla::from(theme.gray_4))
-- .bg(with_alpha(Hsla::from(theme.gray_3), 0.8))
++ .rounded(px(2.))
++ .bg(Hsla::from(theme.editor.ctl_active))
.when(!zoomed_in, |this| this.opacity(0.));
for offset in &model.clip_boundaries {
@@@ -1778,99 -1687,99 +1879,47 @@@
.bottom_0()
.left(gpui::relative((offset / total) as f32))
.w(px(1.))
-- .bg(with_alpha(Hsla::from(theme.gray_6), 0.5)),
++ .bg(with_alpha(TrackKind::Clip.color(), 0.5)),
);
}
-- bar.child(
-- div()
-- .id("timeline-minimap-chip")
-- .absolute()
-- .top_0()
-- .bottom_0()
-- .left(px(chip_left))
-- .w(px(chip_width))
-- .rounded_full()
-- .border_1()
-- .border_color(with_alpha(Hsla::from(theme.gray_7), 0.8))
-- .bg(with_alpha(Hsla::from(theme.gray_6), 0.7))
-- .cursor(gpui::CursorStyle::OpenHand)
-- .hover(|style| style.bg(with_alpha(Hsla::from(theme.gray_7), 0.7)))
-- .children([true, false].map(|left| {
++ div()
++ .w_full()
++ .h_full()
++ .flex()
++ .items_center()
++ .child(
++ bar.child(
div()
++ .id("timeline-minimap-chip")
.absolute()
.top_0()
.bottom_0()
-- .w(px(8.))
-- .when(left, |handle| handle.left_0())
-- .when(!left, |handle| handle.right_0())
-- .cursor(gpui::CursorStyle::ResizeLeftRight)
-- })),
-- )
-- .into_any_element()
--}
--
--/// The edge-fade strength either side of the viewport (`TL/index.tsx:1097-1139`).
--///
--/// The source expresses it as a `mask-image` with a stop whose alpha ramps over
--/// `FADE_RAMP_PX` of scroll; gpui has no mask-image, so [`render_edge_fade`]
--/// paints the same ramp as two gradient overlays in the container's own
--/// background colour. The strengths are the source's exactly.
--pub fn edge_fade_strengths(
-- model: &TimelineModel,
-- view: TimelineView,
-- viewport_width: f32,
--) -> (f32, f32) {
-- let secs_per_pixel = view.transform.secs_per_pixel(content_width(viewport_width));
-- let scroll_left_px = view.transform.position / secs_per_pixel;
-- let left = (scroll_left_px / FADE_RAMP_PX).clamp(0., 1.);
-- let scroll_right_px =
-- (model.total_duration - (view.transform.position + view.transform.zoom)) / secs_per_pixel;
-- let right = (scroll_right_px / FADE_RAMP_PX).clamp(0., 1.);
-- (left as f32, right as f32)
--}
--
--/// The two 32px gradients [`edge_fade_strengths`] describes, painted over the
--/// scroll body's left and right edges in `background`.
--pub fn render_edge_fade(background: Hsla, strengths: (f32, f32)) -> AnyElement {
-- let transparent = with_alpha(background, 0.);
-- div()
-- .absolute()
-- .inset_0()
-- .child(
-- div()
-- .absolute()
-- .top_0()
-- .bottom_0()
-- .left(px(TRACK_GUTTER))
-- .w(px(FADE_WIDTH))
-- .opacity(strengths.0)
-- .bg(gpui::linear_gradient(
-- 90.,
-- gpui::linear_color_stop(background, 0.),
-- gpui::linear_color_stop(transparent, 1.),
-- )),
-- )
-- .child(
-- div()
-- .absolute()
-- .top_0()
-- .bottom_0()
-- .right_0()
-- .w(px(FADE_WIDTH))
-- .opacity(strengths.1)
-- .bg(gpui::linear_gradient(
-- 90.,
-- gpui::linear_color_stop(transparent, 0.),
-- gpui::linear_color_stop(background, 1.),
-- )),
++ .left(px(chip_left))
++ .w(px(chip_width))
++ .rounded(px(2.))
++ .bg(with_alpha(Hsla::from(theme.editor.text_3), 0.5))
++ .cursor(gpui::CursorStyle::OpenHand)
++ .hover(|style| style.bg(with_alpha(Hsla::from(theme.editor.text_3), 0.75)))
++ .children([true, false].map(|left| {
++ div()
++ .absolute()
++ .top_0()
++ .bottom_0()
++ .w(px(8.))
++ .when(left, |handle| handle.left_0())
++ .when(!left, |handle| handle.right_0())
++ .cursor(gpui::CursorStyle::ResizeLeftRight)
++ })),
++ ),
)
.into_any_element()
}
--/// One track row: `flex items-stretch gap-2`, a 104px gutter cell and a
--/// `flex-1 relative overflow-hidden min-w-0` content cell
--/// (`TL/index.tsx:1516-1550`).
++/// One track row, drawn as a single band across the gutter and the lane so a
++/// label always reads as belonging to the strip beside it: the gutter cell in
++/// the band's leading [`TRACK_GUTTER`] pixels, then a `flex-1 relative
++/// overflow-hidden min-w-0` content cell (`TL/index.tsx:1516-1550`).
pub fn render_row(
theme: &Theme,
model: &TimelineModel,
@@@ -1880,19 -1789,19 +1929,34 @@@
ui: SegmentUi<'_>,
) -> AnyElement {
let height = model.track_height();
++ let selected = ui.row_selected(model, row);
++ let active_bg = Hsla::from(theme.editor.ctl_hover);
++ let active_text = Hsla::from(theme.editor.text_1);
div()
++ .relative()
.flex()
.flex_row()
.items_stretch()
-- .gap(px(TRACK_ROW_GAP))
.h(px(height))
.flex_none()
++ .rounded(px(TRACK_BAND_RADIUS))
++ .bg(if selected {
++ active_bg
++ } else {
++ Hsla::from(theme.editor.ctl)
++ })
++ .text_color(if selected {
++ active_text
++ } else {
++ Hsla::from(theme.editor.text_2)
++ })
++ .hover(|style| style.bg(active_bg).text_color(active_text))
.child(
div()
-- .w(px(TRACK_ICON_WIDTH))
++ .w(px(TRACK_GUTTER))
.flex_none()
.relative()
-- .child(track_chip(row.kind)),
++ .child(track_chip(theme, row.kind)),
)
.child(
div()
@@@ -1900,6 -1809,6 +1964,7 @@@
.relative()
.overflow_hidden()
.min_w_0()
++ .rounded_r(px(TRACK_BAND_RADIUS))
.child(render_track_content(
theme,
model,
@@@ -1980,6 -1889,6 +2045,7 @@@ fn render_track_content
&& let Some(ghost) = new_zoom_segment(model, preview, secs_per_pixel)
{
content = content.child(render_gap_ghost(
++ theme,
TrackKind::Zoom,
ghost,
view,
@@@ -1995,6 -1904,6 +2061,7 @@@
&& let Some(ghost) = new_scene_segment(model, preview)
{
content = content.child(render_gap_ghost(
++ theme,
TrackKind::Scene,
ghost,
view,
@@@ -2145,11 -2054,11 +2212,11 @@@ fn render_camera3d_setup_ghost
.bottom_0()
.left(px(x))
.w(px(width))
-- .rounded(px(12.))
++ .rounded(px(SEGMENT_RADIUS))
.border_1()
.border_dashed()
-- .border_color(with_alpha(color, 0.7))
-- .bg(with_alpha(color, 0.14))
++ .border_color(seg_border(theme, color, 0.))
++ .bg(seg_fill(theme, color, false))
.child(
div()
.h(px(height))
@@@ -2160,13 -2069,13 +2227,9 @@@
.px(px(8.))
.child(
div()
-- .px(px(8.))
-- .py(px(2.))
-- .rounded(px(6.))
-- .bg(with_alpha(Hsla::from(theme.gray_1), 0.82))
.text_size(px(12.))
.font_weight(FontWeight::MEDIUM)
-- .text_color(Hsla::from(theme.gray_12))
++ .text_color(seg_label(theme, color))
.child(SharedString::from(label.to_string())),
),
)
@@@ -2174,6 -2083,6 +2237,7 @@@
}
fn render_gap_ghost(
++ theme: &Theme,
kind: TrackKind,
(start, end): (f64, f64),
view: TimelineView,
@@@ -2189,9 -2098,9 +2253,6 @@@
.bottom_0()
.left(px(x))
.w(px(width))
-- .rounded(px(12.))
-- .border_1()
-- .border_color(gpui::transparent_black())
.child(
div()
.relative()
@@@ -2200,200 -2109,200 +2261,109 @@@
.flex()
.items_center()
.justify_center()
-- .rounded(px(12.))
++ .rounded(px(SEGMENT_RADIUS))
.overflow_hidden()
-- .bg(color)
++ .bg(seg_fill(theme, color, false))
.border_1()
-- .border_color(track_fill_border(color))
-- .text_color(gpui::white())
-- // Genuinely 16px, unlike the `text-md` label rows below: the
-- // ghost `<p class="... text-md text-primary">`
-- // (`TL/ZoomTrack.tsx:797`) has *no* sized ancestor anywhere up
-- // to `<body>`, and nothing in the stylesheet sets a body
-- // font-size, so it lands on the 16px UA default. Leave it.
-- .text_size(px(16.))
++ .border_dashed()
++ .border_color(seg_border(theme, color, 0.))
++ .text_size(px(14.))
++ .text_color(seg_label(theme, color))
.child("+"),
)
.into_any_element()
}
--/// Radix emerald steps the empty audio button uses
--/// (`TL/AudioTrack.tsx:405-420`). Step 9 is constant across appearances.
--fn emerald_9() -> Hsla {
-- gpui::rgb(0x30a46c).into()
--}
--
--fn emerald_11(theme: &Theme) -> Hsla {
-- if theme.is_dark() {
-- gpui::rgb(0x6dcea4).into()
-- } else {
-- gpui::rgb(0x18794e).into()
-- }
--}
--
--fn render_add_track_empty(
++/// The in-lane empty prompt: the track's own copy centred on the lane's band
++/// and, where a click fills the lane, the action word that does it. The
++/// floating pills and buttons the source draws are gone.
++fn render_empty_prompt(
theme: &Theme,
-- label: &'static str,
-- accent: Hsla,
-- accent_text: Hsla,
-- active: bool,
++ color: Hsla,
++ copy: &'static str,
++ action: Option<&'static str>,
hovered: bool,
++ active: bool,
) -> AnyElement {
-- let emphasized = active || hovered;
-- let border = if active {
-- accent
-- } else if hovered {
-- with_alpha(accent, 0.6)
-- } else {
-- with_alpha(Hsla::from(theme.gray_4), 0.85)
-- };
-- let background = if active {
-- with_alpha(accent, 0.1)
-- } else if hovered {
-- with_alpha(accent, 0.05)
-- } else {
-- with_alpha(Hsla::from(theme.gray_3), 0.2)
-- };
-- let text = if active {
-- accent_text
-- } else if hovered {
-- Hsla::from(theme.gray_12)
-- } else {
-- Hsla::from(theme.gray_11)
-- };
-- let chip_bg = if emphasized {
-- accent
-- } else {
-- with_alpha(Hsla::from(theme.gray_4), 0.55)
-- };
-- let chip_fg = if emphasized {
-- gpui::white()
-- } else {
-- Hsla::from(theme.gray_12)
-- };
--
div()
.absolute()
.inset_0()
.flex()
.flex_row()
-- .gap(px(8.))
.items_center()
.justify_center()
-- .w_full()
-- .rounded(px(12.))
-- .border_1()
-- .when(!active, |this| this.border_dashed())
-- .border_color(border)
-- .bg(background)
-- .text_size(px(14.))
-- .text_color(text)
-- .child(
++ .gap(px(5.))
++ .px(px(10.))
++ .rounded(px(SEGMENT_RADIUS))
++ .when(active, |this| this.bg(seg_fill(theme, color, false)))
++ .text_size(px(12.))
++ .line_height(px(16.))
++ .text_color(Hsla::from(if hovered {
++ theme.editor.text_2
++ } else {
++ theme.editor.text_3
++ }))
++ .child(div().min_w_0().truncate().child(copy))
++ .children(action.map(|action| {
div()
.flex()
++ .flex_row()
++ .flex_none()
.items_center()
-- .justify_center()
-- .rounded_full()
-- .size(px(24.))
-- .bg(chip_bg)
++ .gap(px(5.))
++ .child("\u{b7}")
.child(
-- svg()
-- .path("icons/plus.svg")
-- .size(px(14.))
-- .text_color(chip_fg),
-- ),
-- )
-- .child(div().font_weight(FontWeight::MEDIUM).child(label))
++ div()
++ .font_weight(FontWeight::MEDIUM)
++ .text_color(Hsla::from(theme.editor.text_2))
++ .child(action),
++ )
++ }))
.into_any_element()
}
--/// The empty-lane states. Only three tracks have one; the rest render nothing.
++/// The empty-lane states. The zoom lane's own prompt is interactive and lives
++/// on the window's row overlay instead.
fn render_empty_track(
theme: &Theme,
kind: TrackKind,
hovered: bool,
active: bool,
) -> Option<AnyElement> {
-- match kind {
++ let (copy, action) = match kind {
// `TL/CaptionsTrack.tsx:146-160`.
-- TrackKind::Caption => Some(
-- div()
-- .absolute()
-- .inset_0()
-- .flex()
-- .flex_col()
-- .gap(px(8.))
-- .items_center()
-- .justify_center()
-- .rounded(px(12.))
-- .bg(with_alpha(Hsla::from(theme.gray_3), 0.1))
-- .text_size(px(14.))
-- .text_color(text_tertiary(theme))
-- .child("No captions")
-- .into_any_element(),
-- ),
++ TrackKind::Caption => ("No captions", None),
// `TL/KeyboardTrack.tsx:146-153`.
-- TrackKind::Keyboard => Some(
-- div()
-- .absolute()
-- .inset_0()
-- .flex()
-- .flex_col()
-- .items_center()
-- .justify_center()
-- .rounded(px(12.))
-- .bg(with_alpha(Hsla::from(theme.gray_3), 0.1))
-- .text_size(px(14.))
-- .text_color(text_tertiary(theme))
-- .child("No keyboard events")
-- .child(
-- div()
-- .mt(px(2.))
-- .text_size(px(10.))
-- .text_color(with_alpha(text_tertiary(theme), 0.4))
-- .child("Record keyboard presses or generate from recording"),
-- )
-- .into_any_element(),
++ TrackKind::Keyboard => ("No keyboard events", None),
++ // `TL/AudioTrack.tsx:400-427`, `TL/ThreeDTrack.tsx:319-337`, and the
++ // scene lane, which had no empty state at all.
++ TrackKind::Audio => (
++ kind.picker_description().trim_end_matches('.'),
++ Some("Add audio"),
),
-- // `TL/AudioTrack.tsx:400-427` -- the dashed "Add audio" button.
-- TrackKind::Audio => Some(render_add_track_empty(
-- theme,
-- "Add audio",
-- emerald_9(),
-- emerald_11(theme),
-- active,
-- hovered,
-- )),
-- // `TL/ThreeDTrack.tsx:319-337`.
-- TrackKind::ThreeD => Some(render_add_track_empty(
-- theme,
-- "Add 3D scene",
-- TrackKind::ThreeD.color(),
-- Hsla::from(theme.gray_12),
-- active,
-- hovered,
-- )),
-- // The empty zoom track's tint (`TL/ZoomTrack.tsx:300`):
-- // `bg-gray-3/20 dark:bg-gray-3/10 rounded-xl`. The generate button is
-- // interactive and lives on the window's row overlay instead.
-- TrackKind::Zoom => Some(
-- div()
-- .absolute()
-- .inset_0()
-- .rounded(px(12.))
-- .bg(with_alpha(
-- Hsla::from(theme.gray_3),
-- if theme.is_dark() { 0.1 } else { 0.2 },
-- ))
-- .into_any_element(),
++ TrackKind::ThreeD => (
++ kind.picker_description().trim_end_matches('.'),
++ Some("Add 3D scene"),
),
-- _ => None,
-- }
++ TrackKind::Scene => (
++ kind.picker_description().trim_end_matches('.'),
++ Some("Add scene"),
++ ),
++ _ => return None,
++ };
++ Some(render_empty_prompt(
++ theme,
++ kind.color(),
++ copy,
++ action,
++ hovered,
++ active,
++ ))
}
--/// `SegmentRoot` (`TL/Track.tsx:100-137`): the positioned outer box with its
--/// selection border, the `cap-track-fill` inner box, the label at whatever tier
--/// its visible width allows, and the two trim handles.
++/// `SegmentRoot` (`TL/Track.tsx:100-137`): the positioned box, its tinted fill
++/// and inset ring, the accent bar flush against its left edge, the label at
++/// whatever tier its visible width allows, and the two trim handles.
#[allow(clippy::too_many_arguments)]
fn render_segment(
theme: &Theme,
@@@ -2408,7 -2317,7 +2378,7 @@@
split_mode: bool,
) -> AnyElement {
let color = if matches!(segment.detail, SegmentDetail::Clip { muted: true, .. }) {
-- gpui::rgb(track_color::MUTED_CLIP).into()
++ muted_clip_color(theme)
} else {
kind.color()
};
@@@ -2437,11 -2340,11 +2407,18 @@@
.w_full()
.flex()
.flex_row()
-- .rounded(px(12.))
++ .rounded(px(SEGMENT_RADIUS))
.overflow_hidden()
-- .bg(color)
-- .border_1()
-- .border_color(track_fill_border(color));
++ .bg(seg_fill(theme, color, selected))
++ .child(
++ div()
++ .absolute()
++ .top_0()
++ .bottom_0()
++ .left_0()
++ .w(px(SEGMENT_ACCENT_BAR))
++ .bg(color),
++ );
// The clip track's waveform and its per-second markings, both under the
// label (`TL/ClipTrack.tsx:943-957`).
@@@ -2460,10 -2363,10 +2437,11 @@@
view,
width,
height,
++ color,
));
}
fill = fill.child(render_clip_markings(
-- theme,
++ color,
segment,
holds,
view,
@@@ -2473,11 -2376,11 +2451,18 @@@
for (hold_start, hold_end) in holds.iter() {
let hold_x = ((hold_start - segment.start) / secs_per_pixel) as f32;
let hold_width = ((hold_end - hold_start) / secs_per_pixel) as f32;
-- fill = fill.child(render_hold(hold_x, hold_width));
++ fill = fill.child(render_hold(theme, color, hold_x, hold_width));
}
}
-- fill = fill.child(render_label(theme, kind, segment, visible_width, center_x));
++ fill = fill.child(render_label(
++ theme,
++ color,
++ segment,
++ visible_width,
++ center_x,
++ kind,
++ ));
// The audio track's fade envelopes (`FadeControl`,
// `TL/AudioTrack.tsx:118-201`). The fade *handles* -- dragging the envelope
@@@ -2493,25 -2396,25 +2478,28 @@@
if fraction <= 0.001 {
continue;
}
-- fill = fill.child(render_fade(edge_in, fraction as f32, width, height));
++ fill = fill.child(render_fade(
++ theme,
++ color,
++ edge_in,
++ fraction as f32,
++ width,
++ height,
++ ));
}
}
// `SegmentHandle` (`TL/Track.tsx:236-258`): a 20px hit target with a 3px
-- // visible bar, half-overhanging each edge. `compact() ? "opacity-55" :
-- // "opacity-35 group-hover:opacity-100"`, and the clip track's own handles
-- // add `opacity-0 group-hover:opacity-100` (`TL/ClipTrack.tsx:1137, 1286`).
-- // A *compact* handle carries no `group-hover` class, so it stays at 0.55
-- // with the pointer on it.
++ // visible bar, half-overhanging each edge. A *compact* handle carries no
++ // `group-hover` class over there, so it stays visible with the pointer on
++ // it (`TL/Track.tsx:250`).
let compact = (width as f64) < 40.;
let handle_opacity = if compact {
0.55
} else if hovered {
-- 1.
-- } else if kind == TrackKind::Clip {
-- 0.
++ 0.9
} else {
-- 0.35
++ 0.
};
div()
@@@ -2520,28 -2423,28 +2508,25 @@@
.bottom_0()
.left(px(x))
.w(px(width))
-- .rounded(px(12.))
-- .border_1()
-- // `isSelected() ? <segColor> : "border-transparent"`, one line per
-- // track; the nine colours are enumerated on `selected_border_color`,
-- // two of which are dead classes in the shipping app and paint nothing.
-- .border_color(if selected {
-- selected_border_color(theme, kind)
-- } else {
-- gpui::transparent_black()
-- })
++ .rounded(px(SEGMENT_RADIUS))
.when_some(dim, |this, opacity| this.opacity(opacity))
// `interactMode === "split" && "timeline-scissors-cursor"`
// (`TL/Track.tsx:107-108`). That cursor is an inline SVG data-URI;
// this rev has the standard set only, so a crosshair stands in.
.when(split_mode, |this| this.cursor(gpui::CursorStyle::Crosshair))
-- .child(fill)
-- .child(render_handle(true, handle_opacity))
-- .child(render_handle(false, handle_opacity))
++ .child(if selected {
++ fill.border(px(1.5))
++ .border_color(Hsla::from(theme.editor.accent))
++ } else {
++ fill.border_1()
++ .border_color(seg_border(theme, color, if hovered { 0.10 } else { 0. }))
++ })
++ .child(render_handle(theme, color, true, handle_opacity))
++ .child(render_handle(theme, color, false, handle_opacity))
.into_any_element()
}
--fn render_handle(start: bool, opacity: f32) -> impl IntoElement {
++fn render_handle(theme: &Theme, color: Hsla, start: bool, opacity: f32) -> impl IntoElement {
div()
.absolute()
.top_0()
@@@ -2560,23 -2463,23 +2545,31 @@@
})
.flex()
.items_center()
-- .justify_center()
.opacity(opacity)
.child(
-- // `w-[3px] h-8 bg-solid-white rounded-full` -- `--solid-white` is
-- // `#ffffff` in both themes (`theme.css:74, 140`).
-- div().w(px(3.)).h(px(32.)).rounded_full().bg(gpui::white()),
++ div()
++ .absolute()
++ .w(px(3.))
++ .h(px(16.))
++ .rounded(px(2.))
++ .bg(seg_handle(theme, color))
++ .map(|this| {
++ if start {
++ this.left(px(15.))
++ } else {
++ this.right(px(15.))
++ }
++ }),
)
}
/// `Markings` (`TL/ClipTrack.tsx:1425-1476`): one hairline per ruler tick,
/// drawn *inside* each clip box in recording time and pushed past the holds the
--/// stretched box inserts before it. The gradient is
--/// `from-transparent to-transparent via-white-transparent-40
--/// dark:via-black-transparent-60`, i.e. a three-stop fade with the mid colour at
--/// the centre -- gpui takes two stops, so it is drawn as two stacked halves.
++/// stretched box inserts before it. The gradient is a three-stop fade with the
++/// mid colour at the centre -- gpui takes two stops, so it is drawn as two
++/// stacked halves.
fn render_clip_markings(
-- theme: &Theme,
++ color: Hsla,
segment: &Segment,
holds: &[(f64, f64)],
view: TimelineView,
@@@ -2596,16 -2499,16 +2589,8 @@@
let first = (visible_min / resolution).floor();
let count = ((visible_max / resolution).ceil() - first).max(0.) as usize;
-- // `--white-transparent-40: rgba(255,255,255,0.4)` in light and
-- // `--black-transparent-60: rgba(255,255,255,0.6)` in dark
-- // (`theme.css:64, 70, 129, 136`) -- the dark override of *both* names is
-- // white, so the hairline is white in either theme, only its alpha changes.
-- let via = if theme.is_dark() {
-- with_alpha(gpui::white(), 0.6)
-- } else {
-- with_alpha(gpui::white(), 0.4)
-- };
-- let transparent = with_alpha(gpui::white(), 0.);
++ let via = with_alpha(color, 0.14);
++ let transparent = with_alpha(color, 0.);
let mut root = div();
let holds_relative: Vec<(f64, f64)> = holds
@@@ -2645,16 -2548,16 +2630,26 @@@
}
/// One audio fade envelope (`fadeGeometry` / `fadeEnvelopeCurve` /
--/// `FadeControl`, `TL/AudioTrack.tsx:63-201`): a 34 %-black shade over the
--/// faded span with a white curve along its top, plus the 10px corner triangle
--/// at the segment's edge.
++/// `FadeControl`, `TL/AudioTrack.tsx:63-201`): the faded span washed back
++/// towards the card with the envelope curve along its top, plus the 10px
++/// corner triangle at the segment's edge.
///
/// The source draws the curve in a `viewBox="0 0 100 100"` with
/// `preserveAspectRatio="none"`, so the two cubic control points are in
/// percent of the span; they are scaled into pixels here.
--fn render_fade(edge_in: bool, fraction: f32, width: f32, height: f32) -> impl IntoElement {
++fn render_fade(
++ theme: &Theme,
++ color: Hsla,
++ edge_in: bool,
++ fraction: f32,
++ width: f32,
++ height: f32,
++) -> impl IntoElement {
let span = (fraction * width).max(0.);
let shade_x = if edge_in { 0. } else { width - span };
++ let shade = with_alpha(Hsla::from(theme.editor.card), 0.55);
++ let curve = with_alpha(seg_label(theme, color), 0.85);
++ let corner = with_alpha(seg_handle(theme, color), 0.8);
div()
.absolute()
@@@ -2666,7 -2569,7 +2661,7 @@@
.bottom_0()
.left(px(shade_x))
.w(px(span))
-- .bg(with_alpha(gpui::black(), 0.34)),
++ .bg(shade),
)
.child(
// `M 0,100 C 0,68 span*0.55,10 span,0` in, and
@@@ -2698,7 -2601,7 +2693,7 @@@
);
}
if let Ok(path) = builder.build() {
-- window.paint_path(path, with_alpha(gpui::white(), 0.94));
++ window.paint_path(path, curve);
}
},
)
@@@ -2737,7 -2640,7 +2732,7 @@@
}
builder.close();
if let Ok(path) = builder.build() {
-- window.paint_path(path, with_alpha(gpui::white(), 0.9));
++ window.paint_path(path, corner);
}
},
)
@@@ -2748,9 -2651,9 +2743,10 @@@
}
/// The paused window a fullscreen text segment inserts inside a clip
--/// (`TL/ClipTrack.tsx:959-1002`): a 45 % black wash with a 45-degree hatch and
--/// a pause glyph.
--fn render_hold(x: f32, width: f32) -> impl IntoElement {
++/// (`TL/ClipTrack.tsx:959-1002`): the clip's tint washed back to the card,
++/// ruled off at both edges, with a pause glyph.
++fn render_hold(theme: &Theme, color: Hsla, x: f32, width: f32) -> impl IntoElement {
++ let ink = with_alpha(seg_label(theme, color), 0.75);
div()
.absolute()
.top_0()
@@@ -2763,23 -2666,23 +2759,23 @@@
.justify_center()
.gap(px(4.))
.overflow_hidden()
-- .bg(with_alpha(gpui::black(), 0.45))
++ .bg(with_alpha(Hsla::from(theme.editor.card), 0.6))
.border_l_1()
.border_r_1()
-- .border_color(with_alpha(gpui::white(), 0.25))
++ .border_color(seg_border(theme, color, 0.))
.child(
svg()
.path("icons/pause.svg")
.size(px(12.))
.flex_none()
-- .text_color(with_alpha(gpui::white(), 0.7)),
++ .text_color(ink),
)
.when(width >= 64., |this| {
this.child(
div()
.text_size(px(10.))
.font_weight(FontWeight::MEDIUM)
-- .text_color(with_alpha(gpui::white(), 0.7))
++ .text_color(ink)
.child("Paused"),
)
})
@@@ -2800,6 -2703,6 +2796,7 @@@ fn render_waveform
view: TimelineView,
width: f32,
height: f32,
++ color: Hsla,
) -> impl IntoElement {
// `micWaveform()` / `systemAudioWaveform()` (`TL/ClipTrack.tsx:713-730`):
// a track muted below -30 dB draws nothing at all.
@@@ -2826,6 -2729,6 +2823,8 @@@
let transform = view.transform;
let segment_start = segment.start;
let full_width = width.max(1.) as f64;
++ let wave_height = height.min(WAVEFORM_MAX_HEIGHT);
++ let wave_color = waveform_color(color);
gpui::canvas(
|bounds, _window, _cx| bounds,
@@@ -2845,13 -2748,13 +2844,10 @@@
bounds.origin.y,
);
let slice_width = ((visible_end - visible_start) * px_per_sec) as f32;
-- let size = gpui::size(px(slice_width), px(height));
++ let size = gpui::size(px(slice_width), px(wave_height));
let samples = waveform_sample_count(slice_width as f64);
-- for (peaks, color, scale) in [
-- (&mic, WAVEFORM_MIC_COLOR, mic_scale),
-- (&system, waveform_system_color(), system_scale),
-- ] {
++ for (peaks, scale) in [(&mic, mic_scale), (&system, system_scale)] {
if let Some(path) = waveform_path(
peaks,
(visible_start, visible_end),
@@@ -2862,27 -2765,27 +2858,29 @@@
size,
scale,
) {
-- window.paint_path(path, color);
++ window.paint_path(path, wave_color);
}
}
},
)
.absolute()
-- .top_0()
++ .bottom_0()
.left_0()
.w(px(width))
-- .h(px(height))
++ .h(px(wave_height))
.into_any_element()
}
/// `SegmentLabel` (`TL/Track.tsx:186-220`): full, compact and glyph tiers,
--/// anchored to the visible box's clamped centre and clipped to its width.
++/// anchored to the visible box and left-aligned inside the segment's own
++/// `0 10px 0 13px` content padding.
fn render_label(
theme: &Theme,
-- kind: TrackKind,
++ color: Hsla,
segment: &Segment,
visible_width: f64,
center_x: f64,
++ kind: TrackKind,
) -> impl IntoElement {
let compact_at = match kind {
TrackKind::Caption | TrackKind::Keyboard | TrackKind::Audio => {
@@@ -2890,7 -2793,7 +2888,6 @@@
}
_ => SEGMENT_LABEL_COMPACT_PX,
};
-- let max_width = (visible_width - 8.).max(0.);
let tier = if visible_width >= SEGMENT_LABEL_FULL_PX {
LabelTier::Full
} else if visible_width >= compact_at {
@@@ -2901,20 -2804,20 +2898,32 @@@
return div();
};
-- let Some(body) = label_body(theme, segment, tier, visible_width) else {
++ let Some(body) = label_body(theme, color, segment, tier, visible_width) else {
return div();
};
++ // A narrow box cannot pay for the accent bar's clearance and still show
++ // anything, so it falls back to a symmetric inset.
++ let (pad_left, pad_right) = if tier == LabelTier::Glyph {
++ (4., 4.)
++ } else if visible_width >= 60. {
++ (SEGMENT_PADDING_LEFT as f64, SEGMENT_PADDING_RIGHT as f64)
++ } else {
++ (6., 4.)
++ };
++ let max_width = (visible_width - pad_left - pad_right).max(0.);
++ let left = center_x - visible_width / 2. + pad_left;
++
div().child(
div()
.absolute()
.top_0()
.bottom_0()
-- .left(px((center_x - max_width / 2.) as f32))
++ .left(px(left as f32))
.w(px(max_width as f32))
.flex()
.items_center()
-- .justify_center()
++ .when(tier == LabelTier::Glyph, |this| this.justify_center())
.overflow_hidden()
.child(body),
)
@@@ -2927,44 -2830,25 +2936,67 @@@ enum LabelTier
Glyph,
}
--/// The nine tracks' label bodies. Every one is a straight transcription of its
--/// `SegmentLabel`'s `full` / `compact` / `glyph` props; a track with no `glyph`
--/// prop renders nothing at that tier, which is why this returns an `Option`.
++fn label_row() -> gpui::Div {
++ div()
++ .flex()
++ .flex_row()
++ .items_center()
++ .gap(px(8.))
++ .min_w_0()
++ .max_w_full()
++}
++
++fn label_primary(theme: &Theme, color: Hsla) -> gpui::Div {
++ div()
++ .min_w_0()
++ .truncate()
++ .text_size(px(12.))
++ .line_height(px(15.))
++ .font_weight(FontWeight::MEDIUM)
++ .text_color(seg_label(theme, color))
++}
++
++fn label_secondary(theme: &Theme, color: Hsla) -> gpui::Div {
++ div()
++ .flex_none()
++ .text_size(px(11.))
++ .line_height(px(15.))
++ .font_features(tabular_numerals())
++ .text_color(seg_muted(theme, color))
++}
++
++fn label_glyph(theme: &Theme, color: Hsla, path: &'static str, size: f32) -> AnyElement {
++ svg()
++ .path(path)
++ .size(px(size))
++ .flex_none()
++ .text_color(seg_label(theme, color))
++ .into_any_element()
++}
++
++/// The eleven tracks' label bodies: a primary name and, where the track has
++/// one, the value that qualifies it.
fn label_body(
theme: &Theme,
++ color: Hsla,
segment: &Segment,
tier: LabelTier,
visible_width: f64,
) -> Option<AnyElement> {
-- // `text-gray-1 dark:text-gray-12` is the label colour on every track but
-- // the clip's, which uses `text-white/70` over `dark:text-gray-12
-- // text-gray-1`.
-- let on_fill = if theme.is_dark() {
-- Hsla::from(theme.gray_12)
-- } else {
-- Hsla::from(theme.gray_1)
-- };
--
Some(match (&segment.detail, tier) {
+ (
+ SegmentDetail::Style { name, .. } | SegmentDetail::Image { name, .. },
+ LabelTier::Full | LabelTier::Compact,
- ) => div()
- .text_color(on_fill)
- .overflow_hidden()
- .text_ellipsis()
- .child(name.clone())
- .into_any_element(),
- (SegmentDetail::Style { .. }, LabelTier::Glyph) => svg()
- .path("icons/palette.svg")
- .size(px(12.))
- .text_color(on_fill)
- .into_any_element(),
- (SegmentDetail::Image { .. }, LabelTier::Glyph) => svg()
- .path("icons/image.svg")
- .size(px(12.))
- .text_color(on_fill)
++ ) => label_row()
++ .child(label_primary(theme, color).child(name.clone()))
+ .into_any_element(),
++ (SegmentDetail::Style { .. }, LabelTier::Glyph) => {
++ label_glyph(theme, color, "icons/palette.svg", 12.)
++ }
++ (SegmentDetail::Image { .. }, LabelTier::Glyph) => {
++ label_glyph(theme, color, "icons/image.svg", 12.)
++ }
++
// -- Clip (`TL/ClipTrack.tsx:1255-1279`) --------------------------
(
SegmentDetail::Clip {
@@@ -2974,70 -2858,70 +3006,10 @@@
..
},
LabelTier::Full,
-- ) => div()
-- .flex()
-- .flex_col()
-- .max_w_full()
-- .min_w_0()
-- .gap(px(4.))
-- .items_center()
-- .justify_center()
-- .text_size(px(12.))
-- .child(
-- div()
-- .flex()
-- .items_center()
-- .gap(px(4.))
-- .max_w_full()
-- .min_w_0()
-- .child(
-- div()
-- .min_w_0()
-- .truncate()
-- .text_color(with_alpha(gpui::white(), 0.7))
-- .child(name.clone()),
-- )
-- .when(*muted, |this| {
-- this.child(
-- div()
-- .flex()
-- .flex_none()
-- .items_center()
-- .gap(px(4.))
-- .px(px(4.))
-- .rounded(px(4.))
-- .bg(with_alpha(gpui::black(), 0.2))
-- .text_color(gpui::white())
-- .text_size(px(10.))
-- .font_weight(FontWeight::SEMIBOLD)
-- .child(svg().path("icons/volume-x.svg").size(px(12.)).flex_none())
-- .child("Muted"),
-- )
-- }),
-- )
-- .child(
-- div()
-- .flex()
-- .flex_row()
-- .gap(px(4.))
-- .items_center()
-- // `text-md` (`TL/ClipTrack.tsx:1259`) is *not* a defined
-- // class in this Tailwind v4 setup -- there is no
-- // `--text-md` token and it emits nothing into the built
-- // CSS -- so the row keeps the `text-xs` it inherits from
-- // the label wrapper (`ClipTrack.tsx:1257`): 12px, not 16.
-- // The clock stays `size-3.5` = 14px regardless.
-- .text_size(px(12.))
-- .text_color(on_fill)
-- .child(
-- svg()
-- .path("icons/clock.svg")
-- .size(px(14.))
-- .flex_none()
-- .text_color(on_fill),
-- )
-- .child(format_clip_time(*source_duration)),
-- )
++ ) => label_row()
++ .child(label_primary(theme, color).child(name.clone()))
++ .when(*muted, |this| this.child(muted_badge(theme, color)))
++ .child(label_secondary(theme, color).child(format_clip_time(*source_duration)))
.into_any_element(),
(
SegmentDetail::Clip {
@@@ -3046,45 -2930,45 +3018,32 @@@
..
},
LabelTier::Compact,
-- ) => div()
-- .flex()
-- .flex_row()
-- .max_w_full()
-- .min_w_0()
++ ) => label_row()
.gap(px(4.))
-- .items_center()
-- .text_size(px(10.))
-- .text_color(on_fill)
.when(*muted, |this| {
-- this.child(svg().path("icons/volume-x.svg").size(px(12.)).flex_none())
++ this.child(
++ svg()
++ .path("icons/volume-x.svg")
++ .size(px(12.))
++ .flex_none()
++ .text_color(seg_label(theme, color)),
++ )
})
-- .child(
-- div()
-- .min_w_0()
-- .truncate()
-- .child(format_clip_time(*source_duration)),
-- )
-- .into_any_element(),
-- (SegmentDetail::Clip { muted: true, .. }, LabelTier::Glyph) => svg()
-- .path("icons/volume-x.svg")
-- .size(px((visible_width - 8.).clamp(8., 14.) as f32))
-- .flex_none()
-- .text_color(gpui::white())
++ .child(label_primary(theme, color).child(format_clip_time(*source_duration)))
.into_any_element(),
++ (SegmentDetail::Clip { muted: true, .. }, LabelTier::Glyph) => label_glyph(
++ theme,
++ color,
++ "icons/volume-x.svg",
++ (visible_width - 8.).clamp(8., 14.) as f32,
++ ),
(SegmentDetail::Clip { .. }, LabelTier::Glyph) => {
return None;
}
// -- Zoom (`TL/ZoomTrack.tsx:696-723`) ----------------------------
-- (SegmentDetail::Zoom { amount, automatic }, LabelTier::Full) => div()
-- .flex()
-- .flex_col()
-- .gap(px(4.))
-- .items_center()
-- .justify_center()
-- .text_size(px(12.))
-- .text_color(on_fill)
-- .child(div().opacity(0.7).child(SharedString::from(
++ (SegmentDetail::Zoom { amount, automatic }, LabelTier::Full) => label_row()
++ .child(label_primary(theme, color).child(SharedString::from(
// The mode label only appears once the visible box is at
// least 140px wide (`TL/ZoomTrack.tsx:700-704`).
if visible_width >= 140. {
@@@ -3097,357 -2981,357 +3056,157 @@@
"Zoom"
},
)))
-- .child(
-- div()
-- .flex()
-- .flex_row()
-- .gap(px(4.))
-- .items_center()
-- // `text-md` (`TL/ZoomTrack.tsx:705`) is undefined over
-- // there, so this inherits the `text-xs` wrapper at
-- // `ZoomTrack.tsx:699`: 12px, not 16.
-- .text_size(px(12.))
-- .child(
-- svg()
-- .path("icons/search.svg")
-- .size(px(14.))
-- .flex_none()
-- .text_color(on_fill),
-- )
-- .child(format!("{amount:.1}x")),
- )
- .into_any_element(),
- (SegmentDetail::Zoom { amount, .. }, LabelTier::Compact) => div()
- .flex()
- .flex_row()
- .gap(px(4.))
- .items_center()
- .text_size(px(12.))
- .text_color(on_fill)
- .child(
- svg()
- .path("icons/search.svg")
- .size(px(12.))
- .flex_none()
- .text_color(on_fill),
-- )
- .child(format!("{amount:.1}x"))
++ .child(label_secondary(theme, color).child(format!("{amount:.1}x")))
.into_any_element(),
- (SegmentDetail::Zoom { amount, .. }, LabelTier::Compact) => div()
- .flex()
- .flex_row()
- .gap(px(4.))
- .items_center()
- .text_size(px(12.))
- .text_color(on_fill)
- .child(
- svg()
- .path("icons/search.svg")
- .size(px(12.))
- .flex_none()
- .text_color(on_fill),
- )
- .child(format!("{amount:.1}x"))
- .into_any_element(),
-- (SegmentDetail::Zoom { .. }, LabelTier::Glyph) => svg()
-- .path("icons/search.svg")
-- .size(px(14.))
-- .text_color(on_fill)
++ (SegmentDetail::Zoom { amount, .. }, LabelTier::Compact) => label_row()
++ .child(label_primary(theme, color).child(format!("{amount:.1}x")))
.into_any_element(),
++ (SegmentDetail::Zoom { .. }, LabelTier::Glyph) => {
++ label_glyph(theme, color, "icons/search.svg", 12.)
++ }
// -- Scene (`TL/SceneTrack.tsx:543-566`) --------------------------
-- (SegmentDetail::Scene { mode }, LabelTier::Full) => div()
-- .flex()
-- .flex_col()
-- .gap(px(4.))
-- .items_center()
-- .justify_center()
-- .text_size(px(12.))
-- .text_color(on_fill)
-- .child(div().opacity(0.7).child("Scene"))
-- .child(
-- div()
-- .flex()
-- .flex_row()
-- .gap(px(4.))
-- .items_center()
-- .child(
-- svg()
-- .path(scene_icon(*mode))
-- .size(px(14.))
-- .flex_none()
-- .text_color(on_fill),
-- )
-- .child(scene_label(*mode)),
- )
- .into_any_element(),
- (SegmentDetail::Scene { mode }, LabelTier::Compact) => div()
- .flex()
- .flex_row()
- .gap(px(4.))
- .items_center()
- .text_size(px(12.))
- .text_color(on_fill)
- .child(
- svg()
- .path(scene_icon(*mode))
- .size(px(14.))
- .flex_none()
- .text_color(on_fill),
-- )
- .child(scene_label(*mode))
++ (SegmentDetail::Scene { mode }, LabelTier::Full) => label_row()
++ .child(label_primary(theme, color).child("Scene"))
++ .child(label_secondary(theme, color).child(scene_label(*mode)))
.into_any_element(),
- (SegmentDetail::Scene { mode }, LabelTier::Compact) => div()
- .flex()
- .flex_row()
- .gap(px(4.))
- .items_center()
- .text_size(px(12.))
- .text_color(on_fill)
- .child(
- svg()
- .path(scene_icon(*mode))
- .size(px(14.))
- .flex_none()
- .text_color(on_fill),
- )
- .child(scene_label(*mode))
- .into_any_element(),
-- (SegmentDetail::Scene { mode }, LabelTier::Glyph) => svg()
-- .path(scene_icon(*mode))
-- .size(px(14.))
-- .text_color(on_fill)
++ (SegmentDetail::Scene { mode }, LabelTier::Compact) => label_row()
++ .child(label_primary(theme, color).child(scene_label(*mode)))
.into_any_element(),
++ (SegmentDetail::Scene { mode }, LabelTier::Glyph) => {
++ label_glyph(theme, color, scene_icon(*mode), 12.)
++ }
// -- 3D (`TL/ThreeDTrack.tsx:655-687`) ----------------------------
-- (SegmentDetail::ThreeD { motion }, LabelTier::Full) => div()
-- .flex()
-- .flex_col()
-- .gap(px(4.))
-- .items_center()
-- .justify_center()
-- .text_size(px(12.))
-- .text_color(on_fill)
-- .child(div().opacity(0.7).child(if visible_width >= 140. {
++ (SegmentDetail::ThreeD { motion }, LabelTier::Full) => label_row()
++ .child(label_primary(theme, color).child(if visible_width >= 140. {
"3D Perspective"
} else {
"3D"
}))
-- .child(
-- div()
-- .flex()
-- .flex_row()
-- .gap(px(4.))
-- .items_center()
-- // `text-md` (`TL/ThreeDTrack.tsx:663`) is undefined over
-- // there, so this inherits the `text-xs` wrapper at
-- // `ThreeDTrack.tsx:657`: 12px, not 16.
-- .text_size(px(12.))
-- .child(
-- svg()
-- .path("icons/rotate-3d.svg")
-- .size(px(14.))
-- .flex_none()
-- .text_color(on_fill),
-- )
-- .child(if *motion { "Motion" } else { "Still" })
-- .when(*motion, |this| {
-- this.child(
-- svg()
-- .path("icons/chevron-right.svg")
-- .size(px(12.))
-- .flex_none()
-- .opacity(0.7)
-- .text_color(on_fill),
-- )
-- }),
- )
- .into_any_element(),
- (SegmentDetail::ThreeD { .. }, LabelTier::Compact) => div()
- .flex()
- .flex_row()
- .gap(px(4.))
- .items_center()
- .text_size(px(12.))
- .text_color(on_fill)
- .child(
- svg()
- .path("icons/rotate-3d.svg")
- .size(px(12.))
- .flex_none()
- .text_color(on_fill),
-- )
- .child("3D")
++ .child(label_secondary(theme, color).child(if *motion { "Motion" } else { "Still" }))
.into_any_element(),
- (SegmentDetail::ThreeD { .. }, LabelTier::Compact) => div()
- .flex()
- .flex_row()
- .gap(px(4.))
- .items_center()
- .text_size(px(12.))
- .text_color(on_fill)
- .child(
- svg()
- .path("icons/rotate-3d.svg")
- .size(px(12.))
- .flex_none()
- .text_color(on_fill),
- )
- .child("3D")
- .into_any_element(),
-- (SegmentDetail::ThreeD { .. }, LabelTier::Glyph) => svg()
-- .path("icons/rotate-3d.svg")
-- .size(px(14.))
-- .text_color(on_fill)
++ (SegmentDetail::ThreeD { .. }, LabelTier::Compact) => label_row()
++ .child(label_primary(theme, color).child("3D"))
.into_any_element(),
++ (SegmentDetail::ThreeD { .. }, LabelTier::Glyph) => {
++ label_glyph(theme, color, "icons/rotate-3d.svg", 12.)
++ }
// -- Text (`TL/TextTrack.tsx:428-481`) ----------------------------
(
SegmentDetail::Text {
content,
-- color,
++ color: text_color,
italic,
bold,
fullscreen,
..
},
-- LabelTier::Full,
-- ) => div()
-- .flex()
-- .flex_col()
-- .gap(px(2.))
-- .items_center()
-- .justify_center()
-- .text_size(px(12.))
-- .text_color(on_fill)
++ LabelTier::Full | LabelTier::Compact,
++ ) => label_row()
++ .gap(px(6.))
.child(
div()
-- .flex()
-- .flex_row()
-- .gap(px(4.))
-- .items_center()
-- .opacity(0.7)
-- .child("Text")
-- .when(*fullscreen, |this| {
-- this.child(
-- svg()
-- .path("icons/pause.svg")
-- .size(px(10.))
-- .flex_none()
-- .text_color(on_fill),
-- )
-- }),
++ .size(px(8.))
++ .flex_none()
++ .rounded_full()
++ .bg(*text_color),
)
-- .child(text_content_row(content, *color, *italic, *bold, on_fill))
++ .child(
++ label_primary(theme, color)
++ .when(*bold, |this| this.font_weight(FontWeight::BOLD))
++ .when(*italic, |this| this.italic())
++ .child(content.clone()),
++ )
++ .when(*fullscreen, |this| {
++ this.child(
++ svg()
++ .path("icons/pause.svg")
++ .size(px(10.))
++ .flex_none()
++ .text_color(seg_muted(theme, color)),
++ )
++ })
.into_any_element(),
-- (
-- SegmentDetail::Text {
-- content,
-- color,
-- italic,
-- bold,
-- ..
-- },
-- LabelTier::Compact,
-- ) => text_content_row(content, *color, *italic, *bold, on_fill).into_any_element(),
(SegmentDetail::Text { fullscreen, .. }, LabelTier::Glyph) => {
if !*fullscreen {
return None;
}
-- svg()
-- .path("icons/pause.svg")
-- .size(px(10.))
-- .opacity(0.7)
-- .text_color(on_fill)
-- .into_any_element()
++ label_glyph(theme, color, "icons/pause.svg", 10.)
}
// -- Mask (`TL/MaskTrack.tsx:481-495`) ----------------------------
-- (SegmentDetail::Mask { label }, LabelTier::Full) => div()
-- .flex()
-- .flex_col()
-- .gap(px(2.))
-- .items_center()
-- .justify_center()
-- .text_size(px(12.))
-- .text_color(on_fill)
-- .child(div().opacity(0.7).child("Mask"))
-- // `text-md` (`TL/MaskTrack.tsx:485`) is undefined over there, so
-- // this inherits the `text-xs` wrapper at `MaskTrack.tsx:483`:
-- // 12px, not 16.
-- .child(div().text_size(px(12.)).child(*label))
++ (SegmentDetail::Mask { label }, LabelTier::Full) => label_row()
++ .child(label_primary(theme, color).child("Mask"))
++ .child(label_secondary(theme, color).child(*label))
.into_any_element(),
-- (SegmentDetail::Mask { label }, LabelTier::Compact) => div()
-- .text_size(px(12.))
-- .text_color(on_fill)
-- .truncate()
-- .child(*label)
++ (SegmentDetail::Mask { label }, LabelTier::Compact) => label_row()
++ .child(label_primary(theme, color).child(*label))
.into_any_element(),
// The mask track passes no `glyph`.
(SegmentDetail::Mask { .. }, LabelTier::Glyph) => return None,
// -- Audio (`TL/AudioTrack.tsx:532-549`) --------------------------
-- (SegmentDetail::Audio { name, .. }, LabelTier::Full) => div()
-- .flex()
-- .flex_row()
-- .gap(px(6.))
-- .items_center()
-- .text_size(px(12.))
-- .text_color(with_alpha(gpui::white(), 0.95))
-- .child(
-- svg()
-- .path("icons/music.svg")
-- .size(px(12.))
-- .flex_none()
-- .opacity(0.9)
-- .text_color(with_alpha(gpui::white(), 0.95)),
-- )
++ (SegmentDetail::Audio { name, .. }, LabelTier::Full) => label_row()
++ .child(label_primary(theme, color).child(name.clone()))
.child(
-- div()
-- .font_weight(FontWeight::MEDIUM)
-- .truncate()
-- .child(name.clone()),
++ label_secondary(theme, color).child(format_clip_time(segment.end - segment.start)),
)
.into_any_element(),
-- (SegmentDetail::Audio { name, .. }, LabelTier::Compact) => div()
-- .text_size(px(12.))
-- .font_weight(FontWeight::MEDIUM)
-- .truncate()
-- .text_color(with_alpha(gpui::white(), 0.95))
-- .child(name.clone())
++ (SegmentDetail::Audio { name, .. }, LabelTier::Compact) => label_row()
++ .child(label_primary(theme, color).child(name.clone()))
.into_any_element(),
(SegmentDetail::Audio { .. }, LabelTier::Glyph) => return None,
// -- Captions (`TL/CaptionsTrack.tsx:174-181, 268-272`) -----------
// One row serves both tiers; it just clips against a smaller box.
-- (SegmentDetail::Caption { text }, LabelTier::Full | LabelTier::Compact) => div()
-- .text_size(px(10.))
-- .opacity(0.8)
-- .truncate()
-- .text_color(on_fill)
-- .child(text.clone())
++ (SegmentDetail::Caption { text }, LabelTier::Full | LabelTier::Compact) => label_row()
++ .child(label_primary(theme, color).child(text.clone()))
.into_any_element(),
(SegmentDetail::Caption { .. }, LabelTier::Glyph) => return None,
// -- Keyboard (`TL/KeyboardTrack.tsx:166-173, 260-268`) -----------
-- (SegmentDetail::Keyboard { text }, LabelTier::Full | LabelTier::Compact) => div()
-- .font_family("monospace")
-- .text_size(px(10.))
-- .opacity(0.8)
-- .truncate()
-- .text_color(on_fill)
-- .child(text.clone())
++ (SegmentDetail::Keyboard { text }, LabelTier::Full | LabelTier::Compact) => label_row()
++ .child(
++ label_primary(theme, color)
++ .font_family("monospace")
++ .child(text.clone()),
++ )
.into_any_element(),
-- (SegmentDetail::Keyboard { .. }, LabelTier::Glyph) => div()
++ (SegmentDetail::Keyboard { .. }, LabelTier::Glyph) => label_primary(theme, color)
.font_family("monospace")
-- .text_size(px(10.))
-- .opacity(0.8)
-- .text_color(on_fill)
.child("\u{2328}")
.into_any_element(),
})
}
--/// `textContentRow` (`TL/TextTrack.tsx:428-450`): the segment's own colour as a
--/// 8px swatch, then its content in the segment's weight and slant.
--fn text_content_row(
-- content: &SharedString,
-- color: Hsla,
-- italic: bool,
-- bold: bool,
-- on_fill: Hsla,
--) -> impl IntoElement {
++/// The muted clip's badge (`TL/ClipTrack.tsx:1265-1276`).
++fn muted_badge(theme: &Theme, color: Hsla) -> impl IntoElement {
div()
.flex()
-- .flex_row()
-- .gap(px(6.))
++ .flex_none()
.items_center()
-- .justify_center()
-- .max_w_full()
-- // `text-md` (`TL/TextTrack.tsx:328`) is undefined over there. Both
-- // call sites wrap this row in `text-xs` (`TextTrack.tsx:461` for the
-- // full tier, `:472` for the compact one), so it is 12px, not 16 --
-- // set explicitly because the compact tier calls this helper with no
-- // sized parent of its own.
-- .text_size(px(12.))
-- .text_color(on_fill)
++ .gap(px(3.))
++ .px(px(5.))
++ .rounded(px(4.))
++ .bg(seg_border(theme, color, 0.))
++ .text_size(px(10.))
++ .line_height(px(14.))
++ .font_weight(FontWeight::MEDIUM)
++ .text_color(seg_label(theme, color))
.child(
-- div()
-- .size(px(8.))
++ svg()
++ .path("icons/volume-x.svg")
++ .size(px(10.))
.flex_none()
-- .rounded_full()
-- .border_1()
-- .border_color(with_alpha(gpui::white(), 0.4))
-- .bg(color),
-- )
-- .child(
-- div()
-- .truncate()
-- .max_w_full()
-- .when(bold, |this| this.font_weight(FontWeight::BOLD))
-- .when(italic, |this| this.italic())
-- .child(content.clone()),
++ .text_color(seg_label(theme, color)),
)
++ .child("Muted")
}
--/// The playhead (`TL/index.tsx:1279-1295`) and the hover ghost (`:1255-1277`).
--///
--/// Both are a 1px column from `PLAYHEAD_TOP_OFFSET` to the container's bottom
--/// with a 12px knob at the top; the ghost is grey and the playhead red, and the
--/// playhead's own x is additionally clamped to the timeline width so it parks
--/// at the right edge instead of running off it.
++/// The playhead's own x is clamped to the timeline width so it parks at the
++/// right edge instead of running off it:
/// `translateX(min((playbackTime - position) / secsPerPixel, timelineWidth))`
/// (`TL/index.tsx:1287-1291`). Only the **upper** bound is clamped, so a
/// playhead left of the viewport really does run off the left edge and the
@@@ -3469,84 -3353,82 +3228,55 @@@ pub fn ghost_offset(view: TimelineView
.map(|time| ((time - view.transform.position) / secs_per_pixel) as f32)
}
--pub fn render_playhead(color: Hsla, x: f32, knob_color: Hsla) -> AnyElement {
-- render_playhead_with_opacity(color, x, knob_color, 1.)
++/// The playhead: a 1px column from the ruler's baseline to the bottom of the
++/// card, with a 12px head ringed in the card's own colour so it reads as a
++/// knob rather than a dot on the line. gpui has no outline, so the ring is a
++/// wider circle of card painted under the head.
++pub fn render_playhead(theme: &Theme, x: f32, opacity: f32) -> AnyElement {
++ let color = Hsla::from(theme.editor.playhead);
++ render_line(
++ color,
++ x,
++ opacity,
++ Some((12., color, theme.editor.card.into())),
++ )
}
--pub fn render_playhead_with_opacity(
-- color: Hsla,
-- x: f32,
-- knob_color: Hsla,
-- opacity: f32,
--) -> AnyElement {
++/// The hover preview line (`TL/index.tsx:1255-1277`).
++pub fn render_preview_line(theme: &Theme, x: f32) -> AnyElement {
++ let color = with_alpha(Hsla::from(theme.editor.text_3), 0.5);
++ render_line(color, x, 1., Some((10., color, theme.editor.card.into())))
++}
++
++fn render_line(color: Hsla, x: f32, opacity: f32, head: Option<(f32, Hsla, Hsla)>) -> AnyElement {
div()
.absolute()
// `left: ${TIMELINE_PADDING + TRACK_GUTTER}px` (`TL/index.tsx:1285`),
-- // i.e. 128 from the container's own left edge -- which is where gpui
-- // resolves an absolutely positioned child from too.
++ // measured from the card's padding box -- which is where gpui resolves
++ // an absolutely positioned child from too.
.left(px(TIMELINE_PADDING + TRACK_GUTTER + x))
.top(px(PLAYHEAD_TOP_OFFSET))
.bottom_0()
.w(px(1.))
-- .rounded_full()
.opacity(opacity)
-- .bg(playhead_gradient(color))
-- .child(
-- // `size-3 rounded-full -mt-2 -ml-[calc(0.37rem-0.5px)]`: a 12px dot
-- // 8px above the top of the column and half a pixel left of centre.
++ .bg(color)
++ .children(head.map(|(size, fill, ring)| {
++ let ring_size = size + 4.;
div()
.absolute()
-- .top(px(-8.))
-- .left(px(-5.42))
-- .size(px(12.))
++ .top(px(-ring_size / 2.))
++ .left(px(-(ring_size - 1.) / 2.))
++ .size(px(ring_size))
.rounded_full()
-- .bg(knob_color),
-- )
++ .flex()
++ .items_center()
++ .justify_center()
++ .bg(ring)
++ .child(div().size(px(size)).rounded_full().bg(fill))
++ }))
.into_any_element()
}
--/// The per-track selected border (`TL/index.tsx` per-track `segColor` blocks,
--/// enumerated in the digest's 4.3).
--///
--/// **`border-green-7` (captions) and `border-sky-7` (keyboard) are dead
--/// classes in the shipping app.** `theme.css` imports Radix
--/// red/gray/blue/indigo/yellow/jade only, and `packages/ui-solid/src/main.css`
--/// maps `--color-emerald-*` to jade and `--color-blue-*` to blue but declares
--/// no `--color-green-*` or `--color-sky-*`, so Tailwind v4 generates no rule
--/// for either. Selecting a caption or keyboard segment changes nothing on
--/// screen today.
--pub fn selected_border_color(theme: &Theme, kind: TrackKind) -> Hsla {
-- match kind {
-- // `border-gray-12`.
-- TrackKind::Clip
-- | TrackKind::Zoom
-- | TrackKind::Scene
-- | TrackKind::ThreeD
- | TrackKind::Mask
- | TrackKind::Style
- | TrackKind::Image => Hsla::from(theme.gray_12),
- | TrackKind::Mask => Hsla::from(theme.gray_12),
-- // `border-blue-7`: Radix blue-7 is `#205d9e` light / `#8ec8f6` dark.
-- TrackKind::Text => {
-- if theme.is_dark() {
-- gpui::rgb(0x8ec8f6).into()
-- } else {
-- gpui::rgb(0x205d9e).into()
-- }
-- }
-- // `border-emerald-11` -> `var(--jade-11)`: `#208368` light,
-- // `#1fd8a4` dark.
-- TrackKind::Audio => {
-- if theme.is_dark() {
-- gpui::rgb(0x1fd8a4).into()
-- } else {
-- gpui::rgb(0x208368).into()
-- }
-- }
-- // The two dead ones; drawn as transparent so nothing is invented.
-- TrackKind::Caption | TrackKind::Keyboard => gpui::transparent_black(),
-- }
--}
--
/// `zoomDelta = (e.deltaY * Math.sqrt(transform().zoom)) / 30`
/// (`TL/index.tsx:1191`). `deltaY` is the **DOM** sign convention: positive is
/// a scroll downwards, which zooms *out*.
@@@ -3757,14 -3639,14 +3487,15 @@@ mod tests
// -- Geometry -----------------------------------------------------------
-- /// The editor's default width: 1275 minus 16 (slot), 32 (padding), 4
-- /// (`pr-1`) and 112 (gutter) = 1111px of track content starting at
-- /// x = 136, with the ruler's own strip four pixels wider.
++ /// The editor's default width: 1275 minus 16 (slot), 24 (the card's
++ /// hairline and padding), 4 (`pr-1`) and 104 (gutter) = 1127px of track
++ /// content starting at x = 124, with the ruler's own strip four pixels
++ /// wider.
#[test]
fn the_content_column_carries_the_scroll_bodys_padding() {
-- assert_eq!(content_width(1275.), 1111.);
-- assert_eq!(ruler_width(1275.), 1115.);
-- assert_eq!(content_left(), 136.);
++ assert_eq!(content_width(1275.), 1127.);
++ assert_eq!(ruler_width(1275.), 1131.);
++ assert_eq!(content_left(), 124.);
}
#[test]
@@@ -3774,10 -3656,10 +3505,10 @@@
let transform = Transform::initial(total);
let content = content_width(width);
-- assert!(time_from_x(136., width, transform, total).abs() < 1e-9);
-- let end = time_from_x(136. + content, width, transform, total);
++ assert!(time_from_x(124., width, transform, total).abs() < 1e-9);
++ let end = time_from_x(124. + content, width, transform, total);
assert!((end - total).abs() < 1e-6, "{end}");
-- let middle = time_from_x(136. + content / 2., width, transform, total);
++ let middle = time_from_x(124. + content / 2., width, transform, total);
assert!((middle - total / 2.).abs() < 1e-6, "{middle}");
}
@@@ -3786,8 -3668,8 +3517,8 @@@
let width = 1275.;
let total = 60.0;
let transform = Transform::initial(total);
-- assert_eq!(time_from_x(136. + 9., width, transform, total), 0.0);
-- assert!(time_from_x(136. + 11., width, transform, total) > 0.0);
++ assert_eq!(time_from_x(124. + 9., width, transform, total), 0.0);
++ assert!(time_from_x(124. + 11., width, transform, total) > 0.0);
assert_eq!(time_from_x(0., width, transform, total), 0.0);
assert_eq!(time_from_x(9_000., width, transform, total), total);
}
@@@ -3801,7 -3683,7 +3532,7 @@@
zoom: 10.,
position: 20.,
};
-- let time = time_from_x(136. + content_width(width) / 2., width, transform, 600.);
++ let time = time_from_x(124. + content_width(width) / 2., width, transform, 600.);
assert!((time - 25.0).abs() < 1e-6, "{time}");
}
@@@ -3811,13 -3693,13 +3542,13 @@@
fn the_hover_preview_clears_outside_the_content_column() {
let width = 1275.;
let transform = Transform::initial(60.);
-- assert_eq!(preview_time_from_x(135., width, transform), None);
++ assert_eq!(preview_time_from_x(123., width, transform), None);
assert_eq!(
-- preview_time_from_x(136. + content_width(width) + 1., width, transform),
++ preview_time_from_x(124. + content_width(width) + 1., width, transform),
None
);
-- assert_eq!(preview_time_from_x(136. + 5., width, transform), Some(0.));
-- let middle = preview_time_from_x(136. + content_width(width) / 2., width, transform);
++ assert_eq!(preview_time_from_x(124. + 5., width, transform), Some(0.));
++ let middle = preview_time_from_x(124. + content_width(width) / 2., width, transform);
assert!((middle.unwrap() - 30.).abs() < 1e-6);
}
@@@ -3895,8 -3777,8 +3626,8 @@@
/// The whole model, built from JSON the way a real `project-config.json`
/// arrives: the row order is the source's mount order, multi-lane tracks
-- /// contribute one row per used lane, and the two locked tracks are always
-- /// there.
++ /// contribute one row per used lane with the highest-priority lane first,
++ /// and the two locked tracks are always there.
#[test]
fn the_row_order_is_the_sources_mount_order() {
let config: ProjectConfiguration = serde_json::from_value(serde_json::json!({
@@@ -3934,10 -3816,10 +3665,9 @@@
// segment, which is the fallback (`ED/context.ts:1414-1416`).
(TrackKind::Caption, 0),
(TrackKind::Keyboard, 0),
-- // Lane 1 exists because lane 2 is used.
-- (TrackKind::Text, 0),
-- (TrackKind::Text, 1),
(TrackKind::Text, 2),
++ (TrackKind::Text, 1),
++ (TrackKind::Text, 0),
(TrackKind::Mask, 0),
(TrackKind::Audio, 0),
(TrackKind::Zoom, 0),
@@@ -3945,8 -3827,8 +3675,7 @@@
(TrackKind::Scene, 0),
]
);
-- // 11 rows > 2, so the compact height.
-- assert_eq!(model.track_height(), TRACK_HEIGHT_COMPACT);
++ assert_eq!(model.track_height(), TRACK_HEIGHT);
assert_eq!(model.clips.len(), 1);
assert!((model.total_duration - 20.0).abs() < 1e-9);
}
@@@ -3973,7 -3855,7 +3702,7 @@@
// Two rows means the roomier track height.
let without_camera = TimelineModel::build(&config, false, false);
assert_eq!(without_camera.rows.len(), 2);
-- assert_eq!(without_camera.track_height(), TRACK_HEIGHT_ROOMY);
++ assert_eq!(without_camera.track_height(), TRACK_HEIGHT);
// `project.camera.hide` takes the row away again.
let mut hidden = base;
@@@ -4076,11 -3958,11 +3805,12 @@@
));
for theme in [Theme::light(), Theme::dark()] {
++ let color = TrackKind::Clip.color();
for (tier, width) in [(LabelTier::Full, 140.0), (LabelTier::Compact, 64.0)] {
-- assert!(label_body(&theme, &model.clips[1], tier, width).is_some());
++ assert!(label_body(&theme, color, &model.clips[1], tier, width).is_some());
}
assert_eq!(
-- label_body(&theme, &model.clips[1], LabelTier::Glyph, 24.0).is_some(),
++ label_body(&theme, color, &model.clips[1], LabelTier::Glyph, 24.0).is_some(),
muted,
);
}
@@@ -4368,66 -4250,35 +4098,85 @@@
assert!(MinimapDrag::begin(10., 0., 0., 3600., &mut transform).is_none());
assert!(MinimapDrag::begin(10., 0., 1000., 3., &mut transform).is_none());
}
-
- // -- The edge fade ------------------------------------------------------
-
- #[test]
- fn the_edge_fade_ramps_over_fifty_pixels_of_scroll() {
- let model = TimelineModel {
- total_duration: 60.,
- ..TimelineModel::default()
- };
- let at_start = TimelineView {
- transform: Transform {
- zoom: 10.,
- position: 0.,
- },
- ..TimelineView::default()
- };
- let (left, right) = edge_fade_strengths(&model, at_start, 1275.);
- assert_eq!(left, 0., "no fade at the very start");
- assert_eq!(right, 1., "fully faded on the right with 50s off screen");
-
- let at_end = TimelineView {
- transform: Transform {
- zoom: 10.,
- position: 50.,
- },
- ..TimelineView::default()
- };
- let (left, right) = edge_fade_strengths(&model, at_end, 1275.);
- assert_eq!(left, 1.);
- assert_eq!(right, 0.);
- }
+}
- // -- The edge fade ------------------------------------------------------
+#[cfg(test)]
+mod style_image_tests {
+ use super::*;
+ #[test]
- fn the_edge_fade_ramps_over_fifty_pixels_of_scroll() {
- let model = TimelineModel {
- total_duration: 60.,
- ..TimelineModel::default()
- };
- let at_start = TimelineView {
- transform: Transform {
- zoom: 10.,
- position: 0.,
- },
- ..TimelineView::default()
- };
- let (left, right) = edge_fade_strengths(&model, at_start, 1275.);
- assert_eq!(left, 0., "no fade at the very start");
- assert_eq!(right, 1., "fully faded on the right with 50s off screen");
-
- let at_end = TimelineView {
- transform: Transform {
- zoom: 10.,
- position: 50.,
- },
- ..TimelineView::default()
- };
- let (left, right) = edge_fade_strengths(&model, at_end, 1275.);
- assert_eq!(left, 1.);
- assert_eq!(right, 0.);
++ fn timeline_rows_follow_the_saved_overlay_order() {
++ let project: ProjectConfiguration = serde_json::from_value(serde_json::json!({
++ "overlayOrder": [
++ {"kind": "mask", "track": 0},
++ {"kind": "image", "track": 0},
++ {"kind": "text", "track": 0}
++ ],
++ "timeline": {
++ "segments": [{"start": 0, "end": 20, "timescale": 1}],
++ "zoomSegments": [],
++ "textSegments": [{"start": 1, "end": 5, "track": 0, "content": "Text"}],
++ "imageSegments": [{"start": 1, "end": 5, "track": 0, "path": "image.png"}],
++ "maskSegments": [{
++ "start": 1,
++ "end": 5,
++ "track": 0,
++ "maskType": "sensitive",
++ "center": {"x": 0.5, "y": 0.5},
++ "size": {"x": 0.2, "y": 0.2}
++ }]
++ }
++ }))
++ .unwrap();
++ let model = TimelineModel::build(&project, false, false);
++ let overlays = model
++ .rows
++ .iter()
++ .filter(|row| row.kind.overlay_track(row.lane).is_some())
++ .copied()
++ .collect::<Vec<_>>();
++ assert_eq!(
++ overlays,
++ [
++ TrackRow {
++ kind: TrackKind::Mask,
++ lane: 0
++ },
++ TrackRow {
++ kind: TrackKind::Image,
++ lane: 0
++ },
++ TrackRow {
++ kind: TrackKind::Text,
++ lane: 0
++ }
++ ]
++ );
++ }
++
+ #[test]
+ fn style_image_scene_availability_uses_source_camera_and_stable_style_requirement() {
+ let mut project: ProjectConfiguration = serde_json::from_value(serde_json::json!({
+ "camera":{"hide":true}, "timeline":{"zoomSegments":[],"segments":[{"start":0,"end":20,"timescale":1}],
+ "styleSegments":[{"start":3,"end":5,"overrides":{"camera":{"hide":false}}}]}
+ }))
+ .unwrap();
+ assert!(scene_available(&project, true));
+ assert!(!scene_available(&project, false));
+ assert!(TrackLanes::from_project(&project, true).scene);
+ assert!(
+ TimelineModel::build(&project, true, false)
+ .rows
+ .iter()
+ .any(|row| row.kind == TrackKind::Scene)
+ );
+ project.timeline.as_mut().unwrap().style_segments[0].enabled = false;
+ assert!(!scene_available(&project, true));
+ project.timeline.as_mut().unwrap().scene_segments.push(
+ serde_json::from_value(serde_json::json!({"start":1,"end":3,"mode":"cameraOnly"}))
+ .unwrap(),
+ );
+ assert!(scene_available(&project, true));
+ assert!(!scene_available(&project, false));
}
}
diff --cc apps/desktop-gpui/src/editor_window.rs
index 201db4aff,44e39b6ac..ce61cf736
--- a/apps/desktop-gpui/src/editor_window.rs
+++ b/apps/desktop-gpui/src/editor_window.rs
@@@ -75,6 -75,6 +75,7 @@@ use crate::
};
mod frame;
++mod scenes;
// ---------------------------------------------------------------------------
// Window geometry
@@@ -132,15 -132,15 +133,25 @@@ pub fn default_preview_resolution() ->
// Shell metrics (`routes/editor/Editor.tsx:77-82`)
// ---------------------------------------------------------------------------
--/// `DEFAULT_TIMELINE_HEIGHT`.
++/// The timeline height used until the project's tracks are known, which is
++/// what the auto height derives from.
const DEFAULT_TIMELINE_HEIGHT: f32 = 260.;
--/// `MIN_TIMELINE_HEIGHT`.
++/// The reference height the player/timeline split scales against on a short
++/// viewport. It is not the floor -- see [`timeline::MIN_HUG_HEIGHT`].
pub const MIN_TIMELINE_HEIGHT: f32 = 240.;
--/// `RESIZE_HANDLE_HEIGHT`.
--const RESIZE_HANDLE_HEIGHT: f32 = 16.;
--/// `MIN_PLAYER_CONTENT_HEIGHT` + `RESIZE_HANDLE_HEIGHT` = `MIN_PLAYER_HEIGHT`.
--const MIN_PLAYER_CONTENT_HEIGHT: f32 = 320.;
--const MIN_PLAYER_HEIGHT: f32 = MIN_PLAYER_CONTENT_HEIGHT + RESIZE_HANDLE_HEIGHT;
++/// The player card's floor: both control rows plus a stage worth looking at.
++const MIN_PLAYER_HEIGHT: f32 = 320.;
++
++/// The player's two control rows: the actions toolbar across the top of the
++/// card, the transport across the bottom.
++const PLAYER_TOOLBAR_HEIGHT: f32 = 44.;
++const PLAYER_BAR_HEIGHT: f32 = 48.;
++
++/// The resize grip: a hit zone straddling the 8px gap between the player row
++/// and the timeline card, with the pill drawn in the middle of the gap.
++const RESIZE_GRIP_HEIGHT: f32 = 14.;
++const RESIZE_GRIP_TOP: f32 = -11.;
++const RESIZE_GRIP_PILL_TOP: f32 = 5.;
/// The magnetic radius for a segment drag, in pixels. Shift disables it, the
/// same as the canvas overlays' snap.
@@@ -151,61 -151,29 +162,93 @@@ const DRAG_SNAP_PX: f64 = 8.
const CLIP_RESIZE_ANIM_DURATION: Duration = Duration::from_millis(180);
const CLIP_RESIZE_ANIM_TICK: Duration = Duration::from_millis(16);
--/// `h-14` on the header row (`Header.tsx:92`).
--const HEADER_HEIGHT: f32 = 56.;
++/// The header row.
++const HEADER_HEIGHT: f32 = 52.;
/// `w-104 min-w-104` on the sidebar column (`Editor.tsx:728`). Tailwind v4
/// arbitrary spacing: 104 x 0.25rem = 26rem = 416px. The column also carries
/// `ml-2`, i.e. an 8px gutter.
pub(crate) const SIDEBAR_WIDTH: f32 = 416.;
--/// `h-16` on the sidebar's tab bar (`ConfigSidebar.tsx:595`).
--pub(crate) const SIDEBAR_TAB_BAR_HEIGHT: f32 = 64.;
++/// The sidebar's tab rail.
++pub(crate) const SIDEBAR_TAB_BAR_HEIGHT: f32 = 46.;
/// `padding = 4` inside `PreviewCanvas` (`Player.tsx:566`).
const PLAYER_CANVAS_PADDING: f32 = 4.;
+#[derive(Clone, Copy, Debug)]
+struct EditorVerticalLayout {
+ player_min_height: f32,
+ timeline_height: f32,
+}
+
+impl EditorVerticalLayout {
+ fn new(viewport_height: f32, preferred_timeline_height: f32) -> Self {
- let available = (viewport_height - HEADER_HEIGHT - 8.).max(0.);
++ // The header, the 8px gap between the player row and the timeline, and
++ // the 8px gutter under the timeline card.
++ let available = (viewport_height - HEADER_HEIGHT - 16.).max(0.);
+ let scale = (available / (MIN_PLAYER_HEIGHT + MIN_TIMELINE_HEIGHT)).min(1.);
+ let player_min_height = MIN_PLAYER_HEIGHT * scale;
- let timeline_min_height = MIN_TIMELINE_HEIGHT * scale;
++ // The floor is one visible row, not the reference split: a project with
++ // three tracks hugs to well under `MIN_TIMELINE_HEIGHT`.
++ let timeline_min_height = (MIN_TIMELINE_HEIGHT * scale).min(timeline::MIN_HUG_HEIGHT);
+ Self {
+ player_min_height,
+ timeline_height: preferred_timeline_height.clamp(
+ timeline_min_height,
+ (available - player_min_height).max(timeline_min_height),
+ ),
+ }
+ }
+}
+
++const PRESETS_MENU_WIDTH: f32 = 288.;
++const PRESET_SUBMENU_WIDTH: f32 = 208.;
++const PRESET_SUBMENU_HEIGHT: f32 = 5. * 32. + 4. * 2. + 8.;
++const POPOVER_WINDOW_INSET: f32 = 8.;
++
++/// The per-preset submenu sits beside the menu, aligned with the row that
++/// summoned it: to the right when it fits, otherwise flipped to the left, and
++/// never past the window's bottom edge.
++fn preset_submenu_origin(
++ menu_origin: gpui::Point<Pixels>,
++ click: gpui::Point<Pixels>,
++ viewport: gpui::Size<Pixels>,
++) -> gpui::Point<Pixels> {
++ let viewport_width: f32 = viewport.width.into();
++ let viewport_height: f32 = viewport.height.into();
++ let menu_x: f32 = menu_origin.x.into();
++ let right = menu_x + PRESETS_MENU_WIDTH + 4.;
++ let x = if right + PRESET_SUBMENU_WIDTH + POPOVER_WINDOW_INSET <= viewport_width {
++ right
++ } else {
++ (menu_x - PRESET_SUBMENU_WIDTH - 4.).max(POPOVER_WINDOW_INSET)
++ };
++ let row_top: f32 = f32::from(click.y) - 20.;
++ let max_y =
++ (viewport_height - PRESET_SUBMENU_HEIGHT - POPOVER_WINDOW_INSET).max(POPOVER_WINDOW_INSET);
++ point(px(x), px(row_top.clamp(POPOVER_WINDOW_INSET, max_y)))
++}
++
+fn compact_header_controls(viewport_width: f32, windows: bool, captions: bool) -> bool {
+ let actions_width = if captions { 416. } else { 304. };
+ let caption_controls_width = if windows { 138. } else { 0. };
+ viewport_width < actions_width * 2. + 144. + caption_controls_width
+}
+
+fn editor_player_width(viewport_width: f32) -> f32 {
+ (viewport_width - SIDEBAR_WIDTH - 8. - 16. - 2.).max(0.)
+}
+
// ---------------------------------------------------------------------------
// Timeline metrics -- all of them now live in [`crate::editor_timeline`],
// which owns the strip itself (`routes/editor/Timeline/index.tsx:62-68`).
// ---------------------------------------------------------------------------
use crate::editor_timeline::{
-- self as timeline, ADD_TRACK_OPTIONS, MINIMAP_HEIGHT, MINIMAP_TOP, SCROLL_BODY_PADDING_RIGHT,
-- START_SNAP_PX, TIMELINE_HEADER_HEIGHT, TIMELINE_PADDING, TIMELINE_SLOT_PADDING,
-- TIMELINE_TOP_PADDING, TRACK_GUTTER, TRACK_ICON_WIDTH, TRACK_ROW_GAP, TimelineModel,
-- TimelineView, TrackKind, TrackLanes, Transform,
++ self as timeline, ADD_TRACK_OPTIONS, MINIMAP_HEIGHT, SCROLL_BODY_PADDING_RIGHT, START_SNAP_PX,
++ TIMELINE_BOTTOM_PADDING, TIMELINE_CARD_BORDER, TIMELINE_HEADER_HEIGHT, TIMELINE_PADDING,
++ TIMELINE_SLOT_PADDING, TIMELINE_TOP_PADDING, TRACK_GUTTER, TRACK_ICON_WIDTH, TRACK_ROW_GAP,
++ TimelineModel, TimelineView, TrackKind, TrackLanes, TrackRow, Transform,
};
// ---------------------------------------------------------------------------
@@@ -564,29 -530,29 +607,38 @@@ pub(crate) enum EditorPreviewFrame
}
impl EditorPreviewFrame {
-- pub(crate) fn paint(&self, bounds: gpui::Bounds<Pixels>, window: &mut Window) {
++ pub(crate) fn paint(&self, bounds: gpui::Bounds<Pixels>, radius: Pixels, window: &mut Window) {
++ let corners = gpui::Corners::all(radius);
match self {
Self::Image(image) => {
-- let _ = window.paint_image(
-- bounds,
-- gpui::Corners::default(),
-- Arc::clone(image),
-- 0,
-- false,
-- );
++ let _ = window.paint_image(bounds, corners, Arc::clone(image), 0, false);
}
#[cfg(target_os = "macos")]
-- Self::Surface(surface) => window.paint_surface(bounds, surface.clone()),
++ Self::Surface(surface) => {
++ window.paint_surface_fitted(bounds, bounds, corners, surface.clone())
++ }
}
}
}
++/// The stage's rounded preview: radius and the hairline ring around it.
++const PREVIEW_RADIUS: f32 = 6.;
++
++/// The breathing room between the fitted frame and the card. [`letterbox`] --
++/// which the crop dialog shares -- already eats `PLAYER_CANVAS_PADDING`, so the
++/// stage only has to inset the remainder before fitting.
++const PLAYER_STAGE_PADDING: f32 = 16.;
++const STAGE_INSET: f32 = PLAYER_STAGE_PADDING - PLAYER_CANVAS_PADDING;
++
struct PreviewFrameView {
frame: Option<EditorPreviewFrame>,
frame_size: (f32, f32),
frame_rect: crate::editor_canvas::CanvasRect,
stats: Option<Arc<PumpStats>>,
frame_sequence: u64,
++ /// The stage's lift under the preview. A canvas paints raw quads, so the
++ /// shadow cannot come from a style and is carried here instead.
++ shadow: Vec<gpui::BoxShadow>,
}
impl PreviewFrameView {
@@@ -597,6 -563,6 +649,7 @@@
frame_rect,
stats: None,
frame_sequence: 0,
++ shadow: crate::theme::preview_shadow(),
}
}
@@@ -625,13 -591,13 +678,20 @@@ impl Render for PreviewFrameView
let frame_rect = self.frame_rect.clone();
let painted = self.stats.clone();
let frame_sequence = self.frame_sequence;
++ let shadow = self.shadow.clone();
gpui::canvas(
|bounds, _window, _cx| bounds,
move |_, bounds, window, _cx| {
let container_width: f32 = bounds.size.width.into();
let container_height: f32 = bounds.size.height.into();
-- let (width, height) = letterbox((container_width, container_height), frame_size);
++ let (width, height) = letterbox(
++ (
++ (container_width - STAGE_INSET * 2.).max(0.),
++ (container_height - STAGE_INSET * 2.).max(0.),
++ ),
++ frame_size,
++ );
let fitted = gpui::Bounds {
origin: gpui::point(
bounds.origin.x + px((container_width - width) / 2.),
@@@ -643,8 -609,8 +703,18 @@@
container: bounds,
frame: fitted,
}));
-- window.paint_quad(gpui::fill(fitted, gpui::black()));
-- frame.paint(fitted, window);
++ let radius = px(PREVIEW_RADIUS);
++ window.paint_drop_shadows(fitted, gpui::Corners::all(radius), &shadow);
++ window.paint_quad(gpui::fill(fitted, gpui::black()).corner_radii(radius));
++ frame.paint(fitted, radius, window);
++ window.paint_quad(gpui::quad(
++ fitted,
++ gpui::Corners::all(radius),
++ gpui::transparent_black(),
++ gpui::Edges::all(px(1.)),
++ gpui::hsla(0., 0., 0., 0.12),
++ gpui::BorderStyle::Solid,
++ ));
if let Some(stats) = &painted {
stats.record_paint(frame_sequence);
}
@@@ -1268,6 -1229,6 +1338,19 @@@ struct Drag
paused: bool,
}
++#[derive(Clone, Copy, Debug)]
++struct LaneReorder {
++ source: TrackRow,
++ target_index: usize,
++ down_x: f32,
++ down_y: f32,
++ pointer_x: f32,
++ pointer_y: f32,
++ dragging: bool,
++ paused: bool,
++ autoscroll_pending: bool,
++}
++
/// The recording-domain edges a clip handle is dragging, uncommitted.
#[derive(Clone, Copy, Debug)]
struct ClipDraft {
@@@ -1380,6 -1341,6 +1463,7 @@@ pub struct EditorWindow
hovered_gutter: Option<(TrackKind, u32)>,
/// The live segment drag, if any.
drag: Option<Drag>,
++ lane_reorder: Option<LaneReorder>,
/// Generation guard for the 60Hz playback redraw ticker.
playback_tick: u64,
/// `isGeneratingAutoZoom` / `sessionDismissedGenerateZoomPrompt`
@@@ -1494,7 -1457,7 +1580,9 @@@
add_track: Option<AddTrackMenu>,
pub(crate) audio_picker: Option<crate::editor_audio::AudioPicker>,
pub(crate) camera3d_setup: Option<Camera3DSetup>,
-- timeline_height: f32,
++ /// The user's drag on the resize grip. `None` means the card hugs its
++ /// track rows and re-hugs whenever a track is added or removed.
++ timeline_height_override: Option<f32>,
timeline_resize: Option<(f32, f32)>,
/// The header's Presets dropdown (`PresetsDropdown.tsx`), and whichever
/// of its three dialogs is up. The dialog closes the menu when it opens,
@@@ -1516,10 -1475,10 +1600,17 @@@ struct PresetsMenu
origin: gpui::Point<Pixels>,
store: crate::presets::PresetsStore,
/// An open per-preset submenu: which row, and where it was summoned.
-- submenu: Option<(usize, gpui::Point<Pixels>)>,
++ submenu: Option<(PresetRow, gpui::Point<Pixels>)>,
scroll: gpui::ScrollHandle,
}
++/// A row of the presets menu: the built-in Default, or a saved preset.
++#[derive(Debug, Clone, Copy, PartialEq, Eq)]
++enum PresetRow {
++ Default,
++ Saved(usize),
++}
++
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PresetDialog {
Create { default: bool },
@@@ -1549,7 -1508,7 +1640,6 @@@ struct ClipSpeedMenu
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ToolbarMenu {
AspectRatio,
-- PreviewQuality,
}
struct OpenToolbarMenu {
@@@ -1561,8 -1520,8 +1651,15 @@@ impl EditorWindow
pub fn new(project_path: PathBuf, window: &mut Window, cx: &mut Context<Self>) -> Self {
crate::theme::bind_window(window, cx);
cx.observe_window_activation(window, |this, window, cx| {
-- if !window.is_window_active() && this.minimap_drag.take().is_some() {
-- cx.notify();
++ if !window.is_window_active() {
++ let minimap_canceled = this.minimap_drag.take().is_some();
++ let lane_reorder_canceled = this.lane_reorder.is_some();
++ if lane_reorder_canceled {
++ this.cancel_lane_reorder(cx);
++ }
++ if minimap_canceled {
++ cx.notify();
++ }
}
})
.detach();
@@@ -1754,6 -1703,6 +1851,7 @@@
scene_preview_time: None,
hovered_gutter: None,
drag: None,
++ lane_reorder: None,
playback_tick: 0,
generating_auto_zoom: false,
auto_zoom_message: None,
@@@ -1801,7 -1752,7 +1901,7 @@@
add_track: None,
audio_picker: None,
camera3d_setup: None,
-- timeline_height: DEFAULT_TIMELINE_HEIGHT,
++ timeline_height_override: None,
timeline_resize: None,
presets_menu: None,
preset_dialog: None,
@@@ -1899,11 -1850,8 +1999,12 @@@
window: &mut Window,
cx: &mut Context<Self>,
) {
+ self.sidebar.style_target = None;
+ self.sidebar.menu = None;
+ self.selection = None;
+ self.canvas_selection = None;
self.project = config;
+ self.synchronize_caption_track(true);
self.history = ProjectHistory::new(self.project.clone());
self.tracks = TrackLanes::from_project(&self.project, self.has_camera);
self.rebuild_timeline();
@@@ -1977,17 -1938,13 +2091,32 @@@
change: impl FnOnce(&mut TimelineConfiguration) -> bool,
window: &mut Window,
cx: &mut Context<Self>,
+ ) -> bool {
- let Some(timeline) = self.project.timeline.as_mut() else {
- return false;
- };
- if !change(timeline) {
++ self.edit_timeline_project(
++ |project| {
++ let Some(timeline) = project.timeline.as_mut() else {
++ return false;
++ };
++ change(timeline)
++ },
++ window,
++ cx,
++ )
++ }
++
++ fn edit_timeline_project(
++ &mut self,
++ change: impl FnOnce(&mut ProjectConfiguration) -> bool,
++ window: &mut Window,
++ cx: &mut Context<Self>,
+ ) -> bool {
+ self.end_field_edit(cx);
+ self.close_color_picker(cx);
+ self.dismiss_frame_controls(cx);
- let Some(timeline) = self.project.timeline.as_mut() else {
- return false;
- };
- if !change(timeline) {
++ if !change(&mut self.project) {
return false;
}
+ self.set_selection(None, cx);
self.project_changed(window, cx);
true
}
@@@ -2052,7 -2007,7 +2179,8 @@@
if !self.project_ready() {
return;
}
+ self.synchronize_caption_track(false);
+ self.history.record(&self.project);
self.publish_project();
cx.notify();
}
@@@ -2597,6 -2515,6 +2700,12 @@@
}
}
++ if self.lane_reorder.is_some() && event.keystroke.key == "escape" && !event.is_held {
++ self.cancel_lane_reorder(cx);
++ cx.stop_propagation();
++ return;
++ }
++
// The canvas arrow-key nudge is scoped outside `useEditorShortcuts`
// precisely so held keys repeat (`CanvasElementsOverlay.tsx:561-565`),
// so it is the one editor shortcut that runs on a repeat.
@@@ -2789,6 -2707,6 +2898,10 @@@
}
"escape" => {
cx.stop_propagation();
++ if self.lane_reorder.is_some() {
++ self.cancel_lane_reorder(cx);
++ return;
++ }
if self.minimap_drag.take().is_some() {
cx.notify();
return;
@@@ -2835,11 -2753,11 +2948,11 @@@
return;
}
cx.stop_propagation();
-- let width = timeline::ruler_width(f32::from(window.viewport_size().width));
++ let (left, width) = timeline::minimap_bounds(f32::from(window.viewport_size().width));
let total = self.total_duration();
self.minimap_drag = timeline::MinimapDrag::begin(
f32::from(event.position.x),
-- timeline::content_left(),
++ left,
width,
total,
&mut self.view.transform,
@@@ -3137,30 -3055,12 +3250,60 @@@
/// `setEditorState("timeline", "selection", ...)`.
pub(crate) fn set_selection(&mut self, selection: Option<Selection>, cx: &mut Context<Self>) {
if self.selection != selection {
+ self.dismiss_frame_controls(cx);
+ self.end_field_edit(cx);
+ self.close_color_picker(cx);
+ self.sidebar.menu = None;
dismiss_indexed_sidebar_menu(&mut self.sidebar.menu);
+ self.sidebar.style_target = None;
++ self.sidebar.scroll.set_offset(gpui::point(px(0.), px(0.)));
+ self.canvas_selection = selection.as_ref().and_then(|selection| {
+ if selection.indices.len() != 1 {
+ return None;
+ }
+ let index = selection.indices[0];
+ match selection.track {
+ TrackKind::Image => Some(crate::editor_canvas::CanvasSelection::Image(index)),
+ TrackKind::Text => Some(crate::editor_canvas::CanvasSelection::Text(index)),
+ TrackKind::Mask => Some(crate::editor_canvas::CanvasSelection::Mask(index)),
+ _ => None,
+ }
+ });
self.selection = selection;
+ self.refresh_image_asset_status();
cx.notify();
}
}
++ fn select_lane_header(&mut self, kind: TrackKind, lane: u32, cx: &mut Context<Self>) {
++ let time = self.preview_or_playhead();
++ let segments = self.timeline.segments(kind);
++ let mut active = segments.iter().enumerate().filter(|(_, segment)| {
++ segment.lane == lane && time >= segment.start && time < segment.end
++ });
++ let active_index = if kind == TrackKind::Clip {
++ active.next_back()
++ } else {
++ active.next()
++ }
++ .map(|(index, _)| index);
++ let index = active_index.or_else(|| {
++ segments
++ .iter()
++ .enumerate()
++ .find(|(_, segment)| segment.lane == lane)
++ .map(|(index, _)| index)
++ });
++ let seek_time = active_index
++ .is_none()
++ .then(|| index.and_then(|index| segments.get(index).map(|segment| segment.start)))
++ .flatten();
++ self.set_selection(index.map(|index| Selection::single(kind, index)), cx);
++ if let Some(time) = seek_time {
++ self.seek_to_time(time, cx);
++ }
++ }
++
/// A press on a track row. Whatever it lands on decides everything:
/// a handle trims, a body moves (or splits, in split mode), and bare track
/// falls through to the timeline container's own press-to-seek -- except on
@@@ -3223,29 -3123,23 +3366,14 @@@
cx,
);
} else if kind == TrackKind::ThreeD {
-- if self
-- .project
-- .timeline
-- .as_ref()
-- .is_none_or(|timeline| timeline.camera3d_segments.is_empty())
-- {
-- cx.stop_propagation();
-- self.start_camera3d_setup(cx);
-- } else if self.camera3d_setup.is_none() {
-- self.begin_gap_create(
-- TrackKind::ThreeD,
-- secs_per_pixel,
-- f32::from(event.position.x),
-- viewport_width,
-- cx,
-- );
-- }
++ cx.stop_propagation();
++ self.start_camera3d_setup_at(press_time, cx);
+ } else if kind == TrackKind::Image {
+ cx.stop_propagation();
+ self.import_image_for_lane(lane, press_time, window, cx);
+ } else if kind == TrackKind::Style {
+ cx.stop_propagation();
+ self.add_style_at(lane, press_time, window, cx);
} else if kind == TrackKind::Audio {
cx.stop_propagation();
self.open_audio_picker(lane, cx);
@@@ -3397,6 -3291,6 +3525,275 @@@
cx.notify();
}
++ fn lane_reorderable(kind: TrackKind) -> bool {
++ matches!(
++ kind,
++ TrackKind::Style
++ | TrackKind::Image
++ | TrackKind::Text
++ | TrackKind::Mask
++ | TrackKind::Audio
++ )
++ }
++
++ fn lane_reorder_rows(&self, source: TrackRow) -> Vec<TrackRow> {
++ let overlay = source.kind.overlay_track(source.lane).is_some();
++ self.timeline
++ .rows
++ .iter()
++ .copied()
++ .filter(|row| {
++ if overlay {
++ row.kind.overlay_track(row.lane).is_some()
++ } else {
++ row.kind == source.kind
++ }
++ })
++ .collect()
++ }
++
++ fn can_reorder_lane(&self, source: TrackRow) -> bool {
++ Self::lane_reorderable(source.kind) && self.lane_reorder_rows(source).len() > 1
++ }
++
++ fn lane_reorder_target_index(&self, source: TrackRow, pointer_y: f32) -> usize {
++ let rows = self.lane_reorder_rows(source);
++ if rows.is_empty() {
++ return 0;
++ }
++ let bounds = self.timeline_scroll.bounds();
++ let content_y =
++ pointer_y - f32::from(bounds.origin.y) - f32::from(self.timeline_scroll.offset().y);
++ let stride = self.timeline.track_height() + TRACK_ROW_GAP;
++ let remaining = self
++ .timeline
++ .rows
++ .iter()
++ .enumerate()
++ .filter(|(_, row)| **row != source && rows.contains(row))
++ .collect::<Vec<_>>();
++ remaining
++ .iter()
++ .position(|(index, _)| {
++ content_y < *index as f32 * stride + self.timeline.track_height() / 2.
++ })
++ .unwrap_or(remaining.len())
++ }
++
++ fn lane_reorder_position_valid(&self, source: TrackRow, x: f32, y: f32) -> bool {
++ let bounds = self.timeline_scroll.bounds();
++ if !(x >= f32::from(bounds.left())
++ && x <= f32::from(bounds.right())
++ && y >= f32::from(bounds.top())
++ && y <= f32::from(bounds.bottom()))
++ {
++ return false;
++ }
++ let content_y = y - f32::from(bounds.top()) - f32::from(self.timeline_scroll.offset().y);
++ let stride = self.timeline.track_height() + TRACK_ROW_GAP;
++ let row_index = (content_y / stride).floor().max(0.) as usize;
++ if content_y - row_index as f32 * stride >= self.timeline.track_height() {
++ return true;
++ }
++ let Some(row) = self.timeline.rows.get(row_index) else {
++ return true;
++ };
++ if source.kind.overlay_track(source.lane).is_some() {
++ row.kind.overlay_track(row.lane).is_some()
++ } else {
++ row.kind == source.kind
++ }
++ }
++
++ fn begin_lane_reorder(
++ &mut self,
++ source: TrackRow,
++ position: Point<Pixels>,
++ window: &mut Window,
++ cx: &mut Context<Self>,
++ ) {
++ if !self.can_reorder_lane(source) || self.lane_reorder.is_some() {
++ return;
++ }
++ self.focus_root(window, cx);
++ let target_index = self
++ .lane_reorder_rows(source)
++ .iter()
++ .position(|row| *row == source)
++ .unwrap_or(0);
++ self.lane_reorder = Some(LaneReorder {
++ source,
++ target_index,
++ down_x: f32::from(position.x),
++ down_y: f32::from(position.y),
++ pointer_x: f32::from(position.x),
++ pointer_y: f32::from(position.y),
++ dragging: false,
++ paused: false,
++ autoscroll_pending: false,
++ });
++ cx.notify();
++ }
++
++ fn update_lane_reorder(
++ &mut self,
++ position: Point<Pixels>,
++ window: &mut Window,
++ cx: &mut Context<Self>,
++ ) {
++ let Some(current) = self.lane_reorder else {
++ return;
++ };
++ let x = f32::from(position.x);
++ let y = f32::from(position.y);
++ let promote = !current.dragging
++ && ((x - current.down_x).abs() >= 4. || (y - current.down_y).abs() >= 4.);
++ if !current.dragging && !promote {
++ return;
++ }
++ let valid_target = self.lane_reorder_position_valid(current.source, x, y);
++ let target_index = valid_target
++ .then(|| self.lane_reorder_target_index(current.source, y))
++ .unwrap_or(current.target_index);
++ if promote {
++ self.history.pause();
++ }
++ if let Some(reorder) = self.lane_reorder.as_mut() {
++ reorder.target_index = target_index;
++ reorder.pointer_x = x;
++ reorder.pointer_y = y;
++ reorder.dragging = true;
++ reorder.paused = true;
++ }
++ self.schedule_lane_reorder_autoscroll(window, cx);
++ cx.notify();
++ }
++
++ fn lane_reorder_autoscroll_delta(&self) -> f32 {
++ let Some(reorder) = self.lane_reorder.filter(|reorder| reorder.dragging) else {
++ return 0.;
++ };
++ if !self.lane_reorder_position_valid(reorder.source, reorder.pointer_x, reorder.pointer_y) {
++ return 0.;
++ }
++ let bounds = self.timeline_scroll.bounds();
++ let top = f32::from(bounds.top());
++ let bottom = f32::from(bounds.bottom());
++ let edge = 32.;
++ if reorder.pointer_y < top + edge {
++ let strength = ((top + edge - reorder.pointer_y) / edge).clamp(0., 1.);
++ 14. * strength * strength
++ } else if reorder.pointer_y > bottom - edge {
++ let strength = ((reorder.pointer_y - (bottom - edge)) / edge).clamp(0., 1.);
++ -14. * strength * strength
++ } else {
++ 0.
++ }
++ }
++
++ fn schedule_lane_reorder_autoscroll(&mut self, window: &mut Window, cx: &mut Context<Self>) {
++ if self.lane_reorder_autoscroll_delta() == 0.
++ || self
++ .lane_reorder
++ .is_none_or(|reorder| reorder.autoscroll_pending)
++ {
++ return;
++ }
++ if let Some(reorder) = self.lane_reorder.as_mut() {
++ reorder.autoscroll_pending = true;
++ }
++ cx.on_next_frame(window, |this, window, cx| {
++ this.lane_reorder_autoscroll_frame(window, cx);
++ });
++ window.request_animation_frame();
++ }
++
++ fn lane_reorder_autoscroll_frame(&mut self, window: &mut Window, cx: &mut Context<Self>) {
++ let Some(reorder) = self.lane_reorder.as_mut() else {
++ return;
++ };
++ reorder.autoscroll_pending = false;
++ let delta = self.lane_reorder_autoscroll_delta();
++ if delta == 0. {
++ return;
++ }
++ let offset = self.timeline_scroll.offset();
++ let current_y = f32::from(offset.y);
++ let max_y = f32::from(self.timeline_scroll.max_offset().y).max(0.);
++ let next_y = (current_y + delta).clamp(-max_y, 0.);
++ if next_y == current_y {
++ return;
++ }
++ self.timeline_scroll.set_offset(point(offset.x, px(next_y)));
++ let Some(reorder) = self.lane_reorder else {
++ return;
++ };
++ let target_index = self.lane_reorder_target_index(reorder.source, reorder.pointer_y);
++ if let Some(reorder) = self.lane_reorder.as_mut() {
++ reorder.target_index = target_index;
++ }
++ cx.notify();
++ window.refresh();
++ self.schedule_lane_reorder_autoscroll(window, cx);
++ }
++
++ fn finish_lane_reorder(&mut self, window: &mut Window, cx: &mut Context<Self>) {
++ let Some(reorder) = self.lane_reorder.take() else {
++ return;
++ };
++ if !reorder.dragging {
++ self.select_lane_header(reorder.source.kind, reorder.source.lane, cx);
++ return;
++ }
++ if !self.lane_reorder_position_valid(reorder.source, reorder.pointer_x, reorder.pointer_y) {
++ if reorder.paused {
++ let config = self.project.clone();
++ self.history.resume(&config);
++ }
++ cx.notify();
++ return;
++ }
++ let rows = self.lane_reorder_rows(reorder.source);
++ let changed = if let Some(from) = reorder.source.kind.overlay_track(reorder.source.lane) {
++ let available = rows
++ .iter()
++ .filter_map(|row| row.kind.overlay_track(row.lane))
++ .collect::<Vec<_>>();
++ edits::reorder_overlay_track(&mut self.project, &available, from, reorder.target_index)
++ } else {
++ rows.get(reorder.target_index).is_some_and(|target| {
++ self.project.timeline.as_mut().is_some_and(|timeline| {
++ edits::reorder_track_lane(
++ timeline,
++ reorder.source.kind,
++ reorder.source.lane,
++ target.lane,
++ )
++ })
++ })
++ };
++ if changed {
++ self.project_changed(window, cx);
++ self.note_edit("reorder-lane", Some(reorder.source.kind));
++ }
++ if reorder.paused {
++ let config = self.project.clone();
++ self.history.resume(&config);
++ }
++ cx.notify();
++ }
++
++ fn cancel_lane_reorder(&mut self, cx: &mut Context<Self>) {
++ let Some(reorder) = self.lane_reorder.take() else {
++ return;
++ };
++ if reorder.paused {
++ let config = self.project.clone();
++ self.history.resume(&config);
++ }
++ cx.notify();
++ }
++
/// `newSegmentDetails()` plus `createSegment` (`TL/ZoomTrack.tsx:104-295`).
/// The ghost the track already draws is where the segment lands; the press
/// arms a drag that stretches its end until the button comes up.
@@@ -3942,60 -3834,230 +4339,245 @@@
}
}
--#[derive(Debug, Clone, Copy, PartialEq, Eq)]
++#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Camera3DSetup {
pub scene_id: &'static str,
-- pub shots: usize,
++ pub start: f64,
++ pub duration: f64,
++ pub sequences_open: bool,
}
type GhostClipLayout = (Vec<(f64, f64)>, Option<(f64, f64)>);
- impl EditorWindow {
- fn clamp_timeline_height(&self, value: f32, viewport_height: f32) -> f32 {
- EditorVerticalLayout::new(viewport_height, value).timeline_height
- }
-
- fn edit_live(
- &mut self,
- change: impl FnOnce(&mut TimelineConfiguration) -> bool,
- cx: &mut Context<Self>,
- ) -> bool {
- let Some(timeline) = self.project.timeline.as_mut() else {
- return false;
- };
- if !change(timeline) {
- return false;
+ fn caption_text_from_words(words: &[cap_project::CaptionWord]) -> String {
+ let mut text = String::new();
+ for word in words {
+ let value = word.text.trim();
+ if value.is_empty() {
+ continue;
+ }
+ let attaches = value.chars().next().is_some_and(|value| {
+ matches!(
+ value,
+ ',' | '.'
+ | '!'
+ | '?'
+ | ';'
+ | ':'
+ | '%'
+ | ')'
+ | ']'
+ | '}'
+ | '\''
+ | '’'
+ | '、'
+ | '。'
+ | '!'
+ | '?'
+ | ';'
+ | ':'
+ | ','
+ )
+ });
+ if !text.is_empty() && !attaches {
+ text.push(' ');
}
- self.history.record(&self.project);
- self.rebuild_timeline();
- self.publish_project();
- cx.notify();
- true
+ text.push_str(value);
}
+ text
+ }
- pub(crate) fn open_audio_picker(&mut self, lane: u32, cx: &mut Context<Self>) {
- self.audio_picker = Some(crate::editor_audio::AudioPicker::Add { lane });
- self.camera3d_setup = None;
- self.set_selection(None, cx);
- cx.notify();
- }
+ fn fresh_caption_source_id(project: &ProjectConfiguration) -> String {
+ use std::hash::{BuildHasher, Hasher};
- pub(crate) fn open_audio_replace(&mut self, index: usize, cx: &mut Context<Self>) {
- self.audio_picker = Some(crate::editor_audio::AudioPicker::Replace { index });
- self.camera3d_setup = None;
- cx.notify();
+ loop {
+ let millis = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|since| since.as_millis())
+ .unwrap_or_default();
+ let random = std::collections::hash_map::RandomState::new()
+ .build_hasher()
+ .finish();
+ let id = format!("cap-split-{millis}-{random:x}");
+ if project
+ .captions
+ .as_ref()
+ .is_none_or(|captions| captions.segments.iter().all(|segment| segment.id != id))
+ {
+ return id;
+ }
}
+ }
- pub(crate) fn add_library_track(
- &mut self,
- id: &'static str,
- name: &'static str,
- window: &mut Window,
- cx: &mut Context<Self>,
- ) {
- let Some(picker) = self.audio_picker else {
- return;
- };
+ fn split_caption_segment(
+ project: &mut ProjectConfiguration,
+ index: usize,
+ at: f64,
+ recording_durations: &[f64],
+ ) -> bool {
+ let Some(timeline) = project.timeline.as_ref() else {
+ return false;
+ };
+ let Some(track) = timeline.caption_segments.get(index) else {
+ return false;
+ };
+ let source_id = cap_project::source_caption_id(&track.id);
+ let Some((source_index, source)) = project
+ .captions
+ .as_ref()
+ .and_then(|captions| {
+ captions
+ .segments
+ .iter()
+ .enumerate()
+ .find(|(_, segment)| segment.id == source_id)
+ })
+ .map(|(index, segment)| (index, segment.clone()))
+ else {
+ return false;
+ };
+ let split_output = track.start + at;
+ let source_range = Some((f64::from(source.start), f64::from(source.end)));
+ let Some(split_source) = crate::transcription::map_edited_time_to_source(
+ split_output,
+ timeline,
+ recording_durations,
+ source_range,
+ ) else {
+ return false;
+ };
+ if split_source <= f64::from(source.start) || split_source >= f64::from(source.end) {
+ return false;
+ }
+ let tail_id = fresh_caption_source_id(project);
+ let Some(timeline) = project.timeline.as_mut() else {
+ return false;
+ };
+ if !edits::split_segment(timeline, TrackKind::Caption, index, at) {
+ return false;
+ }
+ timeline.caption_segments[index + 1].id.clone_from(&tail_id);
+
+ let split_source = split_source as f32;
+ let mut head = source.clone();
+ let mut tail = source;
+ head.end = split_source;
+ tail.id = tail_id;
+ tail.start = split_source;
+ if !head.words.is_empty() {
+ let words = std::mem::take(&mut head.words);
+ tail.words.clear();
+ for word in words {
+ if word.start < split_source {
+ let mut value = word.clone();
+ value.end = value.end.min(split_source);
+ if value.end > value.start {
+ head.words.push(value);
+ }
+ }
+ if word.end > split_source {
+ let mut value = word;
+ value.start = value.start.max(split_source);
+ if value.end > value.start {
+ tail.words.push(value);
+ }
+ }
+ }
+ head.text = caption_text_from_words(&head.words);
+ tail.text = caption_text_from_words(&tail.words);
+ }
+ let Some(captions) = project.captions.as_mut() else {
+ return false;
+ };
+ captions
+ .segments
+ .splice(source_index..=source_index, [head, tail]);
+ true
+ }
+
+ fn delete_caption_segments(project: &mut ProjectConfiguration, indices: &[usize]) -> bool {
+ let Some(timeline) = project.timeline.as_ref() else {
+ return false;
+ };
+ let source_ids = indices
+ .iter()
+ .filter_map(|index| timeline.caption_segments.get(*index))
+ .map(|segment| cap_project::source_caption_id(&segment.id).to_string())
+ .collect::<Vec<_>>();
+ let Some(timeline) = project.timeline.as_mut() else {
+ return false;
+ };
+ if !edits::delete_segments(timeline, TrackKind::Caption, indices) {
+ return false;
+ }
+ if let Some(captions) = project.captions.as_mut() {
+ captions
+ .segments
+ .retain(|segment| !source_ids.contains(&segment.id));
+ }
+ true
+ }
+
+ impl EditorWindow {
+ fn clamp_timeline_height(&self, value: f32, viewport_height: f32) -> f32 {
- let available = (viewport_height - HEADER_HEIGHT - 8.).max(MIN_TIMELINE_HEIGHT);
- let max_height = (available - MIN_PLAYER_HEIGHT).max(MIN_TIMELINE_HEIGHT);
- value.clamp(MIN_TIMELINE_HEIGHT, max_height)
++ EditorVerticalLayout::new(viewport_height, value).timeline_height
++ }
++
++ /// The height the timeline card asks for: the user's dragged override if
++ /// there is one, otherwise the height that hugs the visible track rows.
++ /// Before the project loads there are no rows to hug, so the old fixed
++ /// height stands in and the card does not pop when they arrive.
++ fn preferred_timeline_height(&self) -> f32 {
++ self.timeline_height_override.unwrap_or_else(|| {
++ if self.timeline.rows.is_empty() {
++ DEFAULT_TIMELINE_HEIGHT
++ } else {
++ timeline::hug_height(self.timeline.rows.len())
++ }
++ })
+ }
+
+ fn edit_live(
+ &mut self,
+ change: impl FnOnce(&mut TimelineConfiguration) -> bool,
+ cx: &mut Context<Self>,
+ ) -> bool {
+ let Some(timeline) = self.project.timeline.as_mut() else {
+ return false;
+ };
+ if !change(timeline) {
+ return false;
+ }
++ self.history.record(&self.project);
+ self.rebuild_timeline();
+ self.publish_project();
+ cx.notify();
+ true
+ }
+
+ pub(crate) fn open_audio_picker(&mut self, lane: u32, cx: &mut Context<Self>) {
+ self.audio_picker = Some(crate::editor_audio::AudioPicker::Add { lane });
+ self.camera3d_setup = None;
+ self.set_selection(None, cx);
+ cx.notify();
+ }
+
+ pub(crate) fn open_audio_replace(&mut self, index: usize, cx: &mut Context<Self>) {
+ self.audio_picker = Some(crate::editor_audio::AudioPicker::Replace { index });
+ self.camera3d_setup = None;
+ cx.notify();
+ }
+
+ pub(crate) fn add_library_track(
+ &mut self,
+ id: &'static str,
+ name: &'static str,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ let Some(picker) = self.audio_picker else {
+ return;
+ };
let project_path = self.project_path.clone();
cx.spawn_in(window, async move |this, cx| {
let imported = cx
@@@ -4290,362 -4352,362 +4872,25 @@@
self.note_edit("add-track", Some(kind));
}
-- fn close_camera3d_setup(&mut self, cx: &mut Context<Self>) {
-- self.camera3d_setup = None;
- self.rebuild_timeline();
- cx.notify();
- }
-
- fn start_camera3d_setup(&mut self, cx: &mut Context<Self>) {
- self.set_selection(None, cx);
- self.audio_picker = None;
- self.tracks.three_d = true;
- self.camera3d_setup = Some(Camera3DSetup {
- scene_id: "showcase",
- shots: 3,
- });
-- self.rebuild_timeline();
-- cx.notify();
- }
-
- fn camera3d_setup_preview(&self) -> Vec<(f64, f64, String)> {
- let Some(setup) = self.camera3d_setup else {
- return Vec::new();
- };
- let Some(scene) = crate::editor_panels::CAMERA3D_SCENES
- .iter()
- .find(|scene| scene.id == setup.scene_id)
- else {
- return Vec::new();
- };
- let shots = setup.shots.clamp(1, scene.shots.len());
- let limited = crate::editor_panels::Camera3DScene {
- id: scene.id,
- name: scene.name,
- shots: &scene.shots[..shots],
- };
- let clip_cuts: Vec<f64> = self
- .project
- .timeline
- .as_ref()
- .map(|timeline| {
- let mut acc = 0.0;
- timeline
- .segments
- .iter()
- .map(|segment| {
- acc += (segment.end - segment.start) / segment.timescale.max(0.0001);
- acc
- })
- .collect()
- })
- .unwrap_or_default();
- crate::editor_panels::apply_scene_to_range(&limited, 0.0, self.total_duration(), &clip_cuts)
- .into_iter()
- .enumerate()
- .map(|(index, segment)| (segment.start, segment.end, format!("Shot {}", index + 1)))
- .collect()
- }
-
- pub(crate) fn confirm_camera3d_setup(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- let Some(setup) = self.camera3d_setup else {
- return;
- };
- if self
- .project
- .timeline
- .as_ref()
- .is_some_and(|timeline| !timeline.camera3d_segments.is_empty())
- {
- return;
- }
- if !edits::ensure_timeline(&mut self.project, &self.clip_display_durations) {
- return;
- }
- let total = self.total_duration();
- let clip_cuts: Vec<f64> = self
- .project
- .timeline
- .as_ref()
- .map(|timeline| {
- let mut acc = 0.0;
- timeline
- .segments
- .iter()
- .map(|segment| {
- acc += (segment.end - segment.start) / segment.timescale.max(0.0001);
- acc
- })
- .collect()
- })
- .unwrap_or_default();
- let Some(scene) = crate::editor_panels::CAMERA3D_SCENES
- .iter()
- .find(|scene| scene.id == setup.scene_id)
- else {
- return;
- };
- let shots = setup.shots.clamp(1, scene.shots.len());
- let limited = crate::editor_panels::Camera3DScene {
- id: scene.id,
- name: scene.name,
- shots: &scene.shots[..shots],
- };
- let generated =
- crate::editor_panels::apply_scene_to_range(&limited, 0.0, total, &clip_cuts);
- if generated.is_empty() {
- return;
- }
- let inserted = self.edit(
- |timeline| {
- timeline.camera3d_segments.extend(generated);
- true
- },
- window,
- cx,
- );
- if !inserted {
- return;
- }
- self.camera3d_setup = None;
- self.tracks.three_d = true;
- self.set_selection(Some(Selection::single(TrackKind::ThreeD, 0)), cx);
- self.seek_to_time(0.0, cx);
- self.view.preview_time = None;
- self.note_edit("add-track", Some(TrackKind::ThreeD));
- }
-
- pub(crate) fn render_camera3d_setup(&self, cx: &mut Context<Self>) -> gpui::AnyElement {
- let theme = self.theme;
- let setup = self.camera3d_setup.unwrap_or(Camera3DSetup {
- scene_id: "showcase",
- shots: 3,
- });
- let scene = crate::editor_panels::CAMERA3D_SCENES
- .iter()
- .find(|scene| scene.id == setup.scene_id)
- .unwrap_or(&crate::editor_panels::CAMERA3D_SCENES[0]);
- let max_shots = ((self.total_duration() / crate::editor_panels::CAMERA3D_MIN_SHOT_DURATION)
- .floor() as usize)
- .clamp(1, scene.shots.len());
- let shots = setup.shots.min(max_shots);
-
- div()
- .id("camera3d-setup")
- .flex()
- .flex_col()
- .flex_1()
- .min_h_0()
- .overflow_y_scroll()
- .p(px(16.))
- .gap(px(16.))
- .child(
- div()
- .flex()
- .flex_row()
- .items_center()
- .gap(px(8.))
- .child(
- ui::EditorButton::plain(&theme, "camera3d-setup-close")
- .left_icon("icons/x-mark.svg")
- .icon_size(px(16.))
- .label("Close")
- .on_click(cx.listener(|this, _, _, cx| {
- this.close_camera3d_setup(cx);
- })),
- )
- .child(
- div()
- .text_size(px(14.))
- .text_color(Hsla::from(theme.gray_10))
- .child("New 3D scene"),
- ),
- )
- .child(
- div()
- .text_size(px(12.))
- .text_color(Hsla::from(theme.gray_10))
- .child("Lay a chain of camera moves over the whole video"),
- )
- .child(
- ui::Field::plain(&theme, "Style")
- .icon("icons/rotate-3d.svg")
- .child(div().flex().flex_row().gap(px(8.)).children(
- crate::editor_panels::CAMERA3D_SCENES.iter().map(|item| {
- let selected = item.id == scene.id;
- let id = item.id;
- div()
- .id(SharedString::from(format!("camera3d-setup-{id}")))
- .flex_1()
- .px(px(10.))
- .py(px(12.))
- .rounded(px(12.))
- .border_1()
- .border_color(Hsla::from(if selected {
- theme.blue_9
- } else {
- theme.gray_4
- }))
- .bg(Hsla::from(if selected {
- theme.gray_3
- } else {
- theme.gray_2
- }))
- .cursor_pointer()
- .tab_index(0)
- .when(!selected, |card| {
- card.hover(|style| style.border_color(theme.gray_7))
- })
- .on_click(cx.listener(move |this, _, _, cx| {
- if let Some(setup) = this.camera3d_setup.as_mut() {
- setup.scene_id = id;
- }
- this.rebuild_timeline();
- cx.notify();
- }))
- .child(
- div()
- .text_size(px(12.))
- .font_weight(FontWeight::MEDIUM)
- .text_color(Hsla::from(theme.gray_12))
- .child(item.name),
- )
- .child(
- div()
- .mt(px(4.))
- .text_size(px(10.))
- .text_color(Hsla::from(theme.gray_11))
- .child(format!(
- "{} {}",
- item.shots.len(),
- if item.shots.len() == 1 {
- "shot"
- } else {
- "shots"
- }
- )),
- )
- }),
- )),
- )
- .child(
- ui::Field::plain(&theme, "How many shots?").child(
- div()
- .flex()
- .flex_col()
- .gap(px(8.))
- .child(
- div()
- .flex()
- .flex_row()
- .gap(px(4.))
- .p(px(4.))
- .rounded(px(8.))
- .bg(Hsla::from(theme.gray_3))
- .children((1..=scene.shots.len()).map(|count| {
- let selected = shots == count;
- let too_short = count > max_shots;
- div()
- .id(SharedString::from(format!(
- "camera3d-setup-shots-{count}"
- )))
- .flex_1()
- .py(px(4.))
- .rounded(px(6.))
- .text_center()
- .text_size(px(12.))
- .font_weight(FontWeight::MEDIUM)
- .text_color(Hsla::from(theme.gray_11))
- .when(selected, |this| {
- this.bg(if theme.is_dark() {
- Hsla::from(theme.gray_5)
- } else {
- Hsla::from(theme.gray_1)
- })
- .text_color(Hsla::from(theme.gray_12))
- })
- .when(too_short, |this| this.opacity(0.4))
- .when(!too_short && !selected, |button| {
- button.hover(|style| style.text_color(theme.gray_12))
- })
- .when(!too_short, |this| {
- this.cursor_pointer().tab_index(0).on_click(
- cx.listener(move |this, _, _, cx| {
- if let Some(setup) =
- this.camera3d_setup.as_mut()
- {
- setup.shots = count;
- }
- this.rebuild_timeline();
- cx.notify();
- }),
- )
- })
- .child(count.to_string())
- })),
- )
- .child(
- div()
- .text_size(px(12.))
- .text_color(Hsla::from(theme.gray_10))
- .child("Shots split the video into separate camera moves."),
- ),
- ),
- )
- .child(
- div()
- .flex()
- .flex_row()
- .items_center()
- .gap(px(8.))
- .child(
- ui::Button::plain(
- &theme,
- "camera3d-setup-add",
- ui::ButtonVariant::Primary,
- ui::ButtonSize::Md,
- )
- .label("Add scene")
- .disabled(self.total_duration() <= 0.0)
- .on_click(cx.listener(|this, _, window, cx| {
- this.confirm_camera3d_setup(window, cx);
- })),
- )
- .child(
- ui::Button::plain(
- &theme,
- "camera3d-setup-cancel",
- ui::ButtonVariant::Gray,
- ui::ButtonSize::Md,
- )
- .label("Cancel")
- .on_click(cx.listener(|this, _, _, cx| {
- this.close_camera3d_setup(cx);
- })),
- ),
- )
- .into_any_element()
-- }
-
+ /// `finish(e)`: resume the history, and -- if the drag never promoted --
+ /// select instead, which also moves the playhead
+ /// (`props.handleUpdatePlayhead(e)`).
+ fn drag_mouse_up(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ self.drag_snap_targets = Vec::new();
+ self.drag_snap_time = None;
+ let Some(drag) = self.drag.take() else {
+ self.clip_draft = None;
+ return;
+ };
- fn start_camera3d_setup(&mut self, cx: &mut Context<Self>) {
- self.set_selection(None, cx);
- self.audio_picker = None;
- self.tracks.three_d = true;
- self.camera3d_setup = Some(Camera3DSetup {
- scene_id: "showcase",
- shots: 3,
- });
- self.rebuild_timeline();
- cx.notify();
- }
-
- fn camera3d_setup_preview(&self) -> Vec<(f64, f64, String)> {
- let Some(setup) = self.camera3d_setup else {
- return Vec::new();
- };
- let Some(scene) = crate::editor_panels::CAMERA3D_SCENES
- .iter()
- .find(|scene| scene.id == setup.scene_id)
- else {
- return Vec::new();
- };
- let shots = setup.shots.clamp(1, scene.shots.len());
- let limited = crate::editor_panels::Camera3DScene {
- id: scene.id,
- name: scene.name,
- shots: &scene.shots[..shots],
- };
- let clip_cuts: Vec<f64> = self
- .project
- .timeline
- .as_ref()
- .map(|timeline| {
- let mut acc = 0.0;
- timeline
- .segments
- .iter()
- .map(|segment| {
- acc += (segment.end - segment.start) / segment.timescale.max(0.0001);
- acc
- })
- .collect()
- })
- .unwrap_or_default();
- crate::editor_panels::apply_scene_to_range(&limited, 0.0, self.total_duration(), &clip_cuts)
- .into_iter()
- .enumerate()
- .map(|(index, segment)| (segment.start, segment.end, format!("Shot {}", index + 1)))
- .collect()
- }
-
- pub(crate) fn confirm_camera3d_setup(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- let Some(setup) = self.camera3d_setup else {
- return;
- };
- if self
- .project
- .timeline
- .as_ref()
- .is_some_and(|timeline| !timeline.camera3d_segments.is_empty())
- {
- return;
- }
- if !edits::ensure_timeline(&mut self.project, &self.clip_display_durations) {
- return;
- }
- let total = self.total_duration();
- let clip_cuts: Vec<f64> = self
- .project
- .timeline
- .as_ref()
- .map(|timeline| {
- let mut acc = 0.0;
- timeline
- .segments
- .iter()
- .map(|segment| {
- acc += (segment.end - segment.start) / segment.timescale.max(0.0001);
- acc
- })
- .collect()
- })
- .unwrap_or_default();
- let Some(scene) = crate::editor_panels::CAMERA3D_SCENES
- .iter()
- .find(|scene| scene.id == setup.scene_id)
- else {
- return;
- };
- let shots = setup.shots.clamp(1, scene.shots.len());
- let limited = crate::editor_panels::Camera3DScene {
- id: scene.id,
- name: scene.name,
- shots: &scene.shots[..shots],
- };
- let generated =
- crate::editor_panels::apply_scene_to_range(&limited, 0.0, total, &clip_cuts);
- if generated.is_empty() {
- return;
- }
- let inserted = self.edit(
- |timeline| {
- timeline.camera3d_segments.extend(generated);
- true
- },
- window,
- cx,
- );
- if !inserted {
- return;
- }
- self.camera3d_setup = None;
- self.tracks.three_d = true;
- self.set_selection(Some(Selection::single(TrackKind::ThreeD, 0)), cx);
- self.seek_to_time(0.0, cx);
- self.view.preview_time = None;
- self.note_edit("add-track", Some(TrackKind::ThreeD));
- }
-
- pub(crate) fn render_camera3d_setup(&self, cx: &mut Context<Self>) -> gpui::AnyElement {
- let theme = self.theme;
- let setup = self.camera3d_setup.unwrap_or(Camera3DSetup {
- scene_id: "showcase",
- shots: 3,
- });
- let scene = crate::editor_panels::CAMERA3D_SCENES
- .iter()
- .find(|scene| scene.id == setup.scene_id)
- .unwrap_or(&crate::editor_panels::CAMERA3D_SCENES[0]);
- let max_shots = ((self.total_duration() / crate::editor_panels::CAMERA3D_MIN_SHOT_DURATION)
- .floor() as usize)
- .clamp(1, scene.shots.len());
- let shots = setup.shots.min(max_shots);
-
- div()
- .id("camera3d-setup")
- .flex()
- .flex_col()
- .flex_1()
- .min_h_0()
- .overflow_y_scroll()
- .p(px(16.))
- .gap(px(16.))
- .child(
- div()
- .flex()
- .flex_row()
- .items_center()
- .gap(px(8.))
- .child(
- ui::EditorButton::plain(&theme, "camera3d-setup-close")
- .left_icon("icons/x-mark.svg")
- .icon_size(px(16.))
- .label("Close")
- .on_click(cx.listener(|this, _, _, cx| {
- this.close_camera3d_setup(cx);
- })),
- )
- .child(
- div()
- .text_size(px(14.))
- .text_color(Hsla::from(theme.gray_10))
- .child("New 3D scene"),
- ),
- )
- .child(
- div()
- .text_size(px(12.))
- .text_color(Hsla::from(theme.gray_10))
- .child("Lay a chain of camera moves over the whole video"),
- )
- .child(
- ui::Field::plain(&theme, "Style")
- .icon("icons/rotate-3d.svg")
- .child(div().flex().flex_row().gap(px(8.)).children(
- crate::editor_panels::CAMERA3D_SCENES.iter().map(|item| {
- let selected = item.id == scene.id;
- let id = item.id;
- div()
- .id(SharedString::from(format!("camera3d-setup-{id}")))
- .flex_1()
- .px(px(10.))
- .py(px(12.))
- .rounded(px(12.))
- .border_1()
- .border_color(Hsla::from(if selected {
- theme.blue_9
- } else {
- theme.gray_4
- }))
- .bg(Hsla::from(if selected {
- theme.gray_3
- } else {
- theme.gray_2
- }))
- .cursor_pointer()
- .tab_index(0)
- .when(!selected, |card| {
- card.hover(|style| style.border_color(theme.gray_7))
- })
- .on_click(cx.listener(move |this, _, _, cx| {
- if let Some(setup) = this.camera3d_setup.as_mut() {
- setup.scene_id = id;
- }
- this.rebuild_timeline();
- cx.notify();
- }))
- .child(
- div()
- .text_size(px(12.))
- .font_weight(FontWeight::MEDIUM)
- .text_color(Hsla::from(theme.gray_12))
- .child(item.name),
- )
- .child(
- div()
- .mt(px(4.))
- .text_size(px(10.))
- .text_color(Hsla::from(theme.gray_11))
- .child(format!(
- "{} {}",
- item.shots.len(),
- if item.shots.len() == 1 {
- "shot"
- } else {
- "shots"
- }
- )),
- )
- }),
- )),
- )
- .child(
- ui::Field::plain(&theme, "How many shots?").child(
- div()
- .flex()
- .flex_col()
- .gap(px(8.))
- .child(
- div()
- .flex()
- .flex_row()
- .gap(px(4.))
- .p(px(4.))
- .rounded(px(8.))
- .bg(Hsla::from(theme.gray_3))
- .children((1..=scene.shots.len()).map(|count| {
- let selected = shots == count;
- let too_short = count > max_shots;
- div()
- .id(SharedString::from(format!(
- "camera3d-setup-shots-{count}"
- )))
- .flex_1()
- .py(px(4.))
- .rounded(px(6.))
- .text_center()
- .text_size(px(12.))
- .font_weight(FontWeight::MEDIUM)
- .text_color(Hsla::from(theme.gray_11))
- .when(selected, |this| {
- this.bg(if theme.is_dark() {
- Hsla::from(theme.gray_5)
- } else {
- Hsla::from(theme.gray_1)
- })
- .text_color(Hsla::from(theme.gray_12))
- })
- .when(too_short, |this| this.opacity(0.4))
- .when(!too_short && !selected, |button| {
- button.hover(|style| style.text_color(theme.gray_12))
- })
- .when(!too_short, |this| {
- this.cursor_pointer().tab_index(0).on_click(
- cx.listener(move |this, _, _, cx| {
- if let Some(setup) =
- this.camera3d_setup.as_mut()
- {
- setup.shots = count;
- }
- this.rebuild_timeline();
- cx.notify();
- }),
- )
- })
- .child(count.to_string())
- })),
- )
- .child(
- div()
- .text_size(px(12.))
- .text_color(Hsla::from(theme.gray_10))
- .child("Shots split the video into separate camera moves."),
- ),
- ),
- )
- .child(
- div()
- .flex()
- .flex_row()
- .items_center()
- .gap(px(8.))
- .child(
- ui::Button::plain(
- &theme,
- "camera3d-setup-add",
- ui::ButtonVariant::Primary,
- ui::ButtonSize::Md,
- )
- .label("Add scene")
- .disabled(self.total_duration() <= 0.0)
- .on_click(cx.listener(|this, _, window, cx| {
- this.confirm_camera3d_setup(window, cx);
- })),
- )
- .child(
- ui::Button::plain(
- &theme,
- "camera3d-setup-cancel",
- ui::ButtonVariant::Gray,
- ui::ButtonSize::Md,
- )
- .label("Cancel")
- .on_click(cx.listener(|this, _, _, cx| {
- this.close_camera3d_setup(cx);
- })),
- ),
- )
- .into_any_element()
- }
-
- /// `finish(e)`: resume the history, and -- if the drag never promoted --
- /// select instead, which also moves the playhead
- /// (`props.handleUpdatePlayhead(e)`).
- fn drag_mouse_up(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- self.drag_snap_targets = Vec::new();
- self.drag_snap_time = None;
- let Some(drag) = self.drag.take() else {
- self.clip_draft = None;
- return;
- };
-
- // The ghost trim's single commit, before the history resume below so
- // the resumed snapshot records the committed config.
- if matches!(
- drag.kind,
- DragKind::ClipTrimStart { .. } | DragKind::ClipTrimEnd { .. }
- ) {
- self.commit_clip_draft(window, cx);
- }
+ // The ghost trim's single commit, before the history resume below so
+ // the resumed snapshot records the committed config.
+ if matches!(
+ drag.kind,
+ DragKind::ClipTrimStart { .. } | DragKind::ClipTrimEnd { .. }
+ ) {
+ self.commit_clip_draft(window, cx);
+ }
if let DragKind::CreateZoom {
base_start,
@@@ -4854,12 -4926,21 +5110,22 @@@
return;
}
let local = ((x - left) / width) * (segment.end - segment.start);
- if self.edit(
- |timeline| edits::split_segment(timeline, kind, index, local),
- window,
- cx,
- ) {
+ let split = if kind == TrackKind::Caption {
+ let recording_durations = self.clip_display_durations.clone();
+ self.edit_caption_project(
+ |project| split_caption_segment(project, index, local, &recording_durations),
+ window,
+ cx,
+ )
+ } else {
+ self.edit(
+ |timeline| edits::split_segment(timeline, kind, index, local),
+ window,
+ cx,
+ )
+ };
+ if split {
+ self.set_selection(None, cx);
self.note_edit("split", Some(kind));
}
}
@@@ -4903,8 -4992,8 +5177,14 @@@
{
self.set_selection(None, cx);
}
-- self.edit(
-- |timeline| edits::delete_track_lane(timeline, kind, lane),
++ let available = self
++ .timeline
++ .rows
++ .iter()
++ .filter_map(|row| row.kind.overlay_track(row.lane))
++ .collect::<Vec<_>>();
++ self.edit_timeline_project(
++ |project| edits::delete_track_lane_and_order(project, &available, kind, lane),
window,
cx,
);
@@@ -5449,20 -5514,20 +5729,17 @@@
/// editor takes the plain Radix values, not the material remaps: it is not
/// a chrome route, so none of the `--macos-settings-*` overrides apply.
pub(crate) fn panel_bg(&self) -> Hsla {
-- if self.theme.is_dark() {
-- self.theme.gray_2.into()
-- } else {
-- self.theme.gray_1.into()
-- }
++ self.theme.editor.card.into()
}
-- /// The root's `dark:bg-gray-1 bg-gray-2` (`routes/editor/index.tsx:46-57`).
++ /// The root's window surface (`--ed-window`).
fn root_bg(&self) -> Hsla {
-- if self.theme.is_dark() {
-- self.theme.gray_1.into()
-- } else {
-- self.theme.gray_2.into()
-- }
++ self.theme.editor.window.into()
++ }
++
++ /// The hairline every editor card is ringed with (`--ed-line`).
++ pub(crate) fn card_line(&self) -> Hsla {
++ self.theme.editor.line.into()
}
// -- Header --------------------------------------------------------------
@@@ -5541,11 -5606,11 +5818,6 @@@
})
.collect()
}
-- ToolbarMenu::PreviewQuality => crate::store::EditorPreviewQuality::ALL
-- .iter()
-- .rev()
-- .map(|quality| ui::MenuItem::new(quality.label(), *quality == self.preview_quality))
-- .collect(),
}
}
@@@ -5619,17 -5684,17 +5891,6 @@@
true
});
}
-- ToolbarMenu::PreviewQuality => {
-- let Some(quality) = crate::store::EditorPreviewQuality::ALL
-- .iter()
-- .rev()
-- .nth(index)
-- .copied()
-- else {
-- return;
-- };
-- self.set_preview_quality(quality, cx);
-- }
}
cx.notify();
window.refresh();
@@@ -5640,7 -5705,7 +5901,7 @@@
let kind = menu.kind;
let items = self.toolbar_menu_items(kind);
Some(
-- ui::Menu::plain(&self.theme, "toolbar-menu", items, &menu.state)
++ ui::Menu::editor(&self.theme, "toolbar-menu", items, &menu.state)
.min_width(px(200.))
.on_select(cx.listener(move |this, index: &usize, window, cx| {
this.choose_toolbar_menu(kind, *index, window, cx);
@@@ -5751,17 -5816,15 +6012,19 @@@
window.focus(&focus, cx);
self.toolbar_menu = None;
let viewport = window.viewport_size();
-- // The trigger is `absolute bottom-0 left-0` in the 32px timeline
-- // header, itself under the slot's fixed geometry, so its top edge is a
++ // The trigger is `absolute bottom-0 left-0` in the timeline header,
++ // itself under the card's fixed geometry, so its top edge is a
// constant offset from the window's bottom-left corner.
- let timeline_height =
- self.clamp_timeline_height(self.timeline_height, f32::from(viewport.height));
- let button_top = f32::from(viewport.height) - timeline_height + TIMELINE_TOP_PADDING;
- let button_top = f32::from(viewport.height) - self.timeline_height + TIMELINE_TOP_PADDING;
++ let timeline_height = self
++ .clamp_timeline_height(self.preferred_timeline_height(), f32::from(viewport.height));
++ let button_top = f32::from(viewport.height) - timeline_height
++ + TIMELINE_CARD_BORDER
++ + TIMELINE_TOP_PADDING;
let bottom = f32::from(viewport.height) - (button_top - 8.);
// `overflowPadding: 64` -- stay clear of the titlebar.
let max_height = (button_top - 8. - 64.).max(160.);
self.add_track = Some(AddTrackMenu {
-- left: px(TIMELINE_SLOT_PADDING + TIMELINE_PADDING),
++ left: px(TIMELINE_SLOT_PADDING + TIMELINE_CARD_BORDER + TIMELINE_PADDING),
bottom: px(bottom),
max_height: px(max_height),
});
@@@ -5813,6 -5876,6 +6076,25 @@@
tracing::warn!("preset {index} no longer deserializes; not applied");
return;
};
++ self.apply_project_preset(next, window, cx);
++ }
++
++ /// The built-in Default row: Cap's own look, with this project's timeline
++ /// and clips kept.
++ fn apply_default_preset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
++ let mut next = crate::presets::default_project_config();
++ next.timeline = self.project.timeline.clone();
++ next.overlay_order = self.project.overlay_order.clone();
++ next.clips = self.project.clips.clone();
++ self.apply_project_preset(next, window, cx);
++ }
++
++ fn apply_project_preset(
++ &mut self,
++ next: ProjectConfiguration,
++ window: &mut Window,
++ cx: &mut Context<Self>,
++ ) {
self.presets_menu = None;
self.refresh_animated_gradient_library();
let previous_animated_gradient = self.animated_gradient_config().cloned();
@@@ -6589,10 -6378,10 +6871,8 @@@
viewport_width: f32,
cx: &mut Context<Self>,
) -> gpui::AnyElement {
-- let secs_per_pixel = self
-- .view
-- .transform
-- .secs_per_pixel(timeline::content_width(viewport_width));
++ let lane_width = timeline::content_width(viewport_width);
++ let secs_per_pixel = self.view.transform.secs_per_pixel(lane_width);
let open = self.clip_speed.as_ref().map(|menu| menu.index);
let hovered = match self.hovered_segment {
Some((TrackKind::Clip, _, index)) => Some(index),
@@@ -6622,6 -6411,6 +6902,9 @@@
if width < 28. {
continue;
}
++ // Trailing edge, clamped into view: the segment's label now runs
++ // from its left edge and the trim handle owns the last 8px.
++ let button_left = (x + width - 32.).min(lane_width - 32.).max(x + 6.);
layer = layer.child(
div()
.id(gpui::ElementId::NamedInteger(
@@@ -6629,7 -6418,7 +6912,7 @@@
index as u64,
))
.absolute()
-- .left(px(x + 6.))
++ .left(px(button_left))
.bottom(px(6.))
.size(px(22.))
.rounded_full()
@@@ -6637,8 -6426,8 +6920,13 @@@
.items_center()
.justify_center()
.cursor_pointer()
-- .bg(gpui::hsla(0., 0., 0., if active { 0.5 } else { 0.3 }))
-- .hover(|this| this.bg(gpui::hsla(0., 0., 0., 0.5)))
++ .border_1()
++ .border_color(Hsla::from(self.theme.editor.line))
++ .bg(Hsla::from(self.theme.editor.card))
++ .when(active, |this| {
++ this.bg(Hsla::from(self.theme.editor.ctl_active))
++ })
++ .hover(|this| this.bg(Hsla::from(self.theme.editor.ctl_hover)))
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, event: &MouseDownEvent, window, cx| {
@@@ -6650,7 -6439,7 +6938,7 @@@
svg()
.path("icons/settings.svg")
.size(px(12.))
-- .text_color(gpui::white()),
++ .text_color(Hsla::from(self.theme.editor.text_2)),
),
);
}
@@@ -6706,10 -6495,10 +6994,10 @@@
.gap(px(6.))
.rounded(px(12.))
.border_1()
-- .border_color(Hsla::from(theme.gray_3))
-- .bg(Hsla::from(theme.gray_1))
++ .border_color(Hsla::from(theme.editor.line))
++ .bg(Hsla::from(theme.editor.card))
.p(px(8.))
-- .shadow_lg()
++ .shadow(theme.editor.pop_shadow())
.on_mouse_down(
MouseButton::Left,
cx.listener(|_, _, _, cx| cx.stop_propagation()),
@@@ -6721,7 -6510,7 +7009,7 @@@
.items_center()
.gap(px(4.))
.rounded(px(8.))
-- .bg(Hsla::from(theme.gray_2))
++ .bg(Hsla::from(theme.editor.ctl))
.p(px(4.))
.children(speeds.into_iter().map(|speed| {
let selected = (timescale - speed).abs() < 1e-6;
@@@ -6738,16 -6527,16 +7026,18 @@@
.text_size(px(12.))
.cursor_pointer()
.bg(if selected {
-- Hsla::from(theme.gray_4)
++ Hsla::from(theme.editor.ctl_hover)
} else {
gpui::transparent_black()
})
.text_color(Hsla::from(if selected {
-- theme.gray_12
++ theme.editor.text_1
} else {
-- theme.gray_10
++ theme.editor.text_2
}))
-- .hover(|this| this.text_color(Hsla::from(theme.gray_12)))
++ .hover(|this| {
++ this.text_color(Hsla::from(theme.editor.text_1))
++ })
.child(label)
.on_click(cx.listener(move |this, _, window, cx| {
this.set_clip_timescale(index, speed, window, cx);
@@@ -6761,7 -6550,7 +7051,7 @@@
.items_center()
.gap(px(4.))
.rounded(px(8.))
-- .bg(Hsla::from(theme.gray_2))
++ .bg(Hsla::from(theme.editor.ctl))
.p(px(4.))
.child(
div()
@@@ -6772,16 -6561,16 +7062,18 @@@
.text_size(px(12.))
.cursor_pointer()
.bg(if muted {
-- Hsla::from(theme.gray_4)
++ Hsla::from(theme.editor.ctl_hover)
} else {
gpui::transparent_black()
})
.text_color(Hsla::from(if muted {
-- theme.gray_12
++ theme.editor.text_1
} else {
-- theme.gray_10
++ theme.editor.text_2
}))
-- .hover(|this| this.text_color(Hsla::from(theme.gray_12)))
++ .hover(|this| {
++ this.text_color(Hsla::from(theme.editor.text_1))
++ })
.child(if muted { "Unmute clip" } else { "Mute clip" })
.on_click(cx.listener(move |this, _, window, cx| {
this.set_clip_muted(index, !muted, window, cx);
@@@ -6795,7 -6584,7 +7087,7 @@@
.items_center()
.gap(px(4.))
.rounded(px(8.))
-- .bg(Hsla::from(theme.gray_2))
++ .bg(Hsla::from(theme.editor.ctl))
.p(px(4.))
.children(audio_modes.into_iter().map(|(mode, label)| {
let selected = audio_mode == mode
@@@ -6808,16 -6597,16 +7100,18 @@@
.text_size(px(12.))
.cursor_pointer()
.bg(if selected {
-- Hsla::from(theme.gray_4)
++ Hsla::from(theme.editor.ctl_hover)
} else {
gpui::transparent_black()
})
.text_color(Hsla::from(if selected {
-- theme.gray_12
++ theme.editor.text_1
} else {
-- theme.gray_10
++ theme.editor.text_2
}))
-- .hover(|this| this.text_color(Hsla::from(theme.gray_12)))
++ .hover(|this| {
++ this.text_color(Hsla::from(theme.editor.text_1))
++ })
.child(label)
.on_click(cx.listener(move |this, _, window, cx| {
this.set_clip_speed_audio_mode(index, mode, window, cx);
@@@ -6863,10 -6652,10 +7157,10 @@@
.flex()
.flex_col()
.overflow_hidden()
-- .rounded(px(16.))
++ .rounded(px(12.))
.border_1()
-- .border_color(Hsla::from(theme.gray_3))
-- .bg(Hsla::from(theme.gray_1))
++ .border_color(Hsla::from(theme.editor.line))
++ .bg(Hsla::from(theme.editor.card))
.shadow_lg()
.child(
div()
@@@ -6874,22 -6663,22 +7168,22 @@@
.flex_col()
.flex_none()
.gap(px(2.))
-- .px(px(16.))
-- .pt(px(14.))
-- .pb(px(12.))
++ .px(px(14.))
++ .pt(px(12.))
++ .pb(px(10.))
.border_b_1()
-- .border_color(Hsla::from(theme.gray_3))
++ .border_color(Hsla::from(theme.editor.line))
.child(
div()
.text_size(px(13.))
.font_weight(FontWeight::SEMIBOLD)
-- .text_color(Hsla::from(theme.gray_12))
++ .text_color(Hsla::from(theme.editor.text_1))
.child("Add a track"),
)
.child(
div()
-- .text_size(px(11.))
-- .text_color(Hsla::from(theme.gray_10))
++ .text_size(px(12.))
++ .text_color(Hsla::from(theme.editor.text_2))
.child("Layer captions, audio, zooms and more onto your timeline."),
),
)
@@@ -6918,34 -6707,34 +7212,36 @@@
.flex()
.flex_row()
.items_center()
-- .gap(px(12.))
++ .gap(px(10.))
.p(px(8.))
-- .rounded(px(12.))
++ .rounded(px(8.))
.when(!available, |this| this.opacity(0.55))
.when(available, |this| {
-- this.cursor_pointer().hover(|this| this.bg(Hsla::from(theme.gray_3)))
++ this.cursor_pointer().hover(|this| {
++ this.bg(Hsla::from(theme.editor.ctl_hover))
++ })
})
.child(
div()
.flex()
.items_center()
.justify_center()
-- .size(px(36.))
-- .rounded(px(10.))
++ .size(px(22.))
++ .rounded(px(6.))
.flex_none()
.bg(if available {
-- color
++ timeline::tile_bg(&theme, color)
} else {
-- Hsla::from(theme.gray_3)
++ Hsla::from(theme.editor.ctl)
})
.child(
svg()
.path(kind.icon())
-- .size(px(16.))
++ .size(px(12.))
.text_color(if available {
-- gpui::white()
++ timeline::tile_fg(&theme, color)
} else {
-- Hsla::from(theme.gray_10)
++ Hsla::from(theme.editor.text_3)
}),
),
)
@@@ -6963,7 -6752,7 +7259,7 @@@
.gap(px(6.))
.text_size(px(13.))
.font_weight(FontWeight::MEDIUM)
-- .text_color(Hsla::from(theme.gray_12))
++ .text_color(Hsla::from(theme.editor.text_1))
.child(kind.picker_label())
.when(kind.supports_multiple() && count > 0, |this| {
this.child(
@@@ -6973,8 -6762,8 +7269,8 @@@
.px(px(6.))
.text_size(px(10.))
.font_weight(FontWeight::SEMIBOLD)
-- .text_color(gpui::white())
-- .bg(color)
++ .text_color(timeline::tile_fg(&theme, color))
++ .bg(timeline::tile_bg(&theme, color))
.child(format!("{count}")),
)
}),
@@@ -6982,7 -6771,7 +7278,7 @@@
.child(
div()
.text_size(px(11.))
-- .text_color(Hsla::from(theme.gray_10))
++ .text_color(Hsla::from(theme.editor.text_3))
.child(description),
),
)
@@@ -6991,14 -6780,14 +7287,14 @@@
.flex()
.items_center()
.justify_center()
-- .size(px(24.))
++ .size(px(20.))
.rounded_full()
.flex_none()
-- .bg(color)
++ .bg(Hsla::from(theme.editor.accent))
.child(
svg()
.path("icons/check.svg")
-- .size(px(14.))
++ .size(px(12.))
.text_color(gpui::white()),
)
.into_any_element()
@@@ -7007,16 -6796,16 +7303,16 @@@
.flex()
.items_center()
.justify_center()
-- .size(px(24.))
++ .size(px(20.))
.rounded_full()
.flex_none()
.border_1()
-- .border_color(Hsla::from(theme.gray_5))
++ .border_color(Hsla::from(theme.editor.line_strong))
.child(
svg()
.path("icons/plus.svg")
-- .size(px(14.))
-- .text_color(Hsla::from(theme.gray_10)),
++ .size(px(12.))
++ .text_color(Hsla::from(theme.editor.text_3)),
)
.into_any_element()
})
@@@ -7042,7 -6831,7 +7338,7 @@@
.p(px(6.))
.flex_none()
.border_t_1()
-- .border_color(Hsla::from(theme.gray_3))
++ .border_color(Hsla::from(theme.editor.line))
.child(
div()
.id("add-track-close")
@@@ -7052,21 -6841,21 +7348,19 @@@
.justify_center()
.gap(px(6.))
.w_full()
-- .h(px(36.))
++ .h(px(30.))
.rounded(px(8.))
-- .border_1()
-- .border_color(Hsla::from(theme.gray_4))
-- .bg(Hsla::from(theme.gray_2))
++ .bg(Hsla::from(theme.editor.ctl))
.text_size(px(13.))
.font_weight(FontWeight::MEDIUM)
-- .text_color(Hsla::from(theme.gray_12))
++ .text_color(Hsla::from(theme.editor.text_2))
.cursor_pointer()
-- .hover(|this| this.bg(Hsla::from(theme.gray_3)))
++ .hover(|this| this.bg(Hsla::from(theme.editor.ctl_hover)))
.child(
svg()
.path("icons/x.svg")
-- .size(px(14.))
-- .text_color(Hsla::from(theme.gray_12)),
++ .size(px(13.))
++ .text_color(Hsla::from(theme.editor.text_2)),
)
.child("Close")
.on_click(cx.listener(|this, _, _window, cx| {
@@@ -7090,97 -6879,97 +7384,34 @@@
let store = menu.store.clone();
let submenu = menu.submenu;
-- let rows: Vec<gpui::AnyElement> = if store.presets.is_empty() {
-- vec![
++ let mut rows: Vec<gpui::AnyElement> = vec![self.render_preset_row(
++ PresetRow::Default,
++ "Default".into(),
++ store.default.is_none(),
++ cx,
++ )];
++ if store.presets.is_empty() {
++ rows.push(
div()
.flex()
.items_center()
.justify_center()
-- .h(px(40.))
-- .text_size(px(14.))
-- .text_color(Hsla::from(theme.gray_11))
-- .child("No Presets")
++ .h(px(32.))
++ .text_size(px(12.))
++ .text_color(Hsla::from(theme.editor.text_3))
++ .child("No saved presets")
.into_any_element(),
-- ]
++ );
} else {
-- store
-- .presets
-- .iter()
-- .enumerate()
-- .map(|(index, entry)| {
-- let is_default = store.default == Some(index);
-- div()
-- .id(SharedString::from(format!("preset-{index}")))
-- .flex()
-- .flex_row()
-- .items_center()
-- .flex_none()
-- .gap(px(8.))
-- .h(px(40.))
-- .px(px(8.))
-- .rounded(px(8.))
-- .cursor_pointer()
-- .hover(|this| this.bg(Hsla::from(theme.gray_3)))
-- .child(
-- div()
-- .flex_1()
-- .min_w_0()
-- .truncate()
-- .text_size(px(14.))
-- .text_color(Hsla::from(theme.gray_12))
-- .child(entry.name.clone()),
-- )
-- .when(is_default, |this| {
-- this.child(
-- div()
-- .px(px(8.))
-- .py(px(4.))
-- .rounded_full()
-- .flex_none()
-- .text_size(px(11.))
-- .bg(Hsla::from(theme.gray_2))
-- .text_color(Hsla::from(theme.gray_11))
-- .child("Default"),
-- )
-- })
-- .child(
-- div()
-- .id(SharedString::from(format!("preset-gear-{index}")))
-- .flex()
-- .items_center()
-- .justify_center()
-- .size(px(24.))
-- .rounded(px(6.))
-- .flex_none()
-- .cursor_pointer()
-- .hover(|this| this.bg(Hsla::from(theme.gray_4)))
-- .child(
-- svg()
-- .path("icons/gear.svg")
-- .size(px(16.))
-- .text_color(Hsla::from(theme.gray_11)),
-- )
-- .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
-- .on_click(cx.listener(
-- move |this, event: &gpui::ClickEvent, _window, cx| {
-- cx.stop_propagation();
-- if let Some(menu) = this.presets_menu.as_mut() {
-- menu.submenu = match menu.submenu {
-- Some((open, _)) if open == index => None,
-- _ => Some((index, event.position())),
-- };
-- }
-- cx.notify();
-- },
-- )),
-- )
-- .on_click(cx.listener(move |this, _, window, cx| {
-- this.apply_preset_at(index, window, cx);
-- }))
-- .into_any_element()
-- })
-- .collect()
-- };
++ rows.extend(store.presets.iter().enumerate().map(|(index, entry)| {
++ self.render_preset_row(
++ PresetRow::Saved(index),
++ SharedString::from(entry.name.clone()),
++ store.default == Some(index),
++ cx,
++ )
++ }));
++ }
Some(
div()
@@@ -7195,6 -6984,6 +7426,7 @@@
.top_0()
.left_0()
.size_full()
++ .occlude()
.on_click(cx.listener(|this, _, _window, cx| {
this.presets_menu = None;
cx.notify();
@@@ -7205,14 -6994,14 +7437,15 @@@
.absolute()
.left(menu.origin.x)
.top(menu.origin.y)
-- .w(px(288.))
++ .w(px(PRESETS_MENU_WIDTH))
++ .occlude()
.flex()
.flex_col()
.rounded(px(12.))
.border_1()
-- .border_color(Hsla::from(theme.gray_3))
-- .bg(Hsla::from(theme.gray_1))
-- .shadow_md()
++ .border_color(Hsla::from(theme.editor.line))
++ .bg(Hsla::from(theme.editor.card))
++ .shadow(theme.editor.pop_shadow())
.overflow_hidden()
.child(
div()
@@@ -7231,7 -7020,7 +7464,7 @@@
div()
.p(px(6.))
.border_t_1()
-- .border_color(Hsla::from(theme.gray_3))
++ .border_color(Hsla::from(theme.editor.line))
.child(
div()
.id("preset-create")
@@@ -7243,15 -7032,15 +7476,15 @@@
.px(px(8.))
.rounded(px(8.))
.cursor_pointer()
-- .hover(|this| this.bg(Hsla::from(theme.gray_3)))
++ .hover(|this| this.bg(Hsla::from(theme.editor.ctl_hover)))
.text_size(px(14.))
-- .text_color(Hsla::from(theme.gray_12))
++ .text_color(Hsla::from(theme.editor.text_1))
.child(div().flex_1().child("Create new preset"))
.child(
svg()
.path("icons/circle-plus.svg")
.size(px(16.))
-- .text_color(Hsla::from(theme.gray_11)),
++ .text_color(Hsla::from(theme.editor.text_2)),
)
.on_click(cx.listener(|this, _, window, cx| {
this.open_preset_dialog(
@@@ -7263,89 -7052,89 +7496,203 @@@
),
),
)
-- .children(submenu.map(|(index, at)| self.render_preset_submenu(index, at, cx)))
++ .children(submenu.map(|(row, at)| self.render_preset_submenu(row, at, cx)))
.into_any_element(),
)
}
- /// The per-preset submenu (`w-52`): Apply, Save settings to preset, Set
- /// as default, Rename, Delete.
- fn render_preset_submenu(
++ /// One menu row: the name, the "Default" badge when it is what new
++ /// recordings get, and the gear that opens the row's submenu. Clicking the
++ /// row applies it.
++ fn render_preset_row(
+ &self,
- index: usize,
- at: gpui::Point<Pixels>,
++ row: PresetRow,
++ name: SharedString,
++ is_default: bool,
+ cx: &mut Context<Self>,
+ ) -> gpui::AnyElement {
+ let theme = self.theme;
- let row = |id: SharedString, label: &'static str, danger: bool| {
- div()
- .id(id)
- .flex()
- .flex_row()
- .items_center()
- .h(px(32.))
- .px(px(8.))
- .rounded(px(6.))
- .cursor_pointer()
- .hover(move |this| this.bg(Hsla::from(theme.gray_3)))
- .text_size(px(13.))
- .text_color(if danger {
- Hsla::from(theme.red_9)
- } else {
- Hsla::from(theme.gray_12)
- })
- .child(label)
++ let key = match row {
++ PresetRow::Default => "builtin".to_string(),
++ PresetRow::Saved(index) => index.to_string(),
++ };
++ div()
++ .id(SharedString::from(format!("preset-{key}")))
++ .flex()
++ .flex_row()
++ .items_center()
++ .flex_none()
++ .gap(px(8.))
++ .h(px(40.))
++ .px(px(8.))
++ .rounded(px(8.))
++ .cursor_pointer()
++ .hover(|this| this.bg(Hsla::from(theme.editor.ctl_hover)))
++ .child(
++ div()
++ .flex_1()
++ .min_w_0()
++ .truncate()
++ .text_size(px(14.))
++ .text_color(Hsla::from(theme.editor.text_1))
++ .child(name),
++ )
++ .when(is_default, |this| {
++ this.child(
++ div()
++ .px(px(8.))
++ .py(px(4.))
++ .rounded_full()
++ .flex_none()
++ .text_size(px(11.))
++ .bg(Hsla::from(theme.editor.ctl))
++ .text_color(Hsla::from(theme.editor.text_2))
++ .child("Default"),
++ )
++ })
++ .child(
++ div()
++ .id(SharedString::from(format!("preset-gear-{key}")))
++ .flex()
++ .items_center()
++ .justify_center()
++ .size(px(24.))
++ .rounded(px(6.))
++ .flex_none()
++ .cursor_pointer()
++ .hover(|this| this.bg(Hsla::from(theme.editor.ctl_active)))
++ .child(
++ svg()
++ .path("icons/gear.svg")
++ .size(px(16.))
++ .text_color(Hsla::from(theme.editor.text_2)),
++ )
++ .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
++ .on_click(
++ cx.listener(move |this, event: &gpui::ClickEvent, window, cx| {
++ cx.stop_propagation();
++ let viewport = window.viewport_size();
++ if let Some(menu) = this.presets_menu.as_mut() {
++ menu.submenu = match menu.submenu {
++ Some((open, _)) if open == row => None,
++ _ => Some((
++ row,
++ preset_submenu_origin(
++ menu.origin,
++ event.position(),
++ viewport,
++ ),
++ )),
++ };
++ }
++ cx.notify();
++ }),
++ ),
++ )
++ .on_click(cx.listener(move |this, _, window, cx| match row {
++ PresetRow::Default => this.apply_default_preset(window, cx),
++ PresetRow::Saved(index) => this.apply_preset_at(index, window, cx),
++ }))
++ .into_any_element()
++ }
++
+ /// The per-preset submenu (`w-52`): Apply, Save settings to preset, Set
+ /// as default, Rename, Delete.
+ fn render_preset_submenu(
+ &self,
- index: usize,
++ row: PresetRow,
+ at: gpui::Point<Pixels>,
+ cx: &mut Context<Self>,
+ ) -> gpui::AnyElement {
+ let theme = self.theme;
- let row = |id: SharedString, label: &'static str, danger: bool| {
++ let menu_row = |id: SharedString, label: &'static str, danger: bool| {
+ div()
+ .id(id)
+ .flex()
+ .flex_row()
+ .items_center()
+ .h(px(32.))
+ .px(px(8.))
+ .rounded(px(6.))
+ .cursor_pointer()
- .hover(move |this| this.bg(Hsla::from(theme.gray_3)))
++ .hover(move |this| this.bg(Hsla::from(theme.editor.ctl_hover)))
+ .text_size(px(13.))
+ .text_color(if danger {
+ Hsla::from(theme.red_9)
+ } else {
- Hsla::from(theme.gray_12)
++ Hsla::from(theme.editor.text_1)
+ })
+ .child(label)
};
div()
.absolute()
.left(at.x)
.top(at.y)
-- .w(px(208.))
++ .w(px(PRESET_SUBMENU_WIDTH))
++ .occlude()
.flex()
.flex_col()
.p(px(4.))
.gap(px(2.))
-- .rounded(px(10.))
++ .rounded(px(12.))
.border_1()
-- .border_color(Hsla::from(theme.gray_3))
-- .bg(Hsla::from(theme.gray_1))
-- .shadow_md()
- .child(
- row("preset-apply".into(), "Apply", false).on_click(cx.listener(
- move |this, _, window, cx| {
- this.apply_preset_at(index, window, cx);
- },
- )),
- )
- .child(
- row("preset-save".into(), "Save settings to preset", false).on_click(cx.listener(
- move |this, _, _window, cx| {
- let config = crate::presets::preset_config(&this.project);
- this.mutate_presets(cx, |store| store.save_to(index, config));
- },
- )),
- )
++ .border_color(Hsla::from(theme.editor.line))
++ .bg(Hsla::from(theme.editor.card))
++ .shadow(theme.editor.pop_shadow())
.child(
- row("preset-apply".into(), "Apply", false).on_click(cx.listener(
- move |this, _, window, cx| {
- this.apply_preset_at(index, window, cx);
- row("preset-default".into(), "Set as default", false).on_click(cx.listener(
- move |this, _, _window, cx| {
- this.mutate_presets(cx, |store| store.set_default(index));
++ menu_row("preset-apply".into(), "Apply", false).on_click(cx.listener(
++ move |this, _, window, cx| match row {
++ PresetRow::Default => this.apply_default_preset(window, cx),
++ PresetRow::Saved(index) => this.apply_preset_at(index, window, cx),
},
)),
)
- .child(
- row("preset-save".into(), "Save settings to preset", false).on_click(cx.listener(
- move |this, _, _window, cx| {
- let config = crate::presets::preset_config(&this.project);
- this.mutate_presets(cx, |store| store.save_to(index, config));
- },
- )),
- )
- .child(
- row("preset-default".into(), "Set as default", false).on_click(cx.listener(
- move |this, _, _window, cx| {
- this.mutate_presets(cx, |store| store.set_default(index));
- },
- )),
- )
-- .child(
-- row("preset-rename".into(), "Rename", false).on_click(cx.listener(
-- move |this, _, window, cx| {
-- this.open_preset_dialog(PresetDialog::Rename { index }, window, cx);
-- },
-- )),
-- )
-- .child(
-- row("preset-delete".into(), "Delete", true).on_click(cx.listener(
-- move |this, _, window, cx| {
-- this.open_preset_dialog(PresetDialog::Delete { index }, window, cx);
-- },
-- )),
++ .when(row == PresetRow::Default, |this| {
++ this.child(
++ menu_row("preset-clear-default".into(), "Set as default", false).on_click(
++ cx.listener(move |this, _, _window, cx| {
++ this.mutate_presets(cx, |store| store.clear_default());
++ }),
++ ),
++ )
++ })
++ .when_some(
++ match row {
++ PresetRow::Saved(index) => Some(index),
++ PresetRow::Default => None,
++ },
++ |this, index| {
++ this.child(
++ menu_row("preset-save".into(), "Save settings to preset", false).on_click(
++ cx.listener(move |this, _, _window, cx| {
++ let config = crate::presets::preset_config(&this.project);
++ this.mutate_presets(cx, |store| store.save_to(index, config));
++ }),
++ ),
++ )
++ .child(
++ menu_row("preset-default".into(), "Set as default", false).on_click(
++ cx.listener(move |this, _, _window, cx| {
++ this.mutate_presets(cx, |store| store.set_default(index));
++ }),
++ ),
++ )
++ .child(
++ menu_row("preset-rename".into(), "Rename", false).on_click(cx.listener(
++ move |this, _, window, cx| {
++ this.open_preset_dialog(PresetDialog::Rename { index }, window, cx);
++ },
++ )),
++ )
++ .child(
++ menu_row("preset-delete".into(), "Delete", true).on_click(cx.listener(
++ move |this, _, window, cx| {
++ this.open_preset_dialog(PresetDialog::Delete { index }, window, cx);
++ },
++ )),
++ )
++ },
)
.into_any_element()
}
@@@ -7365,7 -7154,7 +7712,7 @@@
let body: gpui::AnyElement = match dialog {
PresetDialog::Delete { index } => div()
.text_size(px(14.))
-- .text_color(Hsla::from(theme.gray_11))
++ .text_color(Hsla::from(theme.editor.text_2))
.child(SharedString::from(format!(
"Are you sure you want to delete \"{}\"?",
crate::presets::PresetsStore::load()
@@@ -7395,7 -7184,7 +7742,7 @@@
.child(
div()
.text_size(px(14.))
-- .text_color(Hsla::from(theme.gray_12))
++ .text_color(Hsla::from(theme.editor.text_1))
.child("Set as default"),
)
.child(
@@@ -7449,19 -7238,19 +7796,19 @@@
.flex_col()
.rounded(px(12.))
.border_1()
-- .border_color(Hsla::from(theme.gray_3))
-- .bg(Hsla::from(theme.gray_1))
-- .shadow_lg()
++ .border_color(Hsla::from(theme.editor.line))
++ .bg(Hsla::from(theme.editor.card))
++ .shadow(theme.editor.pop_shadow())
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.child(
div()
.px(px(16.))
.py(px(12.))
.border_b_1()
-- .border_color(Hsla::from(theme.gray_3))
++ .border_color(Hsla::from(theme.editor.line))
.text_size(px(14.))
.font_weight(FontWeight::SEMIBOLD)
-- .text_color(Hsla::from(theme.gray_12))
++ .text_color(Hsla::from(theme.editor.text_1))
.child(title),
)
.child(div().p(px(16.)).child(body))
@@@ -7527,10 -7316,10 +7874,10 @@@
.padding_y(px(6.))
.height(px(30.))
.radius(px(8.))
-- .bg(Hsla::from(theme.gray_1))
-- .border(Hsla::from(theme.gray_12))
++ .bg(Hsla::from(theme.editor.card))
++ .border(Hsla::from(theme.editor.line_strong))
.text_size(px(13.))
-- .text_color(Hsla::from(theme.gray_12))
++ .text_color(Hsla::from(theme.editor.text_1))
.into_any_element();
Some(
@@@ -7584,23 -7373,12 +7931,40 @@@
)
}
-- /// `Header.tsx:89-235` -- `h-14`, three groups, the middle one bracketed by
-- /// `border-x border-black-transparent-10`.
++ /// The header row: title block on the left, action cluster on the right.
fn render_header(&self, window: &Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
let name_focused = self.name_input.read(cx).focus_handle().is_focused(window);
+ let has_captions = self.project.captions.as_ref().is_some_and(|captions| {
+ captions
+ .segments
+ .iter()
+ .any(|segment| !segment.words.is_empty())
+ });
+ let compact = compact_header_controls(
+ f32::from(window.viewport_size().width),
+ cfg!(target_os = "windows"),
+ has_captions,
+ );
+
++ let drag_area = |area: gpui::Div| {
++ area.flex_1()
++ .h_full()
++ .when(cfg!(target_os = "windows"), |area| {
++ area.occlude()
++ .window_control_area(gpui::WindowControlArea::Drag)
++ })
++ .when(cfg!(target_os = "macos"), |area| {
++ area.on_mouse_down(gpui::MouseButton::Left, |event, window, _| {
++ if event.click_count == 2 {
++ window.titlebar_double_click();
++ } else {
++ window.start_window_move();
++ }
++ })
++ })
++ };
+
let header = div()
.relative()
.flex()
@@@ -7609,182 -7387,182 +7973,115 @@@
.w_full()
.h(px(HEADER_HEIGHT))
.flex_none()
++ .gap(px(6.))
++ .px(px(10.))
++ .when(compact, |header| header.px(px(6.)))
.when(cfg!(target_os = "windows"), |header| {
header.window_control_area(gpui::WindowControlArea::Drag)
})
-- // Left group: `flex flex-row flex-1 gap-2 items-center px-4 h-full`.
++ // The macOS spacer for the inset traffic lights.
++ .when(!cfg!(target_os = "windows"), |header| {
++ header.child(div().h_full().w(px(82.)).flex_none())
++ })
++ // The name field plus its literal `.cap` suffix, editable. The
++ // Solid version is an `<input>` overlaying a measuring `<span>`;
++ // here the field paints its own text, so the span is not needed and
++ // the `max-w-[200px]` sits on the field itself.
.child(
div()
.flex()
.flex_row()
-- .flex_1()
-- .min_w_0()
-- .gap(px(8.))
.items_center()
-- .px(px(16.))
- .when(compact, |group| group.gap(px(4.)).px(px(8.)))
-- .h_full()
++ .min_w_0()
++ .flex_shrink(1.)
.when(cfg!(target_os = "windows"), |group| group.occlude())
-- // The macOS spacer for the inset traffic lights: `h-full w-16`.
-- .when(!cfg!(target_os = "windows"), |group| {
-- group.child(div().h_full().w(px(64.)).flex_none())
-- })
- .child(
- ui::EditorButton::plain(&theme, "delete-recording")
- .left_icon("icons/trash.svg")
- .tooltip(&theme, "Delete recording")
- .on_click(cx.listener(|this, _, window, cx| {
- this.delete_recording(window, cx);
- })),
- )
- .child(
- ui::EditorButton::plain(&theme, "open-recording-bundle")
- .left_icon("icons/folder.svg")
- .tooltip(&theme, "Open recording bundle")
- .on_click(cx.listener(|this, _, _window, cx| {
- this.open_recording_bundle(cx);
- })),
- )
- // `NameEditor` + the literal `.cap` suffix
- // (`Header.tsx:123-126`), editable. The Solid version is an
- // `<input>` overlaying a measuring `<span>`; here the field
- // paints its own text, so the span is not needed and the
- // `max-w-[200px]` sits on the field itself.
.child(
- ui::EditorButton::plain(&theme, "delete-recording")
- .left_icon("icons/trash.svg")
- .tooltip(&theme, "Delete recording")
- .on_click(cx.listener(|this, _, window, cx| {
- this.delete_recording(window, cx);
- })),
+ div()
- .flex()
- .flex_row()
- .items_center()
+ .min_w_0()
++ .max_w(px(220.))
++ .overflow_hidden()
++ .border_b_1()
++ .border_color(if name_focused {
++ Hsla::from(theme.editor.line_strong)
++ } else {
++ gpui::transparent_black()
++ })
+ .child(
- // `px-px m-0 bg-transparent border-b
- // border-transparent focus:border-gray-7`
- div()
- .max_w(px(200.))
- .border_b_1()
- .border_color(if name_focused {
- Hsla::from(theme.gray_7)
- } else {
- gpui::transparent_black()
- })
- .child(
- ui::TextInput::bare(
- &theme,
- "editor-name",
- &self.name_input,
- )
- // The measuring span's job: the field
- // is as wide as its value, capped by
- // the wrapper's `max-w-[200px]`.
- .fit_content()
- .padding_x(px(1.))
- .text_size(px(14.))
- .text_color(Hsla::from(theme.gray_12)),
- ),
- )
- .child(
- div()
- .text_size(px(14.))
- .text_color(Hsla::from(theme.gray_11))
- .child(".cap"),
++ ui::TextInput::bare(&theme, "editor-name", &self.name_input)
++ .fit_content()
++ .padding_x(px(1.))
++ .text_size(px(13.))
++ .font_weight(FontWeight::MEDIUM)
++ .text_color(Hsla::from(theme.editor.text_1)),
+ ),
)
+ .child(
+ div()
- .flex_1()
- .h_full()
- .when(cfg!(target_os = "windows"), |area| {
- area.occlude()
- .window_control_area(gpui::WindowControlArea::Drag)
- })
- .when(cfg!(target_os = "macos"), |area| {
- area.on_mouse_down(gpui::MouseButton::Left, |event, window, _| {
- if event.click_count == 2 {
- window.titlebar_double_click();
- } else {
- window.start_window_move();
- }
- })
- }),
++ .flex_shrink_0()
++ .text_size(px(13.))
++ .font_weight(FontWeight::MEDIUM)
++ .text_color(Hsla::from(theme.editor.text_3))
++ .child(".cap"),
+ ),
+ )
- // Centre group: `flex flex-row items-center justify-center gap-2
- // px-4 border-x border-black-transparent-10`.
+ .child(
+ div()
+ .flex()
+ .flex_row()
+ .items_center()
- .justify_center()
- .gap(px(8.))
- .px(px(16.))
- .h_full()
- .border_l_1()
- .border_r_1()
- .border_color(gpui::hsla(0., 0., 0., 0.1))
++ .gap(px(2.))
++ .flex_none()
+ .when(cfg!(target_os = "windows"), |group| group.occlude())
.child(
- ui::EditorButton::plain(&theme, "presets")
- .left_icon("icons/presets.svg")
- .label("Presets")
- .disabled(!self.project_ready())
- .right_icon("icons/chevron-down.svg")
- .pressed(self.presets_menu.is_some())
- .on_open(cx.listener(|this, bounds: &Bounds<Pixels>, window, cx| {
- this.open_presets_menu(bounds.bottom_left(), window, cx);
+ ui::EditorButton::plain(&theme, "open-recording-bundle")
+ .left_icon("icons/folder.svg")
+ .tooltip(&theme, "Open recording bundle")
+ .on_click(cx.listener(|this, _, _window, cx| {
+ this.open_recording_bundle(cx);
+ })),
+ )
- // `NameEditor` + the literal `.cap` suffix
- // (`Header.tsx:123-126`), editable. The Solid version is an
- // `<input>` overlaying a measuring `<span>`; here the field
- // paints its own text, so the span is not needed and the
- // `max-w-[200px]` sits on the field itself.
- .child(
- div()
- .flex()
- .flex_row()
- .items_center()
- .min_w_0()
- .child(
- // `px-px m-0 bg-transparent border-b
- // border-transparent focus:border-gray-7`
- div()
- .min_w_0()
- .max_w(px(200.))
- .overflow_hidden()
- .border_b_1()
- .border_color(if name_focused {
- Hsla::from(theme.gray_7)
- } else {
- gpui::transparent_black()
- })
- .child(
- ui::TextInput::bare(
- &theme,
- "editor-name",
- &self.name_input,
- )
- // The measuring span's job: the field
- // is as wide as its value, capped by
- // the wrapper's `max-w-[200px]`.
- .fit_content()
- .padding_x(px(1.))
- .text_size(px(14.))
- .text_color(Hsla::from(theme.gray_12)),
- ),
- )
- .child(
- div()
- .flex_shrink_0()
- .text_size(px(14.))
- .text_color(Hsla::from(theme.gray_11))
- .child(".cap"),
- ),
- )
+ .child(
- div()
- .flex_1()
- .h_full()
- .when(cfg!(target_os = "windows"), |area| {
- area.occlude()
- .window_control_area(gpui::WindowControlArea::Drag)
- })
- .when(cfg!(target_os = "macos"), |area| {
- area.on_mouse_down(gpui::MouseButton::Left, |event, window, _| {
- if event.click_count == 2 {
- window.titlebar_double_click();
- } else {
- window.start_window_move();
- }
- })
- }),
++ ui::EditorButton::plain(&theme, "delete-recording")
++ .left_icon("icons/trash.svg")
++ .tooltip(&theme, "Delete recording")
++ .on_click(cx.listener(|this, _, window, cx| {
++ this.delete_recording(window, cx);
+ })),
),
)
- // Centre group: `flex flex-row items-center justify-center gap-2
- // px-4 border-x border-black-transparent-10`.
- // Right group: `flex-1 h-full flex flex-row items-center gap-2
- // pl-2 pr-2`.
++ .child(drag_area(div()))
++ // The right cluster.
.child(
div()
.flex()
.flex_row()
- .flex_1()
- .min_w_0()
.items_center()
- .justify_center()
- .flex_shrink_0()
-- .gap(px(8.))
- .px(px(16.))
- .when(compact, |group| group.px(px(8.)))
- .pl(px(8.))
- .pr(px(8.))
-- .h_full()
- .border_l_1()
- .border_r_1()
- .border_color(gpui::hsla(0., 0., 0., 0.1))
++ .gap(px(2.))
++ .flex_none()
.when(cfg!(target_os = "windows"), |group| group.occlude())
+ .child(self.history_button("editor-undo", "icons/undo.svg", true, cx))
+ .child(self.history_button("editor-redo", "icons/redo.svg", false, cx))
++ .child(self.header_divider())
.child(
- div()
- .flex_1()
- .h_full()
- .when(cfg!(target_os = "windows"), |area| {
- area.occlude()
- .window_control_area(gpui::WindowControlArea::Drag)
- })
- .when(cfg!(target_os = "macos"), |area| {
- area.on_mouse_down(gpui::MouseButton::Left, |event, window, _| {
- if event.click_count == 2 {
- window.titlebar_double_click();
- } else {
- window.start_window_move();
- }
- })
- }),
+ ui::EditorButton::plain(&theme, "presets")
+ .left_icon("icons/presets.svg")
+ .when(!compact, |button| button.label("Presets"))
+ .tooltip(&theme, "Presets")
+ .disabled(!self.project_ready())
+ .right_icon("icons/chevron-down.svg")
+ .pressed(self.presets_menu.is_some())
+ .on_open(cx.listener(|this, bounds: &Bounds<Pixels>, window, cx| {
+ this.open_presets_menu(bounds.bottom_left(), window, cx);
+ })),
- ),
- )
- // Right group: `flex-1 h-full flex flex-row items-center gap-2
- // pl-2 pr-2`.
- .child(
- div()
- .flex()
- .flex_row()
- .flex_1()
- .min_w_0()
- .when(compact, |group| group.flex_none())
- .items_center()
- .gap(px(8.))
- .pl(px(8.))
- .pr(px(8.))
- .h_full()
- .when(cfg!(target_os = "windows"), |group| group.occlude())
- .child(self.history_button("editor-undo", "icons/undo.svg", true, cx))
- .child(self.history_button("editor-redo", "icons/redo.svg", false, cx))
- .child(
- div()
- .flex_1()
- .h_full()
- .when(cfg!(target_os = "windows"), |area| {
- area.occlude()
- .window_control_area(gpui::WindowControlArea::Drag)
- })
- .when(cfg!(target_os = "macos"), |area| {
- area.on_mouse_down(gpui::MouseButton::Left, |event, window, _| {
- if event.click_count == 2 {
- window.titlebar_double_click();
- } else {
- window.start_window_move();
- }
- })
- }),
)
-- // `Button` (gray), `flex gap-1.5 justify-center h-[40px]`.
-- .child(self.render_clips_pill(cx))
-- // `<Show when={hasTranscript()}>` (`Header.tsx:74-77,
-- // 188`): the pill only exists once a transcript with words
-- // does.
++ .child(self.render_clips_pill(compact, cx))
++ // `<Show when={hasTranscript()}>`: the button only exists
++ // once a transcript with words does.
.children(
- self.project
- .captions
- .as_ref()
- .is_some_and(|captions| {
- captions
- .segments
- .iter()
- .any(|segment| !segment.words.is_empty())
- })
- .then(|| self.header_pill("icons/captions.svg", "Captions")),
+ has_captions
+ .then(|| self.header_pill("icons/captions.svg", "Captions", compact)),
)
++ .child(div().w(px(6.)).flex_none())
.child(self.render_export_button(cx)),
);
@@@ -7800,89 -7578,81 +8097,90 @@@
header
}
-- /// The Captions toggle: `Button variant="gray"` at
-- /// `class="flex gap-1.5 justify-center h-[40px]"` (`Header.tsx:188-209`).
-- /// Inert -- the transcript layout mode does not exist yet. Clips has its
-- /// own live pill (`crate::editor_clips`).
- fn header_pill(&self, icon: &'static str, label: &'static str) -> impl IntoElement {
- let theme = self.theme;
++ /// The 1px x 16px rule between the history pair and the action cluster.
++ fn header_divider(&self) -> impl IntoElement {
+ div()
- .flex()
- .flex_row()
- .items_center()
- .justify_center()
- .gap(px(6.))
- .h(px(40.))
- .px(px(12.))
- .rounded(px(12.))
- .flex_shrink_0()
- .bg(Hsla::from(theme.gray_3))
- .opacity(0.5)
- .text_size(px(13.))
- .font_weight(FontWeight::MEDIUM)
- .text_color(Hsla::from(theme.gray_12))
- .child(
- svg()
- .path(icon)
- .size(px(16.))
- .flex_shrink_0()
- .text_color(Hsla::from(theme.gray_12)),
- )
- .child(label)
++ .w(px(1.))
++ .h(px(16.))
++ .mx(px(6.))
++ .flex_none()
++ .bg(Hsla::from(self.theme.editor.line_strong))
+ }
+
- /// The Export button (`Header.tsx:210-231`): `h-[40px] max-w-[100px]
- /// text-[0.8125rem] font-medium text-white rounded-xl`, gradient
- /// `bg-linear-to-b from-[#3b82f6] to-[#2563eb]`.
++ /// The Captions toggle. Inert -- the transcript layout mode does not exist
++ /// yet. Clips has its own live button (`crate::editor_clips`).
+ fn header_pill(
+ &self,
+ icon: &'static str,
+ label: &'static str,
+ compact: bool,
+ ) -> impl IntoElement {
+ let theme = self.theme;
- div()
- .id("editor-captions-pill")
- .tooltip_show_delay(ui::TOOLTIP_SHOW_DELAY)
- .tooltip(move |_, cx| ui::Tooltip::new(&theme, label).view(cx))
- .flex()
- .flex_row()
- .items_center()
- .justify_center()
- .gap(px(6.))
- .h(px(40.))
- .px(px(12.))
- .rounded(px(12.))
- .flex_shrink_0()
- .bg(Hsla::from(theme.gray_3))
- .opacity(0.5)
- .text_size(px(13.))
- .font_weight(FontWeight::MEDIUM)
- .text_color(Hsla::from(theme.gray_12))
- .child(
- svg()
- .path(icon)
- .size(px(16.))
- .flex_shrink_0()
- .text_color(Hsla::from(theme.gray_12)),
- )
- .when(!compact, |pill| pill.child(label))
++ ui::EditorButton::plain(&theme, "editor-captions-pill")
++ .left_icon(icon)
++ .when(!compact, |button| button.label(label))
++ .tooltip(&theme, label)
++ .disabled(true)
+ }
+
- /// The Export button (`Header.tsx:210-231`): `h-[40px] max-w-[100px]
- /// text-[0.8125rem] font-medium text-white rounded-xl`, gradient
- /// `bg-linear-to-b from-[#3b82f6] to-[#2563eb]`.
++ /// The Export button: the one primary control in the editor, a vertical
++ /// `accent-2 -> accent` gradient with a 1px top highlight.
fn render_export_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
++ let editor = self.theme.editor;
++ let gradient = |top: gpui::Rgba, bottom: gpui::Rgba| {
++ gpui::linear_gradient(
++ 180.,
++ gpui::linear_color_stop(top, 0.),
++ gpui::linear_color_stop(bottom, 1.),
++ )
++ };
div()
.id("editor-export")
++ .relative()
.flex()
.flex_row()
.items_center()
.justify_center()
.gap(px(6.))
-- .px(px(16.))
-- .w(px(100.))
-- .h(px(40.))
++ .pl(px(12.))
++ .pr(px(14.))
++ .h(px(30.))
.flex_none()
-- .rounded(px(12.))
++ .overflow_hidden()
++ .rounded(px(8.))
.when(self.project_ready(), |button| button.cursor_pointer())
.when(!self.project_ready(), |button| button.opacity(0.5))
-- .bg(gpui::linear_gradient(
-- 180.,
-- gpui::linear_color_stop(gpui::rgb(0x3b82f6), 0.),
-- gpui::linear_color_stop(gpui::rgb(0x2563eb), 1.),
-- ))
-- .hover(|style| {
-- style.bg(gpui::linear_gradient(
-- 180.,
-- gpui::linear_color_stop(gpui::rgb(0x408cff), 0.),
-- gpui::linear_color_stop(gpui::rgb(0x286bfe), 1.),
++ .bg(gradient(editor.accent_2, editor.accent))
++ .hover(move |style| {
++ style.bg(gradient(
++ crate::theme::mix(editor.accent_2, gpui::rgb(0xffffff), 0.10),
++ crate::theme::mix(editor.accent, gpui::rgb(0xffffff), 0.10),
))
})
-- .active(|style| {
-- style.bg(gpui::linear_gradient(
-- 180.,
-- gpui::linear_color_stop(gpui::rgb(0x387cea), 0.),
-- gpui::linear_color_stop(gpui::rgb(0x235ede), 1.),
++ .active(move |style| {
++ style.bg(gradient(
++ crate::theme::mix(editor.accent_2, gpui::rgb(0x000000), 0.06),
++ crate::theme::mix(editor.accent, gpui::rgb(0x000000), 0.06),
))
})
.text_size(px(13.))
.font_weight(FontWeight::MEDIUM)
.text_color(gpui::white())
++ // gpui has no box-shadow, so the `inset 0 1px 0 rgba(255,255,255,
++ // .22)` highlight is a painted hairline instead.
++ .child(
++ div()
++ .absolute()
++ .top_0()
++ .left_0()
++ .right_0()
++ .h(px(1.))
++ .bg(gpui::hsla(0., 0., 1., 0.22)),
++ )
.child(
svg()
.path("icons/upload-arrow.svg")
-- .size(px(16.))
++ .size(px(15.))
.flex_shrink_0()
.text_color(gpui::white()),
)
@@@ -7898,7 -7668,7 +8196,8 @@@
// -- Player --------------------------------------------------------------
-- /// `PlayerContent` (`Player.tsx:288-483`): toolbar, canvas, transport.
++ /// `PlayerContent`: one surface -- the actions toolbar, the stage, and the
++ /// transport, with no rule between them.
fn render_player(&self, cx: &mut Context<Self>) -> impl IntoElement {
div()
.flex()
@@@ -7906,106 -7676,100 +8205,154 @@@
.flex_1()
.min_h_0()
.child(
-- self.toolbar
-- .clone()
-- .cached(StyleRefinement::default().w_full().h(px(64.))),
++ self.toolbar.clone().cached(
++ StyleRefinement::default()
++ .w_full()
++ .h(px(PLAYER_TOOLBAR_HEIGHT)),
++ ),
)
.child(self.render_preview_canvas(cx))
.child(
self.transport_controls
.clone()
-- .cached(StyleRefinement::default().w_full().h(px(76.))),
++ .cached(StyleRefinement::default().w_full().h(px(PLAYER_BAR_HEIGHT))),
)
}
-- /// `flex items-center justify-between gap-3 p-3` (`Player.tsx:290`).
- fn render_player_toolbar(&self, cx: &mut Context<Self>) -> impl IntoElement {
++ /// The player's top row: the stage's own triggers on the left, the
++ /// preview-resolution control on the right.
+ fn render_player_toolbar(&self, window: &Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
- let narrow = editor_player_width(f32::from(window.viewport_size().width)) < 480.;
++ let narrow = editor_player_width(f32::from(window.viewport_size().width)) < 560.;
div()
++ .w_full()
++ .h_full()
.flex()
.flex_row()
.items_center()
.justify_between()
-- .gap(px(12.))
-- .p(px(12.))
++ .gap(px(8.))
++ .px(px(12.))
.flex_none()
++ .overflow_hidden()
++ .child(self.render_player_actions(narrow, cx))
.child(
div()
.flex()
.flex_row()
.items_center()
-- .gap(px(12.))
- .when(narrow, |group| group.gap(px(4.)))
++ .flex_none()
++ .gap(px(8.))
.child(
-- ui::EditorButton::plain(&theme, "aspect-ratio")
-- .left_icon("icons/layout.svg")
- .when(!narrow, |button| {
- button.label(Self::aspect_ratio_label(
- self.project.aspect_ratio.as_ref(),
- ))
- })
- .label(Self::aspect_ratio_label(self.project.aspect_ratio.as_ref()))
-- .tooltip(&theme, "Aspect Ratio")
-- .pressed(
-- self.toolbar_menu
-- .as_ref()
-- .is_some_and(|menu| menu.kind == ToolbarMenu::AspectRatio),
-- )
-- .on_open(cx.listener(|this, bounds: &Bounds<Pixels>, window, cx| {
-- this.open_toolbar_menu(
-- ToolbarMenu::AspectRatio,
-- *bounds,
-- window,
-- cx,
-- );
-- })),
++ div()
++ .text_size(px(12.))
++ .font_weight(FontWeight::MEDIUM)
++ .text_color(Hsla::from(theme.editor.text_2))
++ .child("Preview"),
)
-- // `EditorButton tooltipText="Crop Video"`
-- // (`Player.tsx:293-299`) -> `cropDialogHandler`.
-- .child(
-- ui::EditorButton::plain(&theme, "crop")
-- .left_icon("icons/crop.svg")
-- .label("Crop")
-- .tooltip(&theme, "Crop Video")
-- .pressed(self.crop.is_some())
-- .on_click(cx.listener(|this, _, window, cx| {
-- this.open_crop(window, cx);
-- })),
++ .child(self.render_preview_quality(cx)),
++ )
++ }
++
++ /// The toolbar's left cluster.
++ fn render_player_actions(&self, narrow: bool, cx: &mut Context<Self>) -> impl IntoElement {
++ let theme = self.theme;
++ div()
++ .flex()
++ .flex_row()
++ .items_center()
++ .gap(px(2.))
++ .child(
++ ui::EditorButton::plain(&theme, "aspect-ratio")
++ .text(&theme)
++ .left_icon("icons/layout.svg")
++ .when(!narrow, |button| {
++ button.label(Self::aspect_ratio_label(self.project.aspect_ratio.as_ref()))
++ })
++ .tooltip(&theme, "Aspect Ratio")
++ .pressed(
++ self.toolbar_menu
++ .as_ref()
++ .is_some_and(|menu| menu.kind == ToolbarMenu::AspectRatio),
)
-- .child(self.render_frame_button(cx)),
++ .on_open(cx.listener(|this, bounds: &Bounds<Pixels>, window, cx| {
++ this.open_toolbar_menu(ToolbarMenu::AspectRatio, *bounds, window, cx);
++ })),
)
++ // `EditorButton tooltipText="Crop Video"` (`Player.tsx:293-299`)
++ // -> `cropDialogHandler`.
.child(
++ ui::EditorButton::plain(&theme, "crop")
++ .text(&theme)
++ .left_icon("icons/crop.svg")
++ .when(!narrow, |button| button.label("Crop"))
++ .tooltip(&theme, "Crop Video")
++ .pressed(self.crop.is_some())
++ .on_click(cx.listener(|this, _, window, cx| {
++ this.open_crop(window, cx);
++ })),
++ )
++ .child(self.render_frame_button(narrow, cx))
++ }
++
++ /// The preview-resolution control: a segmented `Full | Half | Quarter`.
++ fn render_preview_quality(&self, cx: &mut Context<Self>) -> impl IntoElement {
++ let theme = self.theme;
++ let editor = theme.editor;
++ let qualities: Vec<crate::store::EditorPreviewQuality> =
++ crate::store::EditorPreviewQuality::ALL
++ .iter()
++ .rev()
++ .copied()
++ .collect();
++ let selected_bg = if theme.is_dark() {
++ gpui::hsla(0., 0., 1., 0.12)
++ } else {
++ Hsla::from(editor.card)
++ };
++ div()
++ .id("preview-quality")
++ .flex()
++ .flex_row()
++ .flex_none()
++ .p(px(2.))
++ .rounded(px(8.))
++ .bg(Hsla::from(editor.ctl))
++ .children(qualities.iter().enumerate().map(|(index, quality)| {
++ let quality = *quality;
++ let selected = quality == self.preview_quality;
div()
++ .id(gpui::ElementId::NamedInteger(
++ "preview-quality-item".into(),
++ index as u64,
++ ))
.flex()
-- .flex_row()
.items_center()
-- .gap(px(8.))
- .children((!narrow).then(|| {
- .child(
-- // `text-xs font-medium text-gray-11`.
-- div()
-- .text_size(px(12.))
-- .font_weight(FontWeight::MEDIUM)
-- .text_color(Hsla::from(theme.gray_11))
- .child("Preview quality")
- .child("Preview quality"),
- )
- .child(
- ui::Select::plain(&theme, "preview-quality", self.preview_quality.label())
- .stretch_label()
- .on_open(cx.listener(|this, bounds: &Bounds<Pixels>, window, cx| {
- this.open_toolbar_menu(
- ToolbarMenu::PreviewQuality,
- *bounds,
- window,
- cx,
- );
- })),
- ),
- )
++ .justify_center()
++ .h(px(24.))
++ .min_w(px(24.))
++ .px(px(10.))
++ .rounded(px(6.))
++ .text_size(px(12.))
++ .font_weight(FontWeight::MEDIUM)
++ .map(|this| {
++ if selected {
++ this.bg(selected_bg).text_color(Hsla::from(editor.text_1))
++ } else {
++ this.text_color(Hsla::from(editor.text_2))
++ .cursor_pointer()
++ .hover(|style| style.bg(Hsla::from(editor.ctl_hover)))
++ }
++ })
++ .child(quality.label())
++ .on_click(cx.listener(move |this, _, _window, cx| {
++ this.set_preview_quality(quality, cx);
+ }))
- .child(
- ui::Select::plain(&theme, "preview-quality", self.preview_quality.label())
- .stretch_label()
- .on_open(cx.listener(|this, bounds: &Bounds<Pixels>, window, cx| {
- this.open_toolbar_menu(
- ToolbarMenu::PreviewQuality,
- *bounds,
- window,
- cx,
- );
- })),
- ),
- )
++ }))
}
-- /// `PreviewCanvas` (`Player.tsx:605-648`): a `relative flex-1` container
-- /// with the frame centred inside it at its letterboxed size, over the
-- /// canvas's `background-color: #000000`.
++ /// `PreviewCanvas` (`Player.tsx:605-648`): the stage, with the frame
++ /// centred inside it at its letterboxed size.
///
/// On macOS the frame stays on the GPU end to end: the renderer blits into
/// a BGRA IOSurface-backed CVPixelBuffer and gpui paints it directly via
@@@ -8043,8 -7807,8 +8390,8 @@@
.flex()
.items_center()
.justify_center()
-- .text_size(px(14.))
-- .text_color(Hsla::from(theme.gray_11))
++ .text_size(px(13.))
++ .text_color(Hsla::from(theme.editor.text_2))
.child(if matches!(state, LoadState::Loading) {
"Loading project..."
} else {
@@@ -8055,13 -7819,13 +8402,12 @@@
}
};
-- // `relative flex-1 justify-center items-center` -- no background of
-- // its own; the player card's shows through the letterbox bars.
div()
.relative()
.flex_1()
.min_h_0()
.overflow_hidden()
++ .bg(Hsla::from(theme.editor.card))
.child(body)
// `CanvasElementsOverlay` + `SnapGuidesOverlay`
// (`Player.tsx:636-643`), both mounted inside the letterbox
@@@ -8090,23 -7854,23 +8436,23 @@@
)
.child(
div()
-- .text_size(px(16.))
++ .text_size(px(15.))
.font_weight(FontWeight::MEDIUM)
-- .text_color(gpui::white())
++ .text_color(Hsla::from(theme.editor.text_1))
.child("This recording could not be opened"),
)
.child(
div()
.max_w(px(520.))
.text_size(px(13.))
-- .text_color(Hsla::from(theme.gray_11))
++ .text_color(Hsla::from(theme.editor.text_2))
.child(SharedString::from(message.to_string())),
)
.child(
div()
.max_w(px(520.))
.text_size(px(12.))
-- .text_color(Hsla::from(theme.gray_10))
++ .text_color(Hsla::from(theme.editor.text_3))
.child(SharedString::from(self.project_path.display().to_string())),
)
}
@@@ -8133,11 -7897,11 +8479,16 @@@
};
div()
.id(id)
++ .group(SharedString::from(format!("{id}-group")))
.flex()
.items_center()
.justify_center()
++ .size(px(28.))
++ .flex_none()
++ .rounded(px(7.))
.cursor_pointer()
-- .hover(|this| this.opacity(0.7))
++ .hover(|this| this.bg(Hsla::from(theme.editor.ctl_hover)))
++ .active(|this| this.bg(Hsla::from(theme.editor.ctl_active)))
.tooltip_show_delay(ui::TOOLTIP_SHOW_DELAY)
.tooltip(move |_window, cx| {
ui::Tooltip::new(&theme, label)
@@@ -8147,8 -7911,8 +8498,11 @@@
.child(
svg()
.path(icon)
-- .size(px(20.))
-- .text_color(Hsla::from(theme.gray_12)),
++ .size(px(16.))
++ .text_color(Hsla::from(theme.editor.text_2))
++ .group_hover(SharedString::from(format!("{id}-group")), move |style| {
++ style.text_color(Hsla::from(theme.editor.text_1))
++ }),
)
.on_click(cx.listener(move |this, _, window, cx| {
let origin = this.playhead;
@@@ -8175,13 -7939,10 +8529,14 @@@
cx.notify();
}
-- /// The transport row (`Player.tsx:357-481`): `relative flex overflow-hidden
-- /// z-10 flex-row gap-3 justify-between items-center p-5`.
- fn render_transport(&self, cx: &mut Context<Self>) -> impl IntoElement {
++ /// The player's transport bar: the clock on the left, the transport cluster
++ /// centred across the row, split and zoom on the right.
+ fn render_transport(&self, window: &Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
++ let editor = theme.editor;
+ let player_width = editor_player_width(f32::from(window.viewport_size().width));
- let compact = player_width < 600.;
- let narrow = player_width < 480.;
++ let compact = player_width < 760.;
++ let narrow = player_width < 620.;
let total = self.total_duration();
// `Math.max(editorState.previewTime ?? editorState.playbackTime, 0)`
// (`Player.tsx:359-365`) -- the clock reads the *hover* time when there
@@@ -8196,13 -7957,13 +8551,36 @@@
"icons/pause.svg"
};
++ let skip = |id: &'static str, glyph: &'static str, handler: ui::ClickHandler| {
++ div()
++ .id(id)
++ .tab_index(0)
++ .flex()
++ .items_center()
++ .justify_center()
++ .size(px(24.))
++ .when(live, |this| {
++ this.cursor_pointer().hover(|style| style.opacity(0.7))
++ })
++ .child(
++ svg()
++ .path(glyph)
++ .size(px(14.))
++ .text_color(Hsla::from(editor.text_2)),
++ )
++ .on_click(handler)
++ };
++
div()
.relative()
.w_full()
++ .h_full()
.flex()
.flex_row()
.items_center()
-- .p(px(20.))
++ .justify_between()
++ .gap(px(8.))
++ .px(px(14.))
.flex_none()
.overflow_hidden()
.child(
@@@ -8210,22 -7971,20 +8588,23 @@@
.flex()
.flex_row()
.items_center()
-- .flex_1()
-- .min_w_0()
-- .text_size(px(14.))
- .when(compact, |clock| clock.overflow_hidden())
++ .flex_none()
++ .text_size(px(13.))
+ .when(narrow, |clock| clock.text_size(px(12.)))
.child(
div()
-- .text_color(Hsla::from(theme.gray_12))
++ .font_weight(FontWeight::MEDIUM)
++ .text_color(Hsla::from(editor.text_1))
.child(timeline::format_time(current)),
)
-- .child(div().text_color(Hsla::from(theme.gray_11)).child(" / "))
-- .child(
++ .children((!narrow).then(|| {
div()
-- .text_color(Hsla::from(theme.gray_11))
-- .child(timeline::format_time(total)),
-- ),
++ .text_color(Hsla::from(editor.text_3))
++ .child(SharedString::from(format!(
++ " / {}",
++ timeline::format_time(total)
++ )))
++ })),
)
.child(
div()
@@@ -8241,31 -8000,30 +8620,15 @@@
.flex_row()
.items_center()
.justify_center()
-- .gap(px(32.))
- .when(compact, |group| group.gap(px(16.)))
++ .gap(px(14.))
.when(!live, |this| this.opacity(0.5))
-- .child(
-- div()
-- .id("transport-prev")
-- .tab_index(0)
-- .flex()
-- .items_center()
-- .justify_center()
-- .when(live, |this| {
-- this.cursor_pointer().hover(|style| style.opacity(0.7))
-- })
-- .child(
-- svg()
-- .path("icons/prev.svg")
-- .size(px(12.))
-- .text_color(Hsla::from(theme.gray_12)),
-- )
-- .on_click(
-- cx.listener(|this, _, _window, cx| this.jump_to_start(cx)),
-- ),
-- )
-- // `rounded-full border border-gray-300 bg-gray-3 size-9`
-- // with `hover:bg-gray-4` -- [`ui::IconButton`].
++ .child(skip(
++ "transport-prev",
++ "icons/prev.svg",
++ Box::new(
++ cx.listener(|this, _, _window, cx| this.jump_to_start(cx)),
++ ),
++ ))
.child(
div()
.id("transport-play-tooltip")
@@@ -8278,149 -8036,143 +8641,94 @@@
})
.child(
ui::IconButton::new("transport-play", icon)
-- .size(px(36.))
++ .size(px(32.))
.icon_size(px(12.))
-- .color(Hsla::from(theme.gray_12))
-- .filled(
-- Hsla::from(theme.gray_3),
-- Some(Hsla::from(theme.gray_5)),
-- )
-- .hover_bg(Hsla::from(theme.gray_4))
++ .color(Hsla::from(editor.card))
++ .filled(Hsla::from(editor.text_1), None)
++ .hover_bg(Hsla::from(crate::theme::mix(
++ editor.text_1,
++ editor.card,
++ 0.15,
++ )))
.on_click(cx.listener(|this, _, window, cx| {
this.toggle_play(window, cx);
})),
),
)
-- .child(
-- div()
-- .id("transport-next")
-- .tab_index(0)
-- .flex()
-- .items_center()
-- .justify_center()
-- .when(live, |this| {
-- this.cursor_pointer().hover(|style| style.opacity(0.7))
-- })
-- .child(
-- svg()
-- .path("icons/next.svg")
-- .size(px(12.))
-- .text_color(Hsla::from(theme.gray_12)),
-- )
-- .on_click(
-- cx.listener(|this, _, _window, cx| this.jump_to_end(cx)),
-- ),
-- ),
++ .child(skip(
++ "transport-next",
++ "icons/next.svg",
++ Box::new(cx.listener(|this, _, _window, cx| this.jump_to_end(cx))),
++ )),
),
)
-- // `flex flex-row flex-1 gap-4 justify-end items-center`.
.child(
div()
.flex()
.flex_row()
-- .flex_1()
-- .gap(px(16.))
- .when(compact, |group| group.gap(px(8.)))
++ .flex_none()
++ .gap(px(2.))
.justify_end()
.items_center()
-- // The split toggle (`Player.tsx:409-427`): an
-- // `EditorButton variant="danger"` whose pressed state is
-- // `data-pressed:bg-red-300 data-pressed:text-gray-1`.
++ // The split toggle (`Player.tsx:409-427`).
.child(
-- div()
-- .id("transport-split")
-- .tab_index(0)
-- .tooltip_show_delay(ui::TOOLTIP_SHOW_DELAY)
-- .tooltip(move |_window, cx| {
-- ui::Tooltip::new(&theme, "Toggle Split")
-- .keys(["S"])
-- .view(cx)
-- })
-- .flex()
-- .flex_row()
-- .items_center()
-- .px(px(6.))
-- .h(px(32.))
-- .rounded(px(8.))
-- .cursor_pointer()
-- .when(self.split_mode, |this| this.bg(Hsla::from(theme.red_300)))
-- .when(!self.split_mode, |this| {
-- this.hover(|this| this.bg(Hsla::from(theme.gray_3)))
-- })
-- .child(svg().path("icons/scissors.svg").size(px(20.)).text_color(
-- if self.split_mode {
-- Hsla::from(theme.gray_1)
-- } else {
-- Hsla::from(theme.gray_12)
-- },
-- ))
++ ui::EditorButton::plain(&theme, "transport-split")
++ .left_icon("icons/scissors.svg")
++ .tooltip(&theme, "Toggle Split")
++ .pressed(self.split_mode)
.on_click(cx.listener(|this, _, window, cx| {
this.toggle_split_mode(cx);
window.refresh();
})),
)
-- // `w-px h-8 rounded-full bg-gray-4`.
-- .child(
-- div()
-- .w(px(1.))
-- .h(px(32.))
-- .rounded_full()
-- .bg(Hsla::from(theme.gray_4)),
-- )
++ .child(self.header_divider())
// `IconCapZoomOut` -> `updateZoom(zoom * 1.1,
// playbackTime)`; `IconCapZoomIn` -> `zoom / 1.1`
-- // (`Player.tsx:432-449`). `will-change-[opacity]
-- // transition-opacity hover:opacity-70`.
++ // (`Player.tsx:432-449`).
.child(self.zoom_button("transport-zoom-out", "icons/zoom-out.svg", 1.1, cx))
-- .child(self.zoom_button("transport-zoom-in", "icons/zoom-in.svg", 1. / 1.1, cx))
// `Slider class="w-24" minValue={0} maxValue={1}
-- // step={0.001}`: the 32px row with its 5px track. Fully
-- // left is fully zoomed *out* -- the value is
-- // `1 - zoom / zoomOutLimit()` (`Player.tsx:444-465`).
- .children((!narrow).then(|| {
- .child(
++ // step={0.001}`. Fully left is fully zoomed *out* -- the
++ // value is `1 - zoom / zoomOutLimit()`.
++ .children((!compact).then(|| {
ui::Slider::new(
"timeline-zoom",
self.view.transform.slider_fraction(total),
self.zoom_slider_track.clone(),
)
-- .row_width(px(96.))
-- // `class="relative px-1 h-8"` with the track at
-- // `h-[0.3rem]` = 4.8px (`ui.tsx:93, 107`).
-- .row_height(px(32.))
-- .track(px(4.8), Hsla::from(theme.gray_4))
-- // `KSlider.Fill class="bg-blue-9"` and
-- // `KSlider.Thumb class="bg-gray-1 dark:bg-gray-12
-- // border border-gray-6 size-4 -top-[6.3px]"`
-- // (`ui.tsx:118, 147`).
-- .fill(Hsla::from(theme.blue_9))
++ .row_width(px(72.))
++ .row_height(px(20.))
++ .track(px(3.), Hsla::from(editor.ctl_active))
++ .fill(Hsla::from(editor.accent))
.thumb(
-- px(16.),
-- if theme.is_dark() {
-- Hsla::from(theme.gray_12)
-- } else {
-- Hsla::from(theme.gray_1)
-- },
-- Some(Hsla::from(theme.gray_6)),
++ px(12.),
++ Hsla::from(editor.thumb),
++ Some(gpui::hsla(0., 0., 0., 0.12)),
)
-- .thumb_top(px(-6.3))
++ .thumb_shadow()
.on_drag_start(cx.listener(
|this, event: &MouseDownEvent, window, cx| {
this.zoom_slider_drag = true;
this.apply_zoom_slider(event.position, window, cx);
},
- )),
- ),
+ ))
- })),
++ }))
++ .child(self.zoom_button(
++ "transport-zoom-in",
++ "icons/zoom-in.svg",
++ 1. / 1.1,
++ cx,
++ )),
)
}
// -- Timeline ------------------------------------------------------------
- fn render_timeline(&self, viewport_width: f32, cx: &mut Context<Self>) -> impl IntoElement {
+ fn render_timeline(
+ &self,
+ viewport_width: f32,
- viewport_height: f32,
++ _viewport_height: f32,
+ cx: &mut Context<Self>,
+ ) -> impl IntoElement {
let theme = self.theme;
let content_width = timeline::content_width(viewport_width);
let live = self.transport.is_some();
@@@ -8444,151 -8196,153 +8752,132 @@@
let playhead_x = timeline::playhead_offset(playhead_view, content_width);
let ghost_x = timeline::ghost_offset(self.view, content_width);
-- let minimap_width = (viewport_width
-- - TIMELINE_SLOT_PADDING * 2.
-- - TIMELINE_PADDING
-- - TRACK_GUTTER
-- - TIMELINE_PADDING)
-- .max(1.);
++ let (_, minimap_width) = timeline::minimap_bounds(viewport_width);
- div()
- .flex_none()
- .min_h_0()
- .px(px(TIMELINE_SLOT_PADDING))
- .overflow_hidden()
- .relative()
- .h(px(self.clamp_timeline_height(
- self.timeline_height,
- viewport_height,
- )))
- .child(
- div().h_full().child(
- // `pt-8 relative overflow-hidden flex flex-col gap-2
- // h-full`, `padding-left/right: 16px`.
- div()
- .id("timeline-container")
- .relative()
- .flex()
- .flex_col()
- .gap(px(TRACK_ROW_GAP))
- .h_full()
- .overflow_hidden()
- .pt(px(TIMELINE_TOP_PADDING))
- .pl(px(TIMELINE_PADDING))
- .pr(px(TIMELINE_PADDING))
- // The container's own `onMouseDown` -- a press
- // anywhere in the timeline seeks to that point when it
- // is released (`TL/index.tsx:1155-1169`). The ruler's
- // dedicated surface below sits on top of it and takes
- // precedence, exactly as its `z-40` does.
- .when(live, |this| {
- this.on_mouse_down(
- MouseButton::Left,
- cx.listener(move |this, event: &MouseDownEvent, window, cx| {
- this.timeline_mouse_down(event, false, window, cx);
- }),
- )
- .on_mouse_up(
- MouseButton::Left,
- cx.listener(|this, _: &MouseUpEvent, _window, cx| {
- this.timeline_mouse_up(cx)
- }),
- )
- })
- // `onMouseMove` -> `previewTime` (`:1170-1184`).
- .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, window, cx| {
- this.timeline_hover(f32::from(event.position.x), window, cx);
- }))
- .on_hover(cx.listener(|this, hovered: &bool, window, cx| {
- if !*hovered {
- this.timeline_hover_leave(window, cx);
- }
- }))
- // `onWheel` (`:1189-1207`) and the pinch the webview
- // would have delivered as `ctrl+wheel`.
- .on_scroll_wheel(cx.listener(
- |this, event: &gpui::ScrollWheelEvent, window, cx| {
- this.timeline_wheel(event, window, cx);
- },
- ))
- .on_pinch(cx.listener(|this, event: &gpui::PinchEvent, window, cx| {
- this.timeline_pinch(event, window, cx);
- }))
- .child(
- div()
- .id("timeline-minimap")
- .absolute()
- .top(px(MINIMAP_TOP))
- .left(px(TIMELINE_PADDING + TRACK_GUTTER))
- .right(px(TIMELINE_PADDING))
- .h(px(MINIMAP_HEIGHT))
- .when(
- live && self.total_duration() - self.view.transform.zoom > 0.01,
- |bar| {
- bar.cursor_pointer()
- .capture_any_mouse_down(
- cx.listener(Self::minimap_mouse_down),
- )
- .on_mouse_move(cx.listener(|this, _, window, cx| {
- if this.minimap_drag.is_none() {
- this.timeline_hover_leave(window, cx);
- cx.stop_propagation();
- }
- }))
- },
- )
- .child(timeline::render_minimap(
- &theme,
- &self.timeline,
- self.view,
- minimap_width,
- )),
++ // The card itself is the root shell's; this is its inside, at the
++ // brief's `10px 12px 12px` less the hairline the card already draws.
+ div()
- .flex_none()
++ .size_full()
+ .min_h_0()
- .px(px(TIMELINE_SLOT_PADDING))
- .overflow_hidden()
+ .relative()
- // The persisted height, clamped to `[MIN_TIMELINE_HEIGHT,
- // layoutHeight - MIN_PLAYER_HEIGHT]` (`Editor.tsx:421-435`).
- // Nothing writes it yet -- the drag handle is inert -- so it sits
- // at the default with the floor still expressed.
- .h(px(self.timeline_height))
- .min_h(px(MIN_TIMELINE_HEIGHT))
++ .overflow_hidden()
++ .pt(px(TIMELINE_TOP_PADDING))
++ .pl(px(TIMELINE_PADDING))
++ .pr(px(TIMELINE_PADDING))
++ .pb(px(TIMELINE_BOTTOM_PADDING))
+ .child(
- div().h_full().child(
- // `pt-8 relative overflow-hidden flex flex-col gap-2
- // h-full`, `padding-left/right: 16px`.
- div()
- .id("timeline-container")
- .relative()
- .flex()
- .flex_col()
- .gap(px(TRACK_ROW_GAP))
- .h_full()
- .overflow_hidden()
- .pt(px(TIMELINE_TOP_PADDING))
- .pl(px(TIMELINE_PADDING))
- .pr(px(TIMELINE_PADDING))
- // The container's own `onMouseDown` -- a press
- // anywhere in the timeline seeks to that point when it
- // is released (`TL/index.tsx:1155-1169`). The ruler's
- // dedicated surface below sits on top of it and takes
- // precedence, exactly as its `z-40` does.
- .when(live, |this| {
- this.on_mouse_down(
- MouseButton::Left,
- cx.listener(move |this, event: &MouseDownEvent, window, cx| {
- this.timeline_mouse_down(event, false, window, cx);
- }),
- )
- .on_mouse_up(
- MouseButton::Left,
- cx.listener(|this, _: &MouseUpEvent, _window, cx| {
- this.timeline_mouse_up(cx)
- }),
- )
- })
- // `onMouseMove` -> `previewTime` (`:1170-1184`).
- .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, window, cx| {
- this.timeline_hover(f32::from(event.position.x), window, cx);
- }))
- .on_hover(cx.listener(|this, hovered: &bool, window, cx| {
- if !*hovered {
- this.timeline_hover_leave(window, cx);
- }
- }))
- // `onWheel` (`:1189-1207`) and the pinch the webview
- // would have delivered as `ctrl+wheel`.
- .on_scroll_wheel(cx.listener(
- |this, event: &gpui::ScrollWheelEvent, window, cx| {
- this.timeline_wheel(event, window, cx);
- },
- ))
- .on_pinch(cx.listener(|this, event: &gpui::PinchEvent, window, cx| {
- this.timeline_pinch(event, window, cx);
- }))
- .child(
- div()
- .id("timeline-minimap")
- .absolute()
- .top(px(MINIMAP_TOP))
- .left(px(TIMELINE_PADDING + TRACK_GUTTER))
- .right(px(TIMELINE_PADDING))
- .h(px(MINIMAP_HEIGHT))
- .when(
- live && self.total_duration() - self.view.transform.zoom > 0.01,
- |bar| {
- bar.cursor_pointer()
- .capture_any_mouse_down(
- cx.listener(Self::minimap_mouse_down),
- )
- .on_mouse_move(cx.listener(|this, _, window, cx| {
- if this.minimap_drag.is_none() {
- this.timeline_hover_leave(window, cx);
- cx.stop_propagation();
- }
- }))
- },
- )
- .child(timeline::render_minimap(
- &theme,
- &self.timeline,
- self.view,
- minimap_width,
- )),
++ div()
++ .id("timeline-container")
++ .relative()
++ .flex()
++ .flex_col()
++ .gap(px(timeline::TIMELINE_HEADER_GAP))
++ .h_full()
++ .overflow_hidden()
++ // The container's own `onMouseDown` -- a press
++ // anywhere in the timeline seeks to that point when it
++ // is released (`TL/index.tsx:1155-1169`). The ruler's
++ // dedicated surface below sits on top of it and takes
++ // precedence, exactly as its `z-40` does.
++ .when(live, |this| {
++ this.on_mouse_down(
++ MouseButton::Left,
++ cx.listener(move |this, event: &MouseDownEvent, window, cx| {
++ this.timeline_mouse_down(event, false, window, cx);
++ }),
)
-- .child(self.render_timeline_header(viewport_width, live, cx))
-- .child(self.render_timeline_body(viewport_width, cx))
-- // The hover ghost (`TL/index.tsx:1246-1278`):
-- // `from-gray-400` with a `bg-gray-10` knob. Drawn only
-- // while paused and while the pointer is over the
-- // content column.
-- .children(ghost_x.map(|x| {
-- timeline::render_playhead(
-- Hsla::from(theme.gray_9),
-- x,
-- Hsla::from(theme.gray_10),
-- )
-- }))
-- // The playhead (`:1279-1295`). It dims to 50 % in
-- // split mode, where the cut line is the thing to
-- // watch (`TL/index.tsx:1281`).
-- .child(timeline::render_playhead_with_opacity(
-- timeline::playhead_color(),
-- playhead_x,
-- timeline::playhead_color(),
-- if self.split_mode { 0.5 } else { 1. },
-- ))
-- // The split preview (`TL/index.tsx:1296-1316`): a 1px
-- // column at the cut, blue with a rotated 8px diamond
-- // when it snapped to a boundary and grey otherwise.
-- .children(self.split_mode.then_some(()).and_then(|()| {
-- let (time, snapped) = self.split_preview?;
-- let x = ((time - self.view.transform.position)
-- / self.view.transform.secs_per_pixel(content_width))
-- as f32;
-- Some(render_split_preview(&theme, x, snapped))
-- }))
-- // The drag-snap guide: while a trim, move or create is
-- // magnetised onto an edge, a 1px blue column marks it.
-- .children(self.drag_snap_time.and_then(|time| {
-- let x = ((time - self.view.transform.position)
-- / self.view.transform.secs_per_pixel(content_width))
-- as f32;
-- x.is_finite().then(|| render_split_preview(&theme, x, true))
-- })),
-- ),
++ .on_mouse_up(
++ MouseButton::Left,
++ cx.listener(|this, _: &MouseUpEvent, _window, cx| {
++ this.timeline_mouse_up(cx)
++ }),
++ )
++ })
++ // `onMouseMove` -> `previewTime` (`:1170-1184`).
++ .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, window, cx| {
++ this.timeline_hover(f32::from(event.position.x), window, cx);
++ }))
++ .on_hover(cx.listener(|this, hovered: &bool, window, cx| {
++ if !*hovered {
++ this.timeline_hover_leave(window, cx);
++ }
++ }))
++ // `onWheel` (`:1189-1207`) and the pinch the webview
++ // would have delivered as `ctrl+wheel`.
++ .on_scroll_wheel(cx.listener(
++ |this, event: &gpui::ScrollWheelEvent, window, cx| {
++ this.timeline_wheel(event, window, cx);
++ },
++ ))
++ .on_pinch(cx.listener(|this, event: &gpui::PinchEvent, window, cx| {
++ this.timeline_pinch(event, window, cx);
++ }))
++ .child(self.render_timeline_header(viewport_width, live, cx))
++ .child(self.render_timeline_body(viewport_width, cx)),
++ )
++ // The minimap's 4px scroll indicator sits in the card's bottom
++ // padding, under the last row rather than over it.
++ .child(
++ div()
++ .id("timeline-minimap")
++ .absolute()
++ .bottom(px((TIMELINE_BOTTOM_PADDING - MINIMAP_HEIGHT) / 2.))
++ .right(px(TIMELINE_PADDING))
++ .w(px(minimap_width))
++ .h(px(MINIMAP_HEIGHT))
++ .when(
++ live && self.total_duration() - self.view.transform.zoom > 0.01,
++ |bar| {
++ bar.cursor_pointer()
++ .capture_any_mouse_down(cx.listener(Self::minimap_mouse_down))
++ .on_mouse_move(cx.listener(|this, _, window, cx| {
++ if this.minimap_drag.is_none() {
++ this.timeline_hover_leave(window, cx);
++ cx.stop_propagation();
++ }
++ }))
++ },
++ )
++ .child(timeline::render_minimap(
++ &theme,
++ &self.timeline,
++ self.view,
++ minimap_width,
++ )),
)
++ // The hover ghost (`TL/index.tsx:1246-1278`). Drawn only
++ // while paused and while the pointer is over the content
++ // column.
++ .children(ghost_x.map(|x| timeline::render_preview_line(&theme, x)))
++ // The playhead (`:1279-1295`). It dims to 50 % in split
++ // mode, where the cut line is the thing to watch
++ // (`TL/index.tsx:1281`).
++ .child(timeline::render_playhead(
++ &theme,
++ playhead_x,
++ if self.split_mode { 0.5 } else { 1. },
++ ))
++ // The split preview (`TL/index.tsx:1296-1316`): a 1px
++ // column at the cut, the accent with an 8px marker when it
++ // snapped to a boundary and grey otherwise.
++ .children(self.split_mode.then_some(()).and_then(|()| {
++ let (time, snapped) = self.split_preview?;
++ let x = ((time - self.view.transform.position)
++ / self.view.transform.secs_per_pixel(content_width))
++ as f32;
++ Some(render_split_preview(&theme, x, snapped))
++ }))
++ // The drag-snap guide: while a trim, move or create is
++ // magnetised onto an edge, a 1px accent column marks it.
++ .children(self.drag_snap_time.and_then(|time| {
++ let x = ((time - self.view.transform.position)
++ / self.view.transform.secs_per_pixel(content_width))
++ as f32;
++ x.is_finite().then(|| render_split_preview(&theme, x, true))
++ }))
}
-- /// The 32px header strip (`TL/index.tsx:1220-1245`): the ruler, the "Add
++ /// The 26px header strip (`TL/index.tsx:1220-1245`): the ruler, the "Add
/// track" trigger over the gutter, and the scrub surface over everything
/// right of `TRACK_GUTTER - START_SNAP_PX`.
fn render_timeline_header(
@@@ -8597,6 -8351,6 +8886,7 @@@
live: bool,
cx: &mut Context<Self>,
) -> impl IntoElement {
++ let theme = self.theme;
div()
.relative()
.h(px(TIMELINE_HEADER_HEIGHT))
@@@ -8606,68 -8360,68 +8896,40 @@@
self.view,
viewport_width,
))
-- // `TrackManager`'s trigger (`TL/TrackManager.tsx:174-188`):
-- // `h-8 w-full rounded-lg` with the app's blue gradient, at `z-30`
-- // over the ruler. Its popover -- nine rows with descriptions,
-- // toggles and lane counts -- is E4's, so the trigger is inert; it
-- // is drawn **opaque** rather than at the 50 % wash the header's
-- // other unbuilt affordances carry, because the ruler's leftmost
-- // label sits underneath it (`TL/index.tsx:1227-1236` puts the
-- // trigger above the markings for exactly that reason) and a
-- // translucent button would let it bleed through.
++ // `TrackManager`'s trigger (`TL/TrackManager.tsx:174-188`), now a
++ // ghost pill in the gutter: it sits over the ruler's leftmost
++ // label (`TL/index.tsx:1227-1236`), so it stays opaque.
.child(
div()
.id("add-track")
.absolute()
.bottom_0()
-- .left_0()
-- .w(px(TRACK_ICON_WIDTH))
-- .h(px(32.))
++ .left(px(4.))
++ .h(px(24.))
.flex()
.flex_row()
++ .flex_none()
.items_center()
-- .justify_center()
-- .gap(px(4.))
-- .px(px(8.))
-- .rounded(px(8.))
++ .justify_start()
++ .gap(px(5.))
++ .pl(px(6.))
++ .pr(px(8.))
++ .rounded(px(6.))
.cursor_pointer()
-- .bg(gpui::linear_gradient(
-- 180.,
-- gpui::linear_color_stop(gpui::rgb(0x3b82f6), 0.),
-- gpui::linear_color_stop(gpui::rgb(0x2563eb), 1.),
-- ))
-- .hover(|style| {
-- style.bg(gpui::linear_gradient(
-- 180.,
-- gpui::linear_color_stop(gpui::rgb(0x3f8aff), 0.),
-- gpui::linear_color_stop(gpui::rgb(0x2769f9), 1.),
-- ))
-- })
-- .active(|style| {
-- style.bg(gpui::linear_gradient(
-- 180.,
-- gpui::linear_color_stop(gpui::rgb(0x387cea), 0.),
-- gpui::linear_color_stop(gpui::rgb(0x235ede), 1.),
-- ))
-- })
-- .text_size(px(11.))
++ .bg(Hsla::from(theme.editor.ctl))
++ .hover(|style| style.bg(Hsla::from(theme.editor.ctl_hover)))
++ .active(|style| style.bg(Hsla::from(theme.editor.ctl_active)))
++ .text_size(px(12.))
.font_weight(FontWeight::MEDIUM)
-- .text_color(gpui::white())
++ .text_color(Hsla::from(theme.editor.text_2))
.child(
svg()
.path("icons/plus.svg")
-- .size(px(14.))
-- .flex_none()
-- .text_color(gpui::white()),
-- )
-- .child("Add track")
-- .child(
-- svg()
-- .path("icons/chevron-down.svg")
-- .size(px(10.))
++ .size(px(12.))
.flex_none()
-- .text_color(gpui::white()),
++ .text_color(Hsla::from(theme.editor.text_2)),
)
++ .child(div().flex_none().whitespace_nowrap().child("Add track"))
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_click(cx.listener(|this, _: &gpui::ClickEvent, window, cx| {
this.open_add_track(window, cx);
@@@ -8739,6 -8493,6 +9001,58 @@@
for row in &model.rows {
let kind = row.kind;
let lane = row.lane;
++ let track_row = *row;
++ let overlay = kind.overlay_track(lane).is_some();
++ let can_reorder = Self::lane_reorderable(kind)
++ && model
++ .rows
++ .iter()
++ .filter(|candidate| {
++ if overlay {
++ candidate.kind.overlay_track(candidate.lane).is_some()
++ } else {
++ candidate.kind == kind
++ }
++ })
++ .count()
++ > 1;
++ let row_hovered = self.view.hovered_track == Some(kind);
++ let reorder_source = self
++ .lane_reorder
++ .is_some_and(|reorder| reorder.dragging && reorder.source == track_row);
++ let insertion_before = self.lane_reorder.and_then(|reorder| {
++ if !reorder.dragging
++ || !self.lane_reorder_position_valid(
++ reorder.source,
++ reorder.pointer_x,
++ reorder.pointer_y,
++ )
++ {
++ return None;
++ }
++ let rows = self.lane_reorder_rows(reorder.source);
++ let source_index = rows
++ .iter()
++ .position(|candidate| *candidate == reorder.source)?;
++ if reorder.target_index == source_index {
++ return None;
++ }
++ let remaining = rows
++ .into_iter()
++ .filter(|candidate| *candidate != reorder.source)
++ .collect::<Vec<_>>();
++ let (indicator, before) = remaining
++ .get(reorder.target_index)
++ .copied()
++ .map(|indicator| (indicator, true))
++ .or_else(|| {
++ remaining
++ .last()
++ .copied()
++ .map(|indicator| (indicator, false))
++ })?;
++ (indicator == *row).then_some(before)
++ });
// `TrackRow`'s hover-reveal delete (`TL/index.tsx:1505-1546`):
// caption/keyboard delete themselves, the multi-lane tracks delete
// one lane, and zoom/3D/scene offer "Clear all" once they have
@@@ -8790,7 -8540,7 +9104,16 @@@
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, event: &MouseDownEvent, window, cx| {
-- this.track_mouse_down(kind, lane, event, window, cx);
++ if f32::from(event.position.x) < timeline::content_left() {
++ if can_reorder {
++ this.begin_lane_reorder(track_row, event.position, window, cx);
++ } else {
++ this.select_lane_header(kind, lane, cx);
++ }
++ cx.stop_propagation();
++ } else {
++ this.track_mouse_down(kind, lane, event, window, cx);
++ }
}),
)
.child(timeline::render_row(
@@@ -8801,6 -8551,6 +9124,58 @@@
viewport_width,
ui,
))
++ .when(reorder_source, |this| this.opacity(0.45))
++ .children(insertion_before.map(|before| {
++ div()
++ .absolute()
++ .left_0()
++ .right_0()
++ .when(before, |this| this.top(px(1.)))
++ .when(!before, |this| this.bottom(px(1.)))
++ .h(px(2.))
++ .rounded_full()
++ .bg(Hsla::from(theme.editor.accent))
++ }))
++ // The reorder grip takes the gutter tile's place while
++ // the row is hovered, so the two never overlap.
++ .children(can_reorder.then(|| {
++ div()
++ .id(gpui::ElementId::NamedInteger(
++ "track-reorder-grip".into(),
++ (kind as usize as u64) << 16 | lane as u64,
++ ))
++ .absolute()
++ .left_0()
++ .top_0()
++ .w(px(TRACK_ICON_WIDTH))
++ .h(px(model.track_height()))
++ .flex()
++ .items_center()
++ .justify_start()
++ .pl(px(4.))
++ .cursor(if self.lane_reorder.is_some() {
++ gpui::CursorStyle::ClosedHand
++ } else {
++ gpui::CursorStyle::OpenHand
++ })
++ .when(row_hovered, |this| {
++ this.child(
++ div()
++ .size(px(22.))
++ .rounded(px(6.))
++ .flex()
++ .items_center()
++ .justify_center()
++ .bg(Hsla::from(theme.editor.ctl_active))
++ .child(
++ svg()
++ .path("icons/grip-vertical.svg")
++ .size(px(14.))
++ .text_color(Hsla::from(theme.editor.text_3)),
++ ),
++ )
++ })
++ }))
// The empty zoom track's generate prompt
// (`TL/ZoomTrack.tsx:297-336`): a centered button plus a
// session-dismiss X, shown while cursor data exists.
@@@ -8808,8 -8558,8 +9183,11 @@@
(kind == TrackKind::Clip)
.then(|| self.render_clip_speed_overlays(model, viewport_width, cx)),
)
++ // The empty zoom lane's prompt, as the same dashed row
++ // every other empty lane draws.
.children((kind == TrackKind::Zoom && zoom_prompt).then(|| {
let generating = self.generating_auto_zoom;
++ let hovering = self.hovering_generate_zoom;
div()
.id("zoom-generate-prompt")
.absolute()
@@@ -8817,18 -8567,18 +9195,26 @@@
.right_0()
.top_0()
.bottom_0()
-- .flex()
-- .flex_col()
-- .items_center()
-- .justify_center()
-- .gap(px(2.))
.child(
div()
.id("zoom-generate-hit")
++ .absolute()
++ .inset_0()
.flex()
.flex_row()
.items_center()
-- .gap(px(4.))
++ .justify_center()
++ .gap(px(5.))
++ .px(px(10.))
++ .rounded(px(8.))
++ .text_size(px(12.))
++ .line_height(px(16.))
++ .text_color(Hsla::from(if hovering {
++ theme.editor.text_2
++ } else {
++ theme.editor.text_3
++ }))
++ .when(!generating, |this| this.cursor_pointer())
.on_mouse_down(
MouseButton::Left,
cx.listener(|_, _, _, cx| cx.stop_propagation()),
@@@ -8839,31 -8589,31 +9225,37 @@@
cx.notify();
}
}))
-- .child(
-- ui::Button::plain(
-- &theme,
-- "zoom-generate",
-- ui::ButtonVariant::Gray,
-- ui::ButtonSize::Md,
++ .on_click(cx.listener(move |this, _, window, cx| {
++ if !generating {
++ this.generate_auto_zoom(window, cx);
++ }
++ }))
++ .child(div().min_w_0().truncate().child(if generating {
++ "Generating..."
++ } else {
++ "Generate zoom segments automatically"
++ }))
++ .when(!generating, |this| {
++ this.child("\u{b7}").child(
++ div()
++ .flex_none()
++ .font_weight(FontWeight::MEDIUM)
++ .text_color(Hsla::from(theme.editor.text_2))
++ .child("Generate"),
)
-- .label(if generating {
-- "Generating..."
-- } else {
-- "Click to generate zoom segments"
-- })
-- .disabled(generating)
-- .on_click(
-- cx.listener(|this, _, window, cx| {
-- this.generate_auto_zoom(window, cx);
-- }),
-- ),
-- )
++ }),
++ )
++ .child(
++ div()
++ .absolute()
++ .top(px((model.track_height() - 20.) / 2.))
++ .right(px(6.))
.child(
ui::IconButton::new("zoom-generate-dismiss", "icons/x.svg")
-- .size(px(32.))
-- .icon_size(px(16.))
-- .color(Hsla::from(theme.gray_11))
-- .hover_bg(Hsla::from(theme.gray_5))
++ .size(px(20.))
++ .icon_size(px(12.))
++ .color(Hsla::from(theme.editor.text_3))
++ .hover_bg(Hsla::from(theme.editor.ctl_hover))
.disabled(generating)
.on_click(cx.listener(|this, _, _, cx| {
this.zoom_prompt_dismissed = true;
@@@ -8874,12 -8624,12 +9266,17 @@@
)
.children(self.auto_zoom_message.map(|message| {
div()
-- .text_size(px(11.))
-- .text_color(Hsla::from(theme.gray_11))
++ .absolute()
++ .left(px(10.))
++ .bottom(px(2.))
++ .text_size(px(10.))
++ .text_color(Hsla::from(theme.editor.text_3))
.child(message)
}))
}))
-- .children(delete_label.map(|label| {
++ // The lane's delete: a ghost that only appears with the
++ // row under the pointer, and only turns red under its own.
++ .children(delete_label.map(|_| {
let hovered = self.hovered_gutter == Some((kind, lane));
div()
.id(gpui::ElementId::NamedInteger(
@@@ -8887,10 -8637,10 +9284,10 @@@
(kind as usize as u64) << 16 | lane as u64,
))
.absolute()
-- .left_0()
-- .top_0()
-- .w(px(timeline::TRACK_ICON_WIDTH))
-- .h(px(52.))
++ .left(px(timeline::TRACK_GUTTER - 24.))
++ .top(px((model.track_height() - 20.) / 2.))
++ .w(px(20.))
++ .h(px(20.))
.on_hover(cx.listener(move |this, entered: &bool, _, cx| {
let next = if *entered {
Some((kind, lane))
@@@ -8904,22 -8654,22 +9301,19 @@@
cx.notify();
}
}))
-- .when(hovered, |this| {
++ .when(row_hovered || hovered, |this| {
this.cursor_pointer()
.tab_index(0)
.flex()
-- .flex_col()
.items_center()
.justify_center()
-- .gap(px(2.))
-- .rounded(px(12.))
-- .bg(gpui::linear_gradient(
-- 180.,
-- gpui::linear_color_stop(gpui::rgb(0xef4444), 0.),
-- gpui::linear_color_stop(gpui::rgb(0xdc2626), 1.),
-- ))
-- .active(|style| style.bg(gpui::rgb(0xc92222)))
-- .text_color(gpui::white())
++ .rounded(px(6.))
++ .bg(Hsla::from(theme.editor.ctl_active))
++ .text_color(if hovered {
++ Hsla::from(theme.red_9)
++ } else {
++ Hsla::from(theme.editor.text_3)
++ })
.on_mouse_down(
MouseButton::Left,
cx.listener(move |this, _, window, cx| {
@@@ -8944,28 -8692,28 +9338,27 @@@
}
}),
)
-- .child(
-- svg()
-- .path("icons/trash.svg")
-- .size(px(16.))
-- .text_color(gpui::white()),
-- )
-- .child(
-- div()
-- .text_size(px(10.))
-- .line_height(px(10.))
-- .font_weight(FontWeight::MEDIUM)
-- .child(label),
-- )
++ .child(svg().path("icons/trash.svg").size(px(13.)).text_color(
++ if hovered {
++ Hsla::from(theme.red_9)
++ } else {
++ Hsla::from(theme.editor.text_3)
++ },
++ ))
})
})),
);
}
++ let reorder_ghost = self.lane_reorder.filter(|reorder| reorder.dragging);
++
div()
.relative()
.flex_1()
.min_h_0()
++ // The lane area clips at its own top edge: a scrolled first row
++ // must never bleed into the ruler above it.
++ .overflow_hidden()
.child(
div()
.id("timeline-scroll")
@@@ -8989,25 -8737,25 +9382,62 @@@
))
.child(rows),
)
-- // The `mask-image` edge fade (`TL/index.tsx:1097-1139`) as two
-- // painted gradients; see `edge_fade_strengths` for why.
-- .child(timeline::render_edge_fade(
-- self.root_bg(),
-- timeline::edge_fade_strengths(&self.timeline, self.view, viewport_width),
-- ))
++ .children(reorder_ghost.map(|reorder| {
++ let bounds = self.timeline_scroll.bounds();
++ let height = model.track_height();
++ let max_top = (f32::from(bounds.size.height) - height).max(0.);
++ let top =
++ (reorder.pointer_y - f32::from(bounds.top()) - height / 2.).clamp(0., max_top);
++ div()
++ .absolute()
++ .left_0()
++ .top(px(top))
++ .w(px(TRACK_ICON_WIDTH))
++ .h(px(height))
++ .flex()
++ .items_center()
++ .gap(px(6.))
++ .pl(px(4.))
++ .rounded(px(8.))
++ .border_1()
++ .border_color(Hsla::from(theme.editor.accent))
++ .bg(Hsla::from(theme.editor.card))
++ .shadow_lg()
++ .cursor(gpui::CursorStyle::ClosedHand)
++ .child(
++ svg()
++ .path("icons/grip-vertical.svg")
++ .size(px(14.))
++ .flex_none()
++ .text_color(Hsla::from(theme.editor.text_3)),
++ )
++ .child(
++ div()
++ .min_w_0()
++ .truncate()
++ .text_size(px(11.))
++ .font_weight(FontWeight::MEDIUM)
++ .text_color(Hsla::from(theme.editor.text_2))
++ .child(format!(
++ "{} {}",
++ reorder.source.kind.label(),
++ reorder.source.lane + 1
++ )),
++ )
++ }))
}
}
/// The split-mode cut line (`TL/index.tsx:1296-1316`): `absolute bottom-0 z-20
--/// w-px` from `PLAYHEAD_TOP_OFFSET`, `bg-blue-9` when it snapped to a boundary
--/// and `bg-gray-10/70` when it did not, with a 8px `rotate-45` diamond on the
++/// w-px` from `PLAYHEAD_TOP_OFFSET`, the accent when it snapped to a boundary
++/// and `text-3` when it did not, with an 8px `rotate-45` diamond on the
/// snapped one. gpui has no rotation, so the marker is a small square -- the
/// same missing transform hook the carousel's hover lift ran into.
fn render_split_preview(theme: &Theme, x: f32, snapped: bool) -> impl IntoElement {
let color = if snapped {
-- Hsla::from(theme.blue_9)
++ Hsla::from(theme.editor.accent)
} else {
-- with_alpha(theme.gray_10, 0.7)
++ with_alpha(theme.editor.text_3, 0.7)
};
div()
.absolute()
@@@ -9023,7 -8771,7 +9453,7 @@@
.top(px(-4.))
.left(px(-3.5))
.size(px(8.))
-- .rounded(px(1.))
++ .rounded(px(2.))
.bg(color),
)
})
@@@ -9122,11 -8868,6 +9552,11 @@@ impl Render for EditorWindow
// assuming the default width.
let viewport_width: f32 = window.viewport_size().width.into();
+ let layout = EditorVerticalLayout::new(
+ f32::from(window.viewport_size().height),
- self.timeline_height,
++ self.preferred_timeline_height(),
+ );
+
// `onMount`'s `checkBounds` (`TL/index.tsx:689-703`): once the
// timeline has a width, zoom in until a segment would be at least
// 80px. The source retries every 10ms until the bounds exist; here the
@@@ -9162,6 -8903,6 +9592,10 @@@
| DragKind::ClipTrimEnd { .. } => gpui::CursorStyle::ResizeLeftRight,
DragKind::CreateZoom { .. } => gpui::CursorStyle::Arrow,
})
++ .or(self
++ .lane_reorder
++ .filter(|reorder| reorder.dragging)
++ .map(|_| gpui::CursorStyle::ClosedHand))
.or((self.scrub == Some(Scrub::Ruler)).then_some(gpui::CursorStyle::ResizeLeftRight));
div()
@@@ -9205,6 -8946,6 +9639,7 @@@
.update(cx, |this, cx| {
if this.scrub.is_none()
&& this.drag.is_none()
++ && this.lane_reorder.is_none()
&& this.minimap_drag.is_none()
{
return;
@@@ -9216,13 -8957,13 +9651,21 @@@
// drag at its last state.
this.window_mouse_up(cx);
this.drag_mouse_up(window, cx);
++ this.cancel_lane_reorder(cx);
if this.minimap_drag.take().is_some() {
cx.notify();
}
return;
}
++ if this.lane_reorder.is_some() {
++ this.update_lane_reorder(event.position, window, cx);
++ return;
++ }
if let Some(drag) = this.minimap_drag {
-- this.view.transform = drag.update(f32::from(event.position.x), this.total_duration());
++ this.view.transform = drag.update(
++ f32::from(event.position.x),
++ this.total_duration(),
++ );
this.view.preview_time = None;
cx.notify();
return;
@@@ -9248,12 -8989,12 +9691,14 @@@
.update(cx, |this, cx| {
if this.scrub.is_none()
&& this.drag.is_none()
++ && this.lane_reorder.is_none()
&& this.minimap_drag.is_none()
{
return;
}
this.window_mouse_up(cx);
this.drag_mouse_up(window, cx);
++ this.finish_lane_reorder(window, cx);
if this.minimap_drag.take().is_some() {
this.note_transform("minimap", None);
cx.notify();
@@@ -9280,15 -9021,15 +9725,18 @@@
.flex_1()
.min_h_0()
.w_full()
-- .gap(px(8.))
++ .pb(px(8.))
.overflow_hidden()
++ // No `overflow_hidden` from here down: every card clips its
++ // own children, and an intermediate content mask would cut
++ // the cards' drop shadows off at their own edges.
.child(
div()
.flex()
.flex_col()
.flex_1()
.min_h_0()
-- .overflow_hidden()
++ .gap(px(8.))
// The split container: `flex overflow-hidden
// flex-row flex-1 min-h-0 px-2`, `min-height:
// MIN_PLAYER_HEIGHT`.
@@@ -9299,12 -9040,12 +9747,8 @@@
.flex_1()
.min_h_0()
.px(px(8.))
-- .overflow_hidden()
- .min_h(px(MIN_PLAYER_HEIGHT))
- // The player card: `flex flex-col
- // rounded-xl border bg-gray-1
- // dark:bg-gray-2 border-gray-3
- // overflow-hidden`, `flex: 1 1 0%`.
+ .min_h(px(layout.player_min_height))
- // The player card: `flex flex-col
- // rounded-xl border bg-gray-1
- // dark:bg-gray-2 border-gray-3
- // overflow-hidden`, `flex: 1 1 0%`.
++ // The player card.
.child(
div()
.flex()
@@@ -9314,78 -9055,76 +9758,99 @@@
.min_h_0()
.rounded(px(12.))
.border_1()
-- .border_color(Hsla::from(theme.gray_3))
++ .border_color(self.card_line())
.bg(self.panel_bg())
++ .shadow(theme.editor.card_shadow())
.overflow_hidden()
-- .child(self.render_player(cx))
-- // The 16px horizontal resize
-- // handle with its three grip bars
- // (`Editor.tsx:700-725`).
- // (`Editor.tsx:700-725`). Inert:
- // resizing the timeline is E3.
-- .child(
-- div()
-- .id("timeline-resize-handle")
-- .h(px(RESIZE_HANDLE_HEIGHT))
-- .flex_none()
-- .flex()
-- .flex_col()
-- .gap(px(2.))
-- .items_center()
-- .justify_center()
-- .cursor(gpui::CursorStyle::ResizeRow)
-- .tab_index(0)
-- .border_t_1()
-- .border_color(if theme.is_dark() {
-- Hsla::from(theme.gray_5)
-- } else {
-- Hsla::from(theme.gray_4)
-- })
-- .bg(if theme.is_dark() {
-- with_alpha(theme.gray_3, 0.55)
-- } else {
-- with_alpha(theme.gray_2, 0.95)
-- })
-- .on_mouse_down(
-- MouseButton::Left,
-- cx.listener(
- |this, event: &MouseDownEvent, window, cx| {
- |this, event: &MouseDownEvent, _, cx| {
-- this.timeline_resize = Some((
-- f32::from(event.position.y),
- this.clamp_timeline_height(
- this.timeline_height,
- f32::from(window.viewport_size().height),
- ),
- this.timeline_height,
-- ));
-- cx.notify();
-- },
-- ),
-- )
-- .children((0..3).map(|_| {
-- div()
-- .h(px(2.))
-- .w(px(80.))
-- .rounded_full()
-- .bg(if theme.is_dark() {
-- Hsla::from(theme.gray_7)
-- } else {
-- Hsla::from(theme.gray_6)
-- })
-- })),
-- ),
++ .child(self.render_player(cx)),
)
++ // The 8px gutter is the wrapper's, not the
++ // sidebar view's: a margin inside a cached
++ // element is not honoured.
.child(
-- self.sidebar_view.clone().cached(
-- StyleRefinement::default()
-- .w(px(SIDEBAR_WIDTH + 8.))
-- .h_full(),
++ div().flex_none().h_full().pl(px(8.)).child(
++ self.sidebar_view.clone().cached(
++ StyleRefinement::default()
++ .w(px(SIDEBAR_WIDTH))
++ .h_full(),
++ ),
),
),
)
++ // The timeline card: the wrapper is owned here so
++ // `render_timeline` keeps laying out inside a plain
++ // box.
.child(
-- self.timeline_view.clone().cached(
-- StyleRefinement::default()
-- .w_full()
- .h(px(layout.timeline_height)),
- .h(px(self.timeline_height)),
-- ),
++ div()
++ .relative()
++ .flex_none()
++ .w_full()
++ .px(px(8.))
++ .h(px(layout.timeline_height))
++ .child(
++ div()
++ .size_full()
++ .rounded(px(12.))
++ .border_1()
++ .border_color(self.card_line())
++ .bg(self.panel_bg())
++ .shadow(theme.editor.card_shadow())
++ .overflow_hidden()
++ .child(self.timeline_view.clone().cached(
++ StyleRefinement::default().w_full().h_full(),
++ )),
++ )
++ // The grip rides the gap between the two
++ // cards rather than taking a strip of the
++ // player card for itself.
++ .child(
++ div()
++ .id("timeline-resize-handle")
++ .group("resize-grip")
++ .absolute()
++ .left_0()
++ .right_0()
++ .top(px(RESIZE_GRIP_TOP))
++ .h(px(RESIZE_GRIP_HEIGHT))
++ .flex()
++ .flex_row()
++ .items_start()
++ .justify_center()
++ .pt(px(RESIZE_GRIP_PILL_TOP))
++ .cursor(gpui::CursorStyle::ResizeRow)
++ .tab_index(0)
++ .on_mouse_down(
++ MouseButton::Left,
++ cx.listener(
++ |this, event: &MouseDownEvent, window, cx| {
++ this.timeline_resize = Some((
++ f32::from(event.position.y),
++ this.clamp_timeline_height(
++ this.preferred_timeline_height(),
++ f32::from(
++ window.viewport_size().height,
++ ),
++ ),
++ ));
++ cx.notify();
++ },
++ ),
++ )
++ .child(
++ div()
++ .h(px(4.))
++ .w(px(36.))
++ .rounded(px(2.))
++ .bg(if self.timeline_resize.is_some() {
++ Hsla::from(theme.editor.text_3)
++ } else {
++ Hsla::from(theme.editor.line_strong)
++ })
++ .group_hover("resize-grip", |this| {
++ this.bg(Hsla::from(theme.editor.text_3))
++ }),
++ ),
++ ),
),
),
)
@@@ -9409,8 -9148,8 +9874,8 @@@
};
let viewport_height: f32 = window.viewport_size().height.into();
let delta = f32::from(event.position.y) - start_y;
-- this.timeline_height =
-- this.clamp_timeline_height(start_height - delta, viewport_height);
++ this.timeline_height_override =
++ Some(this.clamp_timeline_height(start_height - delta, viewport_height));
cx.notify();
}),
cx.listener(|this, _: &MouseUpEvent, _window, cx| {
@@@ -9480,13 -9219,13 +9945,16 @@@
// a drag that leaves the letterboxed rect keeps tracking and the
// release closes the undo bracket wherever it happens.
.children(self.canvas_drag.as_ref().map(|drag| {
-- let cursor = drag.resize.as_ref().map_or(gpui::CursorStyle::ClosedHand, |resize| {
-- if resize.dir_x == resize.dir_y {
-- gpui::CursorStyle::ResizeUpLeftDownRight
-- } else {
-- gpui::CursorStyle::ResizeUpRightDownLeft
-- }
-- });
++ let cursor = drag
++ .resize
++ .as_ref()
++ .map_or(gpui::CursorStyle::ClosedHand, |resize| {
++ if resize.dir_x == resize.dir_y {
++ gpui::CursorStyle::ResizeUpLeftDownRight
++ } else {
++ gpui::CursorStyle::ResizeUpRightDownLeft
++ }
++ });
ui::Slider::drag_layer(
"canvas-display-drag",
cx.listener(|this, event: &MouseMoveEvent, window, cx| {
@@@ -9695,76 -9434,178 +10163,274 @@@ fn hex_to_color(rgba: [u8; 4]) -> cap_p
mod tests {
use super::*;
+ #[test]
+ fn caption_split_and_delete_update_the_source_master() {
+ let words = vec![
+ cap_project::CaptionWord {
+ text: "hello".into(),
+ start: 1.0,
+ end: 2.0,
+ },
+ cap_project::CaptionWord {
+ text: "world".into(),
+ start: 3.0,
+ end: 4.0,
+ },
+ ];
+ let track = cap_project::CaptionTrackSegment {
+ id: "spoken".into(),
+ start: 1.0,
+ end: 4.0,
+ text: "hello world".into(),
+ words: words.clone(),
+ fade_duration_override: None,
+ linger_duration_override: None,
+ position_override: None,
+ color_override: None,
+ background_color_override: None,
+ font_size_override: None,
+ };
+ let mut project = ProjectConfiguration {
+ timeline: Some(TimelineConfiguration {
+ segments: vec![cap_project::TimelineSegment {
+ recording_clip: 0,
+ start: 0.0,
+ end: 10.0,
+ timescale: 1.0,
+ name: None,
+ speed_audio_mode: None,
+ }],
+ transitions: Vec::new(),
+ zoom_segments: Vec::new(),
+ scene_segments: Vec::new(),
+ mask_segments: Vec::new(),
+ text_segments: Vec::new(),
+ caption_segments: vec![track],
+ keyboard_segments: Vec::new(),
+ audio_segments: Vec::new(),
+ camera3d_segments: Vec::new(),
++ style_segments: Vec::new(),
++ image_segments: Vec::new(),
+ }),
+ captions: Some(cap_project::CaptionsData {
+ segments: vec![cap_project::CaptionSegment {
+ id: "spoken".into(),
+ start: 1.0,
+ end: 4.0,
+ text: "hello world".into(),
+ words,
+ }],
+ source_timed: true,
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+
+ assert!(split_caption_segment(&mut project, 0, 1.5, &[10.0]));
+ cap_project::synchronize_captions(&mut project, &[10.0]);
+ let captions = project.captions.as_ref().unwrap();
+ assert_eq!(captions.segments.len(), 2);
+ assert_eq!(captions.segments[0].text, "hello");
+ assert_eq!(captions.segments[1].text, "world");
+ assert_eq!(project.timeline.as_ref().unwrap().caption_segments.len(), 2);
+
+ assert!(delete_caption_segments(&mut project, &[1]));
+ cap_project::synchronize_captions(&mut project, &[10.0]);
+ assert_eq!(project.captions.as_ref().unwrap().segments.len(), 1);
+ assert_eq!(project.timeline.as_ref().unwrap().caption_segments.len(), 1);
+ }
+
+ #[test]
+ fn caption_split_delete_survives_a_repeated_trimmed_edl() {
+ let mut project = ProjectConfiguration {
+ timeline: Some(TimelineConfiguration {
+ segments: vec![
+ cap_project::TimelineSegment {
+ recording_clip: 0,
+ start: 0.5,
+ end: 4.5,
+ timescale: 1.0,
+ name: None,
+ speed_audio_mode: None,
+ },
+ cap_project::TimelineSegment {
+ recording_clip: 0,
+ start: 0.5,
+ end: 4.5,
+ timescale: 1.0,
+ name: None,
+ speed_audio_mode: None,
+ },
+ ],
+ transitions: Vec::new(),
+ zoom_segments: Vec::new(),
+ scene_segments: Vec::new(),
+ mask_segments: Vec::new(),
+ text_segments: Vec::new(),
+ caption_segments: Vec::new(),
+ keyboard_segments: Vec::new(),
+ audio_segments: Vec::new(),
+ camera3d_segments: Vec::new(),
++ style_segments: Vec::new(),
++ image_segments: Vec::new(),
+ }),
+ captions: Some(cap_project::CaptionsData {
+ segments: vec![cap_project::CaptionSegment {
+ id: "spoken".into(),
+ start: 1.0,
+ end: 4.0,
+ text: "hello world".into(),
+ words: vec![
+ cap_project::CaptionWord {
+ text: "hello".into(),
+ start: 1.0,
+ end: 2.0,
+ },
+ cap_project::CaptionWord {
+ text: "world".into(),
+ start: 3.0,
+ end: 4.0,
+ },
+ ],
+ }],
+ source_timed: true,
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+ cap_project::synchronize_captions(&mut project, &[10.0]);
+ assert_eq!(
+ project.timeline.as_ref().unwrap().caption_segments[0].id,
+ "spoken::edl0"
+ );
+
+ assert!(split_caption_segment(&mut project, 0, 1.5, &[10.0]));
+ let tail_source_id = project.captions.as_ref().unwrap().segments[1].id.clone();
+ assert_ne!(tail_source_id, "spoken");
+ assert_eq!(
+ cap_project::source_caption_id(&tail_source_id),
+ tail_source_id
+ );
+ assert_eq!(
+ project.timeline.as_ref().unwrap().caption_segments[1].id,
+ tail_source_id
+ );
+
+ cap_project::synchronize_captions(&mut project, &[10.0]);
+ assert_eq!(project.timeline.as_ref().unwrap().caption_segments.len(), 4);
+ let tail_index = project
+ .timeline
+ .as_ref()
+ .unwrap()
+ .caption_segments
+ .iter()
+ .position(|segment| cap_project::source_caption_id(&segment.id) == tail_source_id)
+ .unwrap();
+ assert!(delete_caption_segments(&mut project, &[tail_index]));
+ cap_project::synchronize_captions(&mut project, &[10.0]);
+
+ assert_eq!(project.captions.as_ref().unwrap().segments.len(), 1);
+ assert_eq!(project.captions.as_ref().unwrap().segments[0].id, "spoken");
+ let remaining = &project.timeline.as_ref().unwrap().caption_segments;
+ assert_eq!(remaining.len(), 2);
+ assert!(
+ remaining
+ .iter()
+ .all(|segment| cap_project::source_caption_id(&segment.id) == "spoken")
+ );
+ }
++
+ #[test]
+ fn responsive_editor_fits_the_intel_visible_workarea() {
+ let layout = EditorVerticalLayout::new(652., DEFAULT_TIMELINE_HEIGHT);
- assert_eq!(layout.player_min_height, 336.);
- assert_eq!(layout.timeline_height, 252.);
++ assert_eq!(layout.player_min_height, MIN_PLAYER_HEIGHT);
++ assert_eq!(layout.timeline_height, DEFAULT_TIMELINE_HEIGHT);
+ assert_eq!(editor_player_width(992.), 550.);
+ }
+
++ #[test]
++ fn responsive_editor_hugs_its_rows_and_still_fits_a_short_viewport() {
++ // The four-row scratch project: chrome plus four rows and their gaps.
++ assert_eq!(timeline::hug_height(4), 246.);
++ assert_eq!(timeline::hug_height(0), timeline::MIN_HUG_HEIGHT);
++ for rows in 1..12usize {
++ let hug = timeline::hug_height(rows);
++ assert_eq!(
++ EditorVerticalLayout::new(1200., hug).timeline_height,
++ hug,
++ "{rows} rows should hug exactly on a tall window"
++ );
++ let layout = EditorVerticalLayout::new(652., hug);
++ assert!(
++ layout.player_min_height + layout.timeline_height + HEADER_HEIGHT + 8. <= 652.001
++ );
++ }
++ }
++
+ #[test]
+ fn responsive_editor_restores_the_preferred_split_after_resize() {
+ let preferred = 500.;
+ let sizes = [1200., 652., 600., 480., 1200.];
+ let layouts = sizes.map(|height| EditorVerticalLayout::new(height, preferred));
+ assert_eq!(layouts[0].timeline_height, preferred);
- assert_eq!(layouts[1].timeline_height, 252.);
++ assert_eq!(layouts[1].timeline_height, 264.);
+ assert_eq!(layouts[4].timeline_height, preferred);
+ for (height, layout) in sizes.into_iter().zip(layouts) {
+ assert!(layout.player_min_height > 156.);
+ assert!(layout.timeline_height > 160.);
+ assert!(
+ layout.player_min_height + layout.timeline_height + HEADER_HEIGHT + 8.
+ <= height + 0.001
+ );
+ }
+ }
+
+ #[test]
+ fn responsive_editor_clamps_both_ends_of_the_resize_gesture() {
+ for height in [480., 600., 652., 800., 1200.] {
+ let low = EditorVerticalLayout::new(height, -1000.);
+ let high = EditorVerticalLayout::new(height, 10000.);
+ assert!(low.timeline_height <= high.timeline_height);
+ assert!(low.timeline_height > 0.);
+ assert!(
+ high.player_min_height + high.timeline_height + HEADER_HEIGHT + 8.
+ <= height + 0.001
+ );
+ }
++ // The floor is one visible row, which is what lets a two-track project
++ // hug instead of padding the card out to the reference split.
+ assert_eq!(
+ EditorVerticalLayout::new(800., -1000.).timeline_height,
- 240.
++ timeline::MIN_HUG_HEIGHT
+ );
+ assert_eq!(
+ EditorVerticalLayout::new(800., 10000.).timeline_height,
- 400.
++ 412.
+ );
+ }
+
+ #[test]
+ fn responsive_editor_preserves_the_spacious_layout() {
+ let layout = EditorVerticalLayout::new(800., DEFAULT_TIMELINE_HEIGHT);
+ assert_eq!(layout.player_min_height, MIN_PLAYER_HEIGHT);
+ assert_eq!(layout.timeline_height, DEFAULT_TIMELINE_HEIGHT);
+ for windows in [false, true] {
+ for captions in [false, true] {
+ assert!(!compact_header_controls(1275., windows, captions));
+ }
+ }
+ }
+
+ #[test]
+ fn responsive_editor_reserves_space_for_windows_controls_and_captions() {
+ assert!(compact_header_controls(992., true, true));
+ assert!(!compact_header_controls(992., true, false));
+ assert!(!compact_header_controls(992., false, true));
+ assert!(compact_header_controls(800., true, false));
+ assert!(compact_header_controls(800., false, true));
+ assert_eq!(editor_player_width(800.), 358.);
+ }
+
fn open_sidebar_menu_for_test(
kind: crate::editor_tabs::SidebarMenu,
) -> Option<crate::editor_tabs::OpenMenu> {
diff --cc apps/desktop-gpui/src/editor_window/frame.rs
index 7405d23e0,111fb2b42..30fd98399
--- a/apps/desktop-gpui/src/editor_window/frame.rs
+++ b/apps/desktop-gpui/src/editor_window/frame.rs
@@@ -184,59 -125,11 +184,63 @@@ fn button_content(style: FrameStyle) -
}
impl EditorWindow {
+ fn frame_background(&self) -> &cap_project::BackgroundConfiguration {
+ let index = if self.frame_controls.open {
+ self.frame_controls
+ .style_target
+ .as_ref()
+ .map(|target| target.index)
+ } else {
+ self.selected_style_index()
+ };
+ index
+ .and_then(|index| {
+ self.project
+ .timeline
+ .as_ref()?
+ .style_segments
+ .get(index)?
+ .overrides
+ .background
+ .as_ref()
+ })
+ .unwrap_or(&self.project.background)
+ }
+
+ pub(crate) fn dismiss_frame_controls(&mut self, cx: &mut Context<Self>) {
+ self.finish_frame_text_edit(cx);
+ self.frame_controls.open = false;
+ self.frame_controls.style_target = None;
+ }
+
+ fn edit_frame(&mut self, change: FrameChange, window: &mut Window, cx: &mut Context<Self>) {
+ if !self.frame_controls.open {
+ return;
+ }
+ if !apply_targeted_frame_change(
+ &mut self.project,
+ self.frame_controls.style_target.as_ref(),
+ change,
+ ) {
+ return;
+ }
+ if let Some(target) = &mut self.frame_controls.style_target
+ && let Some(next) = StyleFrameTarget::capture(&self.project, target.index)
+ {
+ *target = next;
+ }
+ self.project_changed(window, cx);
+ }
+
fn frame_style(&self) -> FrameStyle {
- FrameConfiguration::active_style(self.project.background.frame.as_ref())
+ FrameConfiguration::active_style(self.frame_background().frame.as_ref())
}
-- pub(super) fn render_frame_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
++ pub(super) fn render_frame_button(
++ &self,
++ narrow: bool,
++ cx: &mut Context<Self>,
++ ) -> impl IntoElement {
let (label, icon) = button_content(self.frame_style());
let bounds = self.frame_controls.trigger_bounds.clone();
div()
@@@ -244,9 -137,9 +248,10 @@@
.flex_none()
.child(
ui::EditorButton::plain(&self.theme, "frame-settings")
++ .text(&self.theme)
.left_icon(icon)
.right_icon("icons/chevron-down.svg")
-- .label(label)
++ .when(!narrow, |button| button.label(label))
.tooltip(&self.theme, "Add a frame")
.pressed(self.frame_controls.open)
.disabled(self.instance.is_none())
@@@ -378,87 -272,125 +383,90 @@@
.frame
.as_ref()
.map_or(FrameTheme::Dark, |frame| frame.theme);
- let panel =
- div()
- .id("frame-popover")
- .occlude()
- .flex()
- .flex_col()
- .w(px(304.).min(window.viewport_size().width - px(24.)))
- .max_h(window.viewport_size().height - px(24.))
- .overflow_y_scroll()
- .rounded(px(16.))
- .border_1()
- .border_color(theme.gray(3))
- .bg(theme.gray(1))
- .shadow_lg()
- .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
- .child(
- div()
- .flex()
- .flex_col()
- .gap(px(2.))
- .px(px(16.))
- .pt(px(14.))
- .pb(px(12.))
- .border_b_1()
- .border_color(theme.gray(3))
- .child(
- div()
- .text_size(px(13.))
- .font_weight(FontWeight::SEMIBOLD)
- .text_color(theme.gray(12))
- .child("Frame"),
- )
- .child(
- div()
- .text_size(px(11.))
- .text_color(theme.gray(10))
- .child("Wrap your recording in a window or device frame."),
- ),
- )
- .child(div().flex().flex_col().gap(px(2.)).p(px(6.)).children(
- FRAME_STYLES.into_iter().enumerate().map(
- |(index, (value, label, description, icon))| {
- let selected = value == style;
- div()
- .id(("frame-style", index))
- .tab_index(0)
- .flex()
- .items_center()
- .gap(px(12.))
- .p(px(8.))
- .rounded(px(12.))
- .cursor_pointer()
- .hover(|row| row.bg(theme.gray(3)))
- .focus_visible(|row| row.bg(theme.gray(3)))
- .child(
- div()
- .flex()
- .items_center()
- .justify_center()
- .size(px(32.))
- .flex_shrink_0()
- .rounded(px(10.))
- .bg(if selected {
- theme.blue_9.into()
- } else {
- theme.gray(3)
+ let panel = div()
+ .id("frame-popover")
+ .occlude()
+ .flex()
+ .flex_col()
+ .w(px(304.).min(window.viewport_size().width - px(24.)))
- .max_h(window.viewport_size().height - px(24.))
++ .max_h(
++ (window.viewport_size().height - bounds.bottom() - px(20.))
++ .min(window.viewport_size().height - px(24.)),
++ )
+ .overflow_y_scroll()
- .rounded(px(16.))
++ .rounded(px(12.))
+ .border_1()
- .border_color(theme.gray(3))
- .bg(theme.gray(1))
- .shadow_lg()
++ .border_color(gpui::Hsla::from(theme.editor.line))
++ .bg(gpui::Hsla::from(theme.editor.card))
++ .shadow(theme.editor.pop_shadow())
+ .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(2.))
+ .px(px(16.))
+ .pt(px(14.))
+ .pb(px(12.))
+ .border_b_1()
+ .border_color(theme.gray(3))
+ .child(
+ div()
+ .text_size(px(13.))
+ .font_weight(FontWeight::SEMIBOLD)
+ .text_color(theme.gray(12))
+ .child("Frame"),
+ )
+ .child(
+ div().text_size(px(11.)).text_color(theme.gray(10)).child(
+ match &self.frame_controls.style_target {
+ Some(target) if !target.matches(&self.project) => {
+ "This Style changed. Close and reopen Frame.".to_string()
+ }
+ Some(target)
+ if self
+ .project
+ .timeline
+ .as_ref()
+ .and_then(|timeline| {
+ timeline.style_segments.get(target.index)
})
- .child(svg().path(icon).size(px(16.)).text_color(
- if selected {
- gpui::white()
- } else {
- theme.gray(11)
- },
- )),
- )
- .child(
- div()
- .flex()
- .flex_col()
- .flex_1()
- .min_w_0()
- .child(
- div()
- .text_size(px(13.))
- .font_weight(FontWeight::MEDIUM)
- .text_color(theme.gray(12))
- .child(label),
- )
- .child(
- div()
- .text_size(px(11.))
- .text_color(theme.gray(10))
- .child(description),
- ),
- )
- .when(selected, |row| {
- row.child(
- svg()
- .path("icons/circle-check.svg")
- .size(px(16.))
- .flex_shrink_0()
- .text_color(theme.blue_9),
+ .is_some_and(|segment| {
+ segment.overrides.background.is_none()
+ }) =>
+ {
+ format!(
+ "Style {} only · Editing enables its background override.",
+ target.index + 1
)
- })
- .on_click(cx.listener(move |this, _, window, cx| {
- this.change_frame(FrameChange::Style(value), window, cx)
- }))
- },
+ }
+ Some(target) => format!(
+ "Style {} only · Global settings stay unchanged.",
+ target.index + 1
+ ),
+ None => {
+ "Global frame · Applies wherever Style inherits background."
+ .to_string()
+ }
+ },
+ ),
),
- ))
- .when(style != FrameStyle::None, |panel| {
- panel.child(
+ )
+ .child(div().flex().flex_col().gap(px(2.)).p(px(6.)).children(
+ FRAME_STYLES.into_iter().enumerate().map(
+ |(index, (value, label, description, icon))| {
+ let selected = value == style;
div()
+ .id(("frame-style", index))
+ .tab_index(0)
.flex()
- .flex_col()
+ .items_center()
.gap(px(12.))
- .p(px(12.))
- .border_t_1()
- .border_color(theme.gray(3))
+ .p(px(8.))
+ .rounded(px(12.))
+ .cursor_pointer()
+ .hover(|row| row.bg(theme.gray(3)))
+ .focus_visible(|row| row.bg(theme.gray(3)))
.child(
div()
.flex()
@@@ -645,6 -510,6 +653,7 @@@
)
.child(
gpui::anchored()
++ .anchor(gpui::Anchor::TopLeft)
.position(point(bounds.left(), bounds.bottom() + px(8.)))
.snap_to_window_with_margin(px(12.))
.child(panel),
diff --cc apps/desktop-gpui/src/editor_window/scenes.rs
index 000000000,000000000..dd62e5759
new file mode 100644
--- /dev/null
+++ b/apps/desktop-gpui/src/editor_window/scenes.rs
@@@ -1,0 -1,0 +1,547 @@@
++use super::*;
++use crate::editor_panels::{
++ CAMERA3D_SCENES, MOTION_TEMPLATES, apply_motion_template, apply_scene_to_range,
++};
++use cap_project::{Camera3DProperties, Camera3DSegment};
++
++const STARTERS: &[(&str, &str)] = &[
++ ("glide-across", "Move smoothly across the details"),
++ ("unfold", "Reveal your screen with a gentle tilt"),
++ ("pull-back", "Pull out to show the bigger picture"),
++];
++const SEQUENCES: &[(&str, &str)] = &[
++ ("showcase", "Close-up, overhead sweep, then zoom in"),
++ ("product-tour", "Reveal, orbit, then settle on your screen"),
++ ("punch-in", "Zoom into a detail, then pull back"),
++];
++
++fn scene_range(
++ segments: &[(f64, f64)],
++ time: f64,
++ duration: f64,
++ total: f64,
++) -> Option<(f64, f64)> {
++ if ![time, duration, total]
++ .iter()
++ .all(|value| value.is_finite())
++ || duration <= 0.0
++ || total <= 0.0
++ {
++ return None;
++ }
++ let start = time.clamp(0.0, total);
++ let mut gap_start: f64 = 0.0;
++ let mut gap_end = total;
++ for &(existing_start, existing_end) in segments {
++ if existing_start <= start && start < existing_end {
++ return None;
++ }
++ if existing_end <= start {
++ gap_start = gap_start.max(existing_end);
++ } else {
++ gap_end = gap_end.min(existing_start);
++ }
++ }
++ let length = duration.min(gap_end - gap_start);
++ if length < 0.5_f64.min(total) {
++ return None;
++ }
++ let fitted_start = start.min(gap_end - length).max(gap_start);
++ Some((fitted_start, fitted_start + length))
++}
++
++fn scene_details(id: &str) -> Option<(&'static str, Camera3DProperties)> {
++ MOTION_TEMPLATES
++ .iter()
++ .find(|item| item.id == id)
++ .map(|item| (item.name, item.from))
++ .or_else(|| {
++ CAMERA3D_SCENES
++ .iter()
++ .find(|item| item.id == id)
++ .map(|item| (item.name, item.shots[0].from))
++ })
++}
++
++fn scene_segments(id: &str, start: f64, end: f64, cuts: &[f64]) -> Vec<Camera3DSegment> {
++ if let Some(template) = MOTION_TEMPLATES.iter().find(|item| item.id == id) {
++ let mut segment = edits::default_camera3d_segment(start, end);
++ apply_motion_template(&mut segment, template);
++ vec![segment]
++ } else if let Some(scene) = CAMERA3D_SCENES.iter().find(|item| item.id == id) {
++ apply_scene_to_range(scene, start, end, cuts)
++ } else {
++ Vec::new()
++ }
++}
++
++fn projected_point(pose: &Camera3DProperties, x: f32, y: f32) -> Option<(f32, f32)> {
++ let projection = cap_rendering::camera3d::camera3d_inverse_homography(pose, 16.0 / 9.0, None)?;
++ let [[a, b, c], [d, e, f], [g, h, i]] = projection.inverse_rows;
++ let x = x * projection.half_extents.0;
++ let y = y * projection.half_extents.1;
++ let w = (d * h - e * g) * x + (b * g - a * h) * y + a * e - b * d;
++ if w.abs() < 0.00001 {
++ return None;
++ }
++ let px = ((e * i - f * h) * x + (c * h - b * i) * y + b * f - c * e) / w;
++ let py = ((f * g - d * i) * x + (a * i - c * g) * y + c * d - a * f) / w;
++ (px.is_finite() && py.is_finite()).then_some(((px + 1.0) / 2.0, (1.0 - py) / 2.0))
++}
++
++impl EditorWindow {
++ pub(super) fn close_camera3d_setup(&mut self, cx: &mut Context<Self>) {
++ self.camera3d_setup = None;
++ self.rebuild_timeline();
++ cx.notify();
++ }
++
++ pub(super) fn start_camera3d_setup(&mut self, cx: &mut Context<Self>) {
++ self.start_camera3d_setup_at(self.view.playhead, cx);
++ }
++
++ pub(super) fn start_camera3d_setup_at(&mut self, time: f64, cx: &mut Context<Self>) {
++ let previous = self.camera3d_setup;
++ self.set_selection(None, cx);
++ self.sidebar.style_target = None;
++ self.audio_picker = None;
++ self.tracks.three_d = true;
++ self.camera3d_setup = Some(Camera3DSetup {
++ start: time,
++ ..previous.unwrap_or(Camera3DSetup {
++ scene_id: "glide-across",
++ start: time,
++ duration: 6.0,
++ sequences_open: false,
++ })
++ });
++ self.rebuild_timeline();
++ cx.notify();
++ }
++
++ fn planned_camera3d_scene(&self) -> Vec<Camera3DSegment> {
++ let Some(setup) = self.camera3d_setup else {
++ return Vec::new();
++ };
++ let existing = self
++ .project
++ .timeline
++ .as_ref()
++ .map(|timeline| {
++ timeline
++ .camera3d_segments
++ .iter()
++ .map(|segment| (segment.start, segment.end))
++ .collect::<Vec<_>>()
++ })
++ .unwrap_or_default();
++ let Some((start, end)) = scene_range(
++ &existing,
++ setup.start,
++ setup.duration,
++ self.total_duration(),
++ ) else {
++ return Vec::new();
++ };
++ let cuts = self
++ .project
++ .timeline
++ .as_ref()
++ .map(|timeline| {
++ let offsets = crate::editor_timeline::clip_timeline_offsets(timeline);
++ timeline
++ .segments
++ .iter()
++ .zip(offsets)
++ .flat_map(|(segment, offset)| [offset, offset + segment.duration()])
++ .collect::<Vec<_>>()
++ })
++ .unwrap_or_default();
++ scene_segments(setup.scene_id, start, end, &cuts)
++ }
++
++ pub(super) fn camera3d_setup_preview(&self) -> Vec<(f64, f64, String)> {
++ let segments = self.planned_camera3d_scene();
++ let Some((first, last)) = segments.first().zip(segments.last()) else {
++ return Vec::new();
++ };
++ let name = self
++ .camera3d_setup
++ .and_then(|setup| scene_details(setup.scene_id))
++ .map(|(name, _)| name)
++ .unwrap_or("3D scene");
++ vec![(
++ first.start,
++ last.end,
++ format!("{name} · {:.1}s", last.end - first.start),
++ )]
++ }
++
++ pub(crate) fn confirm_camera3d_setup(&mut self, window: &mut Window, cx: &mut Context<Self>) {
++ if !edits::ensure_timeline(&mut self.project, &self.clip_display_durations) {
++ return;
++ }
++ let generated = self.planned_camera3d_scene();
++ let Some(first) = generated.first() else {
++ return;
++ };
++ let start = first.start;
++ let index = self
++ .project
++ .timeline
++ .as_ref()
++ .map(|timeline| {
++ timeline
++ .camera3d_segments
++ .iter()
++ .filter(|segment| segment.start < start)
++ .count()
++ })
++ .unwrap_or(0);
++ if !self.edit(
++ |timeline| {
++ timeline.camera3d_segments.extend(generated);
++ timeline
++ .camera3d_segments
++ .sort_by(|a, b| a.start.total_cmp(&b.start));
++ true
++ },
++ window,
++ cx,
++ ) {
++ return;
++ }
++ self.camera3d_setup = None;
++ self.tracks.three_d = true;
++ self.set_selection(Some(Selection::single(TrackKind::ThreeD, index)), cx);
++ self.rebuild_timeline();
++ self.seek_to_time(start, cx);
++ self.view.preview_time = None;
++ self.note_edit("add-track", Some(TrackKind::ThreeD));
++ }
++
++ fn select_camera3d_scene(&mut self, id: &'static str, cx: &mut Context<Self>) {
++ if let Some(setup) = self.camera3d_setup.as_mut() {
++ setup.scene_id = id;
++ }
++ self.rebuild_timeline();
++ cx.notify();
++ }
++
++ fn render_scene_card(
++ &self,
++ id: &'static str,
++ description: &'static str,
++ cx: &mut Context<Self>,
++ ) -> gpui::AnyElement {
++ let theme = self.theme;
++ let Some((name, pose)) = scene_details(id) else {
++ return div().into_any_element();
++ };
++ let selected = self
++ .camera3d_setup
++ .is_some_and(|setup| setup.scene_id == id);
++ div()
++ .id(SharedString::from(format!("camera3d-setup-{id}")))
++ .flex()
++ .items_center()
++ .gap(px(12.))
++ .p(px(8.))
++ .rounded(px(8.))
++ .border_1()
++ .border_color(Hsla::from(if selected {
++ theme.blue_9
++ } else {
++ theme.gray_4
++ }))
++ .bg(Hsla::from(theme.gray_2))
++ .cursor_pointer()
++ .tab_index(0)
++ .hover(|style| style.border_color(theme.blue_9))
++ .on_click(cx.listener(move |this, _, _, cx| {
++ this.select_camera3d_scene(id, cx);
++ }))
++ .on_key_down(cx.listener(move |this, event: &gpui::KeyDownEvent, _, cx| {
++ if matches!(event.keystroke.key.as_str(), "enter" | "space") {
++ cx.stop_propagation();
++ this.select_camera3d_scene(id, cx);
++ }
++ }))
++ .child(
++ div()
++ .w(px(86.))
++ .h(px(56.))
++ .flex_none()
++ .rounded(px(6.))
++ .overflow_hidden()
++ .bg(Hsla::from(theme.gray_3))
++ .child(
++ gpui::canvas(
++ |bounds, _, _| bounds,
++ move |_, bounds, window, _| {
++ let shapes: &[(&[(f32, f32)], bool)] = &[
++ (&[(-1., 1.), (1., 1.), (1., -1.), (-1., -1.)], true),
++ (&[(-0.8, 0.65), (0.3, 0.65)], false),
++ (&[(-0.8, 0.25), (0.8, 0.25)], false),
++ (&[(-0.8, -0.1), (0.65, -0.1)], false),
++ (&[(-0.8, -0.45), (0.3, -0.45)], false),
++ ];
++ for &(points, fill) in shapes {
++ let mut path = if fill {
++ gpui::PathBuilder::fill()
++ } else {
++ gpui::PathBuilder::stroke(px(2.))
++ };
++ let mut valid = true;
++ for (index, &(x, y)) in points.iter().enumerate() {
++ let Some((x, y)) = projected_point(&pose, x, y) else {
++ valid = false;
++ break;
++ };
++ let point = gpui::point(
++ bounds.origin.x + bounds.size.width * x,
++ bounds.origin.y + bounds.size.height * y,
++ );
++ if index == 0 {
++ path.move_to(point);
++ } else {
++ path.line_to(point);
++ }
++ }
++ if fill {
++ path.close();
++ }
++ if valid && let Ok(path) = path.build() {
++ window.paint_path(
++ path,
++ Hsla::from(if fill {
++ theme.blue_9
++ } else {
++ theme.gray_1
++ }),
++ );
++ }
++ }
++ },
++ )
++ .size_full(),
++ ),
++ )
++ .child(
++ div()
++ .flex_1()
++ .min_w_0()
++ .flex()
++ .flex_col()
++ .gap(px(4.))
++ .child(
++ div()
++ .text_size(px(12.))
++ .font_weight(FontWeight::MEDIUM)
++ .text_color(Hsla::from(theme.gray_12))
++ .child(name),
++ )
++ .child(
++ div()
++ .text_size(px(11.))
++ .text_color(Hsla::from(theme.gray_10))
++ .child(description),
++ ),
++ )
++ .into_any_element()
++ }
++
++ pub(crate) fn render_camera3d_setup(&self, cx: &mut Context<Self>) -> gpui::AnyElement {
++ let theme = self.theme;
++ let Some(setup) = self.camera3d_setup else {
++ return div().into_any_element();
++ };
++ let range = self.camera3d_setup_preview().first().cloned();
++ let name = scene_details(setup.scene_id)
++ .map(|(name, _)| name)
++ .unwrap_or("scene");
++ let content = div()
++ .id("camera3d-setup-scroll")
++ .flex()
++ .flex_col()
++ .flex_1()
++ .min_h_0()
++ .overflow_y_scroll()
++ .p(px(16.))
++ .gap(px(16.))
++ .child(
++ div()
++ .flex()
++ .flex_none()
++ .items_center()
++ .justify_between()
++ .gap(px(8.))
++ .child(
++ div()
++ .text_size(px(14.))
++ .font_weight(FontWeight::MEDIUM)
++ .text_color(Hsla::from(theme.gray_12))
++ .child("Add a 3D scene"),
++ )
++ .child(
++ ui::EditorButton::plain(&theme, "camera3d-setup-close")
++ .left_icon("icons/x-mark.svg")
++ .icon_size(px(16.))
++ .tooltip(&theme, "Close")
++ .on_click(cx.listener(|this, _, _, cx| this.close_camera3d_setup(cx))),
++ ),
++ )
++ .child(
++ div()
++ .flex_none()
++ .text_size(px(12.))
++ .text_color(Hsla::from(theme.gray_10))
++ .child("Choose a camera move. Cap takes care of the animation."),
++ )
++ .child(
++ div().flex().flex_col().flex_none().gap(px(8.)).children(
++ STARTERS
++ .iter()
++ .map(|&(id, description)| self.render_scene_card(id, description, cx)),
++ ),
++ )
++ .child(
++ ui::EditorButton::plain(&theme, "camera3d-sequences")
++ .label("Multi-shot sequences")
++ .left_icon(if setup.sequences_open {
++ "icons/chevron-up.svg"
++ } else {
++ "icons/chevron-down.svg"
++ })
++ .on_click(cx.listener(|this, _, _, cx| {
++ if let Some(setup) = this.camera3d_setup.as_mut() {
++ setup.sequences_open = !setup.sequences_open;
++ }
++ cx.notify();
++ })),
++ )
++ .when(setup.sequences_open, |panel| {
++ panel.child(
++ div().flex().flex_col().flex_none().gap(px(8.)).children(
++ SEQUENCES
++ .iter()
++ .map(|&(id, description)| self.render_scene_card(id, description, cx)),
++ ),
++ )
++ });
++ let durations = div()
++ .flex()
++ .gap(px(4.))
++ .children([3, 6, 10].into_iter().map(|duration| {
++ let variant = if setup.duration == f64::from(duration) {
++ ui::ButtonVariant::Primary
++ } else {
++ ui::ButtonVariant::Gray
++ };
++ ui::Button::plain(
++ &theme,
++ SharedString::from(format!("camera3d-duration-{duration}")),
++ variant,
++ ui::ButtonSize::Md,
++ )
++ .label(format!("{duration}s"))
++ .on_click(cx.listener(move |this, _, _, cx| {
++ if let Some(setup) = this.camera3d_setup.as_mut() {
++ setup.duration = f64::from(duration);
++ }
++ this.rebuild_timeline();
++ cx.notify();
++ }))
++ }));
++ let summary = range.as_ref().map(|(start, end, _)| format!("{start:.1}s – {end:.1}s · {:.1}s. Drag the edges after adding to change the length.", end - start))
++ .unwrap_or_else(|| "Click an empty part of the 3D track to choose where to add your scene.".into());
++ let footer = div()
++ .flex()
++ .flex_col()
++ .flex_none()
++ .p(px(16.))
++ .gap(px(12.))
++ .border_t_1()
++ .border_color(Hsla::from(theme.gray_3))
++ .child(ui::Field::plain(&theme, "Duration").child(durations))
++ .child(
++ div()
++ .text_size(px(12.))
++ .text_color(Hsla::from(theme.gray_10))
++ .child(summary),
++ )
++ .child(
++ ui::Button::plain(
++ &theme,
++ "camera3d-setup-add",
++ ui::ButtonVariant::Primary,
++ ui::ButtonSize::Md,
++ )
++ .label(format!("Add {}", name.to_lowercase()))
++ .disabled(range.is_none())
++ .on_click(
++ cx.listener(|this, _, window, cx| this.confirm_camera3d_setup(window, cx)),
++ ),
++ );
++ div()
++ .id("camera3d-setup")
++ .flex()
++ .flex_col()
++ .flex_1()
++ .min_h_0()
++ .overflow_hidden()
++ .child(content)
++ .child(footer)
++ .into_any_element()
++ }
++}
++
++#[cfg(test)]
++mod tests {
++ use super::*;
++
++ #[test]
++ fn scenes_start_at_the_playhead_and_fit_short_recordings() {
++ assert_eq!(scene_range(&[], 4., 6., 30.), Some((4., 10.)));
++ assert_eq!(scene_range(&[], 9., 6., 10.), Some((4., 10.)));
++ assert_eq!(scene_range(&[], 0., 6., 0.3), Some((0., 0.3)));
++ }
++
++ #[test]
++ fn insertion_preserves_existing_scenes_and_shortens_to_the_gap() {
++ let existing = [(8., 12.), (0., 3.)];
++ assert_eq!(scene_range(&existing, 3., 6., 20.), Some((3., 8.)));
++ assert_eq!(scene_range(&existing, 12., 6., 20.), Some((12., 18.)));
++ assert_eq!(scene_range(&existing, 9., 6., 20.), None);
++ assert_eq!(scene_range(&[(0., 20.)], 20., 6., 20.), None);
++ }
++
++ #[test]
++ fn invalid_ranges_cannot_create_scenes() {
++ for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
++ assert!(scene_range(&[], value, 6., 20.).is_none());
++ assert!(scene_range(&[], 0., value, 20.).is_none());
++ assert!(scene_range(&[], 0., 6., value).is_none());
++ }
++ assert!(scene_range(&[], 0., 0., 20.).is_none());
++ assert!(scene_range(&[], 0., 6., 0.).is_none());
++ assert!(scene_range(&[(0., 3.), (3.2, 6.)], 3., 6., 20.).is_none());
++ }
++
++ #[test]
++ fn starter_presets_create_one_animated_segment() {
++ for &(id, _) in STARTERS {
++ let generated = scene_segments(id, 4., 10., &[]);
++ assert_eq!(generated.len(), 1);
++ assert_eq!((generated[0].start, generated[0].end), (4., 10.));
++ assert_ne!(
++ crate::editor_panels::start_pose(&generated[0]),
++ crate::editor_panels::end_pose(&generated[0])
++ );
++ let (_, pose) = scene_details(id).unwrap();
++ assert!(projected_point(&pose, 0., 0.).is_some());
++ }
++ assert_eq!(scene_segments("showcase", 4., 10., &[]).len(), 3);
++ assert!(scene_segments("unknown", 0., 6., &[]).is_empty());
++ }
++}
diff --cc apps/desktop-gpui/src/main.rs
index 4876bd412,84838963e..f67e3c69e
--- a/apps/desktop-gpui/src/main.rs
+++ b/apps/desktop-gpui/src/main.rs
@@@ -144,10 -142,14 +144,34 @@@ fn init_logging() -> Option<tracing_app
.unwrap_or_else(|_| "cap_gpui=info".into())
};
- let logs_dir = diagnostics::logs_dir();
- let file = match std::fs::create_dir_all(&logs_dir) {
- Ok(()) => {
- let (writer, guard) = tracing_appender::non_blocking(tracing_appender::rolling::daily(
- &logs_dir,
- diagnostics::LOG_FILE_PREFIX,
- ));
- Some((
+ let file = create_log_appender(&diagnostics::logs_dir(), diagnostics::LOG_FILE_PREFIX).map(
+ |appender| {
- let (writer, guard) = tracing_appender::non_blocking(appender);
++ let (writer, guard) = tracing_appender::non_blocking(
++ cap_utils::diagnostic_writer::DiagnosticWriter::new(
++ appender,
++ &diagnostics::logs_dir(),
++ diagnostics::LOG_FILE_PREFIX,
++ ),
++ );
++ let queue_errors = writer.error_counter();
++ cap_utils::operation_diagnostics::install_queue_loss_counter(move || {
++ queue_errors.dropped_lines()
++ });
++ let diagnostic_writer = writer.clone();
++ cap_utils::operation_diagnostics::install_sink(
++ cap_utils::operation_diagnostics::AppInfo {
++ flavor: "gpui",
++ version: env!("CARGO_PKG_VERSION"),
++ source_revision: option_env!("CAP_BUILD_REVISION"),
++ debug_build: cfg!(debug_assertions),
++ source_dirty: option_env!("CAP_BUILD_DIRTY").map(|value| value == "true"),
++ },
++ move |bytes| {
++ use std::io::Write;
++ let _ = diagnostic_writer.clone().write_all(bytes);
++ },
++ );
+ (
tracing_subscriber::fmt::layer()
.with_ansi(false)
.with_writer(writer)
@@@ -225,14 -209,8 +249,15 @@@ fn main()
// registered on the builder -- gpui exposes it nowhere else -- with the
// handler guarding against firing before the window registry exists.
app.on_reopen(crate::app_windows::handle_dock_reopen);
+ #[cfg(target_os = "macos")]
+ app.on_open_urls(|urls| {
+ for url in urls {
+ crate::deeplink::submit_deep_link(&url);
+ }
+ });
app.run(|cx: &mut App| {
gpui_tokio::init(cx);
++ gpui_tokio::Tokio::spawn(cx, cap_utils::operation_diagnostics::run_checkpoints()).detach();
// The dock icon: an unbundled dev binary shows the generic terminal
// document without it. The bytes are the shipping app's icon.png.
platform::set_dock_icon(include_bytes!("../assets/dock-icon.png"));
@@@ -256,11 -234,11 +281,12 @@@
crate::feeds::Feeds::init(cx);
crate::target_overlay::TargetSelect::init(cx);
-- let bounds = Bounds::centered(
-- None,
-- size(px(MAIN_WINDOW_WIDTH), px(MAIN_WINDOW_HEIGHT)),
-- cx,
-- );
++ let dev_restore = dev_restore::load();
++ let main_size = size(px(MAIN_WINDOW_WIDTH), px(MAIN_WINDOW_HEIGHT));
++ let bounds = dev_restore
++ .as_ref()
++ .and_then(|restore| restore.main_window_bounds(main_size, cx))
++ .unwrap_or_else(|| Bounds::centered(None, main_size, cx));
let window_handle = cx
.open_window(
WindowOptions {
@@@ -408,7 -386,7 +434,9 @@@
// `CAP_GPUI_DEV_RESTORE=<state file>`: `dev.sh`'s relaunch loop.
// Reopens the previous process's windows in place and keeps the
// state file current for the next swap.
-- dev_restore::init(cx);
++ if let Some(dev_restore) = dev_restore {
++ dev_restore.init(cx);
++ }
// Enumeration is started here rather than in `MainWindow::new`, which
// runs before the window is fully built -- see `start_enumeration`.
diff --cc apps/desktop-gpui/src/main_window.rs
index 132d3f513,80ec9cd41..a1a13ba77
--- a/apps/desktop-gpui/src/main_window.rs
+++ b/apps/desktop-gpui/src/main_window.rs
@@@ -235,7 -235,7 +235,7 @@@ impl gpui::RenderOnce for ModeHoverCar
"No rendering required — uploads on the fly so you can share the link the moment you stop."
}
Mode::Studio => {
-- "Records at the highest quality for local rendering later. Opens the Cap editor when you're done."
++ "Saves to your computer and opens the editor when you stop. Choose recording quality in settings."
}
Mode::Screenshot => "Capture and annotate stills.",
};
@@@ -5735,11 -5509,11 +5735,6 @@@ impl MainWindow
/// border-gray-5 px-1 py-0.5 bg-gray-3 hover:bg-gray-5`, a button; Pro and
/// Commercial are a non-interactive span on `--blue-400`. Which one
/// applies is [`PlanBadge::current`], the license query's resolution.
-- ///
-- /// Personal opens the pricing page -- the Tauri button opens the Upgrade
-- /// window (950x850), which has no gpui twin yet, and the integrations
-- /// page's upgrade affordance already goes to `/pricing` for the same
-- /// reason.
fn render_plan_badge(&self) -> impl IntoElement {
let theme = self.theme;
@@@ -5763,8 -5537,8 +5758,7 @@@
.child("Personal")
.hover(|style| style.bg(theme.body_hover_fill(5)))
.on_click(|_, _, cx| {
-- let url = format!("{}/pricing", crate::auth::server_url());
-- cx.open_url(&url);
++ cx.open_url(crate::auth::PRICING_URL);
}),
PlanBadge::Pro | PlanBadge::Commercial => badge
.bg(theme.blue_9)
diff --cc apps/desktop-gpui/src/onboarding_window.rs
index bad5687d3,36265a541..1405af3bb
--- a/apps/desktop-gpui/src/onboarding_window.rs
+++ b/apps/desktop-gpui/src/onboarding_window.rs
@@@ -1478,7 -1480,7 +1478,7 @@@ impl OnboardingWindow
.cursor_pointer()
.mt(px(8.))
.on_click(|_, _, cx| {
-- cx.open_url("https://cap.so/pricing")
++ cx.open_url(crate::auth::PRICING_URL)
}),
)
}),
@@@ -1490,7 -1492,7 +1490,7 @@@
copy("View pricing plans ↗", 13., theme.blue_10)
.id("onboarding-pricing")
.cursor_pointer()
-- .on_click(|_, _, cx| cx.open_url("https://cap.so/pricing")),
++ .on_click(|_, _, cx| cx.open_url(crate::auth::PRICING_URL)),
)
.into_any_element()
}
diff --cc apps/desktop-gpui/src/platform.rs
index 06e04d71d,186b1fde8..0ee7f4e0b
--- a/apps/desktop-gpui/src/platform.rs
+++ b/apps/desktop-gpui/src/platform.rs
@@@ -1627,13 -1170,13 +1627,26 @@@ mod mac
}
pub fn save_file_panel(suggested: &str, extensions: &[&str]) -> Option<std::path::PathBuf> {
++ match try_save_file_panel(suggested, extensions) {
++ Ok(path) => path,
++ Err(error) => {
++ tracing::error!(error, "Save dialog failed");
++ None
++ }
++ }
++ }
++
++ pub fn try_save_file_panel(
++ suggested: &str,
++ extensions: &[&str],
++ ) -> Result<Option<std::path::PathBuf>, String> {
use objc2::{class, msg_send};
use objc2_foundation::{NSArray, NSString};
unsafe {
let panel: *mut AnyObject = msg_send![class!(NSSavePanel), savePanel];
if panel.is_null() {
-- return None;
++ return Err("The save dialog is unavailable".to_string());
}
let _: () = msg_send![panel, setCanCreateDirectories: true];
let _: () = msg_send![panel, setNameFieldStringValue: &*NSString::from_str(suggested)];
@@@ -1646,18 -1189,18 +1659,21 @@@
let _: () = msg_send![panel, setAllowedFileTypes: &*types];
}
let response: isize = msg_send![panel, runModal];
++ if response == 0 {
++ return Ok(None);
++ }
if response != 1 {
-- return None;
++ return Err("The save dialog could not be displayed".to_string());
}
let url: *mut AnyObject = msg_send![panel, URL];
if url.is_null() {
-- return None;
++ return Err("The save dialog did not return a file path".to_string());
}
let path: *mut NSString = msg_send![url, path];
if path.is_null() {
-- return None;
++ return Err("The save dialog did not return a file path".to_string());
}
-- Some(std::path::PathBuf::from((*path).to_string()))
++ Ok(Some(std::path::PathBuf::from((*path).to_string())))
}
}
diff --cc apps/desktop-gpui/src/presets.rs
index ced082177,6193b20d1..1ca45d815
--- a/apps/desktop-gpui/src/presets.rs
+++ b/apps/desktop-gpui/src/presets.rs
@@@ -100,6 -100,6 +100,11 @@@ impl PresetsStore
}
}
++ /// New recordings go back to Cap's own defaults.
++ pub fn clear_default(&mut self) {
++ self.default = None;
++ }
++
pub fn rename(&mut self, index: usize, name: String) {
if let Some(entry) = self.presets.get_mut(index) {
entry.name = name;
@@@ -114,6 -114,6 +119,23 @@@
}
}
++/// The built-in "Default" preset: what a fresh screen recording looks like
++/// with no user preset -- `ProjectConfiguration::default()` plus the
++/// presentation defaults the recorder applies (`recording.rs`
++/// `apply_screen_recording_presentation_defaults`): 10% padding, 7.5%
++/// rounding and the default screen-movement spring.
++pub fn default_project_config() -> ProjectConfiguration {
++ let mut config = ProjectConfiguration::default();
++ if config.background.padding <= f64::EPSILON {
++ config.background.padding = 10.0;
++ }
++ if config.background.rounding <= f64::EPSILON {
++ config.background.rounding = 7.5;
++ }
++ config.screen_movement_spring = cap_project::ScreenMovementSpring::default();
++ config
++}
++
/// What a preset stores: the whole project config with `timeline: null` and
/// `clips: []` -- presets style a project, they never carry its cuts
/// (`createPresets.ts:31-35`).
@@@ -122,6 -122,6 +144,7 @@@ pub fn preset_config(project: &ProjectC
if let Some(map) = value.as_object_mut() {
map.insert("timeline".into(), Value::Null);
map.insert("clips".into(), Value::Array(Vec::new()));
++ map.remove("overlayOrder");
}
value
}
@@@ -135,6 -135,6 +158,7 @@@ pub fn apply_preset
) -> Option<ProjectConfiguration> {
let mut next: ProjectConfiguration = serde_json::from_value(config.clone()).ok()?;
next.timeline = current.timeline.clone();
++ next.overlay_order = current.overlay_order.clone();
next.clips = current.clips.clone();
Some(next)
}
@@@ -208,7 -208,7 +232,7 @@@ mod tests
}
#[test]
-- fn applying_keeps_the_current_timeline_and_clips() {
++ fn applying_keeps_the_current_timeline_clips_and_layer_order() {
let current = ProjectConfiguration {
timeline: Some(cap_project::TimelineConfiguration {
segments: Vec::new(),
@@@ -221,9 -221,7 +245,13 @@@
keyboard_segments: Vec::new(),
audio_segments: Vec::new(),
camera3d_segments: Vec::new(),
+ style_segments: Vec::new(),
+ image_segments: Vec::new(),
}),
++ overlay_order: vec![cap_project::OverlayTrack {
++ kind: cap_project::OverlayTrackKind::Image,
++ track: 2,
++ }],
..Default::default()
};
let mut preset_source = ProjectConfiguration::default();
@@@ -232,6 -230,6 +260,7 @@@
let applied = apply_preset(&preset, &current).expect("preset deserializes");
assert_eq!(applied.background.blur, 42.);
++ assert_eq!(applied.overlay_order, current.overlay_order);
assert!(applied.timeline.is_some(), "current timeline is kept");
}
diff --cc apps/desktop-gpui/src/settings_pages.rs
index 47fe84833,47fe84833..9cb81016d
--- a/apps/desktop-gpui/src/settings_pages.rs
+++ b/apps/desktop-gpui/src/settings_pages.rs
@@@ -335,9 -335,9 +335,6 @@@ pub(crate) struct PagesState
// License (license.tsx)
license_input: Entity<ui::TextInputState>,
license_draft: String,
-- /// `isCommercialAnnual`, default true.
-- license_annual: bool,
-- license_checkout_pending: bool,
license_activating: bool,
license_error: Option<String>,
@@@ -437,8 -437,8 +434,6 @@@ impl PagesState
changelog: None,
license_input,
license_draft: String::new(),
-- license_annual: true,
-- license_checkout_pending: false,
license_activating: false,
license_error: None,
integrations_view: IntegrationsView::Index,
@@@ -511,8 -511,8 +506,6 @@@ impl SettingsWindow
Page::Changelog => self.changelog_fetch(window, cx),
Page::License => {
self.pages.license_draft.clear();
-- self.pages.license_annual = true;
-- self.pages.license_checkout_pending = false;
self.pages.license_activating = false;
self.pages.license_error = None;
let input = self.pages.license_input.clone();
@@@ -3697,44 -3697,44 +3690,6 @@@ fn markdown_paragraphs(content: &str) -
const LICENSE_API_BASE: &str = "https://l.cap.so/api";
impl SettingsWindow {
-- /// `createCommercialCheckoutUrl`, opened externally.
-- fn license_checkout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
-- if self.pages.license_checkout_pending {
-- return;
-- }
-- self.pages.license_checkout_pending = true;
-- let kind = if self.pages.license_annual {
-- "yearly"
-- } else {
-- "lifetime"
-- };
-- let url = format!("{LICENSE_API_BASE}/commercial/checkout");
-- self.spawn_tokio(
-- window,
-- cx,
-- async move {
-- http_json(
-- reqwest::Method::POST,
-- url,
-- Vec::new(),
-- Vec::new(),
-- None,
-- HttpBody::Json(json!({ "type": kind })),
-- None,
-- )
-- .await
-- },
-- |this, result, _window, cx| {
-- this.pages.license_checkout_pending = false;
-- if let Ok((200, body)) = result
-- && let Some(url) = body.get("url").and_then(Value::as_str)
-- {
-- cx.open_url(url);
-- }
-- },
-- );
-- }
--
/// `activateCommercialLicense`: key and instance id go as headers, and a
/// 200 writes `general_settings.commercialLicense` in the exact shape
/// license.tsx's `onActivated` writes.
@@@ -3805,66 -3805,66 +3760,55 @@@
pub(crate) fn render_license(&self, cx: &mut Context<Self>) -> Vec<gpui::AnyElement> {
let theme = self.theme;
let auth = store::auth_snapshot();
--
-- // `createLicenseQuery`: pro from the auth plan, else commercial from
-- // the store, else the purchase/activate pair.
-- if auth.plan_upgraded {
-- return vec![
-- div()
-- .flex()
-- .flex_col()
-- .items_center()
-- .w_full()
-- .pt(px(96.))
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .items_center()
-- .gap(px(12.))
-- .w_full()
-- .max_w(px(448.))
-- .p(px(24.))
-- .rounded(px(24.))
-- .border_1()
-- .border_color(theme.settings_border())
-- .bg(theme.settings_card_bg())
-- .child(
-- div()
-- .text_size(px(24.))
-- .font_weight(FontWeight::MEDIUM)
-- .child("Cap Pro License"),
-- )
-- .child(
-- div()
-- .text_size(px(13.))
-- .line_height(px(20.))
-- .text_color(theme.settings_muted())
-- .child(
-- "Your account is upgraded to Cap Pro and already \
-- includes a commercial license.",
-- ),
-- ),
-- )
-- .into_any_element(),
-- ];
-- }
--
-- if let Some(license) = store::commercial_license() {
-- return vec![self.render_license_active(license, cx)];
++ let pro = auth.is_upgraded();
++ let license = store::commercial_license();
++ let (name, description) = if pro {
++ (
++ "Cap Pro",
++ "Your account includes cloud sharing, Pro features and a desktop license for commercial use.",
++ )
++ } else if license.is_some() {
++ (
++ "Desktop License",
++ "Your desktop license covers commercial recording and editing. Cap Pro adds cloud sharing and collaboration features.",
++ )
++ } else {
++ (
++ "Cap Free",
++ "Record and edit locally for personal use. Choose a paid plan for commercial use or more cloud features.",
++ )
++ };
++ let mut content = vec![
++ self.section("Plan & license", Some("Your Cap plan and desktop license, in one place."), None, vec![]).into_any_element(),
++ self.section("Your plan", None, None, vec![self.card(true).child(
++ div().flex().flex_col().gap(px(8.))
++ .child(div().text_size(px(18.)).font_weight(FontWeight::SEMIBOLD).child(name))
++ .child(div().text_size(px(12.)).line_height(px(18.)).text_color(theme.settings_muted()).child(description))
++ .when(auth.signed_in(), |this| this.child(
++ div().flex().flex_col().items_start().gap(px(8.)).child(self.button(
++ "refresh-plan", (ui::ButtonVariant::Gray, None),
++ if self.plan_refresh_pending { "Checking…" } else { "Refresh plan" },
++ self.plan_refresh_pending, cx, |this, window, cx| this.refresh_plan(window, cx),
++ )).when(self.plan_refresh_failed, |this| this.child(div().text_size(px(12.)).text_color(theme.settings_muted()).child("Couldn't refresh your plan. Please try again.")))
++ ))
++ .when(!auth.signed_in(), |this| this.child(div().text_size(px(12.)).line_height(px(18.)).text_color(theme.settings_muted()).child("Already have Cap Pro? Sign in with your account from the sidebar.")))
++ ).into_any_element()]).into_any_element(),
++ self.section("Explore plans", Some("Compare current pricing and everything included on our website."), None, vec![self.card(true).child(
++ div().flex().flex_col().items_start().gap(px(12.))
++ .child(div().text_size(px(12.)).line_height(px(18.)).child("Desktop License · Commercial use of the desktop recorder and editor."))
++ .child(div().text_size(px(12.)).line_height(px(18.)).child("Cap Pro · A desktop license, plus cloud sharing, AI features and collaboration."))
++ .child(ui::Button::settings(&theme, "license-pricing", ui::ButtonVariant::Dark, ui::ButtonSize::Sm).label("View plans & pricing ↗").on_click(|_, _, cx| cx.open_url(crate::auth::PRICING_URL)))
++ .child(div().text_size(px(12.)).text_color(theme.settings_muted()).child("Opens cap.so/pricing in your browser."))
++ ).into_any_element()]).into_any_element(),
++ ];
++ if !pro {
++ content.push(if let Some(license) = license {
++ self.render_license_active(license, cx)
++ } else {
++ self.render_license_activate(cx).into_any_element()
++ });
}
--
-- vec![
-- div()
-- .flex()
-- .flex_col()
-- .items_center()
-- .gap(px(12.))
-- .w_full()
-- .child(self.render_license_purchase(cx))
-- .child(self.render_license_activate(cx))
-- .into_any_element(),
-- ]
++ content
}
/// The activated-commercial card.
@@@ -3903,7 -3903,7 +3847,7 @@@
div()
.text_size(px(24.))
.font_weight(FontWeight::MEDIUM)
-- .child("Commercial License"),
++ .child("Desktop license"),
),
)
.child(
@@@ -3959,168 -3959,168 +3903,6 @@@
.into_any_element()
}
-- /// `CommercialLicensePurchase`'s pricing card. The Rive card-stack
-- /// animation has no gpui equivalent and is omitted.
-- fn render_license_purchase(&self, cx: &mut Context<Self>) -> impl IntoElement {
-- let theme = self.theme;
-- let annual = self.pages.license_annual;
-- let pending = self.pages.license_checkout_pending;
--
-- let left = div()
-- .flex()
-- .flex_col()
-- .items_center()
-- .gap(px(16.))
-- .p(px(20.))
-- .flex_1()
-- .min_w_0()
-- .rounded_l(px(12.))
-- .border_1()
-- .border_color(theme.settings_border())
-- .bg(theme.settings_fill())
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .items_center()
-- .gap(px(4.))
-- .child(
-- div()
-- .text_size(px(24.))
-- .font_weight(FontWeight::MEDIUM)
-- .child("Commercial License"),
-- )
-- .child(
-- div()
-- .text_size(px(13.))
-- .text_color(theme.settings_muted())
-- .child("For commercial use"),
-- ),
-- )
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .items_center()
-- .mt(px(20.))
-- .child(
-- div()
-- .flex()
-- .flex_row()
-- .items_end()
-- .child(div().text_size(px(36.)).child(if annual {
-- "$29"
-- } else {
-- "$58"
-- }))
-- .child(
-- div()
-- .text_size(px(16.))
-- .text_color(theme.settings_muted())
-- .child(".00 /"),
-- ),
-- )
-- .child(
-- div()
-- .text_size(px(16.))
-- .font_weight(FontWeight::MEDIUM)
-- .text_color(theme.settings_muted())
-- .child(if annual {
-- "billed annually"
-- } else {
-- "one-time payment"
-- }),
-- ),
-- )
-- .child(
-- div()
-- .id("license-billing-toggle")
-- .px(px(12.))
-- .py(px(8.))
-- .rounded_full()
-- .bg(theme.settings_selection())
-- .cursor_pointer()
-- .hover(|style| style.bg(theme.settings_fill()))
-- .child(div().text_size(px(12.)).child(format!(
-- "Switch to {}: {}",
-- if annual { "lifetime" } else { "yearly" },
-- if annual { "$58" } else { "$29" }
-- )))
-- .on_click(cx.listener(|this, _, _window, cx| {
-- this.pages.license_annual = !this.pages.license_annual;
-- cx.notify();
-- })),
-- )
-- .child(
-- div().w_full().mt(px(40.)).child(
-- ui::Button::settings(
-- &theme,
-- "license-purchase",
-- ui::ButtonVariant::Dark,
-- ui::ButtonSize::Lg,
-- )
-- .label(if pending {
-- "Loading..."
-- } else {
-- "Purchase License"
-- })
-- .radius(px(24.))
-- .height(px(48.))
-- .full_width()
-- .font_weight(FontWeight::MEDIUM)
-- .disabled_settings(&theme, pending)
-- .on_click(cx.listener(|this, _, window, cx| this.license_checkout(window, cx))),
-- ),
-- );
--
-- let features = [
-- "Commercial Use of Cap Recorder + Editor",
-- "Community Support",
-- "Local-only features",
-- "Perpetual license option",
-- ];
-- let right = div()
-- .flex()
-- .flex_col()
-- .justify_center()
-- .items_center()
-- .gap(px(16.))
-- .p(px(20.))
-- .flex_1()
-- .min_w_0()
-- .rounded_r(px(12.))
-- .border_1()
-- .border_color(theme.settings_border())
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(8.))
-- .children(features.into_iter().map(|feature| {
-- div()
-- .flex()
-- .flex_row()
-- .items_center()
-- .gap(px(4.))
-- .child(
-- svg()
-- .path("icons/check.svg")
-- .size(px(16.))
-- .flex_shrink_0()
-- .text_color(theme.settings_text()),
-- )
-- .child(div().text_size(px(14.)).child(feature))
-- })),
-- );
--
-- div()
-- .w_full()
-- .max_w(px(700.))
-- .rounded(px(12.))
-- .bg(theme.settings_card_bg())
-- .child(div().flex().flex_row().child(left).child(right))
-- }
--
/// `LicenseKeyActivate`.
fn render_license_activate(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
@@@ -4507,7 -4507,7 +4289,6 @@@ impl SettingsWindow
"{}/api/desktop/storage/google-drive/connect",
self.settings.server_url
);
-- let server = self.settings.server_url.clone();
self.spawn_tokio(
window,
cx,
@@@ -4532,9 -4532,9 +4313,7 @@@
this.gdrive_wait_for_connection(window, cx);
}
}
-- // `showWindow("Upgrade")` has no gpui equivalent; the
-- // pricing page is the closest external destination.
-- Ok((403, _)) => cx.open_url(&format!("{server}/pricing")),
++ Ok((403, _)) => cx.open_url(crate::auth::PRICING_URL),
Ok(_) => {
this.pages.gdrive.error =
Some("Failed to start Google Drive connection".to_string())
@@@ -4782,7 -4782,7 +4561,6 @@@
.as_ref()
.and_then(|storage| storage.managed_by_organization.as_ref())
.map(|organization| organization.name.clone());
-- let server = self.settings.server_url.clone();
let apps: [(&'static str, &'static str, &'static str, IntegrationsView); 2] = [
(
@@@ -4820,7 -4820,7 +4598,6 @@@
"Configure"
};
let managed_here = managed.is_some();
-- let server = server.clone();
self.card(true)
.flex()
.flex_col()
@@@ -4859,9 -4859,9 +4636,7 @@@
return;
}
if !store::auth_snapshot().plan_upgraded {
-- // `showWindow("Upgrade")` in the Tauri
-- // app; no upgrade window exists here.
-- cx.open_url(&format!("{server}/pricing"));
++ cx.open_url(crate::auth::PRICING_URL);
return;
}
match view {
diff --cc apps/desktop-gpui/src/settings_window.rs
index 05b9a97d0,e092c0193..d0d5578d3
--- a/apps/desktop-gpui/src/settings_window.rs
+++ b/apps/desktop-gpui/src/settings_window.rs
@@@ -76,13 -76,13 +76,10 @@@ const SIDEBAR_SPACER: f32 = 44.
/// The sidebar list, in `settingsItems` order. `href` is the route segment,
/// which is also what `showWindow({ Settings: { page } })` takes.
--///
--/// Nothing in the list is gated: `settingsItems` is a plain array with no
--/// `Show`, no platform check and no plan check, so a free user on Windows sees
--/// the same twelve rows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Page {
General,
++ Quality,
Shortcuts,
Cli,
Recordings,
@@@ -99,6 -99,6 +96,7 @@@
impl Page {
pub const ALL: &'static [Page] = &[
Page::General,
++ Page::Quality,
Page::Shortcuts,
Page::Cli,
Page::Recordings,
@@@ -117,6 -117,6 +115,7 @@@
fn label(self) -> &'static str {
match self {
Self::General => "General",
++ Self::Quality => "Recording quality",
Self::Shortcuts => "Shortcuts",
Self::Cli => "CLI",
Self::Recordings => "Recordings",
@@@ -124,7 -124,7 +123,7 @@@
Self::Automations => "Automations",
Self::Transcription => "Transcription",
Self::Integrations => "Integrations",
-- Self::License => "License",
++ Self::License => "Plan & license",
Self::Experimental => "Experimental",
Self::Feedback => "Feedback",
Self::Changelog => "Changelog",
@@@ -135,6 -135,6 +134,7 @@@
pub fn slug(self) -> &'static str {
match self {
Self::General => "general",
++ Self::Quality => "quality",
Self::Shortcuts => "hotkeys",
Self::Cli => "cli",
Self::Recordings => "recordings",
@@@ -158,7 -158,7 +158,7 @@@
Self::General | Self::Experimental => "icons/settings.svg",
Self::Shortcuts => "icons/hotkeys.svg",
Self::Cli => "icons/terminal.svg",
-- Self::Recordings => "icons/square-play.svg",
++ Self::Recordings | Self::Quality => "icons/square-play.svg",
Self::Screenshots => "icons/image.svg",
Self::Automations => "icons/zap.svg",
Self::Transcription => "icons/captions.svg",
@@@ -231,31 -231,31 +231,41 @@@ const COUNTDOWN_OPTIONS: &[(u32, &str)
(10, "10 seconds"),
];
--/// `STUDIO_QUALITY_TIERS`: label, summary, "Best for".
const STUDIO_QUALITY_TIERS: &[(StudioQuality, &str, &str)] = &[
(
-- StudioQuality::Compatibility,
-- "Lower bitrate to keep older or low-power machines smooth.",
-- "Older Intel Macs, 8GB MacBook Air, weaker laptops.",
++ StudioQuality::Balanced,
++ "Balanced",
++ "Clear, detailed recordings with a practical file size. Best for everyday use.",
),
(
-- StudioQuality::Balanced,
-- "Sharp footage with sensible CPU and disk usage.",
-- "Most modern Macs and PCs with 16GB+ RAM.",
++ StudioQuality::Compatibility,
++ "Smaller files",
++ "Uses less disk space. Can reduce detail, especially when recording with a camera.",
),
(
StudioQuality::Ultra,
-- "Maximum detail for color-graded, large-display edits.",
-- "M-series Pro/Max, discrete GPUs, 32GB+ RAM, NVMe.",
++ "Maximum detail",
++ "Preserves more detail for demanding edits. Creates larger files and needs more disk space.",
),
];
--/// `INSTANT_RESOLUTION_TIERS`.
const INSTANT_RESOLUTION_TIERS: &[(u32, &str, &str)] = &[
-- (1280, "720p", "Smallest size, low bandwidth."),
-- (1920, "1080p", "Recommended. Sharp on most networks."),
-- (2560, "1440p", "More detail for desktop content."),
-- (3840, "4K", "Max clarity. Needs fast upload."),
++ (1280, "720p", "Smaller uploads. Good for quick updates."),
++ (
++ 1920,
++ "1080p",
++ "Clear text and a practical upload size. Recommended with Cap Pro.",
++ ),
++ (
++ 2560,
++ "1440p",
++ "More detail for larger screens. Takes longer to upload.",
++ ),
++ (
++ 3840,
++ "4K",
++ "The most detail and largest uploads. Best with a fast connection.",
++ ),
];
/// `FREE_INSTANT_MODE_MAX_RESOLUTION`.
@@@ -263,7 -263,7 +273,6 @@@ const FREE_INSTANT_MODE_MAX_RESOLUTION
#[derive(Clone, Copy)]
enum InstantQualityNotice {
-- UpgradeRequired,
SaveFailed,
}
@@@ -615,7 -615,7 +624,10 @@@ pub struct SettingsWindow
studio_quality_anchor: ScrollAnchor,
quality_scroll_request: Option<Mode>,
has_cap_pro: bool,
++ pub(crate) plan_refresh_pending: bool,
++ pub(crate) plan_refresh_failed: bool,
instant_quality_notice: Option<InstantQualityNotice>,
++ studio_quality_save_failed: bool,
/// Everything the pages in `settings_pages.rs` own -- their fetch state,
/// drafts and text-input entities.
pub(crate) pages: crate::settings_pages::PagesState,
@@@ -736,7 -736,7 +748,10 @@@ impl SettingsWindow
page_scroll,
quality_scroll_request: None,
has_cap_pro: store::auth_snapshot().is_upgraded(),
++ plan_refresh_pending: false,
++ plan_refresh_failed: false,
instant_quality_notice: None,
++ studio_quality_save_failed: false,
project_name_input,
server_url_input,
_field_events: field_events,
@@@ -791,6 -791,6 +806,7 @@@
}
self.quality_scroll_request = None;
self.instant_quality_notice = None;
++ self.studio_quality_save_failed = false;
self.has_cap_pro = store::auth_snapshot().is_upgraded();
self.page = page;
self.menu = None;
@@@ -811,8 -811,8 +827,8 @@@
if mode == Mode::Screenshot {
return;
}
-- if self.page != Page::General {
-- self.set_page(Page::General, window, cx);
++ if self.page != Page::Quality {
++ self.set_page(Page::Quality, window, cx);
}
self.quality_scroll_request = Some(mode);
cx.notify();
@@@ -832,6 -832,6 +848,9 @@@
/// scheduling a frame.
pub fn page_shown(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.pages_shown(window, cx);
++ if matches!(self.page, Page::Quality | Page::License) {
++ self.refresh_plan(window, cx);
++ }
if self.page == Page::Recordings {
self.screenshots.scan = None;
self.refresh_recordings(window, cx);
@@@ -1503,7 -1499,7 +1522,7 @@@ impl Render for SettingsWindow
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.sync_appearance(window, cx);
let theme = self.theme;
-- if self.page == Page::General
++ if self.page == Page::Quality
&& let Some(mode) = self.quality_scroll_request.take()
{
match mode {
@@@ -1898,6 -1894,6 +1917,27 @@@ impl SettingsWindow
cx.notify();
}
++ pub(crate) fn refresh_plan(&mut self, window: &mut Window, cx: &mut Context<Self>) {
++ if self.plan_refresh_pending || !store::auth_snapshot().signed_in() {
++ return;
++ }
++ self.plan_refresh_pending = true;
++ self.plan_refresh_failed = false;
++ cx.spawn_in(window, async move |this, cx| {
++ let result = gpui_tokio::Tokio::spawn(cx, crate::auth::update_auth_plan()).await;
++ this.update_in(cx, |this, window, cx| {
++ this.plan_refresh_pending = false;
++ this.plan_refresh_failed = !matches!(result, Ok(Ok(())));
++ this.has_cap_pro = store::auth_snapshot().is_upgraded();
++ cx.notify();
++ window.refresh();
++ })
++ .ok();
++ })
++ .detach();
++ cx.notify();
++ }
++
fn clear_local_auth(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if !crate::auth::sign_out() {
tracing::error!("failed to clear the auth session");
@@@ -2052,6 -2048,6 +2092,7 @@@
.gap(px(28.))
.children(match self.page {
Page::General => self.render_general(window, cx),
++ Page::Quality => self.render_recording_quality(cx),
Page::Recordings => self.render_recordings(cx),
Page::Screenshots => self.render_screenshots(cx),
Page::Shortcuts => self.render_shortcuts(cx),
@@@ -2887,8 -2883,8 +2928,6 @@@
vec![
self.render_appearance(cx).into_any_element(),
self.render_app_section(cx).into_any_element(),
-- self.render_cap_pro(cx).into_any_element(),
-- self.render_quality(cx).into_any_element(),
self.render_recording(cx).into_any_element(),
self.render_storage(cx).into_any_element(),
self.render_project_name(window, cx).into_any_element(),
@@@ -3037,8 -3033,8 +3076,10 @@@
};
self.has_cap_pro = store::auth_snapshot().is_upgraded();
if !self.has_cap_pro && resolution != FREE_INSTANT_MODE_MAX_RESOLUTION {
-- self.instant_quality_notice = Some(InstantQualityNotice::UpgradeRequired);
-- } else if store::set_store_setting(
++ cx.notify();
++ return;
++ }
++ if store::set_store_setting(
GENERAL_SETTINGS,
"instantModeMaxResolution",
Value::from(resolution),
@@@ -3051,7 -3047,7 +3092,51 @@@
cx.notify();
}
-- fn render_cap_pro(&self, cx: &mut Context<Self>) -> impl IntoElement {
++ fn render_recording_quality(&self, cx: &mut Context<Self>) -> Vec<gpui::AnyElement> {
++ vec![
++ self.section(
++ "Recording quality",
++ Some("Choose how new recordings look and how much space they use."),
++ None,
++ vec![],
++ )
++ .into_any_element(),
++ self.render_studio_quality(cx).into_any_element(),
++ self.render_instant_quality(cx).into_any_element(),
++ self.section(
++ "Sharing",
++ None,
++ None,
++ vec![
++ self.rows(vec![
++ self.setting_row(
++ "Open share links automatically",
++ Some("Open the link in your browser when an upload finishes."),
++ self.toggle(
++ "auto-open-links",
++ !self.settings.disable_auto_open_links,
++ cx,
++ |this, cx| {
++ this.settings.disable_auto_open_links =
++ !this.settings.disable_auto_open_links;
++ this.write_bool(
++ "disableAutoOpenLinks",
++ this.settings.disable_auto_open_links,
++ cx,
++ );
++ },
++ )
++ .into_any_element(),
++ ),
++ ])
++ .into_any_element(),
++ ],
++ )
++ .into_any_element(),
++ ]
++ }
++
++ fn render_instant_quality(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
let effective = if self.has_cap_pro {
self.settings.instant_mode_max_resolution
@@@ -3063,184 -3059,184 +3148,78 @@@
.find(|(value, _, _)| *value == effective)
.map(|(_, _, summary)| *summary)
.unwrap_or_default();
--
-- let resolution = div()
-- .flex()
-- .flex_col()
-- .items_end()
-- .gap(px(6.))
-- .child(
-- self.segmented_raw(
-- "instant-resolution",
-- INSTANT_RESOLUTION_TIERS
-- .iter()
-- .map(|(value, label, _)| {
-- ui::SegmentOption::new(*label, *value == effective)
-- })
-- .collect(),
-- cx,
-- |this, index, cx| this.select_instant_resolution(index, cx),
-- ),
-- )
-- .child(
-- div()
-- .text_size(px(11.))
-- .line_height(px(15.))
-- .text_color(theme.settings_muted())
-- .child(summary),
-- );
--
++ let body = self.card(true).child(
++ div().id("settings-instant-quality").anchor_scroll(Some(self.instant_quality_anchor.clone()))
++ .flex().flex_col().gap(px(12.))
++ .child(div().text_size(px(13.)).font_weight(FontWeight::MEDIUM).child("Maximum resolution"))
++ .child(self.segmented_raw("instant-resolution", INSTANT_RESOLUTION_TIERS.iter().map(|(value, label, _)| {
++ let locked = !self.has_cap_pro && *value > FREE_INSTANT_MODE_MAX_RESOLUTION;
++ ui::SegmentOption::new(if locked { format!("{label} · Pro") } else { (*label).to_string() }, *value == effective).disabled(locked)
++ }).collect(), cx, |this, index, cx| this.select_instant_resolution(index, cx)))
++ .child(div().text_size(px(12.)).line_height(px(18.)).text_color(theme.settings_muted()).child(format!("{summary} Resolution is limited by the screen or area you record.")))
++ .when(!self.has_cap_pro, |this| this.child(
++ div().flex().flex_col().items_start().gap(px(12.)).pt(px(12.)).border_t_1().border_color(theme.settings_border())
++ .child(div().text_size(px(12.)).line_height(px(18.)).child("720p is included. Cap Pro unlocks 1080p, 1440p and 4K for Instant recordings."))
++ .child(ui::Button::settings(&theme, "instant-quality-pricing", ui::ButtonVariant::Gray, ui::ButtonSize::Sm)
++ .label("View plans ↗").on_click(|_, _, cx| cx.open_url(crate::auth::PRICING_URL)))
++ ))
++ .when_some(self.instant_quality_notice, |this, _| this.child(div().text_size(px(12.)).text_color(Hsla::from(theme.amber_11)).child("Couldn't save your recording settings. Please try again."))),
++ );
self.section(
-- "Cap Pro",
-- Some("Settings available with a Cap Pro license."),
++ "Instant",
++ Some("Uploads while you record, so your share link is ready when you stop."),
None,
-- vec![
-- self.rows(vec![
-- div()
-- .id("settings-instant-quality")
-- .anchor_scroll(Some(self.instant_quality_anchor.clone()))
-- .child(self.setting_row(
-- "Instant Mode quality",
-- Some(if self.has_cap_pro {
-- "Choose the maximum upload resolution for Instant recordings."
-- } else {
-- "Instant recordings are locked to 720p. Cap Pro unlocks higher resolutions."
-- }),
-- resolution.into_any_element(),
-- ))
-- .when_some(self.instant_quality_notice, |this, notice| {
-- this.child(
-- div()
-- .flex()
-- .flex_col()
-- .items_start()
-- .gap(px(8.))
-- .px(px(12.))
-- .pb(px(12.))
-- .text_size(px(12.))
-- .line_height(px(18.))
-- .text_color(Hsla::from(theme.amber_11))
-- .child(match notice {
-- InstantQualityNotice::UpgradeRequired => {
-- "Upgrade to Cap Pro to record Instant Mode videos above 720p."
-- }
-- InstantQualityNotice::SaveFailed => {
-- "Failed to save Instant Mode quality. Please try again."
-- }
-- })
-- .when(matches!(notice, InstantQualityNotice::UpgradeRequired), |this| {
-- this.child(
-- ui::Button::settings(
-- &theme,
-- "instant-quality-upgrade",
-- ui::ButtonVariant::Gray,
-- ui::ButtonSize::Xs,
-- )
-- .label("Upgrade")
-- .on_click(|_, _, cx| {
-- cx.open_url(&format!("{}/pricing", crate::auth::server_url()));
-- }),
-- )
-- }),
-- )
-- })
-- .into_any_element(),
-- self.setting_row(
-- "Auto-open shareable links",
-- Some("Open the share link in your browser as soon as the upload finishes."),
-- self.toggle(
-- "auto-open-links",
-- !self.settings.disable_auto_open_links,
-- cx,
-- |this, cx| {
-- this.settings.disable_auto_open_links =
-- !this.settings.disable_auto_open_links;
-- let value = this.settings.disable_auto_open_links;
-- this.write_bool("disableAutoOpenLinks", value, cx);
-- },
-- )
-- .into_any_element(),
-- ),
-- ])
-- .into_any_element(),
-- ],
++ vec![body.into_any_element()],
)
-- .pro()
}
-- /// `QualitySection` / `StudioQualitySubsection` -- `studioRecordingQuality`.
-- fn render_quality(&self, cx: &mut Context<Self>) -> impl IntoElement {
++ fn select_studio_quality(&mut self, quality: StudioQuality, cx: &mut Context<Self>) {
++ self.studio_quality_save_failed = !store::set_store_setting(
++ GENERAL_SETTINGS,
++ "studioRecordingQuality",
++ Value::String(quality.as_json().to_string()),
++ );
++ if !self.studio_quality_save_failed {
++ self.settings.studio_recording_quality = quality;
++ }
++ cx.notify();
++ }
++
++ fn render_studio_quality(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
let current = self.settings.studio_recording_quality;
-- let (_, summary, best_for) = STUDIO_QUALITY_TIERS
-- .iter()
-- .find(|(value, _, _)| *value == current)
-- .copied()
-- .unwrap_or(STUDIO_QUALITY_TIERS[1]);
--
-- let body = div()
-- .id("settings-studio-quality")
-- .anchor_scroll(Some(self.studio_quality_anchor.clone()))
-- // `flex flex-col gap-3 px-4 py-4`
-- .flex()
-- .flex_col()
-- .gap(px(12.))
-- .px(px(16.))
-- .py(px(16.))
-- .child(
-- div()
-- .flex()
-- .flex_row()
-- .justify_between()
-- .items_start()
-- .gap(px(16.))
-- .child(
-- div()
-- .flex()
-- .flex_col()
-- .gap(px(2.))
-- .min_w_0()
-- .child(div().text_size(px(13.)).child("Studio mode"))
-- .child(
-- div()
-- .text_size(px(12.))
-- .line_height(px(16.))
-- .text_color(theme.settings_muted())
-- .child("Encoder profile for local Studio recordings."),
-- ),
-- )
-- .child(self.segmented::<StudioQuality>(
-- "studio-quality",
-- current,
-- cx,
-- |this, value, cx| {
-- this.settings.studio_recording_quality = value;
-- this.write_enum("studioRecordingQuality", value, cx);
-- },
-- )),
-- )
-- .child(
-- self.note_box()
-- .child(div().text_size(px(12.)).child(summary))
-- .child(
-- div()
-- .flex()
-- .flex_row()
-- .gap(px(4.))
-- .text_size(px(11.))
-- .line_height(px(15.))
-- .text_color(theme.settings_muted())
-- .child(div().child("Best for:"))
-- .child(div().child(best_for)),
-- ),
-- );
--
-- self.section(
-- "Quality",
-- Some("Pick the right profile for local Studio recordings."),
-- None,
-- vec![self.card(false).child(body).into_any_element()],
-- )
++ let body = self.card(true).child(
++ div().id("settings-studio-quality").anchor_scroll(Some(self.studio_quality_anchor.clone()))
++ .flex().flex_col().gap(px(8.))
++ .children(STUDIO_QUALITY_TIERS.iter().copied().map(|(quality, label, description)| {
++ let selected = current == quality;
++ div().id(SharedString::from(format!("studio-quality-{}", quality.as_json())))
++ .tab_index(0).aria_label(label).aria_description(description).aria_selected(selected)
++ .cursor_pointer().flex().flex_col().gap(px(4.)).p(px(12.)).rounded(px(8.))
++ .border_1().border_color(if selected { Hsla::from(theme.blue_9) } else { theme.settings_border() })
++ .bg(if selected { theme.settings_selection() } else { theme.settings_card_bg() })
++ .hover(|style| style.bg(theme.settings_fill()))
++ .child(div().flex().items_center().gap(px(8.))
++ .child(div().text_size(px(13.)).font_weight(FontWeight::MEDIUM).child(label))
++ .when(quality == StudioQuality::Balanced, |this| this.child(div().text_size(px(10.)).text_color(Hsla::from(theme.blue_11)).child("Recommended")))
++ .when(selected, |this| this.child(div().text_size(px(12.)).text_color(Hsla::from(theme.blue_11)).child("✓"))))
++ .child(div().text_size(px(12.)).line_height(px(18.)).text_color(theme.settings_muted()).child(description))
++ .on_click(cx.listener(move |this, _, _, cx| {
++ this.select_studio_quality(quality, cx);
++ }))
++ .on_key_down(cx.listener(move |this, event: &gpui::KeyDownEvent, _, cx| {
++ if event.keystroke.modifiers == Default::default()
++ && matches!(event.keystroke.key.as_str(), "enter" | "space")
++ {
++ this.select_studio_quality(quality, cx);
++ cx.stop_propagation();
++ }
++ }))
++ }))
++ .when(self.studio_quality_save_failed, |this| this.child(div().text_size(px(12.)).line_height(px(18.)).text_color(Hsla::from(theme.amber_11)).child("Couldn't save your recording settings. Please try again.")))
++ .child(div().mt(px(4.)).text_size(px(12.)).line_height(px(18.)).text_color(theme.settings_muted()).child("These options affect the original recording. Choose your final export resolution and file size in the editor.")),
++ );
++ self.section("Studio", Some("Saved to your computer, ready to edit. All three quality options are available on every plan."), None, vec![body.into_any_element()])
}
/// The Recording card: thirteen rows, in TSX order.
@@@ -4502,11 -4498,11 +4481,10 @@@ mod tests
/// addresses by slug.
#[test]
fn every_page_round_trips_through_its_slug() {
-- assert_eq!(Page::ALL.len(), 12);
++ assert_eq!(Page::ALL.len(), 13);
for page in Page::ALL {
assert_eq!(Page::from_slug(page.slug()), Some(*page));
}
-- // The label and the route disagree for exactly one entry.
assert_eq!(Page::Shortcuts.slug(), "hotkeys");
assert_eq!(Page::from_slug("nope"), None);
}
diff --cc apps/desktop-gpui/src/theme.rs
index 07711e4ae,07711e4ae..879fe06b1
--- a/apps/desktop-gpui/src/theme.rs
+++ b/apps/desktop-gpui/src/theme.rs
@@@ -6,7 -6,7 +6,9 @@@
//! `.dark`). The overridden ones are marked below -- they are *not* stock Radix,
//! so regenerating this from a Radix crate would silently change the palette.
--use gpui::{App, Context, Global, Hsla, Rgba, Window, WindowAppearance, rgb, rgba};
++use gpui::{
++ App, BoxShadow, Context, Global, Hsla, Rgba, Window, WindowAppearance, point, px, rgb, rgba,
++};
use crate::platform::{self, ForcedAppearance, MaterialKind};
use crate::store::AppTheme;
@@@ -419,6 -419,6 +421,209 @@@ pub struct Theme
/// `--text-primary`, the root text colour. Slightly translucent by design.
pub text_primary: Rgba,
++
++ /// The editor's layered surface system (`--ed-*` in `theme.css`).
++ pub editor: EditorPalette,
++}
++
++/// Editor surfaces, transcribed from the `--ed-*` custom properties in
++/// `apps/desktop/src/styles/theme.css`. A layered, low-contrast system
++/// (window < card < control) with one accent; change both files together.
++#[derive(Debug, Clone, Copy, PartialEq)]
++pub struct EditorPalette {
++ pub window: Rgba,
++ pub card: Rgba,
++ pub card_2: Rgba,
++ pub stage: Rgba,
++ pub line: Rgba,
++ pub line_strong: Rgba,
++ pub text_1: Rgba,
++ pub text_2: Rgba,
++ pub text_3: Rgba,
++ pub ctl: Rgba,
++ pub ctl_hover: Rgba,
++ pub ctl_active: Rgba,
++ pub accent: Rgba,
++ pub accent_2: Rgba,
++ pub playhead: Rgba,
++ pub thumb: Rgba,
++ /// `--ed-seg-tint`: how much of a track colour a segment fill carries.
++ pub seg_tint: f32,
++ /// `--ed-seg-line`: the segment border's alpha.
++ pub seg_line: f32,
++ /// `--ed-seg-label-base` / `--ed-seg-label-mix`: segment text is the
++ /// track colour pulled this far toward black (light) or white (dark).
++ pub seg_label_base: Rgba,
++ pub seg_label_mix: f32,
++ /// `--ed-card-shadow` / `--ed-pop-shadow`: how black each surface's drop
++ /// shadow is. A card lifts barely at all on white and much more on the dark
++ /// window, where the hairline alone is invisible.
++ pub card_shadow_alpha: f32,
++ pub pop_shadow_alpha: f32,
++ pub pop_shadow_offset: f32,
++ pub pop_shadow_blur: f32,
++}
++
++impl EditorPalette {
++ pub fn light() -> Self {
++ Self {
++ window: rgb(0xf1f1f3),
++ card: rgb(0xffffff),
++ card_2: rgb(0xf6f6f7),
++ stage: rgb(0xe9e9ec),
++ line: rgba(0x00000013),
++ line_strong: rgba(0x0000001f),
++ text_1: rgb(0x1c1c1e),
++ text_2: rgb(0x6e6e75),
++ text_3: rgb(0xa0a0a8),
++ ctl: rgba(0x0000000b),
++ ctl_hover: rgba(0x00000013),
++ ctl_active: rgba(0x0000001c),
++ accent: rgb(0x007aff),
++ accent_2: rgb(0x2b8cff),
++ playhead: rgb(0xff3b30),
++ thumb: rgb(0xffffff),
++ seg_tint: 0.13,
++ seg_line: 0.34,
++ seg_label_base: rgb(0x000000),
++ seg_label_mix: 0.58,
++ card_shadow_alpha: 0.04,
++ pop_shadow_alpha: 0.25,
++ pop_shadow_offset: 12.,
++ pop_shadow_blur: 32.,
++ }
++ }
++
++ pub fn dark() -> Self {
++ Self {
++ window: rgb(0x131315),
++ card: rgb(0x1b1b1e),
++ card_2: rgb(0x202024),
++ stage: rgb(0x121214),
++ line: rgba(0xffffff14),
++ line_strong: rgba(0xffffff21),
++ text_1: rgb(0xf4f4f5),
++ text_2: rgb(0x9a9aa3),
++ text_3: rgb(0x62626a),
++ ctl: rgba(0xffffff0f),
++ ctl_hover: rgba(0xffffff17),
++ ctl_active: rgba(0xffffff21),
++ accent: rgb(0x0a84ff),
++ accent_2: rgb(0x3d9bff),
++ playhead: rgb(0xff453a),
++ thumb: rgb(0xe8e8ea),
++ seg_tint: 0.20,
++ seg_line: 0.42,
++ seg_label_base: rgb(0xffffff),
++ seg_label_mix: 0.55,
++ card_shadow_alpha: 0.30,
++ pop_shadow_alpha: 0.60,
++ pop_shadow_offset: 16.,
++ pop_shadow_blur: 40.,
++ }
++ }
++
++ /// `color-mix(in srgb, color <tint>, card)`: the segment fill.
++ pub fn seg_fill(&self, color: Rgba) -> Rgba {
++ mix(self.card, color, self.seg_tint)
++ }
++
++ /// A selected segment: the tint plus ten points.
++ pub fn seg_fill_selected(&self, color: Rgba) -> Rgba {
++ mix(self.card, color, self.seg_tint + 0.10)
++ }
++
++ /// The segment's 1px inset border.
++ pub fn seg_border(&self, color: Rgba) -> Rgba {
++ rgba_alpha(color, self.seg_line)
++ }
++
++ /// Segment label text.
++ pub fn seg_label(&self, color: Rgba) -> Rgba {
++ mix(self.seg_label_base, color, self.seg_label_mix)
++ }
++
++ /// Segment secondary text (durations, amounts): the label colour at 45%
++ /// toward `text_3`.
++ pub fn seg_muted(&self, color: Rgba) -> Rgba {
++ mix(self.text_3, color, 0.45)
++ }
++
++ /// The track gutter's icon tile: `color 16%` over transparent.
++ pub fn tile_bg(&self, color: Rgba) -> Rgba {
++ rgba_alpha(color, 0.16)
++ }
++
++ /// The tile's glyph: the track colour pulled 62% toward the label base.
++ pub fn tile_fg(&self, color: Rgba) -> Rgba {
++ mix(self.seg_label_base, color, 0.62)
++ }
++
++ /// Trim handles: the colour at 70% toward the label base.
++ pub fn seg_handle(&self, color: Rgba) -> Rgba {
++ mix(self.seg_label_base, color, 0.70)
++ }
++
++ /// `--ed-card-shadow`: `0 1px 2px` under every editor card.
++ pub fn card_shadow(&self) -> Vec<BoxShadow> {
++ vec![BoxShadow {
++ color: gpui::hsla(0., 0., 0., self.card_shadow_alpha),
++ offset: point(px(0.), px(1.)),
++ blur_radius: px(2.),
++ spread_radius: px(0.),
++ inset: false,
++ }]
++ }
++
++ /// `--ed-pop-shadow`: the lift under a menu, popover or dialog.
++ pub fn pop_shadow(&self) -> Vec<BoxShadow> {
++ vec![BoxShadow {
++ color: gpui::hsla(0., 0., 0., self.pop_shadow_alpha),
++ offset: point(px(0.), px(self.pop_shadow_offset)),
++ blur_radius: px(self.pop_shadow_blur),
++ spread_radius: px(-12.),
++ inset: false,
++ }]
++ }
++}
++
++/// The drop shadow under the stage's letterboxed preview. The stage is nearly
++/// black in both themes, so this one does not vary with the appearance.
++pub fn preview_shadow() -> Vec<BoxShadow> {
++ vec![BoxShadow {
++ color: gpui::hsla(0., 0., 0., 0.35),
++ offset: point(px(0.), px(12.)),
++ blur_radius: px(32.),
++ spread_radius: px(-8.),
++ inset: false,
++ }]
++}
++
++/// The drop shadow under a slider knob.
++pub fn thumb_shadow() -> Vec<BoxShadow> {
++ vec![BoxShadow {
++ color: gpui::hsla(0., 0., 0., 0.25),
++ offset: point(px(0.), px(1.)),
++ blur_radius: px(3.),
++ spread_radius: px(0.),
++ inset: false,
++ }]
++}
++
++/// `color-mix(in srgb, b <t>, a)`: straight sRGB interpolation, which is what
++/// the CSS side does.
++pub fn mix(a: Rgba, b: Rgba, t: f32) -> Rgba {
++ let t = t.clamp(0.0, 1.0);
++ Rgba {
++ r: a.r + (b.r - a.r) * t,
++ g: a.g + (b.g - a.g) * t,
++ b: a.b + (b.b - a.b) * t,
++ a: a.a + (b.a - a.a) * t,
++ }
++}
++
++pub fn rgba_alpha(color: Rgba, alpha: f32) -> Rgba {
++ Rgba { a: alpha, ..color }
}
impl Theme {
@@@ -462,6 -462,6 +667,7 @@@
Self {
appearance: Appearance::Light,
material: None,
++ editor: EditorPalette::light(),
gray_1: rgb(0xfcfcfc),
gray_2: rgb(0xf9f9f9),
@@@ -516,6 -516,6 +722,7 @@@
Self {
appearance: Appearance::Dark,
material: None,
++ editor: EditorPalette::dark(),
// gray 1-6 and 11 are the theme.css overrides, not stock Radix.
gray_1: rgb(0x111111),
diff --cc apps/desktop-gpui/src/ui/color_picker.rs
index 616ab1c1e,616ab1c1e..360308484
--- a/apps/desktop-gpui/src/ui/color_picker.rs
+++ b/apps/desktop-gpui/src/ui/color_picker.rs
@@@ -271,9 -271,9 +271,9 @@@ impl RenderOnce for ColorPicker
.gap(px(GAP))
.rounded(px(12.))
.border_1()
-- .border_color(Hsla::from(theme.gray_3))
-- .bg(Hsla::from(theme.gray_1))
-- .shadow_md()
++ .border_color(Hsla::from(theme.editor.line))
++ .bg(Hsla::from(theme.editor.card))
++ .shadow(theme.editor.pop_shadow())
// A press on the panel body must not fall through to the
// caller's click-away backdrop underneath.
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
diff --cc apps/desktop-gpui/src/ui/editor_button.rs
index 8881f737c,8881f737c..d91892b2d
--- a/apps/desktop-gpui/src/ui/editor_button.rs
+++ b/apps/desktop-gpui/src/ui/editor_button.rs
@@@ -3,16 -3,16 +3,10 @@@
//! player toolbar's triggers, the background section's Reset and Import
//! actions, and every selection panel's Done/Delete pair.
//!
--//! `cva` gives it two variants and a pile of group-driven icon colours. The
--//! two that matter are reproduced:
--//!
--//! - **primary** `text-gray-12 enabled:hover:not-data-pressed:bg-gray-3
--//! data-expanded:bg-gray-3` -- it self-highlights while the popover it
--//! triggers is open;
--//! - **danger** whose *pressed/expanded* state flips to a solid `bg-red-300
--//! text-gray-1` rather than a wash.
--//!
--//! Disabled is `opacity-50 text-gray-11` on both.
++//! Visually it is the editor's ghost button: 28px tall, transparent at rest
++//! with a `text-2` label, `ctl-hover` + `text-1` on hover and `ctl-active`
++//! while pressed. `danger` keeps its solid red pressed state, and `text`
++//! promotes the resting label to `text-1` for the player toolbar's triggers.
//!
use gpui::{
App, ClickEvent, ElementId, Hsla, InteractiveElement, IntoElement, ParentElement, Pixels,
@@@ -48,10 -48,10 +42,13 @@@ pub struct EditorButton
/// `data-pressed` / `data-expanded`.
pressed: bool,
text: Hsla,
++ hover_text: Hsla,
disabled_text: Hsla,
hover_bg: Hsla,
++ active_bg: Hsla,
pressed_bg: Hsla,
pressed_text: Hsla,
++ chevron: Hsla,
tooltip: Option<(Theme, SharedString)>,
on_click: Option<ClickHandler>,
on_open: Option<OpenHandler>,
@@@ -65,17 -65,17 +62,20 @@@ impl EditorButton
left_icon: None,
right_icon: None,
right_icon_end: false,
-- icon_size: px(20.),
-- right_icon_size: px(12.),
++ icon_size: px(16.),
++ right_icon_size: px(10.),
width: None,
variant: EditorButtonVariant::Primary,
disabled: false,
pressed: false,
-- text: Hsla::from(theme.gray_12),
-- disabled_text: Hsla::from(theme.gray_11),
-- hover_bg: Hsla::from(theme.gray_3),
-- pressed_bg: Hsla::from(theme.gray_3),
-- pressed_text: Hsla::from(theme.gray_12),
++ text: Hsla::from(theme.editor.text_2),
++ hover_text: Hsla::from(theme.editor.text_1),
++ disabled_text: Hsla::from(theme.editor.text_3),
++ hover_bg: Hsla::from(theme.editor.ctl_hover),
++ active_bg: Hsla::from(theme.editor.ctl_active),
++ pressed_bg: Hsla::from(theme.editor.ctl_hover),
++ pressed_text: Hsla::from(theme.editor.text_1),
++ chevron: Hsla::from(theme.editor.text_3),
tooltip: None,
on_click: None,
on_open: None,
@@@ -91,6 -91,6 +91,12 @@@
self
}
++ /// The "text" ghost: the resting label is `text-1` rather than `text-2`.
++ pub fn text(mut self, theme: &Theme) -> Self {
++ self.text = Hsla::from(theme.editor.text_1);
++ self
++ }
++
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = Some(label.into());
self
@@@ -168,10 -168,10 +174,13 @@@ impl RenderOnce for EditorButton
disabled,
pressed,
text,
++ hover_text,
disabled_text,
hover_bg,
++ active_bg,
pressed_bg,
pressed_text,
++ chevron,
tooltip,
on_click,
on_open,
@@@ -184,33 -184,33 +193,50 @@@
} else {
text
};
++ // gpui svgs do not inherit a parent's text colour, so the icon follows
++ // the label through a group rather than through the cascade.
++ let group: SharedString = match &id {
++ ElementId::Name(name) => SharedString::from(format!("eb-{name}")),
++ other => SharedString::from(format!("eb-{other:?}")),
++ };
++ let icon_hover = (!disabled && !pressed).then_some(hover_text);
div()
.id(id)
++ .group(group.clone())
.tab_index(0)
.flex()
.flex_row()
.items_center()
-- .px(px(6.))
++ .justify_center()
++ .px(px(7.))
.gap(px(6.))
-- .h(px(32.))
-- .rounded(px(8.))
++ .h(px(28.))
++ .min_w(px(28.))
++ .rounded(px(7.))
.flex_shrink_0()
.when(right_icon_end, |this| this.justify_between())
.when_some(width, |this, width| this.w(width))
-- .text_size(px(14.))
++ .text_size(px(13.))
++ .font_weight(gpui::FontWeight::MEDIUM)
.text_color(foreground)
-- .when(disabled, |this| this.opacity(0.5))
++ .when(disabled, |this| this.opacity(0.45))
.when(pressed, |this| this.bg(pressed_bg))
.when(!disabled && !pressed, |this| {
-- this.cursor_pointer().hover(|this| this.bg(hover_bg))
++ this.cursor_pointer()
++ .hover(move |this| this.bg(hover_bg).text_color(hover_text))
++ .active(move |this| this.bg(active_bg))
})
.children(left_icon.map(|icon| {
++ let group = group.clone();
svg()
.path(icon)
.size(icon_size)
.flex_shrink_0()
.text_color(foreground)
++ .when_some(icon_hover, |this, color| {
++ this.group_hover(group, move |style| style.text_color(color))
++ })
}))
.children(label.map(|label| div().truncate().child(label)))
.children(right_icon.map(|icon| {
@@@ -219,7 -219,7 +245,7 @@@
.size(right_icon_size)
.flex_shrink_0()
.when(right_icon_end, |this| this.ml_auto())
-- .text_color(foreground)
++ .text_color(if disabled { disabled_text } else { chevron })
}))
.when_some(tooltip, |this, (theme, label)| {
this.tooltip_show_delay(crate::ui::TOOLTIP_SHOW_DELAY)
diff --cc apps/desktop-gpui/src/ui/field.rs
index 7e407280b,7e407280b..3f3bdbfec
--- a/apps/desktop-gpui/src/ui/field.rs
+++ b/apps/desktop-gpui/src/ui/field.rs
@@@ -1,24 -1,24 +1,50 @@@
//! `Field` and `Subfield` -- the config sidebar's two labelled setting
//! containers (`routes/editor/ui.tsx:25-69`).
//!
--//! They are layout-only in the source and layout-only here: a `Field` is a
--//! header row (icon, name, optional badge pill, optional right-aligned slot)
--//! stacked `gap-4` above whatever control it wraps, and a `Subfield` is a
--//! single `justify-between` row of label and control. Between them they carry
--//! every section header in the sidebar, so their spacing is load-bearing -- the
--//! background tab's rhythm is `gap-6` between fields and `gap-4` inside one.
++//! They are layout-only in the source and layout-only here. `Field` has four
++//! shapes:
++//!
++//! | shape | used for | header |
++//! |---|---|---|
++//! | `plain` | the export flow and the screenshot editor | 13px/600 with an icon |
++//! | `section` | a sidebar group title, with an optional trailing ghost action | 12px/500 `text_2` |
++//! | `stacked` | a complex control that cannot sit on one row | 13px/400 `text_1` |
++//! | `inline` | one control on a 34px row: label, control, value | 13px/400 `text_1` |
++//!
++//! `Subfield` is the inline row for controls whose label is a sentence rather
++//! than a column heading.
//!
//! `ui.tsx` is imported by the settings pages and the main window too, which is
//! why these live in the shared library rather than next to the editor window.
++use std::sync::Arc;
++
use gpui::{
-- AnyElement, FontWeight, Hsla, IntoElement, ParentElement, Pixels, RenderOnce, SharedString,
-- Styled, Window, div, prelude::FluentBuilder, px, svg,
++ AnyElement, FontFeatures, FontWeight, Hsla, IntoElement, ParentElement, Pixels, RenderOnce,
++ SharedString, Styled, Window, div, prelude::FluentBuilder, px, svg,
};
use crate::theme::Theme;
--/// `<Field>`: `flex flex-col gap-4` with a header row above the children.
++/// The label column every inline row shares, so a column of sliders starts at
++/// the same x.
++const INLINE_LABEL_WIDTH: f32 = 96.;
++const INLINE_ROW_HEIGHT: f32 = 34.;
++const INLINE_VALUE_WIDTH: f32 = 36.;
++
++fn tabular_numerals() -> FontFeatures {
++ FontFeatures(Arc::new(vec![("tnum".to_string(), 1)]))
++}
++
++#[derive(Debug, Clone, Copy, PartialEq, Eq)]
++enum FieldStyle {
++ Plain,
++ Section,
++ Stacked,
++ Inline,
++}
++
++/// `<Field>`: a header row above the children, or -- inline -- one row.
#[derive(IntoElement)]
pub struct Field {
name: SharedString,
@@@ -29,9 -29,9 +55,14 @@@
badge: Option<SharedString>,
/// The `ml-auto` slot. Every header toggle in the sidebar lives here.
value: Option<AnyElement>,
++ /// The inline row's right-hand readout.
++ value_text: Option<SharedString>,
children: Vec<AnyElement>,
gap: Pixels,
++ style: FieldStyle,
text: Hsla,
++ muted: Hsla,
++ value_color: Hsla,
disabled_text: Hsla,
badge_bg: Hsla,
badge_text: Hsla,
@@@ -39,26 -39,26 +70,48 @@@
}
impl Field {
-- /// The editor surface: Radix, no material.
-- pub fn plain(theme: &Theme, name: impl Into<SharedString>) -> Self {
++ fn new(theme: &Theme, name: impl Into<SharedString>, style: FieldStyle, gap: Pixels) -> Self {
Self {
name: name.into(),
icon: None,
icon_size: px(16.),
badge: None,
value: None,
++ value_text: None,
children: Vec::new(),
-- // `gap-4`
-- gap: px(16.),
-- text: Hsla::from(theme.gray_12),
-- // `data-[disabled='true']:text-gray-10`
-- disabled_text: Hsla::from(theme.gray_10),
-- badge_bg: Hsla::from(theme.gray_3),
-- badge_text: Hsla::from(theme.gray_11),
++ gap,
++ style,
++ text: Hsla::from(theme.editor.text_1),
++ muted: Hsla::from(theme.editor.text_2),
++ value_color: Hsla::from(theme.editor.text_3),
++ disabled_text: Hsla::from(theme.editor.text_3),
++ badge_bg: Hsla::from(theme.editor.ctl),
++ badge_text: Hsla::from(theme.editor.text_2),
disabled: false,
}
}
++ /// The editor surface: Radix, no material.
++ pub fn plain(theme: &Theme, name: impl Into<SharedString>) -> Self {
++ Self::new(theme, name, FieldStyle::Plain, px(16.))
++ }
++
++ /// A sidebar group title: 12px/500 `text_2`, no icon, with the group's
++ /// action (`None`, `Save`, `Reset`) in the `value` slot.
++ pub fn section(theme: &Theme, name: impl Into<SharedString>) -> Self {
++ Self::new(theme, name, FieldStyle::Section, px(10.))
++ }
++
++ /// A control that needs its own block under the label.
++ pub fn stacked(theme: &Theme, name: impl Into<SharedString>) -> Self {
++ Self::new(theme, name, FieldStyle::Stacked, px(8.))
++ }
++
++ /// One control on one row: label, control, readout.
++ pub fn inline(theme: &Theme, name: impl Into<SharedString>) -> Self {
++ Self::new(theme, name, FieldStyle::Inline, px(0.))
++ }
++
/// `<IconCapImage class="size-4" />` and friends. Some call sites pass no
/// class at all, which is `text-lg`'s 18px; those pass their own size.
pub fn icon(mut self, icon: impl Into<SharedString>) -> Self {
@@@ -81,6 -81,6 +134,11 @@@
self
}
++ pub fn value_text(mut self, value: impl Into<SharedString>) -> Self {
++ self.value_text = Some(value.into());
++ self
++ }
++
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
@@@ -111,33 -111,33 +169,92 @@@ impl RenderOnce for Field
icon_size,
badge,
value,
++ value_text,
children,
gap,
++ style,
text,
++ muted,
++ value_color,
disabled_text,
badge_bg,
badge_text,
disabled,
} = self;
-- let label_color = if disabled { disabled_text } else { text };
++ let label_color = match (disabled, style) {
++ (true, _) => disabled_text,
++ (false, FieldStyle::Section) => muted,
++ (false, _) => text,
++ };
++
++ if style == FieldStyle::Inline {
++ return div()
++ .flex()
++ .flex_row()
++ .items_center()
++ .h(px(INLINE_ROW_HEIGHT))
++ .gap(px(10.))
++ .child(
++ div()
++ .flex_none()
++ .min_w(px(INLINE_LABEL_WIDTH))
++ .text_size(px(13.))
++ .font_weight(FontWeight::NORMAL)
++ .text_color(label_color)
++ .child(name),
++ )
++ .child(
++ div()
++ .flex_1()
++ .min_w_0()
++ .flex()
++ .flex_row()
++ .items_center()
++ .justify_end()
++ .gap(px(8.))
++ .children(children),
++ )
++ .when_some(value_text, |this, value_text| {
++ this.child(
++ div()
++ .flex_none()
++ .min_w(px(INLINE_VALUE_WIDTH))
++ .text_right()
++ .text_size(px(11.))
++ .font_features(tabular_numerals())
++ .text_color(value_color)
++ .child(value_text),
++ )
++ })
++ .when_some(value, |this, value| {
++ this.child(div().flex_none().flex().items_center().child(value))
++ });
++ }
++
++ let (label_size, label_weight) = match style {
++ FieldStyle::Section => (px(12.), FontWeight::MEDIUM),
++ FieldStyle::Stacked => (px(13.), FontWeight::NORMAL),
++ _ => (px(13.), FontWeight::SEMIBOLD),
++ };
++ let show_icon = style == FieldStyle::Plain;
div()
.flex()
.flex_col()
.gap(gap)
.child(
-- // `flex flex-row items-center gap-1.5 text-gray-12 font-medium
-- // text-sm`
div()
.flex()
.flex_row()
.items_center()
.gap(px(6.))
-- .text_size(px(14.))
-- .font_weight(FontWeight::MEDIUM)
++ .when(style == FieldStyle::Section, |this| this.min_h(px(22.)))
++ .text_size(label_size)
++ .font_weight(label_weight)
.text_color(label_color)
.children(
-- icon.map(|icon| svg().path(icon).size(icon_size).text_color(label_color)),
++ icon.filter(|_| show_icon)
++ .map(|icon| svg().path(icon).size(icon_size).text_color(label_color)),
)
.child(name)
.children(badge.map(|badge| {
@@@ -159,8 -159,8 +276,7 @@@
}
}
--/// `<Subfield>`: `flex flex-row justify-between items-center`, label
--/// `font-medium text-gray-12`, control on the right.
++/// `<Subfield>`: one 34px row of label and control, the control at the end.
#[derive(IntoElement)]
pub struct Subfield {
name: SharedString,
@@@ -179,8 -179,8 +295,8 @@@ impl Subfield
required: false,
children: Vec::new(),
gap: None,
-- text: Hsla::from(theme.gray_12),
-- accent: Hsla::from(theme.blue_500),
++ text: Hsla::from(theme.editor.text_1),
++ accent: Hsla::from(theme.editor.accent),
}
}
@@@ -217,13 -217,13 +333,16 @@@ impl RenderOnce for Subfield
.flex_row()
.justify_between()
.items_center()
++ .min_h(px(INLINE_ROW_HEIGHT))
.when_some(gap, |this, gap| this.gap(gap))
.child(
div()
.flex()
.flex_row()
.items_center()
-- .font_weight(FontWeight::MEDIUM)
++ .flex_none()
++ .text_size(px(13.))
++ .font_weight(FontWeight::NORMAL)
.text_color(text)
.child(name)
.when(required, |this| {
diff --cc apps/desktop-gpui/src/ui/menu.rs
index f19ed5b21,f19ed5b21..eefeebe02
--- a/apps/desktop-gpui/src/ui/menu.rs
+++ b/apps/desktop-gpui/src/ui/menu.rs
@@@ -156,6 -156,6 +156,8 @@@ pub struct Menu
highlighted: Option<usize>,
min_width: Pixels,
max_height: Pixels,
++ radius: Pixels,
++ shadow: Vec<gpui::BoxShadow>,
bg: Hsla,
border: Hsla,
hover: Hsla,
@@@ -184,6 -184,6 +186,8 @@@ impl Menu
highlighted: state.visible_highlight(),
min_width: px(180.),
max_height: px(320.),
++ radius: px(8.),
++ shadow: Vec::new(),
bg,
border: theme.settings_border(),
hover: theme.settings_hover(),
@@@ -210,6 -210,6 +214,24 @@@
}
}
++ /// The editor's popovers: an `ed-card` panel behind an `ed-line` hairline.
++ pub fn editor(
++ theme: &Theme,
++ id: impl Into<ElementId>,
++ items: Vec<MenuItem>,
++ state: &MenuState,
++ ) -> Self {
++ Self {
++ radius: px(12.),
++ shadow: theme.editor.pop_shadow(),
++ bg: Hsla::from(theme.editor.card),
++ border: Hsla::from(theme.editor.line),
++ hover: Hsla::from(theme.editor.ctl_hover),
++ text: Hsla::from(theme.editor.text_1),
++ ..Self::settings(theme, id, items, state)
++ }
++ }
++
pub fn min_width(mut self, width: Pixels) -> Self {
self.min_width = width;
self
@@@ -289,6 -289,6 +311,8 @@@ impl RenderOnce for Menu
highlighted,
min_width,
max_height,
++ radius,
++ shadow,
bg,
border,
hover,
@@@ -345,7 -345,7 +369,8 @@@
.max_h(max_height)
.overflow_y_scroll()
.p(px(4.))
-- .rounded(px(8.))
++ .rounded(radius)
++ .shadow(shadow)
.border_1()
.border_color(border)
.bg(bg)
diff --cc apps/desktop-gpui/src/ui/segmented.rs
index b931ecc05,b931ecc05..aebd871a5
--- a/apps/desktop-gpui/src/ui/segmented.rs
+++ b/apps/desktop-gpui/src/ui/segmented.rs
@@@ -85,6 -85,6 +85,7 @@@ pub struct SegmentedControl
container_border: Option<Hsla>,
item_padding_x: Pixels,
item_padding_y: Pixels,
++ item_height: Option<Pixels>,
item_radius: Pixels,
item_gap: Pixels,
text_size: Pixels,
@@@ -111,6 -111,6 +112,7 @@@ impl SegmentedControl
container_border: None,
item_padding_x: px(12.),
item_padding_y: px(4.),
++ item_height: None,
item_radius: px(6.),
item_gap: px(6.),
text_size: px(12.),
@@@ -158,6 -158,6 +160,29 @@@
}
}
++ /// The editor's segmented control: an `ed-ctl` trough with a raised
++ /// `ed-card` pill on the selected item (a white 12% wash in dark, where a
++ /// lifted card would read as a hole).
++ pub fn editor(theme: &Theme, id: impl Into<ElementId>, options: Vec<SegmentOption>) -> Self {
++ let editor = theme.editor;
++ Self {
++ container_bg: Some(Hsla::from(editor.ctl)),
++ container_border: None,
++ item_padding_x: px(10.),
++ item_padding_y: px(0.),
++ item_height: Some(px(24.)),
++ selected_bg: Some(if theme.is_dark() {
++ gpui::hsla(0., 0., 1., 0.12)
++ } else {
++ Hsla::from(editor.card)
++ }),
++ selected_text: Hsla::from(editor.text_1),
++ idle_text: Hsla::from(editor.text_2),
++ hover_bg: Some(Hsla::from(editor.ctl_hover)),
++ ..Self::base(theme, id, options)
++ }
++ }
++
/// The text-align icon grid: `grid grid-cols-N gap-1 rounded-lg border
/// border-gray-3 bg-gray-2 p-1`, selected `bg-gray-5 text-gray-12`.
pub fn icons(theme: &Theme, id: impl Into<ElementId>, options: Vec<SegmentOption>) -> Self {
@@@ -184,6 -184,6 +209,11 @@@
self
}
++ pub fn item_height(mut self, height: Pixels) -> Self {
++ self.item_height = Some(height);
++ self
++ }
++
pub fn item_padding(mut self, x: Pixels, y: Pixels) -> Self {
self.item_padding_x = x;
self.item_padding_y = y;
@@@ -213,6 -213,6 +243,7 @@@ impl RenderOnce for SegmentedControl
container_border,
item_padding_x,
item_padding_y,
++ item_height,
item_radius,
item_gap,
text_size,
@@@ -257,7 -257,7 +288,10 @@@
.justify_center()
.gap(item_gap)
.px(item_padding_x)
-- .py(item_padding_y)
++ .when(f32::from(item_padding_y) > 0., |this| {
++ this.py(item_padding_y)
++ })
++ .when_some(item_height, |this, height| this.h(height))
.rounded(item_radius)
.text_size(text_size)
.when(stretch, |this| this.flex_1())
diff --cc apps/desktop-gpui/src/ui/select.rs
index 07db73057,07db73057..172d2d398
--- a/apps/desktop-gpui/src/ui/select.rs
+++ b/apps/desktop-gpui/src/ui/select.rs
@@@ -74,28 -74,28 +74,23 @@@ impl Select
}
}
-- /// The editor's `KSelect.Trigger`: `flex items-center gap-2 h-9 px-3
-- /// rounded-lg border border-gray-3 bg-gray-2 dark:bg-gray-3 text-sm
-- /// text-gray-12`.
++ /// The editor's `KSelect.Trigger`: a borderless `ed-ctl` pill.
pub fn plain(theme: &Theme, id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
Self {
-- padding_x: px(12.),
++ padding_x: px(10.),
padding_y: px(0.),
-- height: Some(px(36.)),
-- text_size: px(14.),
++ height: Some(px(30.)),
++ radius: px(7.),
++ text_size: px(13.),
// `KSelect.Value` is `text-sm ... font-normal`, which opts out of
// `body`'s Medium (`ConfigSidebar.tsx:740`, `:3121`, `:3173`,
// `:3369`, `:5283`, `:5380`).
weight: FontWeight::NORMAL,
-- bg: Some(if theme.is_dark() {
-- Hsla::from(theme.gray_3)
-- } else {
-- Hsla::from(theme.gray_2)
-- }),
-- border: Some(Hsla::from(theme.gray_3)),
-- text: Hsla::from(theme.gray_12),
-- chevron: Hsla::from(theme.gray_11),
-- chevron_size: px(16.),
++ bg: Some(Hsla::from(theme.editor.ctl)),
++ border: None,
++ text: Hsla::from(theme.editor.text_1),
++ chevron: Hsla::from(theme.editor.text_3),
++ chevron_size: px(12.),
gap: px(8.),
..Self::settings(theme, id, label)
}
@@@ -165,6 -165,6 +160,7 @@@ impl RenderOnce for Select
.rounded(radius)
.when_some(border, |this, border| this.border_1().border_color(border))
.when_some(bg, |this, bg| this.bg(bg))
++ .when(!disabled, |this| this.cursor_pointer())
.text_size(text_size)
// The label is the only text under here -- the chevron is an svg.
.font_weight(weight)
diff --cc apps/desktop-gpui/src/ui/selection_header.rs
index 13a8717cf,13a8717cf..e0d56fbda
--- a/apps/desktop-gpui/src/ui/selection_header.rs
+++ b/apps/desktop-gpui/src/ui/selection_header.rs
@@@ -68,8 -68,8 +68,8 @@@ impl SelectionHeader
id: id.into(),
label: label.into(),
select_all: None,
-- label_color: Hsla::from(theme.gray_10),
-- action_color: Hsla::from(theme.blue_11),
++ label_color: Hsla::from(theme.editor.text_2),
++ action_color: Hsla::from(theme.editor.accent),
theme: *theme,
on_done: None,
on_delete: None,
@@@ -134,7 -134,7 +134,7 @@@ impl RenderOnce for SelectionHeader
)
.child(
div()
-- .text_size(px(14.))
++ .text_size(px(12.))
.text_color(label_color)
.child(label),
)
@@@ -142,7 -142,7 +142,7 @@@
this.child(
div()
.id(SharedString::from(format!("{id}-select-all")))
-- .text_size(px(14.))
++ .text_size(px(12.))
.font_weight(FontWeight::MEDIUM)
.text_color(action_color)
.cursor_pointer()
diff --cc apps/desktop-gpui/src/ui/slider.rs
index c249da706,c249da706..315fad2ef
--- a/apps/desktop-gpui/src/ui/slider.rs
+++ b/apps/desktop-gpui/src/ui/slider.rs
@@@ -89,11 -89,11 +89,12 @@@ pub struct Slider
on_drag_start: Option<DragStartHandler>,
}
--#[derive(Debug, Clone, Copy)]
++#[derive(Debug, Clone)]
struct ThumbStyle {
size: Pixels,
fill: Hsla,
border: Option<Hsla>,
++ shadow: Vec<gpui::BoxShadow>,
/// The thumb's `top`. Defaults to centring it over the track; the settings
/// zoom slider sits one pixel high of centre and that is transcribed, not
/// corrected.
@@@ -155,11 -155,11 +156,21 @@@ impl Slider
size,
fill,
border,
++ shadow: Vec::new(),
top,
});
self
}
++ /// A knob that has to read on a light track needs the lift the CSS one
++ /// gets from `0 1px 3px rgba(0,0,0,.25)`.
++ pub fn thumb_shadow(mut self) -> Self {
++ if let Some(thumb) = self.thumb.as_mut() {
++ thumb.shadow = crate::theme::thumb_shadow();
++ }
++ self
++ }
++
pub fn thumb_top(mut self, top: Pixels) -> Self {
if let Some(thumb) = self.thumb.as_mut() {
thumb.top = top;
@@@ -266,6 -266,6 +277,7 @@@ impl RenderOnce for Slider
.size(thumb.size)
.rounded_full()
.bg(thumb.fill)
++ .shadow(thumb.shadow.clone())
.when_some(thumb.border, |this, border| {
this.border_1().border_color(border)
})
diff --cc apps/desktop-gpui/src/ui/tab_rail.rs
index 3d2e3a6c7,3d2e3a6c7..81208c1fc
--- a/apps/desktop-gpui/src/ui/tab_rail.rs
+++ b/apps/desktop-gpui/src/ui/tab_rail.rs
@@@ -11,6 -11,6 +11,10 @@@
//! The indicator does not slide (no transform in this gpui rev); the selected
//! item paints the `size-9 rounded-lg bg-gray-3` box itself, which is what the
//! editor window has always done.
++//!
++//! Each tab is exactly one element -- the pill. A wrapper carrying the hit box,
++//! the tooltip anchor or a focus ring would paint its own square corners around
++//! the pill's radius, which is what the first pass shipped.
use gpui::{
App, ElementId, Hsla, InteractiveElement, IntoElement, ParentElement, Pixels, RenderOnce,
@@@ -22,14 -22,14 +26,23 @@@ use crate::theme::Theme
#[derive(Debug, Clone)]
pub struct TabRailItem {
pub icon: SharedString,
++ /// The tab's name. It is not drawn -- the rail is icon-only -- so it is
++ /// carried as the tooltip instead.
++ pub label: SharedString,
pub selected: bool,
pub disabled: bool,
}
impl TabRailItem {
-- pub fn new(icon: impl Into<SharedString>, selected: bool, disabled: bool) -> Self {
++ pub fn new(
++ icon: impl Into<SharedString>,
++ label: impl Into<SharedString>,
++ selected: bool,
++ disabled: bool,
++ ) -> Self {
Self {
icon: icon.into(),
++ label: label.into(),
selected,
disabled,
}
@@@ -46,19 -46,19 +59,21 @@@ pub struct TabRail
items: Vec<TabRailItem>,
height: Pixels,
box_size: Pixels,
++ box_width: Pixels,
icon_size: Pixels,
bg: Hsla,
border: Hsla,
indicator: Hsla,
++ hover: Hsla,
selected_icon: Hsla,
idle_icon: Hsla,
++ theme: Theme,
on_select: Option<TabHandler>,
}
impl TabRail {
-- /// The editor's config sidebar rail: an `h-16` bar over `bg-gray-1
-- /// dark:bg-gray-2` with a `border-b border-gray-3`, `size-9` boxes and
-- /// `text-lg` (18px) icons.
++ /// The editor's config sidebar rail: a 46px bar on the card surface under
++ /// an `ed-line` hairline, with 40x30 tab boxes and 16px icons.
pub fn editor(
theme: &Theme,
id: impl Into<ElementId>,
@@@ -68,14 -68,14 +83,17 @@@
Self {
id: id.into(),
items,
-- height: px(64.),
-- box_size: px(36.),
-- icon_size: px(18.),
++ height: px(46.),
++ box_size: px(30.),
++ box_width: px(40.),
++ icon_size: px(16.),
bg: panel_bg,
-- border: Hsla::from(theme.gray_3),
-- indicator: Hsla::from(theme.gray_3),
-- selected_icon: Hsla::from(theme.gray_12),
-- idle_icon: Hsla::from(theme.gray_11),
++ border: Hsla::from(theme.editor.line),
++ indicator: Hsla::from(theme.editor.ctl_hover),
++ hover: Hsla::from(theme.editor.ctl),
++ selected_icon: Hsla::from(theme.editor.text_1),
++ idle_icon: Hsla::from(theme.editor.text_2),
++ theme: *theme,
on_select: None,
}
}
@@@ -100,12 -100,12 +118,15 @@@ impl RenderOnce for TabRail
items,
height,
box_size,
++ box_width,
icon_size,
bg,
border,
indicator,
++ hover,
selected_icon,
idle_icon,
++ theme,
on_select,
} = self;
@@@ -124,6 -124,6 +145,8 @@@
.h(height)
.flex_none()
.overflow_hidden()
++ .justify_around()
++ .px(px(10.))
.border_b_1()
.border_color(border)
.bg(bg)
@@@ -131,36 -131,36 +154,29 @@@
let handler = handler.clone();
let selected = item.selected;
let disabled = item.disabled;
++ let label = item.label.clone();
-- // Trigger: `flex relative z-10 flex-1 justify-center
-- // items-center px-4 py-2`.
div()
.id(SharedString::from(format!("{prefix}-{index}")))
-- .tab_index(0)
-- .relative()
.flex()
-- .flex_1()
-- .justify_center()
++ .flex_none()
.items_center()
-- .px(px(16.))
-- .py(px(8.))
-- .when(disabled, |this| this.opacity(0.5))
++ .justify_center()
++ .h(box_size)
++ .w(box_width)
++ .rounded(px(9.))
++ .when(disabled, |this| this.opacity(0.6))
++ .when(selected, |this| this.bg(indicator))
++ .when(!selected && !disabled, |this| {
++ this.cursor_pointer().hover(move |style| style.bg(hover))
++ })
++ .tooltip_show_delay(crate::ui::TOOLTIP_SHOW_DELAY)
++ .tooltip(move |_, cx| crate::ui::Tooltip::new(&theme, label.clone()).view(cx))
.child(
-- // The icon box and, under it, the selection pill: both
-- // `size-9`, the pill `rounded-lg bg-gray-3`.
-- div()
-- .flex()
-- .items_center()
-- .justify_center()
-- .size(box_size)
-- .rounded(px(8.))
-- .when(selected, |this| this.bg(indicator))
-- .child(
-- svg()
-- .path(item.icon)
-- .size(icon_size)
-- .text_color(if selected { selected_icon } else { idle_icon }),
-- ),
++ svg()
++ .path(item.icon)
++ .size(icon_size)
++ .text_color(if selected { selected_icon } else { idle_icon }),
)
.when_some(handler.filter(|_| !disabled), |this, handler| {
this.on_click(move |_, window, cx| handler(&index, window, cx))
diff --cc apps/desktop-gpui/src/ui/text_input.rs
index 9b889fd00,9b889fd00..88bc8eb30
--- a/apps/desktop-gpui/src/ui/text_input.rs
+++ b/apps/desktop-gpui/src/ui/text_input.rs
@@@ -1671,9 -1671,9 +1671,15 @@@ impl TextInput
/// sidebar's hex inputs.
pub fn plain(theme: &Theme, id: impl Into<ElementId>, state: &Entity<TextInputState>) -> Self {
Self {
-- bg: Some(theme.gray(1)),
-- border: Some(theme.gray(4)),
-- focus_border: Some(theme.gray(7)),
++ radius: px(7.),
++ text_size: px(13.),
++ bg: Some(Hsla::from(theme.editor.ctl)),
++ border: None,
++ focus_border: Some(Hsla::from(theme.editor.accent)),
++ text: Hsla::from(theme.editor.text_1),
++ muted: Hsla::from(theme.editor.text_3),
++ icon_color: Hsla::from(theme.editor.text_3),
++ caret_color: Hsla::from(theme.editor.text_1),
..Self::base(theme, id, state)
}
}
diff --cc apps/desktop-gpui/src/ui/toggle.rs
index 64a0b05c5,64a0b05c5..72d9f0197
--- a/apps/desktop-gpui/src/ui/toggle.rs
+++ b/apps/desktop-gpui/src/ui/toggle.rs
@@@ -27,7 -27,7 +27,7 @@@ pub enum ToggleSize
impl ToggleSize {
fn track(self) -> (Pixels, Pixels, Pixels) {
match self {
-- ToggleSize::Sm => (px(36.), px(20.), px(2.)),
++ ToggleSize::Sm => (px(34.), px(20.), px(2.)),
ToggleSize::Md => (px(44.), px(24.), px(2.)),
ToggleSize::Lg => (px(56.), px(28.), px(3.)),
}
@@@ -58,14 -58,14 +58,14 @@@ pub struct Toggle
}
impl Toggle {
-- /// The plain Radix track: `bg-gray-6`, checked `bg-blue-500`.
++ /// The editor track: `ed-ctl-active` off, `ed-accent` on, white knob.
pub fn plain(theme: &Theme, id: impl Into<ElementId>, checked: bool) -> Self {
Self {
id: id.into(),
checked,
-- size: ToggleSize::Md,
-- off_fill: Hsla::from(theme.gray_6),
-- on_fill: Hsla::from(theme.blue_500),
++ size: ToggleSize::Sm,
++ off_fill: Hsla::from(theme.editor.ctl_active),
++ on_fill: Hsla::from(theme.editor.accent),
thumb: gpui::white(),
disabled: false,
on_click: None,
@@@ -104,11 -104,11 +104,10 @@@
self
}
-- /// `data-disabled:bg-gray-3`.
pub fn disabled(mut self, theme: &Theme, disabled: bool) -> Self {
self.disabled = disabled;
if disabled && !self.checked {
-- self.off_fill = Hsla::from(theme.gray_3);
++ self.off_fill = Hsla::from(theme.editor.ctl);
}
self
}
@@@ -148,6 -148,6 +147,7 @@@ impl RenderOnce for Toggle
// `data-checked:translate-x-[calc(100%)]` on the thumb -- the same
// end position a flex justification reaches, without a transform.
.when(checked, |this| this.justify_end())
++ .when(!disabled, |this| this.cursor_pointer())
.bg(if checked { on_fill } else { off_fill })
.child(div().size(size.thumb()).rounded_full().bg(thumb))
.when_some(on_click.filter(|_| !disabled), |this, handler| {
diff --cc apps/desktop/src-tauri/Cargo.toml
index 7bc6bba7d,9ecd55089..8e3205312
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@@ -127,6 -127,6 +127,7 @@@ aho-corasick.workspace = tru
[target.'cfg(target_os = "macos")'.dependencies]
++block2 = "0.6.1"
core-graphics = "0.24.0"
core-foundation = "0.10.0"
objc2-app-kit = { version = "0.3.0", features = [
diff --cc apps/desktop/src-tauri/build.rs
index 822939282,822939282..b76325a59
--- a/apps/desktop/src-tauri/build.rs
+++ b/apps/desktop/src-tauri/build.rs
@@@ -1,4 -1,4 +1,8 @@@
++#[path = "../../../scripts/diagnostic-build.rs"]
++mod diagnostic_build;
++
fn main() {
++ diagnostic_build::emit();
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows")
&& std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc")
{
diff --cc apps/desktop/src-tauri/src/clean_capture.rs
index ddce0399c,509ec1aff..f4156327a
--- a/apps/desktop/src-tauri/src/clean_capture.rs
+++ b/apps/desktop/src-tauri/src/clean_capture.rs
@@@ -138,77 -131,6 +138,77 @@@ struct ControlError
message: String,
}
+#[derive(Clone)]
+pub(crate) struct StopNoticeOwner {
+ sequence: u64,
+ directory: PathBuf,
+ generation: Option<u32>,
+ confirmed: Arc<AtomicBool>,
+}
+
+impl StopNoticeOwner {
+ pub(crate) fn is_confirmed(&self) -> bool {
+ self.confirmed.load(Ordering::Acquire)
+ }
+
+ pub(crate) fn same_attempt(&self, other: &Self) -> bool {
+ Arc::ptr_eq(&self.confirmed, &other.confirmed)
+ }
+}
+
+#[derive(Clone)]
+pub(crate) struct StopNoticeTicket {
+ sequence: u64,
+ pub(crate) owner: StopNoticeOwner,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(crate) enum StopNoticeKind {
+ Unconfirmed,
+ ConfirmedFailure,
+ ControlFailure,
+}
+
+struct StopNotice {
+ ticket: StopNoticeTicket,
+ kind: StopNoticeKind,
+ message: String,
+ previous_message: Option<String>,
+ restoration: Option<Result<(), String>>,
+}
+
+impl StopNotice {
+ fn error(&self) -> String {
+ let confirmed =
+ self.ticket.owner.is_confirmed() || self.kind == StopNoticeKind::ConfirmedFailure;
+ let status = if confirmed {
+ match (&self.restoration, self.ticket.owner.generation) {
+ (Some(Err(_)), _) => "Recording stopped; window restoration failed",
+ (None, Some(_)) => "Recording stopped; window restoration is pending",
+ _ => "Recording stopped",
+ }
+ } else {
+ "Stop could not be confirmed"
+ };
+ let mut message = format!(
+ "{status} ({}): {}",
+ self.ticket.owner.directory.display(),
+ self.message
+ );
+ if let Some(previous) = &self.previous_message {
- message.push_str("\n");
++ message.push('\n');
+ message.push_str(previous);
+ }
+ if let Some(Err(error)) = &self.restoration
+ && !self.message.contains(error)
+ {
- message.push_str("\n");
++ message.push('\n');
+ message.push_str(error);
+ }
+ message
+ }
+}
+
struct RestorationReceipt {
generation: u32,
result: Result<(), String>,
@@@ -2284,1584 -1986,1584 +2284,1393 @@@ pub async fn reveal_capture_window
reveal_with_options(window, generation, main, main).await
}
--#[cfg(test)]
--mod tests {
++#[cfg(all(test, target_os = "linux"))]
++mod instant_activation_tests {
use super::*;
++ use std::sync::{
++ Arc,
++ atomic::{AtomicUsize, Ordering},
++ };
-- #[test]
-- fn wayland_blocks_all_floating_labels_while_capture_can_run() {
-- for mode in [
-- cap_recording::RecordingMode::Studio,
-- cap_recording::RecordingMode::Instant,
-- ] {
-- for phase in [
-- Phase::Starting,
-- Phase::Recording,
-- Phase::Pausing,
-- Phase::Resuming,
-- Phase::ResumeFailed,
-- Phase::Restarting,
-- Phase::Stopping,
-- ] {
-- let mut inner = fixture();
-- let lease = inner.lease.as_mut().unwrap();
-- lease.mode = mode;
-- lease.wayland = true;
-- lease.phase = phase;
-- for label in [
-- "main",
-- "camera",
-- "teleprompter",
-- "settings",
-- "editor-4",
-- "unknown-js-window",
-- ] {
-- assert!(!inner.may_reveal(1, label), "{phase:?}: {label}");
-- }
-- }
-- }
++ #[tokio::test]
++ async fn instant_seal_waits_for_hide_ack_then_settle_then_revalidates() {
++ let (hide_tx, hide_rx) = tokio::sync::oneshot::channel();
++ let (settle_tx, settle_rx) = tokio::sync::oneshot::channel();
++ let (settling_tx, settling_rx) = tokio::sync::oneshot::channel();
++ let stage = Arc::new(AtomicUsize::new(0));
++ let observed = stage.clone();
++ let task = tokio::spawn(async move {
++ let validated = observed.clone();
++ seal_then_settle(
++ async { hide_rx.await.map_err(|_| "hide ack lost".to_string()) },
++ async {
++ observed.store(1, Ordering::SeqCst);
++ settling_tx.send(()).unwrap();
++ settle_rx.await.map_err(|_| "settle cancelled".to_string())
++ },
++ |owner| async move {
++ validated.store(2, Ordering::SeqCst);
++ Ok(owner)
++ },
++ )
++ .await
++ });
++ tokio::task::yield_now().await;
++ assert_eq!(stage.load(Ordering::SeqCst), 0);
++ assert!(!task.is_finished());
++ hide_tx.send(7).unwrap();
++ settling_rx.await.unwrap();
++ assert_eq!(stage.load(Ordering::SeqCst), 1);
++ assert!(!task.is_finished());
++ settle_tx.send(()).unwrap();
++ assert_eq!(task.await.unwrap().unwrap(), 7);
++ assert_eq!(stage.load(Ordering::SeqCst), 2);
}
-- #[test]
-- fn x11_floating_admission_is_unchanged() {
-- let mut inner = fixture();
-- inner.lease.as_mut().unwrap().phase = Phase::Recording;
-- assert!(!inner.lease.as_ref().unwrap().wayland);
-- assert!(inner.may_reveal(1, "teleprompter"));
-- assert!(inner.may_reveal(1, "settings"));
-- assert!(!inner.may_reveal(1, "camera"));
++ #[tokio::test]
++ async fn instant_lost_hide_ack_never_settles_or_builds() {
++ let (tx, rx) = tokio::sync::oneshot::channel::<u32>();
++ drop(tx);
++ let result = seal_then_settle(
++ async { rx.await.map_err(|_| "hide ack lost".to_string()) },
++ async { panic!("settle cannot begin before hide acknowledgement") },
++ |_| async { panic!("build validation cannot begin") },
++ )
++ .await;
++ assert_eq!(result.unwrap_err(), "hide ack lost");
}
-- #[test]
-- fn wayland_restore_keeps_non_camera_window_intent() {
-- for label in ["teleprompter", "settings", "editor-4", "unknown-js-window"] {
-- assert!(restore_floating_window(Some(label)));
-- }
-- assert!(restore_floating_window(None));
-- for label in [
-- "capture-area",
-- "in-progress-recording",
-- "target-select-overlay-1",
-- "window-capture-occluder-1",
-- ] {
-- assert!(!restore_floating_window(Some(label)));
-- }
++ #[tokio::test]
++ async fn instant_cancelled_settle_does_not_revalidate_or_build() {
++ let result = seal_then_settle(
++ async { Ok(7) },
++ async { Err("cancelled".into()) },
++ |_| async { panic!("cancelled preparation cannot build") },
++ )
++ .await;
++ assert_eq!(result.unwrap_err(), "cancelled");
}
-- #[test]
-- fn wayland_safe_ui_phases_allow_mapping_but_old_generation_does_not() {
-- for phase in [Phase::AwaitingShortcut, Phase::Paused, Phase::Restoring] {
-- assert!(!wayland_blocks_mapping(phase));
-- let mut inner = fixture();
-- let lease = inner.lease.as_mut().unwrap();
-- lease.wayland = true;
-- lease.phase = phase;
-- assert!(inner.may_reveal(1, "teleprompter"));
-- assert!(!inner.may_reveal(0, "teleprompter"));
-- }
++ #[tokio::test]
++ async fn instant_changed_effect_or_geometry_after_settle_rejects_owner() {
++ let result = seal_then_settle(async { Ok(7) }, async { Ok(()) }, |owner| async move {
++ assert_eq!(owner, 7);
++ Err("prepared presentation changed".into())
++ })
++ .await;
++ assert_eq!(result.unwrap_err(), "prepared presentation changed");
}
#[tokio::test]
-- async fn restore_pass_waits_for_successful_ack_before_following_work() {
-- let (tx, rx) = tokio::sync::oneshot::channel();
-- let work = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
-- let observed = work.clone();
++ async fn instant_restore_waits_for_main_and_camera_acknowledgements() {
++ let (main_tx, main_rx) = tokio::sync::oneshot::channel();
++ let (camera_tx, camera_rx) = tokio::sync::oneshot::channel();
++ let (inputs_tx, inputs_rx) = tokio::sync::oneshot::channel();
++ let stage = Arc::new(AtomicUsize::new(0));
++ let observed = stage.clone();
let task = tokio::spawn(async move {
-- if restore_pass_acknowledged(true, rx).await {
-- observed.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
-- }
++ restore_instant_sequence(
++ async { main_rx.await.map_err(|_| "main ack lost".to_string()) },
++ || async {
++ observed.store(1, Ordering::SeqCst);
++ inputs_tx.send(()).unwrap();
++ },
++ || async { camera_rx.await.map_err(|_| "camera ack lost".to_string()) },
++ )
++ .await
});
tokio::task::yield_now().await;
++ assert_eq!(stage.load(Ordering::SeqCst), 0);
++ main_tx.send(()).unwrap();
++ inputs_rx.await.unwrap();
++ assert_eq!(stage.load(Ordering::SeqCst), 1);
assert!(!task.is_finished());
-- assert_eq!(work.load(std::sync::atomic::Ordering::SeqCst), 0);
-- tx.send(Ok(())).unwrap();
-- task.await.unwrap();
-- assert_eq!(work.load(std::sync::atomic::Ordering::SeqCst), 1);
++ camera_tx.send(()).unwrap();
++ task.await.unwrap().unwrap();
}
#[tokio::test]
-- async fn rejected_restore_pass_does_not_authorize_following_work() {
-- let (tx, rx) = tokio::sync::oneshot::channel();
-- tx.send(Err("Instant cleanup is unconfirmed".into()))
-- .unwrap();
-- assert!(!restore_pass_acknowledged(true, rx).await);
++ async fn instant_restore_rejected_or_lost_main_ack_never_restores_inputs() {
++ for rejected in [true, false] {
++ let (tx, rx) = tokio::sync::oneshot::channel::<Result<(), String>>();
++ if rejected {
++ tx.send(Err("unsafe cleanup".into())).unwrap();
++ } else {
++ drop(tx);
++ }
++ let result = restore_instant_sequence(
++ async { rx.await.map_err(|_| "main ack lost".to_string())? },
++ || async { panic!("inputs must remain untouched") },
++ || async { panic!("camera must remain hidden") },
++ )
++ .await;
++ assert!(result.is_err());
++ }
}
#[tokio::test]
-- async fn dropped_restore_ack_does_not_authorize_following_work() {
++ async fn instant_open_cap_waits_for_stop_ack_and_never_polls_studio_pause() {
let (tx, rx) = tokio::sync::oneshot::channel();
-- drop(tx);
-- assert!(!restore_pass_acknowledged(true, rx).await);
++ let task = tokio::spawn(finish_main_controls(
++ Some(Phase::Recording),
++ Some(async { rx.await.map_err(|_| "stop ack lost".to_string()) }),
++ async { panic!("Instant OpenCap must not pause") },
++ ));
++ tokio::task::yield_now().await;
++ assert!(!task.is_finished());
++ tx.send(()).unwrap();
++ task.await.unwrap().unwrap();
}
#[tokio::test]
-- async fn unscheduled_restore_pass_does_not_wait_for_an_ack() {
-- let (tx, rx) = tokio::sync::oneshot::channel();
-- assert!(
-- !tokio::time::timeout(
-- std::time::Duration::from_millis(100),
-- restore_pass_acknowledged(false, rx),
-- )
-- .await
-- .unwrap()
-- );
-- assert!(tx.is_closed());
++ async fn instant_open_cap_preserves_stop_failure_without_pause_or_reveal_permission() {
++ let result = finish_main_controls(
++ Some(Phase::Starting),
++ Some(async { Err("capture cleanup unconfirmed".into()) }),
++ async { panic!("Instant OpenCap must not pause") },
++ )
++ .await;
++ assert_eq!(result.unwrap_err(), "capture cleanup unconfirmed");
}
-- #[cfg(target_os = "linux")]
-- fn x11_studio_restoring_fixture() -> Mutex<Inner> {
-- let mut inner = fixture();
-- inner.lease.as_mut().unwrap().phase = Phase::Restoring;
-- Mutex::new(inner)
++ #[tokio::test]
++ async fn studio_open_cap_waits_for_pause_ack_before_allowing_reveal() {
++ let (started_tx, started_rx) = tokio::sync::oneshot::channel();
++ let (paused_tx, paused_rx) = tokio::sync::oneshot::channel();
++ let reveals = Arc::new(AtomicUsize::new(0));
++ let observed = reveals.clone();
++ let task = tokio::spawn(async move {
++ finish_main_controls(
++ Some(Phase::Recording),
++ None::<std::future::Ready<Result<(), String>>>,
++ async {
++ started_tx.send(()).unwrap();
++ paused_rx.await.map_err(|_| "pause ack lost".to_string())
++ },
++ )
++ .await?;
++ observed.fetch_add(1, Ordering::SeqCst);
++ Ok::<(), String>(())
++ });
++ started_rx.await.unwrap();
++ assert!(!task.is_finished());
++ assert_eq!(reveals.load(Ordering::SeqCst), 0);
++ paused_tx.send(()).unwrap();
++ task.await.unwrap().unwrap();
++ assert_eq!(reveals.load(Ordering::SeqCst), 1);
}
-- #[cfg(target_os = "linux")]
#[tokio::test]
-- async fn x11_studio_restore_waits_for_windows_before_stop_cleanup_and_receipt() {
-- use std::sync::{
-- Arc,
-- atomic::{AtomicUsize, Ordering},
-- };
-
- let inner = Arc::new(x11_studio_restoring_fixture());
- let inputs = Arc::new(AtomicUsize::new(0));
- let cleanup = Arc::new(AtomicUsize::new(0));
- let (main_tx, main_rx) = tokio::sync::oneshot::channel::<Result<(), String>>();
- let (camera_tx, camera_rx) = tokio::sync::oneshot::channel::<Result<(), String>>();
- let (inputs_tx, inputs_rx) = tokio::sync::oneshot::channel();
- let task = tokio::spawn({
- let inner = inner.clone();
- let inputs = inputs.clone();
- let cleanup = cleanup.clone();
- async move {
- let result = restore_instant_sequence(
- async { main_rx.await.unwrap() },
- || async move {
- inputs.fetch_add(1, Ordering::SeqCst);
- inputs_tx.send(()).unwrap();
- },
- || async { camera_rx.await.unwrap() },
- )
- .await;
- assert!(finish_x11_studio_restoration(&inner, 1, result, || {
- cleanup.fetch_add(1, Ordering::SeqCst);
- Ok(())
- }));
- }
- });
- tokio::task::yield_now().await;
- assert!(!task.is_finished());
- assert_eq!(inputs.load(Ordering::SeqCst), 0);
- assert_eq!(cleanup.load(Ordering::SeqCst), 0);
- assert!(inner.lock().unwrap().restored.is_none());
- main_tx.send(Ok(())).unwrap();
- inputs_rx.await.unwrap();
- assert!(!task.is_finished());
- assert_eq!(inputs.load(Ordering::SeqCst), 1);
- assert_eq!(cleanup.load(Ordering::SeqCst), 0);
- assert!(inner.lock().unwrap().lease.is_some());
- assert!(inner.lock().unwrap().restored.is_none());
- camera_tx.send(Ok(())).unwrap();
- task.await.unwrap();
- let inner = inner.lock().unwrap();
- assert!(inner.lease.is_none());
- assert_eq!(inner.generation, 2);
- let receipt = inner.restored.as_ref().unwrap();
- assert_eq!(receipt.generation, 1);
- assert_eq!(receipt.restart_result(), Ok(()));
- assert_eq!(cleanup.load(Ordering::SeqCst), 1);
++ async fn studio_open_cap_preserves_pause_failure_without_allowing_reveal() {
++ let result: Result<(), String> = async {
++ finish_main_controls(
++ Some(Phase::Recording),
++ None::<std::future::Ready<Result<(), String>>>,
++ async { Err("pause acknowledgement failed".into()) },
++ )
++ .await?;
++ panic!("a failed pause must not permit controls to be revealed")
++ }
++ .await;
++ assert_eq!(result.unwrap_err(), "pause acknowledgement failed");
+ }
- #[cfg(target_os = "linux")]
- #[test]
- fn x11_studio_restore_failures_retain_ownership_and_report_failure_until_retry() {
- for (windows, cleanup, error, cleanup_calls) in [
- (
- Err("window restoration failed".to_string()),
- Ok(()),
- "window restoration failed",
- 0,
- ),
- (
- Ok(()),
- Err("Stop cleanup failed".to_string()),
- "Stop cleanup failed",
- 1,
- ),
- let inner = Arc::new(x11_studio_restoring_fixture());
- let inputs = Arc::new(AtomicUsize::new(0));
- let cleanup = Arc::new(AtomicUsize::new(0));
- let (main_tx, main_rx) = tokio::sync::oneshot::channel::<Result<(), String>>();
- let (camera_tx, camera_rx) = tokio::sync::oneshot::channel::<Result<(), String>>();
- let (inputs_tx, inputs_rx) = tokio::sync::oneshot::channel();
- let task = tokio::spawn({
- let inner = inner.clone();
- let inputs = inputs.clone();
- let cleanup = cleanup.clone();
- async move {
- let result = restore_instant_sequence(
- async { main_rx.await.unwrap() },
- || async move {
- inputs.fetch_add(1, Ordering::SeqCst);
- inputs_tx.send(()).unwrap();
- },
- || async { camera_rx.await.unwrap() },
- )
- .await;
- assert!(finish_x11_studio_restoration(&inner, 1, result, || {
- cleanup.fetch_add(1, Ordering::SeqCst);
- Ok(())
- }));
- }
- });
- tokio::task::yield_now().await;
- assert!(!task.is_finished());
- assert_eq!(inputs.load(Ordering::SeqCst), 0);
- assert_eq!(cleanup.load(Ordering::SeqCst), 0);
- assert!(inner.lock().unwrap().restored.is_none());
- main_tx.send(Ok(())).unwrap();
- inputs_rx.await.unwrap();
- assert!(!task.is_finished());
- assert_eq!(inputs.load(Ordering::SeqCst), 1);
- assert_eq!(cleanup.load(Ordering::SeqCst), 0);
- assert!(inner.lock().unwrap().lease.is_some());
- assert!(inner.lock().unwrap().restored.is_none());
- camera_tx.send(Ok(())).unwrap();
- task.await.unwrap();
- let inner = inner.lock().unwrap();
- assert!(inner.lease.is_none());
- assert_eq!(inner.generation, 2);
- let receipt = inner.restored.as_ref().unwrap();
- assert_eq!(receipt.generation, 1);
- assert_eq!(receipt.restart_result(), Ok(()));
- assert_eq!(cleanup.load(Ordering::SeqCst), 1);
++ #[tokio::test]
++ async fn repeated_studio_open_cap_keeps_the_recording_paused() {
++ for _ in 0..3 {
++ finish_main_controls(
++ Some(Phase::Paused),
++ None::<std::future::Ready<Result<(), String>>>,
++ async { panic!("an already paused recording must not be changed") },
++ )
++ .await
++ .unwrap();
++ }
+ }
+
- #[cfg(target_os = "linux")]
- #[test]
- fn x11_studio_restore_failures_retain_ownership_and_report_failure_until_retry() {
- for (windows, cleanup, error, cleanup_calls) in [
- (
- Err("window restoration failed".to_string()),
- Ok(()),
- "window restoration failed",
- 0,
- ),
- (
- Ok(()),
- Err("Stop cleanup failed".to_string()),
- "Stop cleanup failed",
- 1,
- ),
++ #[tokio::test]
++ async fn studio_open_cap_rejects_pending_transitions_without_changing_capture() {
++ for phase in [
++ Phase::Starting,
++ Phase::Pausing,
++ Phase::Resuming,
++ Phase::ResumeFailed,
++ Phase::Restarting,
++ Phase::Stopping,
] {
-- let state = x11_studio_restoring_fixture();
-- let calls = std::cell::Cell::new(0);
-- assert!(!finish_x11_studio_restoration(&state, 1, windows, || {
-- calls.set(calls.get() + 1);
-- cleanup
-- }));
-- assert_eq!(calls.get(), cleanup_calls);
-- {
-- let inner = state.lock().unwrap();
-- assert_eq!(inner.generation, 1);
-- let lease = inner.lease.as_ref().unwrap();
-- assert_eq!(lease.phase, Phase::Restoring);
-- assert!(lease.registered_shortcut);
-- assert!(inner.x11_cleanup.is_none());
-- assert_eq!(inner.snapshot().error.as_deref(), Some(error));
-- let receipt = inner.restored.as_ref().unwrap();
-- assert_eq!(receipt.generation, 1);
-- assert_eq!(receipt.restart_result(), Err(error.to_string()));
-- }
-- assert!(!finish_x11_studio_restoration(&state, 1, Ok(()), || {
-- panic!("a duplicate completion cannot retry cleanup")
-- }));
-- {
-- let mut inner = state.lock().unwrap();
-- assert_eq!(inner.begin_x11_studio_restore_retry(false), None);
-- assert_eq!(inner.begin_x11_studio_restore_retry(true), Some(1));
-- assert!(inner.lease.as_ref().unwrap().stop_requested);
-- }
-- assert!(finish_x11_studio_restoration(&state, 1, Ok(()), || Ok(())));
-- let inner = state.lock().unwrap();
-- assert!(inner.lease.is_none());
-- assert_eq!(inner.generation, 2);
++ let result = finish_main_controls(
++ Some(phase),
++ None::<std::future::Ready<Result<(), String>>>,
++ async { panic!("a pending recording transition must not be changed") },
++ )
++ .await;
assert_eq!(
-- inner.restored.as_ref().unwrap().restart_result(),
-- Err("Recording restart was cancelled by Stop".into())
++ result.unwrap_err(),
++ "Recording is changing state. Use Ctrl+Shift+F9 to stop."
);
}
}
-- #[cfg(target_os = "linux")]
-- #[test]
-- fn x11_studio_stale_and_duplicate_restore_cannot_release_another_owner() {
-- let state = x11_studio_restoring_fixture();
-- assert!(!finish_x11_studio_restoration(&state, 0, Ok(()), || {
-- panic!("a stale generation must not release the shortcut")
-- }));
-- assert!(state.lock().unwrap().restored.is_none());
-- state.lock().unwrap().lease.as_mut().unwrap().phase = Phase::Starting;
-- assert!(!finish_x11_studio_restoration(&state, 1, Ok(()), || {
-- panic!("a live recording must not release the shortcut")
-- }));
-- state.lock().unwrap().lease.as_mut().unwrap().phase = Phase::Restoring;
-- assert!(finish_x11_studio_restoration(&state, 1, Ok(()), || Ok(())));
-- assert!(!finish_x11_studio_restoration(&state, 1, Ok(()), || {
-- panic!("a duplicate completion must not release the shortcut")
-- }));
-- assert_eq!(state.lock().unwrap().generation, 2);
-- let next = x11_studio_restoring_fixture();
-- {
-- let mut inner = next.lock().unwrap();
-- inner.generation = 2;
-- inner.lease.as_mut().unwrap().generation = 2;
- }
- assert!(!finish_x11_studio_restoration(&next, 1, Ok(()), || {
- panic!("an old completion must not release the new shortcut")
- }));
- let inner = next.lock().unwrap();
- assert_eq!(inner.generation, 2);
- assert!(inner.lease.as_ref().unwrap().registered_shortcut);
- assert!(inner.restored.is_none());
- }
-
- #[cfg(target_os = "linux")]
- #[test]
- fn x11_studio_restore_keeps_the_users_existing_stop_shortcut() {
- let state = x11_studio_restoring_fixture();
- state
- .lock()
- .unwrap()
- .lease
- .as_mut()
- .unwrap()
- .registered_shortcut = false;
- assert!(finish_x11_studio_restoration(&state, 1, Ok(()), || {
- panic!("the user shortcut is not owned by this restoration")
- }));
- let inner = state.lock().unwrap();
- assert_eq!(inner.restored.as_ref().unwrap().restart_result(), Ok(()));
- }
-
- #[cfg(target_os = "linux")]
- #[test]
- fn x11_studio_stop_during_restoration_prevents_restart_after_cleanup() {
- let state = x11_studio_restoring_fixture();
- assert!(state.lock().unwrap().shortcut(true));
- assert!(finish_x11_studio_restoration(&state, 1, Ok(()), || Ok(())));
- let inner = state.lock().unwrap();
- assert!(inner.lease.is_none());
- assert_eq!(
- inner.restored.as_ref().unwrap().restart_result(),
- Err("Recording restart was cancelled by Stop".into())
- );
- }
-
- #[cfg(target_os = "linux")]
- #[test]
- fn x11_studio_completion_does_not_accept_instant_or_wayland_leases() {
- for (mode, wayland) in [
- (cap_recording::RecordingMode::Instant, false),
- (cap_recording::RecordingMode::Studio, true),
- ] {
- let state = x11_studio_restoring_fixture();
- {
- let mut inner = state.lock().unwrap();
- let lease = inner.lease.as_mut().unwrap();
- lease.mode = mode;
- lease.wayland = wayland;
- assert_eq!(inner.begin_x11_studio_restore_retry(true), None);
- }
- assert!(!finish_x11_studio_restoration(&state, 1, Ok(()), || {
- panic!("another restoration path owns this shortcut")
- }));
- let inner = state.lock().unwrap();
- assert!(inner.restored.is_none());
- assert!(inner.lease.is_some());
- }
- }
-
- #[cfg(target_os = "linux")]
- #[test]
- fn x11_studio_unregister_allows_the_f9_callback_to_lock_and_latch_stop() {
- let state = x11_studio_restoring_fixture();
- let (request_tx, request_rx) = std::sync::mpsc::channel();
- let (reply_tx, reply_rx) = std::sync::mpsc::channel();
- std::thread::scope(|scope| {
- let callback_state = &state;
- let callback = scope.spawn(move || {
- request_rx.recv_timeout(Duration::from_secs(1)).unwrap();
- let mut inner = callback_state.lock().unwrap();
- assert!(inner.x11_cleanup.is_some());
- assert!(inner.lease.as_ref().unwrap().registered_shortcut);
- assert!(inner.reserve_x11_studio_cleanup(1, Ok(())).is_none());
- assert!(inner.shortcut(true));
- drop(inner);
- reply_tx.send(()).unwrap();
- });
- assert!(finish_x11_studio_restoration(&state, 1, Ok(()), || {
- request_tx.send(()).unwrap();
- reply_rx
- .recv_timeout(Duration::from_secs(1))
- .map_err(|_| "F9 callback could not acquire restoration state".into())
- }));
- callback.join().unwrap();
- });
- let inner = state.lock().unwrap();
- assert!(inner.x11_cleanup.is_none());
- assert!(inner.lease.is_none());
- assert_eq!(
- inner.restored.as_ref().unwrap().restart_result(),
- Err("Recording restart was cancelled by Stop".into())
- );
- }
-
- #[cfg(target_os = "linux")]
- #[test]
- fn x11_studio_old_cleanup_completion_cannot_finish_a_retry() {
- let state = x11_studio_restoring_fixture();
- let mut inner = state.lock().unwrap();
- let first = inner.reserve_x11_studio_cleanup(1, Ok(())).unwrap();
- assert!(inner.reserve_x11_studio_cleanup(1, Ok(())).is_none());
- assert!(!inner.complete_x11_studio_restoration(first, Err("unregister failed".into())));
- assert_eq!(inner.begin_x11_studio_restore_retry(true), Some(1));
- let retry = inner.reserve_x11_studio_cleanup(1, Ok(())).unwrap();
- assert_ne!(first.sequence, retry.sequence);
- assert!(!inner.complete_x11_studio_restoration(first, Ok(())));
- assert!(inner.x11_cleanup == Some(retry));
- assert!(inner.lease.as_ref().unwrap().registered_shortcut);
- assert!(inner.complete_x11_studio_restoration(retry, Ok(())));
- assert!(!inner.complete_x11_studio_restoration(retry, Ok(())));
- assert_eq!(inner.generation, 2);
- }
-
- #[cfg(target_os = "linux")]
+ #[tokio::test]
- async fn x11_studio_pending_waiter_rejects_restart_after_error_f9_and_retry_success() {
- let state = State {
- inner: x11_studio_restoring_fixture(),
- ..State::default()
- };
- let mut waiter = Box::pin(wait_for_restoration(&state, 1));
- assert!(futures::poll!(&mut waiter).is_pending());
- assert!(!finish_x11_studio_restoration(
- &state.inner,
- 1,
- Err("window acknowledgement failed".into()),
- || panic!("window failure must retain the Stop shortcut"),
- ));
- state.changed.notify_waiters();
- {
- let mut inner = state.inner.lock().unwrap();
- assert_eq!(inner.begin_x11_studio_restore_retry(true), Some(1));
- assert!(inner.restored.is_none());
- assert!(inner.lease.as_ref().unwrap().stop_requested);
- }
- assert!(finish_x11_studio_restoration(
- &state.inner,
- 1,
- Ok(()),
- || Ok(())
- ));
- state.changed.notify_waiters();
- assert_eq!(
- waiter.await,
- Err("Recording restart was cancelled by Stop".into())
- );
++ async fn open_cap_keeps_preflight_visible_and_studio_pause_semantics() {
++ finish_main_controls(
++ Some(Phase::AwaitingShortcut),
++ Some(async { panic!("preflight must not issue Stop") }),
++ async { panic!("preflight must not issue Pause") },
++ )
++ .await
++ .unwrap();
++ finish_main_controls(
++ Some(Phase::Recording),
++ None::<std::future::Ready<Result<(), String>>>,
++ async { Ok(()) },
++ )
++ .await
++ .unwrap();
+ }
+
- fn fixture() -> Inner {
++ fn restoring() -> Inner {
+ Inner {
- generation: 1,
- control_error: None,
- restored: None,
- #[cfg(target_os = "linux")]
- x11_cleanup_sequence: 0,
- #[cfg(target_os = "linux")]
- x11_cleanup: None,
++ generation: 7,
+ lease: Some(Lease {
- mode: cap_recording::RecordingMode::Studio,
- generation: 1,
- phase: Phase::AwaitingShortcut,
++ mode: cap_recording::RecordingMode::Instant,
++ generation: 7,
++ phase: Phase::Restoring,
+ pressed: false,
+ stop_requested: false,
+ registered_shortcut: true,
+ wayland: false,
+ stop_route: None,
+ stop_description: None,
+ stop_error: None,
+ lost_stop_routes: [false; 2],
+ recording_dir: None,
+ windows: Vec::new(),
+ }),
++ ..Inner::default()
}
- assert!(!finish_x11_studio_restoration(&next, 1, Ok(()), || {
- panic!("an old completion must not release the new shortcut")
- }));
- let inner = next.lock().unwrap();
- assert_eq!(inner.generation, 2);
- assert!(inner.lease.as_ref().unwrap().registered_shortcut);
- assert!(inner.restored.is_none());
}
- #[cfg(target_os = "linux")]
#[test]
- fn x11_studio_restore_keeps_the_users_existing_stop_shortcut() {
- let state = x11_studio_restoring_fixture();
- state
- .lock()
- .unwrap()
- .lease
- .as_mut()
- .unwrap()
- .registered_shortcut = false;
- assert!(finish_x11_studio_restoration(&state, 1, Ok(()), || {
- panic!("the user shortcut is not owned by this restoration")
- }));
- let inner = state.lock().unwrap();
- assert_eq!(inner.restored.as_ref().unwrap().restart_result(), Ok(()));
- fn requires_delivered_press_then_release() {
- let mut state = fixture();
- assert!(state.shortcut(false));
- assert_eq!(state.lease.as_ref().unwrap().phase, Phase::AwaitingShortcut);
- assert!(state.shortcut(true));
- assert_eq!(state.lease.as_ref().unwrap().phase, Phase::AwaitingShortcut);
- assert!(state.shortcut(false));
- assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Starting);
- assert!(!state.lease.as_ref().unwrap().stop_requested);
- assert!(state.shortcut(true));
- assert!(state.lease.as_ref().unwrap().stop_requested);
- }
-
- #[test]
- fn delayed_reveal_cannot_cross_generation() {
- let mut state = fixture();
- assert!(state.may_reveal(1, "main"));
- state.generation = 2;
- state.lease = None;
- assert!(!state.may_reveal(1, "main"));
- assert!(!state.may_reveal(1, "camera"));
- assert!(state.may_reveal(2, "main"));
- }
-
- #[test]
- fn wayland_requires_delivered_current_stop_input() {
- let mut state = fixture();
- let lease = state.lease.as_mut().unwrap();
- lease.wayland = true;
- assert!(!lease.accept_stop_input(None, true));
- assert!(!lease.accept_stop_input(Some((2, StopRoute::Tray)), true));
- assert!(!lease.accept_stop_input(Some((1, StopRoute::Portal)), false));
- assert_eq!(lease.phase, Phase::AwaitingShortcut);
- assert!(lease.accept_stop_input(Some((1, StopRoute::Portal)), true));
- assert!(state.shortcut(true));
- assert!(
- !state
- .lease
- .as_mut()
- .unwrap()
- .accept_stop_input(Some((1, StopRoute::Tray)), false)
- );
- assert!(
- state
- .lease
- .as_mut()
- .unwrap()
- .accept_stop_input(Some((1, StopRoute::Portal)), false)
- );
- assert!(state.shortcut(false));
- assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Starting);
- }
-
- #[test]
- fn wayland_tray_activation_starts_and_next_activation_stops() {
- let mut state = fixture();
- state.lease.as_mut().unwrap().wayland = true;
- for pressed in [true, false] {
- assert!(
- state
- .lease
- .as_mut()
- .unwrap()
- .accept_stop_input(Some((1, StopRoute::Tray)), pressed)
- );
- assert!(state.shortcut(pressed));
- }
- assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Starting);
- state.lease.as_mut().unwrap().phase = Phase::Recording;
- assert!(
- state
- .lease
- .as_mut()
- .unwrap()
- .accept_stop_input(Some((1, StopRoute::Tray)), true)
++ fn instant_restore_error_retains_lease_shortcut_and_error_until_successful_retry() {
++ let mut inner = restoring();
++ assert_eq!(
++ inner.complete_instant_restoration(7, Err("camera ack lost".into())),
++ None
+ );
- assert!(state.shortcut(true));
- assert!(state.lease.as_ref().unwrap().stop_requested);
++ assert_eq!(inner.snapshot().error.as_deref(), Some("camera ack lost"));
++ assert!(inner.lease.as_ref().unwrap().registered_shortcut);
++ assert_eq!(inner.generation, 7);
++ assert_eq!(inner.complete_instant_restoration(7, Ok(())), Some(true));
++ assert!(inner.lease.is_none());
++ assert_eq!(inner.generation, 8);
++ let receipt = inner.restored.as_ref().unwrap();
++ assert_eq!(receipt.generation, 7);
++ assert_eq!(receipt.restart_result(), Ok(()));
}
- #[cfg(target_os = "linux")]
#[test]
- fn x11_studio_stop_during_restoration_prevents_restart_after_cleanup() {
- let state = x11_studio_restoring_fixture();
- assert!(state.lock().unwrap().shortcut(true));
- assert!(finish_x11_studio_restoration(&state, 1, Ok(()), || Ok(())));
- let inner = state.lock().unwrap();
- fn wayland_loss_cannot_start_or_silently_switch_control() {
- let mut state = fixture();
- let lease = state.lease.as_mut().unwrap();
- lease.wayland = true;
- assert!(!lease.lose_stop_route(StopRoute::Portal));
- assert!(!lease.stop_requested);
- assert!(!lease.accept_stop_input(Some((1, StopRoute::Portal)), true));
- assert!(lease.accept_stop_input(Some((1, StopRoute::Tray)), true));
- lease.phase = Phase::Recording;
- assert!(lease.lose_stop_route(StopRoute::Tray));
- assert!(lease.stop_requested);
- assert!(!lease.accept_stop_input(Some((1, StopRoute::Tray)), true));
++ fn instant_stop_during_restoration_prevents_restart_after_successful_window_ack() {
++ let mut inner = restoring();
++ assert!(inner.shortcut(true));
++ assert_eq!(inner.complete_instant_restoration(7, Ok(())), Some(true));
+ assert!(inner.lease.is_none());
- assert_eq!(
- inner.restored.as_ref().unwrap().restart_result(),
- Err("Recording restart was cancelled by Stop".into())
- );
++ assert_eq!(inner.generation, 8);
++ assert!(inner.restored.as_ref().unwrap().restart_result().is_err());
}
- #[cfg(target_os = "linux")]
#[test]
- fn x11_studio_completion_does_not_accept_instant_or_wayland_leases() {
- for (mode, wayland) in [
- (cap_recording::RecordingMode::Instant, false),
- (cap_recording::RecordingMode::Studio, true),
- ] {
- let state = x11_studio_restoring_fixture();
- {
- let mut inner = state.lock().unwrap();
- let lease = inner.lease.as_mut().unwrap();
- lease.mode = mode;
- lease.wayland = wayland;
- assert_eq!(inner.begin_x11_studio_restore_retry(true), None);
- }
- assert!(!finish_x11_studio_restoration(&state, 1, Ok(()), || {
- panic!("another restoration path owns this shortcut")
- }));
- let inner = state.lock().unwrap();
- assert!(inner.restored.is_none());
- assert!(inner.lease.is_some());
- }
- fn wayland_both_missing_controls_cancel_visible_preflight() {
- let mut state = fixture();
- let lease = state.lease.as_mut().unwrap();
- lease.wayland = true;
- assert!(!lease.lose_stop_route(StopRoute::Tray));
- assert!(!lease.lose_stop_route(StopRoute::Portal));
- assert!(lease.stop_requested);
- assert_eq!(lease.phase, Phase::AwaitingShortcut);
++ fn instant_stale_restore_receipt_cannot_clear_new_lease_or_error() {
++ let mut inner = restoring();
++ assert_eq!(inner.complete_instant_restoration(6, Ok(())), None);
++ assert!(inner.restored.is_none());
++ inner.lease.as_mut().unwrap().phase = Phase::Starting;
++ assert_eq!(inner.complete_instant_restoration(7, Ok(())), None);
++ assert!(inner.lease.as_ref().unwrap().registered_shortcut);
++ assert!(inner.restored.is_none());
}
++}
- #[cfg(target_os = "linux")]
-- #[test]
- fn x11_studio_unregister_allows_the_f9_callback_to_lock_and_latch_stop() {
- let state = x11_studio_restoring_fixture();
- let (request_tx, request_rx) = std::sync::mpsc::channel();
- let (reply_tx, reply_rx) = std::sync::mpsc::channel();
- std::thread::scope(|scope| {
- let callback_state = &state;
- let callback = scope.spawn(move || {
- request_rx.recv_timeout(Duration::from_secs(1)).unwrap();
- let mut inner = callback_state.lock().unwrap();
- assert!(inner.x11_cleanup.is_some());
- assert!(inner.lease.as_ref().unwrap().registered_shortcut);
- assert!(inner.reserve_x11_studio_cleanup(1, Ok(())).is_none());
- assert!(inner.shortcut(true));
- drop(inner);
- reply_tx.send(()).unwrap();
- });
- assert!(finish_x11_studio_restoration(&state, 1, Ok(()), || {
- request_tx.send(()).unwrap();
- reply_rx
- .recv_timeout(Duration::from_secs(1))
- .map_err(|_| "F9 callback could not acquire restoration state".into())
- }));
- callback.join().unwrap();
- });
- let inner = state.lock().unwrap();
- assert!(inner.x11_cleanup.is_none());
- assert!(inner.lease.is_none());
- assert_eq!(
- inner.restored.as_ref().unwrap().restart_result(),
- Err("Recording restart was cancelled by Stop".into())
- );
- fn wayland_control_loss_during_start_is_retained_until_cleanup() {
- let mut state = fixture();
- let lease = state.lease.as_mut().unwrap();
- lease.wayland = true;
- lease.stop_route = Some(StopRoute::Tray);
- lease.phase = Phase::Starting;
- assert!(!lease.lose_stop_route(StopRoute::Tray));
- assert!(lease.stop_requested);
- assert_eq!(lease.phase, Phase::Starting);
-- }
++#[cfg(target_os = "linux")]
++thread_local! {
++ static WAYLAND_WINDOWS: std::cell::RefCell<std::collections::HashMap<u32, Vec<gtk::ApplicationWindow>>> = std::cell::RefCell::new(std::collections::HashMap::new());
++}
- #[cfg(target_os = "linux")]
-- #[test]
- fn x11_studio_old_cleanup_completion_cannot_finish_a_retry() {
- let state = x11_studio_restoring_fixture();
- let mut inner = state.lock().unwrap();
- let first = inner.reserve_x11_studio_cleanup(1, Ok(())).unwrap();
- assert!(inner.reserve_x11_studio_cleanup(1, Ok(())).is_none());
- assert!(!inner.complete_x11_studio_restoration(first, Err("unregister failed".into())));
- assert_eq!(inner.begin_x11_studio_restore_retry(true), Some(1));
- let retry = inner.reserve_x11_studio_cleanup(1, Ok(())).unwrap();
- assert_ne!(first.sequence, retry.sequence);
- assert!(!inner.complete_x11_studio_restoration(first, Ok(())));
- assert!(inner.x11_cleanup == Some(retry));
- assert!(inner.lease.as_ref().unwrap().registered_shortcut);
- assert!(inner.complete_x11_studio_restoration(retry, Ok(())));
- assert!(!inner.complete_x11_studio_restoration(retry, Ok(())));
- assert_eq!(inner.generation, 2);
- fn only_acknowledged_pause_allows_main() {
- let mut state = fixture();
- for phase in [
- Phase::Starting,
- Phase::Recording,
- Phase::Pausing,
- Phase::Resuming,
- Phase::Restarting,
- Phase::Stopping,
- ] {
- state.lease.as_mut().unwrap().phase = phase;
- assert!(!state.may_reveal(1, "main"));
- assert!(!state.may_reveal(1, "camera"));
- assert!(!state.may_reveal(1, "in-progress-recording"));
- }
- state.lease.as_mut().unwrap().phase = Phase::Paused;
- assert!(state.may_reveal(1, "main"));
- assert!(!state.may_reveal(1, "camera"));
-- }
++#[cfg(target_os = "linux")]
++pub(crate) fn wayland_generation(app: &AppHandle) -> Option<u32> {
++ let state = app.try_state::<State>()?;
++ let inner = state.inner.lock().unwrap();
++ inner
++ .lease
++ .as_ref()
++ .filter(|lease| lease.wayland)
++ .map(|lease| lease.generation)
++}
- #[cfg(target_os = "linux")]
- #[tokio::test]
- async fn x11_studio_pending_waiter_rejects_restart_after_error_f9_and_retry_success() {
- let state = State {
- inner: x11_studio_restoring_fixture(),
- ..State::default()
- };
- let mut waiter = Box::pin(wait_for_restoration(&state, 1));
- assert!(futures::poll!(&mut waiter).is_pending());
- assert!(!finish_x11_studio_restoration(
- &state.inner,
- 1,
- Err("window acknowledgement failed".into()),
- || panic!("window failure must retain the Stop shortcut"),
- ));
- state.changed.notify_waiters();
- {
- let mut inner = state.inner.lock().unwrap();
- assert_eq!(inner.begin_x11_studio_restore_retry(true), Some(1));
- assert!(inner.restored.is_none());
- assert!(inner.lease.as_ref().unwrap().stop_requested);
- #[test]
- fn instant_uses_capture_backend_without_loosening_studio_environment() {
- use cap_recording::RecordingMode;
- for strict_x11 in [false, true] {
- assert!(capture_environment_is_x11(
- RecordingMode::Instant,
- strict_x11,
- false
- ));
- assert!(!capture_environment_is_x11(
- RecordingMode::Instant,
- strict_x11,
- true
- ));
- for uses_wayland_portal in [false, true] {
- assert_eq!(
- capture_environment_is_x11(
- RecordingMode::Studio,
- strict_x11,
- uses_wayland_portal
- ),
- strict_x11
- );
- }
-- }
- assert!(finish_x11_studio_restoration(
- &state.inner,
- 1,
- Ok(()),
- || Ok(())
- assert!(!x11_environment(true, false, None));
- assert!(capture_environment_is_x11(
- RecordingMode::Instant,
- x11_environment(true, false, None),
- false
-- ));
- state.changed.notify_waiters();
- assert_eq!(
- waiter.await,
- Err("Recording restart was cancelled by Stop".into())
- );
- assert!(!x11_environment(true, true, Some("x11")));
- assert!(capture_environment_is_x11(
- RecordingMode::Instant,
- x11_environment(true, true, Some("x11")),
- false
- ));
++#[cfg(target_os = "linux")]
++pub(crate) fn describe_wayland_stop(app: &AppHandle, generation: u32, description: String) {
++ let state = app.state::<State>();
++ let mut inner = state.inner.lock().unwrap();
++ if let Some(lease) = inner
++ .lease
++ .as_mut()
++ .filter(|lease| lease.generation == generation && lease.wayland)
++ {
++ lease.stop_description = Some(description);
}
++ drop(inner);
++ notify(app);
++}
- fn fixture() -> Inner {
- Inner {
- generation: 1,
- control_error: None,
- restored: None,
- #[test]
- fn monitor_visibility_requires_x11_for_both_recording_modes() {
- use cap_recording::{RecordingMode, screen_capture::ScreenCaptureTarget};
- let display = ScreenCaptureTarget::Display {
- id: "1".parse().unwrap(),
- };
- let area = ScreenCaptureTarget::Area {
- screen: "1".parse().unwrap(),
- bounds: scap_targets::bounds::LogicalBounds::new(
- scap_targets::bounds::LogicalPosition::new(0.0, 0.0),
- scap_targets::bounds::LogicalSize::new(100.0, 100.0),
- ),
- };
- let window = ScreenCaptureTarget::Window {
- id: "1".parse().unwrap(),
- };
- for mode in [RecordingMode::Studio, RecordingMode::Instant] {
- for target in [&display, &area] {
- assert_eq!(
- validate_capture_visibility(mode, target, false, false, true),
- Ok(true)
- );
- assert!(validate_capture_visibility(mode, target, false, false, false).is_err());
++async fn save_windows(app: &AppHandle, generation: u32) -> Result<Vec<SavedWindow>, String> {
++ let (tx, rx) = tokio::sync::oneshot::channel();
++ let handle = app.clone();
++ app.run_on_main_thread(move || {
++ let result = (|| {
++ if !is_current(&handle, generation) {
++ return Err("Recording preflight was superseded".to_string());
+ }
- for target in [&window, &ScreenCaptureTarget::CameraOnly] {
- assert_eq!(
- validate_capture_visibility(mode, target, false, false, true),
- Ok(false)
- );
- assert_eq!(
- validate_capture_visibility(mode, target, false, false, false),
- Ok(false)
- );
+ #[cfg(target_os = "linux")]
- x11_cleanup_sequence: 0,
++ if wayland_generation(&handle) == Some(generation) {
++ install_wayland_window_guard(&handle)?;
++ remember_wayland_windows(&handle, generation)?;
+ }
- }
- assert_eq!(
- validate_capture_visibility(RecordingMode::Screenshot, &display, false, false, false),
- Ok(false)
- );
- }
-
- #[test]
- fn window_camera_visibility_is_required_only_for_x11_instant() {
- use cap_recording::{RecordingMode, screen_capture::ScreenCaptureTarget};
- let target = ScreenCaptureTarget::Window {
- id: "1".parse().unwrap(),
- };
- for mode in [
- RecordingMode::Studio,
- RecordingMode::Instant,
- RecordingMode::Screenshot,
- ] {
- for camera in [false, true] {
- for wayland in [false, true] {
- let required = mode == RecordingMode::Instant && camera && !wayland;
- assert_eq!(
- validate_capture_visibility(mode, &target, camera, wayland, true),
- Ok(required)
- );
- let unsupported =
- validate_capture_visibility(mode, &target, camera, wayland, false);
- if required {
- assert!(unsupported.is_err());
- } else {
- assert_eq!(unsupported, Ok(false));
+ #[cfg(target_os = "linux")]
- x11_cleanup: None,
- lease: Some(Lease {
- mode: cap_recording::RecordingMode::Studio,
- generation: 1,
- phase: Phase::AwaitingShortcut,
- pressed: false,
- stop_requested: false,
- registered_shortcut: true,
- wayland: false,
- stop_route: None,
- stop_description: None,
- stop_error: None,
- lost_stop_routes: [false; 2],
- recording_dir: None,
- windows: Vec::new(),
- }),
- }
- }
++ let save_all = wayland_generation(&handle) == Some(generation);
++ #[cfg(not(target_os = "linux"))]
++ let save_all = false;
++ let mut saved = Vec::new();
++ for (label, window) in handle.webview_windows() {
++ if save_all
++ || matches!(
++ label.parse::<CapWindowId>(),
++ Ok(CapWindowId::Main | CapWindowId::Camera)
++ )
++ {
++ #[cfg(target_os = "linux")]
++ if wayland_generation(&handle) == Some(generation) {
++ let gtk = window.gtk_window().map_err(|error| error.to_string())?;
++ WAYLAND_WINDOWS.with_borrow_mut(|windows| {
++ windows.entry(generation).or_default().push(gtk)
++ });
+ }
++ saved.push(SavedWindow {
++ label,
++ native_id: native_id(&window)?,
++ visible: window.is_visible().map_err(|error| error.to_string())?,
++ });
+ }
+ }
- }
- }
-
- #[test]
- fn refuses_wayland_and_ambiguous_sessions() {
- assert!(x11_environment(true, false, Some("x11")));
- assert!(!x11_environment(true, true, Some("x11")));
- assert!(!x11_environment(true, false, Some("wayland")));
- assert!(!x11_environment(true, false, None));
- assert!(!x11_environment(false, false, Some("x11")));
- }
-
- #[test]
- fn cancel_preflight_never_starts() {
- let mut state = fixture();
- assert!(state.queue_stop());
- assert!(state.shortcut(true));
- assert!(state.shortcut(false));
- assert!(state.lease.as_ref().unwrap().stop_requested);
- }
++ Ok(saved)
++ })();
++ let _ = tx.send(result);
++ })
++ .map_err(|error| error.to_string())?;
++ tokio::time::timeout(Duration::from_secs(2), rx)
++ .await
++ .map_err(|_| "Timed out saving recording windows".to_string())?
++ .map_err(|_| "Recording windows could not be saved".to_string())?
++}
-- #[test]
- fn requires_delivered_press_then_release() {
- let mut state = fixture();
- assert!(state.shortcut(false));
- assert_eq!(state.lease.as_ref().unwrap().phase, Phase::AwaitingShortcut);
- assert!(state.shortcut(true));
- assert_eq!(state.lease.as_ref().unwrap().phase, Phase::AwaitingShortcut);
- assert!(state.shortcut(false));
- assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Starting);
- assert!(!state.lease.as_ref().unwrap().stop_requested);
- assert!(state.shortcut(true));
- assert!(state.lease.as_ref().unwrap().stop_requested);
- fn stop_is_retained_through_start_restart_and_control_transitions() {
- for phase in [Phase::Starting, Phase::Restarting, Phase::Pausing] {
- let mut state = fixture();
- state.lease.as_mut().unwrap().phase = phase;
- assert!(state.queue_stop());
- assert!(state.lease.as_ref().unwrap().stop_requested);
- assert_eq!(state.lease.as_ref().unwrap().phase, phase);
++fn set_native_visibility(window: &WebviewWindow, visible: bool) -> Result<(), String> {
++ #[cfg(target_os = "linux")]
++ {
++ use gtk::prelude::*;
++ let gtk = window.gtk_window().map_err(|error| error.to_string())?;
++ // Tao queues GTK visibility changes even on the UI thread; this gate needs
++ // the native change to complete before checking its acknowledgement.
++ if visible {
++ gtk.show_all();
++ } else {
++ gtk.hide();
++ }
++ if gtk.is_visible() != visible || (!visible && gtk.is_mapped()) {
++ return Err("GTK did not acknowledge the recording window visibility change".into());
+ }
++ Ok(())
}
--
-- #[test]
- fn delayed_reveal_cannot_cross_generation() {
- fn active_stop_claims_cleanup_once() {
-- let mut state = fixture();
- assert!(state.may_reveal(1, "main"));
- state.generation = 2;
- state.lease = None;
- assert!(!state.may_reveal(1, "main"));
- assert!(!state.may_reveal(1, "camera"));
- assert!(state.may_reveal(2, "main"));
- state.lease.as_mut().unwrap().phase = Phase::Recording;
- assert!(!state.queue_stop());
- assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Stopping);
- assert!(state.queue_stop());
- assert!(state.lease.as_ref().unwrap().stop_requested);
++ #[cfg(not(target_os = "linux"))]
++ {
++ if visible {
++ window.show()
++ } else {
++ window.hide()
++ }
++ .map_err(|error| error.to_string())
}
++}
- #[test]
- fn wayland_requires_delivered_current_stop_input() {
- let mut state = fixture();
- let lease = state.lease.as_mut().unwrap();
- lease.wayland = true;
- assert!(!lease.accept_stop_input(None, true));
- assert!(!lease.accept_stop_input(Some((2, StopRoute::Tray)), true));
- assert!(!lease.accept_stop_input(Some((1, StopRoute::Portal)), false));
- assert_eq!(lease.phase, Phase::AwaitingShortcut);
- assert!(lease.accept_stop_input(Some((1, StopRoute::Portal)), true));
- assert!(state.shortcut(true));
- assert!(
- !state
- .lease
- .as_mut()
- .unwrap()
- .accept_stop_input(Some((1, StopRoute::Tray)), false)
- );
- assert!(
- state
- .lease
- .as_mut()
- .unwrap()
- .accept_stop_input(Some((1, StopRoute::Portal)), false)
- );
- assert!(state.shortcut(false));
- assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Starting);
- }
-
- #[test]
- fn wayland_tray_activation_starts_and_next_activation_stops() {
- let mut state = fixture();
- state.lease.as_mut().unwrap().wayland = true;
- for pressed in [true, false] {
- assert!(
- state
- .lease
- .as_mut()
- .unwrap()
- .accept_stop_input(Some((1, StopRoute::Tray)), pressed)
- );
- assert!(state.shortcut(pressed));
- }
- assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Starting);
- state.lease.as_mut().unwrap().phase = Phase::Recording;
- assert!(
- state
- .lease
- .as_mut()
- .unwrap()
- .accept_stop_input(Some((1, StopRoute::Tray)), true)
- );
- assert!(state.shortcut(true));
- assert!(state.lease.as_ref().unwrap().stop_requested);
- }
-
- #[test]
- fn wayland_loss_cannot_start_or_silently_switch_control() {
- let mut state = fixture();
- let lease = state.lease.as_mut().unwrap();
- lease.wayland = true;
- assert!(!lease.lose_stop_route(StopRoute::Portal));
- assert!(!lease.stop_requested);
- assert!(!lease.accept_stop_input(Some((1, StopRoute::Portal)), true));
- assert!(lease.accept_stop_input(Some((1, StopRoute::Tray)), true));
- lease.phase = Phase::Recording;
- assert!(lease.lose_stop_route(StopRoute::Tray));
- assert!(lease.stop_requested);
- assert!(!lease.accept_stop_input(Some((1, StopRoute::Tray)), true));
- }
-
- #[test]
- fn wayland_both_missing_controls_cancel_visible_preflight() {
- let mut state = fixture();
- let lease = state.lease.as_mut().unwrap();
- lease.wayland = true;
- assert!(!lease.lose_stop_route(StopRoute::Tray));
- assert!(!lease.lose_stop_route(StopRoute::Portal));
- assert!(lease.stop_requested);
- assert_eq!(lease.phase, Phase::AwaitingShortcut);
- }
-
-- #[test]
- fn wayland_control_loss_during_start_is_retained_until_cleanup() {
- fn unconfirmed_resume_failure_keeps_main_hidden_and_stop_actionable() {
-- let mut state = fixture();
- let dir = PathBuf::from("recording-a");
-- let lease = state.lease.as_mut().unwrap();
- lease.wayland = true;
- lease.stop_route = Some(StopRoute::Tray);
- lease.phase = Phase::Starting;
- assert!(!lease.lose_stop_route(StopRoute::Tray));
- assert!(lease.stop_requested);
- assert_eq!(lease.phase, Phase::Starting);
- }
-
- #[test]
- fn only_acknowledged_pause_allows_main() {
- let mut state = fixture();
- for phase in [
- Phase::Starting,
- Phase::Recording,
- Phase::Pausing,
- Phase::Resuming,
- Phase::Restarting,
- Phase::Stopping,
- ] {
- state.lease.as_mut().unwrap().phase = phase;
- assert!(!state.may_reveal(1, "main"));
- assert!(!state.may_reveal(1, "camera"));
- assert!(!state.may_reveal(1, "in-progress-recording"));
- }
- state.lease.as_mut().unwrap().phase = Phase::Paused;
- assert!(state.may_reveal(1, "main"));
- assert!(!state.may_reveal(1, "camera"));
- }
-
- #[test]
- fn instant_uses_capture_backend_without_loosening_studio_environment() {
- use cap_recording::RecordingMode;
- for strict_x11 in [false, true] {
- assert!(capture_environment_is_x11(
- RecordingMode::Instant,
- strict_x11,
- false
- ));
- assert!(!capture_environment_is_x11(
- RecordingMode::Instant,
- strict_x11,
- true
- ));
- for uses_wayland_portal in [false, true] {
- assert_eq!(
- capture_environment_is_x11(
- RecordingMode::Studio,
- strict_x11,
- uses_wayland_portal
- ),
- strict_x11
- );
- }
- }
- assert!(!x11_environment(true, false, None));
- assert!(capture_environment_is_x11(
- RecordingMode::Instant,
- x11_environment(true, false, None),
- false
- ));
- assert!(!x11_environment(true, true, Some("x11")));
- assert!(capture_environment_is_x11(
- RecordingMode::Instant,
- x11_environment(true, true, Some("x11")),
- false
- ));
- }
-
- #[test]
- fn monitor_visibility_requires_x11_for_both_recording_modes() {
- use cap_recording::{RecordingMode, screen_capture::ScreenCaptureTarget};
- let display = ScreenCaptureTarget::Display {
- id: "1".parse().unwrap(),
- };
- let area = ScreenCaptureTarget::Area {
- screen: "1".parse().unwrap(),
- bounds: scap_targets::bounds::LogicalBounds::new(
- scap_targets::bounds::LogicalPosition::new(0.0, 0.0),
- scap_targets::bounds::LogicalSize::new(100.0, 100.0),
- ),
- };
- let window = ScreenCaptureTarget::Window {
- id: "1".parse().unwrap(),
- };
- for mode in [RecordingMode::Studio, RecordingMode::Instant] {
- for target in [&display, &area] {
- assert_eq!(
- validate_capture_visibility(mode, target, false, false, true),
- Ok(true)
- );
- assert!(validate_capture_visibility(mode, target, false, false, false).is_err());
- lease.recording_dir = Some(dir.clone());
- lease.phase = Phase::Resuming;
- assert!(state.complete_control(
- 1,
- &dir,
- true,
- &ControlOutcome::ActorFailed {
- error: "actor transport failed".into(),
- paused: false,
++#[cfg(target_os = "linux")]
++async fn wayland_fence(app: &AppHandle, generation: u32, hidden: bool) -> Result<(), String> {
++ let (tx, rx) = tokio::sync::oneshot::channel();
++ let handle = app.clone();
++ app.run_on_main_thread(move || {
++ let display = (|| {
++ use gtk::prelude::*;
++ if !is_current(&handle, generation) {
++ return Err("Recording visibility fence was superseded".to_string());
}
- for target in [&window, &ScreenCaptureTarget::CameraOnly] {
- assert_eq!(
- validate_capture_visibility(mode, target, false, false, true),
- Ok(false)
- );
- assert_eq!(
- validate_capture_visibility(mode, target, false, false, false),
- Ok(false)
- ));
- assert_eq!(state.lease.as_ref().unwrap().phase, Phase::ResumeFailed);
- assert!(state.shortcut(true));
- assert!(state.lease.as_ref().unwrap().phase.can_stop());
- assert!(!state.may_reveal(1, "main"));
- assert!(!state.queue_stop());
- assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Stopping);
++ let gtk = if let Some(window) = CapWindowId::Main.get(&handle) {
++ window.gtk_window().map_err(|error| error.to_string())?
++ } else if !hidden && phase(&handle) == Some(Phase::Restoring) {
++ WAYLAND_WINDOWS
++ .with_borrow(|windows| {
++ windows
++ .get(&generation)
++ .and_then(|windows| windows.first())
++ .cloned()
++ })
++ .ok_or("Retained recording display disappeared")?
++ } else {
++ return Err("Main recording window disappeared".into());
++ };
++ let display = gtk.display();
++ if display.type_().name() != "GdkWaylandDisplay" {
++ return Err(
++ "The recording window is not connected to the Wayland compositor".into(),
+ );
+ }
- }
- assert_eq!(
- validate_capture_visibility(RecordingMode::Screenshot, &display, false, false, false),
- Ok(false)
- );
- }
-
- #[test]
- fn window_camera_visibility_is_required_only_for_x11_instant() {
- use cap_recording::{RecordingMode, screen_capture::ScreenCaptureTarget};
- let target = ScreenCaptureTarget::Window {
- id: "1".parse().unwrap(),
- };
- for mode in [
- RecordingMode::Studio,
- RecordingMode::Instant,
- RecordingMode::Screenshot,
- ] {
- for camera in [false, true] {
- for wayland in [false, true] {
- let required = mode == RecordingMode::Instant && camera && !wayland;
- assert_eq!(
- validate_capture_visibility(mode, &target, camera, wayland, true),
- Ok(required)
- );
- let unsupported =
- validate_capture_visibility(mode, &target, camera, wayland, false);
- if required {
- assert!(unsupported.is_err());
- } else {
- assert_eq!(unsupported, Ok(false));
- }
- }
++ Ok(display)
++ })();
++ match display {
++ Ok(display) => wayland_ack::start(display, handle, generation, hidden, tx),
++ Err(error) => {
++ let _ = tx.send(Err(error));
+ }
+ }
++ })
++ .map_err(|error| error.to_string())?;
++ tokio::time::timeout(Duration::from_secs(3), rx)
++ .await
++ .map_err(|_| "Wayland visibility acknowledgement timed out".to_string())?
++ .map_err(|_| "Wayland visibility acknowledgement was lost".to_string())??;
++ if !is_current(app, generation) {
++ return Err("Recording visibility acknowledgement was superseded".into());
}
++ Ok(())
++}
- #[test]
- fn refuses_wayland_and_ambiguous_sessions() {
- assert!(x11_environment(true, false, Some("x11")));
- assert!(!x11_environment(true, true, Some("x11")));
- assert!(!x11_environment(true, false, Some("wayland")));
- assert!(!x11_environment(true, false, None));
- assert!(!x11_environment(false, false, Some("x11")));
- }
-
-- #[test]
- fn cancel_preflight_never_starts() {
- fn old_control_acknowledgement_cannot_publish_into_new_recording() {
-- let mut state = fixture();
- assert!(state.queue_stop());
- assert!(state.shortcut(true));
- assert!(state.shortcut(false));
- assert!(state.lease.as_ref().unwrap().stop_requested);
- }
-
- #[test]
- fn stop_is_retained_through_start_restart_and_control_transitions() {
- for phase in [Phase::Starting, Phase::Restarting, Phase::Pausing] {
- let mut state = fixture();
- state.lease.as_mut().unwrap().phase = phase;
- assert!(state.queue_stop());
- assert!(state.lease.as_ref().unwrap().stop_requested);
- assert_eq!(state.lease.as_ref().unwrap().phase, phase);
- }
- let lease = state.lease.as_mut().unwrap();
- lease.phase = Phase::Pausing;
- lease.recording_dir = Some(PathBuf::from("recording-b"));
- lease.generation = 2;
- state.generation = 2;
- assert!(!state.complete_control(
- 1,
- std::path::Path::new("recording-a"),
- false,
- &ControlOutcome::Succeeded
- ));
- assert!(!state.complete_control(
- 2,
- std::path::Path::new("recording-a"),
- false,
- &ControlOutcome::Succeeded
- ));
- assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Pausing);
-- }
++#[cfg(target_os = "linux")]
++mod wayland_ack {
++ use gtk::{gdk, prelude::*};
++ use std::{
++ cell::{Cell, RefCell},
++ ffi::c_void,
++ rc::Rc,
++ time::Duration,
++ };
++ use wayland_sys::{client::*, common::*};
-- #[test]
- fn active_stop_claims_cleanup_once() {
- fn target_overlays_stay_hidden_even_during_preflight_and_pause() {
-- let mut state = fixture();
- state.lease.as_mut().unwrap().phase = Phase::Recording;
- assert!(!state.queue_stop());
- assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Stopping);
- assert!(state.queue_stop());
- assert!(state.lease.as_ref().unwrap().stop_requested);
- for phase in [
- Phase::AwaitingShortcut,
- Phase::Recording,
- Phase::Paused,
- Phase::Restarting,
- Phase::Restoring,
- ] {
- state.lease.as_mut().unwrap().phase = phase;
- assert!(!state.may_reveal(1, "target-select-overlay-1"));
++ type Reply = tokio::sync::oneshot::Sender<Result<(), String>>;
++ struct Pending {
++ callback: Cell<*mut wl_proxy>,
++ reply: RefCell<Option<Reply>>,
++ _display: gdk::Display,
++ app: tauri::AppHandle,
++ generation: u32,
++ hidden: bool,
+ }
-
- #[test]
- fn unconfirmed_resume_failure_keeps_main_hidden_and_stop_actionable() {
- let mut state = fixture();
- let dir = PathBuf::from("recording-a");
- let lease = state.lease.as_mut().unwrap();
- lease.recording_dir = Some(dir.clone());
- lease.phase = Phase::Resuming;
- assert!(state.complete_control(
- 1,
- &dir,
- true,
- &ControlOutcome::ActorFailed {
- error: "actor transport failed".into(),
- paused: false,
++ impl Pending {
++ fn finish(&self, result: Result<(), String>) {
++ let callback = self.callback.replace(std::ptr::null_mut());
++ if !callback.is_null() {
++ unsafe {
++ (wayland_client_handle().wl_proxy_destroy)(callback);
++ }
++ }
++ if let Some(reply) = self.reply.borrow_mut().take() {
++ let _ = reply.send(result);
+ }
- ));
- assert_eq!(state.lease.as_ref().unwrap().phase, Phase::ResumeFailed);
- assert!(state.shortcut(true));
- assert!(state.lease.as_ref().unwrap().phase.can_stop());
- assert!(!state.may_reveal(1, "main"));
- assert!(!state.queue_stop());
- assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Stopping);
- }
-
- #[test]
- fn old_control_acknowledgement_cannot_publish_into_new_recording() {
- let mut state = fixture();
- let lease = state.lease.as_mut().unwrap();
- lease.phase = Phase::Pausing;
- lease.recording_dir = Some(PathBuf::from("recording-b"));
- lease.generation = 2;
- state.generation = 2;
- assert!(!state.complete_control(
- 1,
- std::path::Path::new("recording-a"),
- false,
- &ControlOutcome::Succeeded
- ));
- assert!(!state.complete_control(
- 2,
- std::path::Path::new("recording-a"),
- false,
- &ControlOutcome::Succeeded
- ));
- assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Pausing);
- }
-
- #[test]
- fn target_overlays_stay_hidden_even_during_preflight_and_pause() {
- let mut state = fixture();
- for phase in [
- Phase::AwaitingShortcut,
- Phase::Recording,
- Phase::Paused,
- Phase::Restarting,
- Phase::Restoring,
- ] {
- state.lease.as_mut().unwrap().phase = phase;
- assert!(!state.may_reveal(1, "target-select-overlay-1"));
- }
- }
-
- #[test]
- fn restore_preserves_hidden_camera_and_rejects_replaced_native_window() {
- for visible in [false, true] {
- let saved = SavedWindow {
- label: "camera".into(),
- native_id: 42,
- visible,
- };
- assert_eq!(saved.visibility_for(42), Some(visible));
- assert_eq!(saved.visibility_for(43), None);
}
}
--
-- #[test]
- fn startup_failure_cannot_own_a_different_pending_recording() {
- let mut state = fixture();
- let old = PathBuf::from("failed-start-a");
- let new = PathBuf::from("pending-start-b");
- state.lease.as_mut().unwrap().phase = Phase::Starting;
- state.lease.as_mut().unwrap().recording_dir = Some(old.clone());
- assert_eq!(state.owner(&old), Some(1));
- assert_eq!(state.owner(&new), None);
- state.lease.as_mut().unwrap().recording_dir = Some(new.clone());
- state.lease.as_mut().unwrap().generation = 2;
- state.generation = 2;
- assert_eq!(state.owner(&old), None);
- assert_eq!(state.owner(&new), Some(2));
- }
-
- #[tokio::test]
- async fn pending_pause_does_not_reveal_main_and_retains_queued_stop_after_ack() {
- let state = std::sync::Arc::new(Mutex::new(fixture()));
- let dir = PathBuf::from("recording-a");
- {
- let mut state = state.lock().unwrap();
- let lease = state.lease.as_mut().unwrap();
- lease.phase = Phase::Pausing;
- lease.recording_dir = Some(dir.clone());
- }
- let (acknowledge, received) = tokio::sync::oneshot::channel();
- let pending = {
- let state = state.clone();
- tokio::spawn(async move {
- received.await.unwrap();
- state
- .lock()
- .unwrap()
- .complete_control(1, &dir, false, &ControlOutcome::Succeeded)
- })
- fn restore_preserves_hidden_camera_and_rejects_replaced_native_window() {
- for visible in [false, true] {
- let saved = SavedWindow {
- label: "camera".into(),
- native_id: 42,
- visible,
- };
- assert_eq!(saved.visibility_for(42), Some(visible));
- assert_eq!(saved.visibility_for(43), None);
++ static CALLBACK: wl_interface = wl_interface {
++ name: c"wl_callback".as_ptr(),
++ version: 1,
++ request_count: 0,
++ requests: std::ptr::null(),
++ event_count: 1,
++ events: &wl_message {
++ name: c"done".as_ptr(),
++ signature: c"u".as_ptr(),
++ types: std::ptr::null(),
++ },
++ };
++ unsafe extern "C" fn dispatch(
++ _: *const c_void,
++ data: *mut c_void,
++ opcode: u32,
++ _: *const wl_message,
++ _: *const wl_argument,
++ ) -> i32 {
++ let pending = unsafe {
++ &*((wayland_client_handle().wl_proxy_get_user_data)(data.cast()).cast::<Pending>())
++ };
++ pending.finish(if opcode == 0 {
++ if pending.hidden {
++ super::verify_wayland_hidden(&pending.app, pending.generation)
++ } else {
++ super::verify_wayland_restored(&pending.app, pending.generation)
++ }
++ } else {
++ Err("Unexpected Wayland visibility acknowledgement".into())
++ });
++ 0
++ }
++ pub(super) fn start(
++ display: gdk::Display,
++ app: tauri::AppHandle,
++ generation: u32,
++ hidden: bool,
++ reply: Reply,
++ ) {
++ let Some(client) = wayland_client_option() else {
++ let _ = reply.send(Err("Wayland client library is unavailable".into()));
++ return;
+ };
- {
- let mut state = state.lock().unwrap();
- assert!(!state.may_reveal(1, "main"));
- assert!(state.queue_stop());
++ let raw =
++ unsafe { gdk_wayland_sys::gdk_wayland_display_get_wl_display(display.as_ptr().cast()) }
++ .cast::<wl_display>();
++ if raw.is_null() {
++ let _ = reply.send(Err("Wayland display connection is unavailable".into()));
++ return;
+ }
- acknowledge.send(()).unwrap();
- assert!(pending.await.unwrap());
- let mut state = state.lock().unwrap();
- assert!(state.lease.as_ref().unwrap().stop_requested);
- assert!(!state.queue_stop());
- assert!(!state.may_reveal(1, "main"));
- }
-
- #[tokio::test]
- async fn stopped_owner_rejects_delayed_resume_acknowledgement() {
- let state = std::sync::Arc::new(Mutex::new(fixture()));
- let dir = PathBuf::from("recording-a");
- {
- let mut state = state.lock().unwrap();
- let lease = state.lease.as_mut().unwrap();
- lease.phase = Phase::Resuming;
- lease.recording_dir = Some(dir.clone());
++ let mut args = [wl_argument {
++ o: std::ptr::null(),
++ }];
++ let callback = unsafe {
++ (client.wl_proxy_marshal_array_constructor)(raw.cast(), 0, args.as_mut_ptr(), &CALLBACK)
++ };
++ if callback.is_null() {
++ let _ = reply.send(Err(
++ "Could not queue Wayland visibility acknowledgement".into()
++ ));
++ return;
+ }
- let (acknowledge, received) = tokio::sync::oneshot::channel();
- let pending = {
- let state = state.clone();
- tokio::spawn(async move {
- received.await.unwrap();
- state
- .lock()
- .unwrap()
- .complete_control(1, &dir, true, &ControlOutcome::Succeeded)
- })
++ let pending = Rc::new(Pending {
++ callback: Cell::new(callback),
++ reply: RefCell::new(Some(reply)),
++ _display: display.clone(),
++ app,
++ generation,
++ hidden,
++ });
++ let result = unsafe {
++ (client.wl_proxy_add_dispatcher)(
++ callback,
++ dispatch,
++ std::ptr::null(),
++ Rc::as_ptr(&pending).cast_mut().cast(),
++ )
+ };
- state.lock().unwrap().lease.as_mut().unwrap().phase = Phase::Restoring;
- acknowledge.send(()).unwrap();
- assert!(!pending.await.unwrap());
- assert_eq!(
- state.lock().unwrap().lease.as_ref().unwrap().phase,
- Phase::Restoring
- );
++ if result != 0 {
++ pending.finish(Err(
++ "Could not subscribe to Wayland visibility acknowledgement".into(),
++ ));
++ return;
+ }
++ // GDK owns dispatch on this connection. The timeout retains listener data until
++ // either the callback or timeout destroys the proxy, without reading GDK's queue.
++ gtk::glib::timeout_add_local_once(Duration::from_secs(2), move || {
++ pending.finish(Err(
++ "Wayland compositor did not acknowledge window visibility".into(),
++ ))
++ });
++ display.flush();
}
++}
- struct RunningControl {
- state: std::sync::Arc<Mutex<Inner>>,
- stages: tokio::sync::mpsc::UnboundedReceiver<&'static str>,
- hide: Option<tokio::sync::oneshot::Sender<Result<(), String>>>,
- change: Option<tokio::sync::oneshot::Sender<Result<(), String>>>,
- paused: Option<tokio::sync::oneshot::Sender<bool>>,
- reveal: Option<tokio::sync::oneshot::Sender<()>>,
- result: tokio::task::JoinHandle<Result<(), String>>,
- #[test]
- fn startup_failure_cannot_own_a_different_pending_recording() {
- let mut state = fixture();
- let old = PathBuf::from("failed-start-a");
- let new = PathBuf::from("pending-start-b");
- state.lease.as_mut().unwrap().phase = Phase::Starting;
- state.lease.as_mut().unwrap().recording_dir = Some(old.clone());
- assert_eq!(state.owner(&old), Some(1));
- assert_eq!(state.owner(&new), None);
- state.lease.as_mut().unwrap().recording_dir = Some(new.clone());
- state.lease.as_mut().unwrap().generation = 2;
- state.generation = 2;
- assert_eq!(state.owner(&old), None);
- assert_eq!(state.owner(&new), Some(2));
++#[cfg(target_os = "linux")]
++pub(crate) fn wayland_stop_lost(app: &AppHandle, generation: u32, route: StopRoute, error: String) {
++ let state = app.state::<State>();
++ let mut inner = state.inner.lock().unwrap();
++ let Some(lease) = inner
++ .lease
++ .as_mut()
++ .filter(|lease| lease.generation == generation && lease.wayland)
++ else {
++ return;
++ };
++ let stop = lease.lose_stop_route(route);
++ let studio_stop = (lease.mode == cap_recording::RecordingMode::Studio
++ && (stop || lease.stop_requested && lease.phase == Phase::Stopping))
++ .then(|| lease.recording_dir.clone())
++ .flatten();
++ if lease.stop_requested {
++ lease.stop_error = Some(error);
++ } else if route == StopRoute::Tray {
++ lease.stop_description = Some("the portal shortcut shown by your desktop".into());
+ }
-
- impl RunningControl {
- fn start(resume: bool) -> Self {
- let state = std::sync::Arc::new(Mutex::new(fixture()));
- {
- let mut inner = state.lock().unwrap();
- let lease = inner.lease.as_mut().unwrap();
- lease.phase = if resume {
- Phase::Resuming
- } else {
- Phase::Pausing
- };
- lease.recording_dir = Some(PathBuf::from("recording-a"));
- }
- let (stages, observed) = tokio::sync::mpsc::unbounded_channel();
- let (hide, hidden) = tokio::sync::oneshot::channel();
- let (change, changed) = tokio::sync::oneshot::channel();
- let (paused, acknowledged) = tokio::sync::oneshot::channel();
- let (reveal, mapping) = tokio::sync::oneshot::channel();
- let control_state = state.clone();
- let result = tokio::spawn(async move {
- let dir = PathBuf::from("recording-a");
- ControlOperation {
- resume,
- generation: 1,
- dir: &dir,
- hide: async {
- stages.send("hide").unwrap();
- hidden.await.unwrap()
- },
- change: async {
- stages.send("actor").unwrap();
- changed.await.unwrap()
- },
- paused: async {
- stages.send("confirm-paused").unwrap();
- acknowledged.await.unwrap()
- },
- restore: async {
- stages.send("queue-main").unwrap();
- mapping.await.unwrap();
- if control_state
- .lock()
- .unwrap()
- .may_restore_paused_main(1, &dir)
- {
- stages.send("show-main").unwrap();
- Ok(())
- } else {
- stages.send("suppress-main").unwrap();
- Err("Recording changed before mapping".into())
- }
- },
- stop: async {
- stages.send("stop").unwrap();
- assert!(!control_state.lock().unwrap().queue_stop());
- Ok(())
- },
- notify: || stages.send("notify").unwrap(),
- }
- .run(&control_state)
- .await
- });
- Self {
- state,
- stages: observed,
- hide: Some(hide),
- change: Some(change),
- paused: Some(paused),
- reveal: Some(reveal),
- result,
++ drop(inner);
++ notify(app);
++ if let Some(directory) = studio_stop {
++ crate::recording::queue_clean_studio_stop(app, generation, directory);
++ } else if stop {
++ let app = app.clone();
++ drop(tauri::async_runtime::spawn(async move {
++ if let Err(error) = crate::recording::stop_recording(app.clone(), app.state()).await {
++ tracing::error!(%error, "Could not stop recording after losing its Stop control");
+ }
- }
++ }));
+ }
++}
- async fn dispatch_stop(
- &self,
- ) -> (
- tokio::sync::oneshot::Sender<()>,
- tokio::task::JoinHandle<()>,
- ) {
- {
- let mut inner = self.state.lock().unwrap();
- assert!(inner.shortcut(true));
- assert!(inner.lease.as_ref().unwrap().phase.can_stop());
- assert!(!inner.queue_stop());
- }
- let (entered, delivered) = tokio::sync::oneshot::channel();
- let (acknowledge, joined) = tokio::sync::oneshot::channel();
- let state = self.state.clone();
- let stop = tokio::spawn(async move {
- entered.send(()).unwrap();
- joined.await.unwrap();
- let mut inner = state.lock().unwrap();
- if inner.owner(std::path::Path::new("recording-a")) == Some(1)
- && inner.lease.as_ref().unwrap().phase == Phase::Stopping
- {
- inner.lease.as_mut().unwrap().phase = Phase::Restoring;
- }
- });
- tokio::time::timeout(Duration::from_secs(1), delivered)
- .await
- .unwrap()
- .unwrap();
- (acknowledge, stop)
- #[tokio::test]
- async fn pending_pause_does_not_reveal_main_and_retains_queued_stop_after_ack() {
- let state = std::sync::Arc::new(Mutex::new(fixture()));
- let dir = PathBuf::from("recording-a");
- {
- let mut state = state.lock().unwrap();
- let lease = state.lease.as_mut().unwrap();
- lease.phase = Phase::Pausing;
- lease.recording_dir = Some(dir.clone());
- }
- let (acknowledge, received) = tokio::sync::oneshot::channel();
- let pending = {
- let state = state.clone();
- tokio::spawn(async move {
- received.await.unwrap();
- state
- .lock()
- .unwrap()
- .complete_control(1, &dir, false, &ControlOutcome::Succeeded)
- })
- };
- {
- let mut state = state.lock().unwrap();
- assert!(!state.may_reveal(1, "main"));
- assert!(state.queue_stop());
++#[cfg(target_os = "linux")]
++fn verify_wayland_hidden(app: &AppHandle, generation: u32) -> Result<(), String> {
++ use gtk::prelude::*;
++ if !is_current(app, generation) || stop_requested(app, generation) {
++ return Err("Recording hide acknowledgement was superseded or cancelled".into());
++ }
++ let main = CapWindowId::Main
++ .get(app)
++ .ok_or("Main recording window disappeared")?
++ .gtk_window()
++ .map_err(|error| error.to_string())?;
++ let display = main.display();
++ for window in wayland_application(app)?.windows() {
++ if window.display() != display || window.is_visible() || window.is_mapped() {
++ return Err("A Cap window is visible or uses another display connection".into());
}
- acknowledge.send(()).unwrap();
- assert!(pending.await.unwrap());
- let mut state = state.lock().unwrap();
- assert!(state.lease.as_ref().unwrap().stop_requested);
- assert!(!state.queue_stop());
- assert!(!state.may_reveal(1, "main"));
+ }
++ Ok(())
++}
- async fn expect(&mut self, stage: &'static str) {
- assert_eq!(
- tokio::time::timeout(Duration::from_secs(1), self.stages.recv())
- .await
- .unwrap(),
- Some(stage)
- );
- #[tokio::test]
- async fn stopped_owner_rejects_delayed_resume_acknowledgement() {
- let state = std::sync::Arc::new(Mutex::new(fixture()));
- let dir = PathBuf::from("recording-a");
- {
- let mut state = state.lock().unwrap();
- let lease = state.lease.as_mut().unwrap();
- lease.phase = Phase::Resuming;
- lease.recording_dir = Some(dir.clone());
++#[cfg(target_os = "linux")]
++fn verify_wayland_restored(app: &AppHandle, generation: u32) -> Result<(), String> {
++ use gtk::prelude::*;
++ for (saved, wanted) in wayland_restore_plan(app, generation, true)? {
++ if saved.window.is_visible() != wanted || saved.window.is_mapped() != wanted {
++ return Err("The compositor restore acknowledgement did not match Cap windows".into());
}
- let (acknowledge, received) = tokio::sync::oneshot::channel();
- let pending = {
- let state = state.clone();
- tokio::spawn(async move {
- received.await.unwrap();
- state
- .lock()
- .unwrap()
- .complete_control(1, &dir, true, &ControlOutcome::Succeeded)
- })
- };
- state.lock().unwrap().lease.as_mut().unwrap().phase = Phase::Restoring;
- acknowledge.send(()).unwrap();
- assert!(!pending.await.unwrap());
- assert_eq!(
- state.lock().unwrap().lease.as_ref().unwrap().phase,
- Phase::Restoring
- );
+ }
++ Ok(())
++}
- async fn finish(self) -> Result<(), String> {
- tokio::time::timeout(Duration::from_secs(1), self.result)
- .await
- .unwrap()
- .unwrap()
- struct RunningControl {
- state: std::sync::Arc<Mutex<Inner>>,
- stages: tokio::sync::mpsc::UnboundedReceiver<&'static str>,
- hide: Option<tokio::sync::oneshot::Sender<Result<(), String>>>,
- change: Option<tokio::sync::oneshot::Sender<Result<(), String>>>,
- paused: Option<tokio::sync::oneshot::Sender<bool>>,
- reveal: Option<tokio::sync::oneshot::Sender<()>>,
- result: tokio::task::JoinHandle<Result<(), String>>,
- }
++fn wayland_blocks_mapping(phase: Phase) -> bool {
++ !matches!(
++ phase,
++ Phase::AwaitingShortcut | Phase::Paused | Phase::Restoring
++ )
++}
+
- impl RunningControl {
- fn start(resume: bool) -> Self {
- let state = std::sync::Arc::new(Mutex::new(fixture()));
- {
- let mut inner = state.lock().unwrap();
- let lease = inner.lease.as_mut().unwrap();
- lease.phase = if resume {
- Phase::Resuming
- } else {
- Phase::Pausing
- };
- lease.recording_dir = Some(PathBuf::from("recording-a"));
- }
- let (stages, observed) = tokio::sync::mpsc::unbounded_channel();
- let (hide, hidden) = tokio::sync::oneshot::channel();
- let (change, changed) = tokio::sync::oneshot::channel();
- let (paused, acknowledged) = tokio::sync::oneshot::channel();
- let (reveal, mapping) = tokio::sync::oneshot::channel();
- let control_state = state.clone();
- let result = tokio::spawn(async move {
- let dir = PathBuf::from("recording-a");
- ControlOperation {
- resume,
- generation: 1,
- dir: &dir,
- hide: async {
- stages.send("hide").unwrap();
- hidden.await.unwrap()
- },
- change: async {
- stages.send("actor").unwrap();
- changed.await.unwrap()
- },
- paused: async {
- stages.send("confirm-paused").unwrap();
- acknowledged.await.unwrap()
- },
- restore: async {
- stages.send("queue-main").unwrap();
- mapping.await.unwrap();
- if control_state
- .lock()
- .unwrap()
- .may_restore_paused_main(1, &dir)
- {
- stages.send("show-main").unwrap();
- Ok(())
- } else {
- stages.send("suppress-main").unwrap();
- Err("Recording changed before mapping".into())
- }
- },
- stop: async {
- stages.send("stop").unwrap();
- assert!(!control_state.lock().unwrap().queue_stop());
- Ok(())
- },
- notify: || stages.send("notify").unwrap(),
- }
- .run(&control_state)
- .await
- });
- Self {
- state,
- stages: observed,
- hide: Some(hide),
- change: Some(change),
- paused: Some(paused),
- reveal: Some(reveal),
- result,
- }
- }
++#[cfg(any(target_os = "linux", test))]
++fn restore_floating_window(label: Option<&str>) -> bool {
++ !matches!(
++ label.and_then(|label| label.parse::<CapWindowId>().ok()),
++ Some(
++ CapWindowId::RecordingControls
++ | CapWindowId::TargetSelectOverlay { .. }
++ | CapWindowId::WindowCaptureOccluder { .. }
++ | CapWindowId::CaptureArea
++ )
++ )
++}
+
- async fn dispatch_stop(
- &self,
- ) -> (
- tokio::sync::oneshot::Sender<()>,
- tokio::task::JoinHandle<()>,
- ) {
- {
- let mut inner = self.state.lock().unwrap();
- assert!(inner.shortcut(true));
- assert!(inner.lease.as_ref().unwrap().phase.can_stop());
- assert!(!inner.queue_stop());
++#[cfg(target_os = "linux")]
++#[derive(Clone)]
++struct RetainedWaylandWindow {
++ window: gtk::Window,
++ label: Option<String>,
++ visible: bool,
++ requested_during_stop: bool,
++}
++
++#[cfg(target_os = "linux")]
++thread_local! {
++ static WAYLAND_GUARD_APPLICATION: std::cell::RefCell<Option<gtk::glib::WeakRef<gtk::Application>>> = const { std::cell::RefCell::new(None) };
++ static WAYLAND_GUARDED_WINDOWS: std::cell::RefCell<Vec<gtk::glib::WeakRef<gtk::Window>>> = const { std::cell::RefCell::new(Vec::new()) };
++ static WAYLAND_CAPTURE_WINDOWS: std::cell::RefCell<std::collections::HashMap<u32, Vec<RetainedWaylandWindow>>> = std::cell::RefCell::new(std::collections::HashMap::new());
++}
++
++#[cfg(target_os = "linux")]
++fn wayland_application(app: &AppHandle) -> Result<gtk::Application, String> {
++ use gtk::prelude::*;
++ CapWindowId::Main
++ .get(app)
++ .ok_or("Main recording window disappeared")?
++ .gtk_window()
++ .map_err(|error| error.to_string())?
++ .application()
++ .ok_or("Recording GTK application disappeared".into())
++}
++
++#[cfg(target_os = "linux")]
++fn wayland_window_label(app: &AppHandle, native: &gtk::Window) -> Option<String> {
++ use gtk::prelude::*;
++ app.webview_windows()
++ .into_iter()
++ .find_map(|(label, window)| {
++ window
++ .gtk_window()
++ .ok()
++ .filter(|window| window.upcast_ref::<gtk::Window>() == native)
++ .map(|_| label)
++ })
++}
++
++#[cfg(target_os = "linux")]
++fn remember_wayland_window(
++ app: &AppHandle,
++ generation: u32,
++ window: &gtk::Window,
++ during_stop: bool,
++) {
++ use gtk::prelude::*;
++ let label = wayland_window_label(app, window);
++ WAYLAND_CAPTURE_WINDOWS.with_borrow_mut(|windows| {
++ let windows = windows.entry(generation).or_default();
++ if let Some(saved) = windows.iter_mut().find(|saved| saved.window == *window) {
++ if during_stop {
++ saved.requested_during_stop = true;
+ }
- let (entered, delivered) = tokio::sync::oneshot::channel();
- let (acknowledge, joined) = tokio::sync::oneshot::channel();
- let state = self.state.clone();
- let stop = tokio::spawn(async move {
- entered.send(()).unwrap();
- joined.await.unwrap();
- let mut inner = state.lock().unwrap();
- if inner.owner(std::path::Path::new("recording-a")) == Some(1)
- && inner.lease.as_ref().unwrap().phase == Phase::Stopping
- {
- inner.lease.as_mut().unwrap().phase = Phase::Restoring;
- }
++ } else {
++ windows.push(RetainedWaylandWindow {
++ window: window.clone(),
++ label,
++ visible: window.is_visible(),
++ requested_during_stop: during_stop,
+ });
- tokio::time::timeout(Duration::from_secs(1), delivered)
- .await
- .unwrap()
- .unwrap();
- (acknowledge, stop)
}
- }
++ });
++}
- #[tokio::test]
- async fn resume_hide_failure_restores_main_without_calling_actor() {
- let mut run = RunningControl::start(true);
- run.expect("hide").await;
- run.hide
- .take()
- .unwrap()
- .send(Err("partial unmap failed".into()))
- .unwrap();
- run.expect("notify").await;
- run.expect("queue-main").await;
- async fn expect(&mut self, stage: &'static str) {
- assert_eq!(
- tokio::time::timeout(Duration::from_secs(1), self.stages.recv())
- .await
- .unwrap(),
- Some(stage)
- );
++#[cfg(target_os = "linux")]
++fn guard_wayland_window(app: &AppHandle, window: &gtk::Window) {
++ use gtk::prelude::*;
++ let already_guarded = WAYLAND_GUARDED_WINDOWS.with_borrow_mut(|windows| {
++ windows.retain(|window| window.upgrade().is_some());
++ if windows
++ .iter()
++ .any(|saved| saved.upgrade().as_ref() == Some(window))
+ {
- let inner = run.state.lock().unwrap();
- assert_eq!(inner.lease.as_ref().unwrap().phase, Phase::Paused);
- assert!(!inner.may_reveal(1, "camera"));
- assert!(!inner.may_reveal(1, "in-progress-recording"));
- assert!(inner.lease.as_ref().unwrap().registered_shortcut);
++ true
++ } else {
++ windows.push(window.downgrade());
++ false
+ }
- run.reveal.take().unwrap().send(()).unwrap();
- run.expect("show-main").await;
- assert_eq!(run.finish().await.unwrap_err(), "partial unmap failed");
++ });
++ if already_guarded {
++ return;
+ }
++ let app = app.clone();
++ window.connect_map(move |window| {
++ let blocked = {
++ let state = app.state::<State>();
++ let inner = state.inner.lock().unwrap();
++ inner
++ .lease
++ .as_ref()
++ .filter(|lease| lease.wayland && wayland_blocks_mapping(lease.phase))
++ .map(|lease| (lease.generation, lease.phase == Phase::Stopping))
++ };
++ if let Some((generation, during_stop)) = blocked {
++ remember_wayland_window(&app, generation, window, during_stop);
++ // GTK's map default handler sends an empty Wayland commit with updates frozen
++ // until initial configure. This synchronous handler unmaps before that dispatch.
++ window.hide();
+ }
++ });
++}
- #[tokio::test]
- async fn actor_resume_error_waits_for_quiescent_pause_ack_before_mapping() {
- let mut run = RunningControl::start(true);
- run.expect("hide").await;
- run.hide.take().unwrap().send(Ok(())).unwrap();
- run.expect("actor").await;
- run.change
- .take()
- .unwrap()
- .send(Err("segment setup failed".into()))
- .unwrap();
- run.expect("confirm-paused").await;
- assert!(!run.state.lock().unwrap().may_reveal(1, "main"));
- run.paused.take().unwrap().send(true).unwrap();
- run.expect("notify").await;
- run.expect("queue-main").await;
- run.reveal.take().unwrap().send(()).unwrap();
- run.expect("show-main").await;
- assert_eq!(run.finish().await.unwrap_err(), "segment setup failed");
- async fn finish(self) -> Result<(), String> {
- tokio::time::timeout(Duration::from_secs(1), self.result)
- .await
- .unwrap()
- .unwrap()
++#[cfg(target_os = "linux")]
++fn install_wayland_window_guard(app: &AppHandle) -> Result<(), String> {
++ use gtk::prelude::*;
++ let application = wayland_application(app)?;
++ let installed = WAYLAND_GUARD_APPLICATION
++ .with_borrow(|saved| saved.as_ref().and_then(gtk::glib::WeakRef::upgrade));
++ if let Some(installed) = installed {
++ if installed != application {
++ return Err("Recording GTK application identity changed".into());
+ }
++ return Ok(());
++ }
++ let handle = app.clone();
++ application.connect_window_added(move |_, window| guard_wayland_window(&handle, window));
++ for window in application.windows() {
++ guard_wayland_window(app, &window);
}
++ WAYLAND_GUARD_APPLICATION.with_borrow_mut(|saved| *saved = Some(application.downgrade()));
++ Ok(())
++}
-- #[tokio::test]
- async fn unknown_resume_error_does_not_map_and_stop_remains_executable() {
- async fn resume_hide_failure_restores_main_without_calling_actor() {
-- let mut run = RunningControl::start(true);
-- run.expect("hide").await;
- run.hide.take().unwrap().send(Ok(())).unwrap();
- run.expect("actor").await;
- run.change
- run.hide
-- .take()
-- .unwrap()
- .send(Err("transport failed".into()))
- .send(Err("partial unmap failed".into()))
-- .unwrap();
- run.expect("confirm-paused").await;
- run.paused.take().unwrap().send(false).unwrap();
-- run.expect("notify").await;
- let state = run.state.clone();
- assert!(
- run.finish()
- .await
- .unwrap_err()
- .contains("pause could not be confirmed")
- );
- let mut state = state.lock().unwrap();
- assert_eq!(state.lease.as_ref().unwrap().phase, Phase::ResumeFailed);
- assert!(state.shortcut(true));
- assert!(state.lease.as_ref().unwrap().phase.can_stop());
- assert!(!state.may_reveal(1, "main"));
- assert!(!state.queue_stop());
- run.expect("queue-main").await;
- {
- let inner = run.state.lock().unwrap();
- assert_eq!(inner.lease.as_ref().unwrap().phase, Phase::Paused);
- assert!(!inner.may_reveal(1, "camera"));
- assert!(!inner.may_reveal(1, "in-progress-recording"));
- assert!(inner.lease.as_ref().unwrap().registered_shortcut);
- }
- run.reveal.take().unwrap().send(()).unwrap();
- run.expect("show-main").await;
- assert_eq!(run.finish().await.unwrap_err(), "partial unmap failed");
++#[cfg(target_os = "linux")]
++fn remember_wayland_windows(app: &AppHandle, generation: u32) -> Result<(), String> {
++ use gtk::prelude::*;
++ for window in wayland_application(app)?.windows() {
++ remember_wayland_window(app, generation, &window, false);
}
++ Ok(())
++}
-- #[tokio::test]
- async fn stop_during_hide_executes_before_resume_and_rejects_late_hide() {
- for hidden in [Ok(()), Err("hide failed".into())] {
- let mut run = RunningControl::start(true);
- run.expect("hide").await;
- let (ack, stopped) = run.dispatch_stop().await;
- assert!(!run.result.is_finished());
- ack.send(()).unwrap();
- stopped.await.unwrap();
- run.hide.take().unwrap().send(hidden).unwrap();
- assert!(run.finish().await.unwrap_err().contains("changed during"));
- async fn actor_resume_error_waits_for_quiescent_pause_ack_before_mapping() {
- let mut run = RunningControl::start(true);
- run.expect("hide").await;
- run.hide.take().unwrap().send(Ok(())).unwrap();
- run.expect("actor").await;
- run.change
- .take()
- .unwrap()
- .send(Err("segment setup failed".into()))
- .unwrap();
- run.expect("confirm-paused").await;
- assert!(!run.state.lock().unwrap().may_reveal(1, "main"));
- run.paused.take().unwrap().send(true).unwrap();
- run.expect("notify").await;
- run.expect("queue-main").await;
- run.reveal.take().unwrap().send(()).unwrap();
- run.expect("show-main").await;
- assert_eq!(run.finish().await.unwrap_err(), "segment setup failed");
++#[cfg(target_os = "linux")]
++fn hide_wayland_windows(app: &AppHandle, generation: u32) -> Result<(), String> {
++ use gtk::prelude::*;
++ remember_wayland_windows(app, generation)?;
++ for window in wayland_application(app)?.windows() {
++ window.hide();
++ if window.is_visible() || window.is_mapped() {
++ return Err("GTK could not hide a Cap window".into());
+ }
}
++ Ok(())
++}
-- #[tokio::test]
- async fn stop_during_pause_confirmation_executes_without_waiting_for_it() {
- for paused in [true, false] {
- let mut run = RunningControl::start(true);
- run.expect("hide").await;
- run.hide.take().unwrap().send(Ok(())).unwrap();
- run.expect("actor").await;
- run.change
- .take()
- .unwrap()
- .send(Err("setup failed".into()))
- .unwrap();
- run.expect("confirm-paused").await;
- let (ack, stopped) = run.dispatch_stop().await;
- assert!(!run.result.is_finished());
- ack.send(()).unwrap();
- stopped.await.unwrap();
- run.paused.take().unwrap().send(paused).unwrap();
- assert!(run.finish().await.unwrap_err().contains("changed during"));
- }
- async fn unknown_resume_error_does_not_map_and_stop_remains_executable() {
- let mut run = RunningControl::start(true);
- run.expect("hide").await;
- run.hide.take().unwrap().send(Ok(())).unwrap();
- run.expect("actor").await;
- run.change
- .take()
- .unwrap()
- .send(Err("transport failed".into()))
- .unwrap();
- run.expect("confirm-paused").await;
- run.paused.take().unwrap().send(false).unwrap();
- run.expect("notify").await;
- let state = run.state.clone();
- assert!(
- run.finish()
- .await
- .unwrap_err()
- .contains("pause could not be confirmed")
- );
- let mut state = state.lock().unwrap();
- assert_eq!(state.lease.as_ref().unwrap().phase, Phase::ResumeFailed);
- assert!(state.shortcut(true));
- assert!(state.lease.as_ref().unwrap().phase.can_stop());
- assert!(!state.may_reveal(1, "main"));
- assert!(!state.queue_stop());
++#[cfg(target_os = "linux")]
++pub(crate) fn admit_wayland_window_creation(app: &AppHandle) -> Result<(), String> {
++ let state = app.state::<State>();
++ let inner = state.inner.lock().unwrap();
++ if inner.lease.as_ref().is_some_and(|lease| {
++ lease.wayland && wayland_blocks_mapping(lease.phase) && lease.phase != Phase::Stopping
++ }) {
++ return Err("Pause or stop recording before opening another Cap window".into());
}
++ Ok(())
++}
-- #[tokio::test]
- async fn pending_resume_does_not_block_stop_and_late_result_cannot_publish() {
- for resumed in [Ok(()), Err("cancelled setup".into())] {
- async fn stop_during_hide_executes_before_resume_and_rejects_late_hide() {
- for hidden in [Ok(()), Err("hide failed".into())] {
-- let mut run = RunningControl::start(true);
-- run.expect("hide").await;
- run.hide.take().unwrap().send(Ok(())).unwrap();
- run.expect("actor").await;
-- let (ack, stopped) = run.dispatch_stop().await;
-- assert!(!run.result.is_finished());
- assert_eq!(
- run.state.lock().unwrap().lease.as_ref().unwrap().phase,
- Phase::Stopping
- );
-- ack.send(()).unwrap();
-- stopped.await.unwrap();
- assert!(!run.result.is_finished());
- let failed = resumed.is_err();
- run.change.take().unwrap().send(resumed).unwrap();
- if failed {
- run.expect("confirm-paused").await;
- run.paused.take().unwrap().send(true).unwrap();
- }
- let state = run.state.clone();
- run.hide.take().unwrap().send(hidden).unwrap();
-- assert!(run.finish().await.unwrap_err().contains("changed during"));
- let inner = state.lock().unwrap();
- assert_eq!(inner.lease.as_ref().unwrap().phase, Phase::Restoring);
- assert!(inner.snapshot().error.is_none());
++#[cfg(target_os = "linux")]
++fn wayland_restore_plan(
++ app: &AppHandle,
++ generation: u32,
++ require_inputs: bool,
++) -> Result<Vec<(RetainedWaylandWindow, bool)>, String> {
++ use gtk::prelude::*;
++ let saved_main = {
++ let state = app.state::<State>();
++ let inner = state.inner.lock().unwrap();
++ let lease = inner
++ .lease
++ .as_ref()
++ .filter(|lease| lease.generation == generation && lease.phase == Phase::Restoring)
++ .ok_or("Wayland restoration was superseded")?;
++ lease
++ .windows
++ .iter()
++ .find(|window| window.label == CapWindowId::Main.label())
++ .cloned()
++ };
++ let requested = if require_inputs {
++ Some(
++ app.state::<crate::RequestedInputsState>()
++ .ready_snapshot()?,
++ )
++ } else {
++ None
++ };
++ let retained = WAYLAND_CAPTURE_WINDOWS
++ .with_borrow(|windows| windows.get(&generation).cloned())
++ .ok_or("Retained Wayland windows disappeared")?;
++ let application = WAYLAND_GUARD_APPLICATION
++ .with_borrow(|saved| saved.as_ref().and_then(gtk::glib::WeakRef::upgrade))
++ .ok_or("Retained GTK application disappeared")?;
++ let current = application.windows();
++ let mut result = Vec::new();
++ for mut saved in retained {
++ let label = wayland_window_label(app, &saved.window);
++ let label_changed = saved.label.is_some() && saved.label != label;
++ if saved.label.is_none() {
++ saved.label = label;
+ }
- }
-
- #[tokio::test]
- async fn delayed_pause_confirmation_cannot_publish_to_new_owner() {
- let mut run = RunningControl::start(true);
- run.expect("hide").await;
- run.hide.take().unwrap().send(Ok(())).unwrap();
- run.expect("actor").await;
- run.change
- .take()
- .unwrap()
- .send(Err("setup failed".into()))
- .unwrap();
- run.expect("confirm-paused").await;
- {
- let mut inner = run.state.lock().unwrap();
- inner.generation = 2;
- let lease = inner.lease.as_mut().unwrap();
- lease.generation = 2;
- lease.recording_dir = Some(PathBuf::from("recording-b"));
++ let camera = saved
++ .label
++ .as_deref()
++ .is_some_and(|label| matches!(label.parse(), Ok(CapWindowId::Camera)));
++ let editor = saved
++ .label
++ .as_deref()
++ .is_some_and(|label| matches!(label.parse(), Ok(CapWindowId::Editor { .. })));
++ let mut wanted = (saved.visible || (editor && saved.requested_during_stop))
++ && restore_floating_window(saved.label.as_deref())
++ && (!camera
++ || requested
++ .as_ref()
++ .is_some_and(|snapshot| snapshot.camera.value.is_some()));
++ if saved.label.as_deref() == Some("main") {
++ wanted = saved_main.as_ref().is_some_and(|saved| saved.visible);
+ }
- run.paused.take().unwrap().send(true).unwrap();
- let state = run.state.clone();
- assert!(run.finish().await.unwrap_err().contains("changed during"));
- assert_eq!(
- state.lock().unwrap().lease.as_ref().unwrap().phase,
- Phase::Resuming
- );
++ if wanted && label_changed {
++ return Err("A retained Cap window changed identity".into());
++ }
++ if wanted && !current.contains(&saved.window) {
++ return Err("A retained Cap window disappeared before restoration".into());
+ }
++ result.push((saved, wanted));
++ }
++ if requested.as_ref().is_some_and(|requested| {
++ !app.state::<crate::RequestedInputsState>()
++ .is_current(requested)
++ }) {
++ return Err("Requested inputs changed during Wayland restoration".into());
}
++ Ok(result)
++}
-- #[tokio::test]
- async fn delayed_main_mapping_rechecks_owner_phase_and_stop() {
- for mutation in 0..4 {
- async fn stop_during_pause_confirmation_executes_without_waiting_for_it() {
- for paused in [true, false] {
-- let mut run = RunningControl::start(true);
-- run.expect("hide").await;
- run.hide
- run.hide.take().unwrap().send(Ok(())).unwrap();
- run.expect("actor").await;
- run.change
-- .take()
-- .unwrap()
- .send(Err("hide failed".into()))
- .send(Err("setup failed".into()))
-- .unwrap();
- run.expect("notify").await;
- run.expect("queue-main").await;
- run.expect("confirm-paused").await;
- let (ack, stopped) = run.dispatch_stop().await;
- assert!(!run.result.is_finished());
- ack.send(()).unwrap();
- stopped.await.unwrap();
- run.paused.take().unwrap().send(paused).unwrap();
- assert!(run.finish().await.unwrap_err().contains("changed during"));
++#[cfg(target_os = "linux")]
++fn restore_wayland_windows(
++ app: &AppHandle,
++ generation: u32,
++ main_only: bool,
++) -> Result<(), String> {
++ use gtk::prelude::*;
++ for (saved, wanted) in wayland_restore_plan(app, generation, !main_only)? {
++ if (saved.label.as_deref() == Some("main")) != main_only {
++ continue;
++ }
++ if wanted {
++ saved.window.show_all();
++ if saved.requested_during_stop
++ && saved
++ .label
++ .as_deref()
++ .is_some_and(|label| matches!(label.parse(), Ok(CapWindowId::Editor { .. })))
+ {
- let mut inner = run.state.lock().unwrap();
- match mutation {
- 0 => {
- inner.generation = 2;
- inner.lease.as_mut().unwrap().generation = 2;
- }
- 1 => {
- inner.lease.as_mut().unwrap().recording_dir =
- Some(PathBuf::from("recording-b"))
- }
- 2 => inner.lease.as_mut().unwrap().phase = Phase::Resuming,
- _ => inner.lease.as_mut().unwrap().stop_requested = true,
- }
++ saved.window.present();
+ }
- run.reveal.take().unwrap().send(()).unwrap();
- run.expect("suppress-main").await;
- assert!(
- run.finish()
- .await
- .unwrap_err()
- .contains("Could not restore controls")
- );
++ } else {
++ saved.window.hide();
++ }
++ if saved.window.is_visible() != wanted || (!wanted && saved.window.is_mapped()) {
++ return Err("GTK did not acknowledge Cap window restoration".into());
}
}
++ Ok(())
++}
-- #[tokio::test]
- async fn ordinary_pause_and_successful_resume_never_use_failure_restore() {
- for resume in [false, true] {
- let mut run = RunningControl::start(resume);
- if resume {
- run.expect("hide").await;
- run.hide.take().unwrap().send(Ok(())).unwrap();
- }
- async fn pending_resume_does_not_block_stop_and_late_result_cannot_publish() {
- for resumed in [Ok(()), Err("cancelled setup".into())] {
- let mut run = RunningControl::start(true);
- run.expect("hide").await;
- run.hide.take().unwrap().send(Ok(())).unwrap();
-- run.expect("actor").await;
- run.change.take().unwrap().send(Ok(())).unwrap();
- run.expect("notify").await;
- let state = run.state.clone();
- assert!(run.finish().await.is_ok());
- let (ack, stopped) = run.dispatch_stop().await;
- assert!(!run.result.is_finished());
-- assert_eq!(
- state.lock().unwrap().lease.as_ref().unwrap().phase,
- if resume {
- Phase::Recording
- } else {
- Phase::Paused
- run.state.lock().unwrap().lease.as_ref().unwrap().phase,
- Phase::Stopping
- );
- ack.send(()).unwrap();
- stopped.await.unwrap();
- assert!(!run.result.is_finished());
- let failed = resumed.is_err();
- run.change.take().unwrap().send(resumed).unwrap();
- if failed {
- run.expect("confirm-paused").await;
- run.paused.take().unwrap().send(true).unwrap();
++#[cfg(test)]
++mod tests {
++ use super::*;
++
++ #[test]
++ fn wayland_blocks_all_floating_labels_while_capture_can_run() {
++ for mode in [
++ cap_recording::RecordingMode::Studio,
++ cap_recording::RecordingMode::Instant,
++ ] {
++ for phase in [
++ Phase::Starting,
++ Phase::Recording,
++ Phase::Pausing,
++ Phase::Resuming,
++ Phase::ResumeFailed,
++ Phase::Restarting,
++ Phase::Stopping,
++ ] {
++ let mut inner = fixture();
++ let lease = inner.lease.as_mut().unwrap();
++ lease.mode = mode;
++ lease.wayland = true;
++ lease.phase = phase;
++ for label in [
++ "main",
++ "camera",
++ "teleprompter",
++ "settings",
++ "editor-4",
++ "unknown-js-window",
++ ] {
++ assert!(!inner.may_reveal(1, label), "{phase:?}: {label}");
+ }
- );
+ }
- let state = run.state.clone();
- assert!(run.finish().await.unwrap_err().contains("changed during"));
- let inner = state.lock().unwrap();
- assert_eq!(inner.lease.as_ref().unwrap().phase, Phase::Restoring);
- assert!(inner.snapshot().error.is_none());
}
}
-- #[tokio::test]
- async fn stale_hide_completion_never_invokes_actor_or_restores_main() {
- for success in [false, true] {
- let mut run = RunningControl::start(true);
- run.expect("hide").await;
- run.state.lock().unwrap().lease.as_mut().unwrap().phase = Phase::Restoring;
- run.hide
- .take()
- .unwrap()
- .send(if success {
- Ok(())
- } else {
- Err("hide failed".into())
- })
- .unwrap();
- assert!(run.finish().await.unwrap_err().contains("changed during"));
- }
- async fn delayed_pause_confirmation_cannot_publish_to_new_owner() {
- let mut run = RunningControl::start(true);
- run.expect("hide").await;
- run.hide.take().unwrap().send(Ok(())).unwrap();
- run.expect("actor").await;
- run.change
- .take()
- .unwrap()
- .send(Err("setup failed".into()))
- .unwrap();
- run.expect("confirm-paused").await;
- {
- let mut inner = run.state.lock().unwrap();
- inner.generation = 2;
++ #[test]
++ fn x11_floating_admission_is_unchanged() {
++ let mut inner = fixture();
++ inner.lease.as_mut().unwrap().phase = Phase::Recording;
++ assert!(!inner.lease.as_ref().unwrap().wayland);
++ assert!(inner.may_reveal(1, "teleprompter"));
++ assert!(inner.may_reveal(1, "settings"));
++ assert!(!inner.may_reveal(1, "camera"));
+ }
+
- #[tokio::test]
- async fn failed_pause_does_not_run_resume_probe_or_restore() {
- let mut run = RunningControl::start(false);
- run.expect("actor").await;
- run.change
- .take()
- .unwrap()
- .send(Err("pause failed".into()))
- .unwrap();
- run.expect("notify").await;
- let state = run.state.clone();
- assert_eq!(run.finish().await.unwrap_err(), "pause failed");
- assert_eq!(
- state.lock().unwrap().lease.as_ref().unwrap().phase,
- Phase::Recording
- );
- assert!(!state.lock().unwrap().may_reveal(1, "main"));
++ #[test]
++ fn wayland_restore_keeps_non_camera_window_intent() {
++ for label in ["teleprompter", "settings", "editor-4", "unknown-js-window"] {
++ assert!(restore_floating_window(Some(label)));
++ }
++ assert!(restore_floating_window(None));
++ for label in [
++ "capture-area",
++ "in-progress-recording",
++ "target-select-overlay-1",
++ "window-capture-occluder-1",
++ ] {
++ assert!(!restore_floating_window(Some(label)));
++ }
+ }
+
+ #[test]
- fn control_error_survives_stop_and_release_but_not_a_new_owner() {
- let mut inner = fixture();
- let dir = PathBuf::from("recording-a");
- inner.lease.as_mut().unwrap().recording_dir = Some(dir.clone());
- inner.lease.as_mut().unwrap().phase = Phase::Resuming;
- assert!(inner.complete_control(
- 1,
- &dir,
- true,
- &ControlOutcome::ActorFailed {
- error: "capture setup failed".into(),
- paused: false
- }
- ));
- assert_eq!(
- inner.snapshot().error.as_deref(),
- Some("capture setup failed")
- );
- assert!(!inner.queue_stop());
- assert_eq!(
- inner.snapshot().error.as_deref(),
- Some("capture setup failed")
- );
- inner.lease = None;
- assert_eq!(
- inner.snapshot().error.as_deref(),
- Some("capture setup failed")
- );
- inner.generation = 2;
- assert!(inner.snapshot().error.is_none());
++ fn wayland_safe_ui_phases_allow_mapping_but_old_generation_does_not() {
++ for phase in [Phase::AwaitingShortcut, Phase::Paused, Phase::Restoring] {
++ assert!(!wayland_blocks_mapping(phase));
++ let mut inner = fixture();
+ let lease = inner.lease.as_mut().unwrap();
- lease.generation = 2;
- lease.recording_dir = Some(PathBuf::from("recording-b"));
++ lease.wayland = true;
++ lease.phase = phase;
++ assert!(inner.may_reveal(1, "teleprompter"));
++ assert!(!inner.may_reveal(0, "teleprompter"));
+ }
- run.paused.take().unwrap().send(true).unwrap();
- let state = run.state.clone();
- assert!(run.finish().await.unwrap_err().contains("changed during"));
- assert_eq!(
- state.lock().unwrap().lease.as_ref().unwrap().phase,
- Phase::Resuming
- );
}
- }
-
- #[cfg(all(test, target_os = "linux"))]
- mod instant_activation_tests {
- use super::*;
- use std::sync::{
- Arc,
- atomic::{AtomicUsize, Ordering},
- };
#[tokio::test]
- async fn instant_seal_waits_for_hide_ack_then_settle_then_revalidates() {
- let (hide_tx, hide_rx) = tokio::sync::oneshot::channel();
- let (settle_tx, settle_rx) = tokio::sync::oneshot::channel();
- let (settling_tx, settling_rx) = tokio::sync::oneshot::channel();
- let stage = Arc::new(AtomicUsize::new(0));
- let observed = stage.clone();
- async fn delayed_main_mapping_rechecks_owner_phase_and_stop() {
- for mutation in 0..4 {
- let mut run = RunningControl::start(true);
- run.expect("hide").await;
- run.hide
- .take()
- .unwrap()
- .send(Err("hide failed".into()))
- .unwrap();
- run.expect("notify").await;
- run.expect("queue-main").await;
- {
- let mut inner = run.state.lock().unwrap();
- match mutation {
- 0 => {
- inner.generation = 2;
- inner.lease.as_mut().unwrap().generation = 2;
- }
- 1 => {
- inner.lease.as_mut().unwrap().recording_dir =
- Some(PathBuf::from("recording-b"))
- }
- 2 => inner.lease.as_mut().unwrap().phase = Phase::Resuming,
- _ => inner.lease.as_mut().unwrap().stop_requested = true,
- }
++ async fn restore_pass_waits_for_successful_ack_before_following_work() {
++ let (tx, rx) = tokio::sync::oneshot::channel();
++ let work = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
++ let observed = work.clone();
+ let task = tokio::spawn(async move {
- let validated = observed.clone();
- seal_then_settle(
- async { hide_rx.await.map_err(|_| "hide ack lost".to_string()) },
- async {
- observed.store(1, Ordering::SeqCst);
- settling_tx.send(()).unwrap();
- settle_rx.await.map_err(|_| "settle cancelled".to_string())
- },
- |owner| async move {
- validated.store(2, Ordering::SeqCst);
- Ok(owner)
- },
- )
- .await
++ if restore_pass_acknowledged(true, rx).await {
++ observed.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ }
- run.reveal.take().unwrap().send(()).unwrap();
- run.expect("suppress-main").await;
- assert!(
- run.finish()
- .await
- .unwrap_err()
- .contains("Could not restore controls")
- );
- }
+ });
+ tokio::task::yield_now().await;
- assert_eq!(stage.load(Ordering::SeqCst), 0);
- assert!(!task.is_finished());
- hide_tx.send(7).unwrap();
- settling_rx.await.unwrap();
- assert_eq!(stage.load(Ordering::SeqCst), 1);
+ assert!(!task.is_finished());
- settle_tx.send(()).unwrap();
- assert_eq!(task.await.unwrap().unwrap(), 7);
- assert_eq!(stage.load(Ordering::SeqCst), 2);
++ assert_eq!(work.load(std::sync::atomic::Ordering::SeqCst), 0);
++ tx.send(Ok(())).unwrap();
++ task.await.unwrap();
++ assert_eq!(work.load(std::sync::atomic::Ordering::SeqCst), 1);
}
#[tokio::test]
- async fn instant_lost_hide_ack_never_settles_or_builds() {
- let (tx, rx) = tokio::sync::oneshot::channel::<u32>();
- drop(tx);
- let result = seal_then_settle(
- async { rx.await.map_err(|_| "hide ack lost".to_string()) },
- async { panic!("settle cannot begin before hide acknowledgement") },
- |_| async { panic!("build validation cannot begin") },
- )
- .await;
- assert_eq!(result.unwrap_err(), "hide ack lost");
- async fn ordinary_pause_and_successful_resume_never_use_failure_restore() {
- for resume in [false, true] {
- let mut run = RunningControl::start(resume);
- if resume {
- run.expect("hide").await;
- run.hide.take().unwrap().send(Ok(())).unwrap();
- }
- run.expect("actor").await;
- run.change.take().unwrap().send(Ok(())).unwrap();
- run.expect("notify").await;
- let state = run.state.clone();
- assert!(run.finish().await.is_ok());
- assert_eq!(
- state.lock().unwrap().lease.as_ref().unwrap().phase,
- if resume {
- Phase::Recording
- } else {
- Phase::Paused
- }
- );
- }
++ async fn rejected_restore_pass_does_not_authorize_following_work() {
++ let (tx, rx) = tokio::sync::oneshot::channel();
++ tx.send(Err("Instant cleanup is unconfirmed".into()))
++ .unwrap();
++ assert!(!restore_pass_acknowledged(true, rx).await);
}
#[tokio::test]
- async fn instant_cancelled_settle_does_not_revalidate_or_build() {
- let result = seal_then_settle(
- async { Ok(7) },
- async { Err("cancelled".into()) },
- |_| async { panic!("cancelled preparation cannot build") },
- )
- .await;
- assert_eq!(result.unwrap_err(), "cancelled");
- async fn stale_hide_completion_never_invokes_actor_or_restores_main() {
- for success in [false, true] {
- let mut run = RunningControl::start(true);
- run.expect("hide").await;
- run.state.lock().unwrap().lease.as_mut().unwrap().phase = Phase::Restoring;
- run.hide
- .take()
- .unwrap()
- .send(if success {
- Ok(())
- } else {
- Err("hide failed".into())
- })
- .unwrap();
- assert!(run.finish().await.unwrap_err().contains("changed during"));
- }
++ async fn dropped_restore_ack_does_not_authorize_following_work() {
++ let (tx, rx) = tokio::sync::oneshot::channel();
++ drop(tx);
++ assert!(!restore_pass_acknowledged(true, rx).await);
}
#[tokio::test]
- async fn instant_changed_effect_or_geometry_after_settle_rejects_owner() {
- let result = seal_then_settle(async { Ok(7) }, async { Ok(()) }, |owner| async move {
- assert_eq!(owner, 7);
- Err("prepared presentation changed".into())
- })
- .await;
- assert_eq!(result.unwrap_err(), "prepared presentation changed");
- async fn failed_pause_does_not_run_resume_probe_or_restore() {
- let mut run = RunningControl::start(false);
- run.expect("actor").await;
- run.change
- .take()
++ async fn unscheduled_restore_pass_does_not_wait_for_an_ack() {
++ let (tx, rx) = tokio::sync::oneshot::channel();
++ assert!(
++ !tokio::time::timeout(
++ std::time::Duration::from_millis(100),
++ restore_pass_acknowledged(false, rx),
++ )
++ .await
+ .unwrap()
- .send(Err("pause failed".into()))
- .unwrap();
- run.expect("notify").await;
- let state = run.state.clone();
- assert_eq!(run.finish().await.unwrap_err(), "pause failed");
- assert_eq!(
- state.lock().unwrap().lease.as_ref().unwrap().phase,
- Phase::Recording
+ );
- assert!(!state.lock().unwrap().may_reveal(1, "main"));
++ assert!(tx.is_closed());
+ }
+
- #[test]
- fn control_error_survives_stop_and_release_but_not_a_new_owner() {
++ #[cfg(target_os = "linux")]
++ fn x11_studio_restoring_fixture() -> Mutex<Inner> {
+ let mut inner = fixture();
- let dir = PathBuf::from("recording-a");
- inner.lease.as_mut().unwrap().recording_dir = Some(dir.clone());
- inner.lease.as_mut().unwrap().phase = Phase::Resuming;
- assert!(inner.complete_control(
- 1,
- &dir,
- true,
- &ControlOutcome::ActorFailed {
- error: "capture setup failed".into(),
- paused: false
- }
- ));
- assert_eq!(
- inner.snapshot().error.as_deref(),
- Some("capture setup failed")
- );
- assert!(!inner.queue_stop());
- assert_eq!(
- inner.snapshot().error.as_deref(),
- Some("capture setup failed")
- );
- inner.lease = None;
- assert_eq!(
- inner.snapshot().error.as_deref(),
- Some("capture setup failed")
- );
- inner.generation = 2;
- assert!(inner.snapshot().error.is_none());
++ inner.lease.as_mut().unwrap().phase = Phase::Restoring;
++ Mutex::new(inner)
}
-}
-
-#[cfg(all(test, target_os = "linux"))]
-mod instant_activation_tests {
- use super::*;
- use std::sync::{
- Arc,
- atomic::{AtomicUsize, Ordering},
- };
++ #[cfg(target_os = "linux")]
#[tokio::test]
- async fn instant_restore_waits_for_main_and_camera_acknowledgements() {
- let (main_tx, main_rx) = tokio::sync::oneshot::channel();
- let (camera_tx, camera_rx) = tokio::sync::oneshot::channel();
- async fn instant_seal_waits_for_hide_ack_then_settle_then_revalidates() {
- let (hide_tx, hide_rx) = tokio::sync::oneshot::channel();
- let (settle_tx, settle_rx) = tokio::sync::oneshot::channel();
- let (settling_tx, settling_rx) = tokio::sync::oneshot::channel();
- let stage = Arc::new(AtomicUsize::new(0));
- let observed = stage.clone();
- let task = tokio::spawn(async move {
- let validated = observed.clone();
- seal_then_settle(
- async { hide_rx.await.map_err(|_| "hide ack lost".to_string()) },
- async {
- observed.store(1, Ordering::SeqCst);
- settling_tx.send(()).unwrap();
- settle_rx.await.map_err(|_| "settle cancelled".to_string())
- },
- |owner| async move {
- validated.store(2, Ordering::SeqCst);
- Ok(owner)
- },
- )
- .await
- });
- tokio::task::yield_now().await;
- assert_eq!(stage.load(Ordering::SeqCst), 0);
- assert!(!task.is_finished());
- hide_tx.send(7).unwrap();
- settling_rx.await.unwrap();
- assert_eq!(stage.load(Ordering::SeqCst), 1);
- assert!(!task.is_finished());
- settle_tx.send(()).unwrap();
- assert_eq!(task.await.unwrap().unwrap(), 7);
- assert_eq!(stage.load(Ordering::SeqCst), 2);
- }
++ async fn x11_studio_restore_waits_for_windows_before_stop_cleanup_and_receipt() {
++ use std::sync::{
++ Arc,
++ atomic::{AtomicUsize, Ordering},
++ };
+
- #[tokio::test]
- async fn instant_lost_hide_ack_never_settles_or_builds() {
- let (tx, rx) = tokio::sync::oneshot::channel::<u32>();
- drop(tx);
- let result = seal_then_settle(
- async { rx.await.map_err(|_| "hide ack lost".to_string()) },
- async { panic!("settle cannot begin before hide acknowledgement") },
- |_| async { panic!("build validation cannot begin") },
- )
- .await;
- assert_eq!(result.unwrap_err(), "hide ack lost");
- }
-
- #[tokio::test]
- async fn instant_cancelled_settle_does_not_revalidate_or_build() {
- let result = seal_then_settle(
- async { Ok(7) },
- async { Err("cancelled".into()) },
- |_| async { panic!("cancelled preparation cannot build") },
- )
- .await;
- assert_eq!(result.unwrap_err(), "cancelled");
- }
-
- #[tokio::test]
- async fn instant_changed_effect_or_geometry_after_settle_rejects_owner() {
- let result = seal_then_settle(async { Ok(7) }, async { Ok(()) }, |owner| async move {
- assert_eq!(owner, 7);
- Err("prepared presentation changed".into())
- })
- .await;
- assert_eq!(result.unwrap_err(), "prepared presentation changed");
- }
-
- #[tokio::test]
- async fn instant_restore_waits_for_main_and_camera_acknowledgements() {
- let (main_tx, main_rx) = tokio::sync::oneshot::channel();
- let (camera_tx, camera_rx) = tokio::sync::oneshot::channel();
++ let inner = Arc::new(x11_studio_restoring_fixture());
++ let inputs = Arc::new(AtomicUsize::new(0));
++ let cleanup = Arc::new(AtomicUsize::new(0));
++ let (main_tx, main_rx) = tokio::sync::oneshot::channel::<Result<(), String>>();
++ let (camera_tx, camera_rx) = tokio::sync::oneshot::channel::<Result<(), String>>();
let (inputs_tx, inputs_rx) = tokio::sync::oneshot::channel();
-- let stage = Arc::new(AtomicUsize::new(0));
-- let observed = stage.clone();
-- let task = tokio::spawn(async move {
-- restore_instant_sequence(
-- async { main_rx.await.map_err(|_| "main ack lost".to_string()) },
-- || async {
-- observed.store(1, Ordering::SeqCst);
-- inputs_tx.send(()).unwrap();
-- },
-- || async { camera_rx.await.map_err(|_| "camera ack lost".to_string()) },
-- )
-- .await
++ let task = tokio::spawn({
++ let inner = inner.clone();
++ let inputs = inputs.clone();
++ let cleanup = cleanup.clone();
++ async move {
++ let result = restore_instant_sequence(
++ async { main_rx.await.unwrap() },
++ || async move {
++ inputs.fetch_add(1, Ordering::SeqCst);
++ inputs_tx.send(()).unwrap();
++ },
++ || async { camera_rx.await.unwrap() },
++ )
++ .await;
++ assert!(finish_x11_studio_restoration(&inner, 1, result, || {
++ cleanup.fetch_add(1, Ordering::SeqCst);
++ Ok(())
++ }));
++ }
});
tokio::task::yield_now().await;
-- assert_eq!(stage.load(Ordering::SeqCst), 0);
-- main_tx.send(()).unwrap();
++ assert!(!task.is_finished());
++ assert_eq!(inputs.load(Ordering::SeqCst), 0);
++ assert_eq!(cleanup.load(Ordering::SeqCst), 0);
++ assert!(inner.lock().unwrap().restored.is_none());
++ main_tx.send(Ok(())).unwrap();
inputs_rx.await.unwrap();
-- assert_eq!(stage.load(Ordering::SeqCst), 1);
assert!(!task.is_finished());
-- camera_tx.send(()).unwrap();
-- task.await.unwrap().unwrap();
++ assert_eq!(inputs.load(Ordering::SeqCst), 1);
++ assert_eq!(cleanup.load(Ordering::SeqCst), 0);
++ assert!(inner.lock().unwrap().lease.is_some());
++ assert!(inner.lock().unwrap().restored.is_none());
++ camera_tx.send(Ok(())).unwrap();
++ task.await.unwrap();
++ let inner = inner.lock().unwrap();
++ assert!(inner.lease.is_none());
++ assert_eq!(inner.generation, 2);
++ let receipt = inner.restored.as_ref().unwrap();
++ assert_eq!(receipt.generation, 1);
++ assert_eq!(receipt.restart_result(), Ok(()));
++ assert_eq!(cleanup.load(Ordering::SeqCst), 1);
}
-- #[tokio::test]
-- async fn instant_restore_rejected_or_lost_main_ack_never_restores_inputs() {
-- for rejected in [true, false] {
-- let (tx, rx) = tokio::sync::oneshot::channel::<Result<(), String>>();
-- if rejected {
-- tx.send(Err("unsafe cleanup".into())).unwrap();
-- } else {
-- drop(tx);
++ #[cfg(target_os = "linux")]
++ #[test]
++ fn x11_studio_restore_failures_retain_ownership_and_report_failure_until_retry() {
++ for (windows, cleanup, error, cleanup_calls) in [
++ (
++ Err("window restoration failed".to_string()),
++ Ok(()),
++ "window restoration failed",
++ 0,
++ ),
++ (
++ Ok(()),
++ Err("Stop cleanup failed".to_string()),
++ "Stop cleanup failed",
++ 1,
++ ),
++ ] {
++ let state = x11_studio_restoring_fixture();
++ let calls = std::cell::Cell::new(0);
++ assert!(!finish_x11_studio_restoration(&state, 1, windows, || {
++ calls.set(calls.get() + 1);
++ cleanup
++ }));
++ assert_eq!(calls.get(), cleanup_calls);
++ {
++ let inner = state.lock().unwrap();
++ assert_eq!(inner.generation, 1);
++ let lease = inner.lease.as_ref().unwrap();
++ assert_eq!(lease.phase, Phase::Restoring);
++ assert!(lease.registered_shortcut);
++ assert!(inner.x11_cleanup.is_none());
++ assert_eq!(inner.snapshot().error.as_deref(), Some(error));
++ let receipt = inner.restored.as_ref().unwrap();
++ assert_eq!(receipt.generation, 1);
++ assert_eq!(receipt.restart_result(), Err(error.to_string()));
}
-- let result = restore_instant_sequence(
-- async { rx.await.map_err(|_| "main ack lost".to_string())? },
-- || async { panic!("inputs must remain untouched") },
-- || async { panic!("camera must remain hidden") },
-- )
-- .await;
-- assert!(result.is_err());
++ assert!(!finish_x11_studio_restoration(&state, 1, Ok(()), || {
++ panic!("a duplicate completion cannot retry cleanup")
++ }));
++ {
++ let mut inner = state.lock().unwrap();
++ assert_eq!(inner.begin_x11_studio_restore_retry(false), None);
++ assert_eq!(inner.begin_x11_studio_restore_retry(true), Some(1));
++ assert!(inner.lease.as_ref().unwrap().stop_requested);
++ }
++ assert!(finish_x11_studio_restoration(&state, 1, Ok(()), || Ok(())));
++ let inner = state.lock().unwrap();
++ assert!(inner.lease.is_none());
++ assert_eq!(inner.generation, 2);
++ assert_eq!(
++ inner.restored.as_ref().unwrap().restart_result(),
++ Err("Recording restart was cancelled by Stop".into())
++ );
}
}
-- #[tokio::test]
-- async fn instant_open_cap_waits_for_stop_ack_and_never_polls_studio_pause() {
-- let (tx, rx) = tokio::sync::oneshot::channel();
-- let task = tokio::spawn(finish_main_controls(
-- Some(Phase::Recording),
-- Some(async { rx.await.map_err(|_| "stop ack lost".to_string()) }),
-- async { panic!("Instant OpenCap must not pause") },
-- ));
-- tokio::task::yield_now().await;
-- assert!(!task.is_finished());
-- tx.send(()).unwrap();
-- task.await.unwrap().unwrap();
++ #[cfg(target_os = "linux")]
++ #[test]
++ fn x11_studio_stale_and_duplicate_restore_cannot_release_another_owner() {
++ let state = x11_studio_restoring_fixture();
++ assert!(!finish_x11_studio_restoration(&state, 0, Ok(()), || {
++ panic!("a stale generation must not release the shortcut")
++ }));
++ assert!(state.lock().unwrap().restored.is_none());
++ state.lock().unwrap().lease.as_mut().unwrap().phase = Phase::Starting;
++ assert!(!finish_x11_studio_restoration(&state, 1, Ok(()), || {
++ panic!("a live recording must not release the shortcut")
++ }));
++ state.lock().unwrap().lease.as_mut().unwrap().phase = Phase::Restoring;
++ assert!(finish_x11_studio_restoration(&state, 1, Ok(()), || Ok(())));
++ assert!(!finish_x11_studio_restoration(&state, 1, Ok(()), || {
++ panic!("a duplicate completion must not release the shortcut")
++ }));
++ assert_eq!(state.lock().unwrap().generation, 2);
++ let next = x11_studio_restoring_fixture();
++ {
++ let mut inner = next.lock().unwrap();
++ inner.generation = 2;
++ inner.lease.as_mut().unwrap().generation = 2;
++ }
++ assert!(!finish_x11_studio_restoration(&next, 1, Ok(()), || {
++ panic!("an old completion must not release the new shortcut")
++ }));
++ let inner = next.lock().unwrap();
++ assert_eq!(inner.generation, 2);
++ assert!(inner.lease.as_ref().unwrap().registered_shortcut);
++ assert!(inner.restored.is_none());
}
-- #[tokio::test]
-- async fn instant_open_cap_preserves_stop_failure_without_pause_or_reveal_permission() {
-- let result = finish_main_controls(
-- Some(Phase::Starting),
-- Some(async { Err("capture cleanup unconfirmed".into()) }),
-- async { panic!("Instant OpenCap must not pause") },
-- )
-- .await;
-- assert_eq!(result.unwrap_err(), "capture cleanup unconfirmed");
++ #[cfg(target_os = "linux")]
++ #[test]
++ fn x11_studio_restore_keeps_the_users_existing_stop_shortcut() {
++ let state = x11_studio_restoring_fixture();
++ state
++ .lock()
++ .unwrap()
++ .lease
++ .as_mut()
++ .unwrap()
++ .registered_shortcut = false;
++ assert!(finish_x11_studio_restoration(&state, 1, Ok(()), || {
++ panic!("the user shortcut is not owned by this restoration")
++ }));
++ let inner = state.lock().unwrap();
++ assert_eq!(inner.restored.as_ref().unwrap().restart_result(), Ok(()));
}
-- #[tokio::test]
-- async fn studio_open_cap_waits_for_pause_ack_before_allowing_reveal() {
-- let (started_tx, started_rx) = tokio::sync::oneshot::channel();
-- let (paused_tx, paused_rx) = tokio::sync::oneshot::channel();
-- let reveals = Arc::new(AtomicUsize::new(0));
-- let observed = reveals.clone();
-- let task = tokio::spawn(async move {
-- finish_main_controls(
-- Some(Phase::Recording),
-- None::<std::future::Ready<Result<(), String>>>,
-- async {
-- started_tx.send(()).unwrap();
-- paused_rx.await.map_err(|_| "pause ack lost".to_string())
-- },
-- )
-- .await?;
-- observed.fetch_add(1, Ordering::SeqCst);
-- Ok::<(), String>(())
-- });
-- started_rx.await.unwrap();
-- assert!(!task.is_finished());
-- assert_eq!(reveals.load(Ordering::SeqCst), 0);
-- paused_tx.send(()).unwrap();
-- task.await.unwrap().unwrap();
-- assert_eq!(reveals.load(Ordering::SeqCst), 1);
++ #[cfg(target_os = "linux")]
++ #[test]
++ fn x11_studio_stop_during_restoration_prevents_restart_after_cleanup() {
++ let state = x11_studio_restoring_fixture();
++ assert!(state.lock().unwrap().shortcut(true));
++ assert!(finish_x11_studio_restoration(&state, 1, Ok(()), || Ok(())));
++ let inner = state.lock().unwrap();
++ assert!(inner.lease.is_none());
++ assert_eq!(
++ inner.restored.as_ref().unwrap().restart_result(),
++ Err("Recording restart was cancelled by Stop".into())
++ );
}
-- #[tokio::test]
-- async fn studio_open_cap_preserves_pause_failure_without_allowing_reveal() {
-- let result: Result<(), String> = async {
-- finish_main_controls(
-- Some(Phase::Recording),
-- None::<std::future::Ready<Result<(), String>>>,
-- async { Err("pause acknowledgement failed".into()) },
-- )
-- .await?;
-- panic!("a failed pause must not permit controls to be revealed")
++ #[cfg(target_os = "linux")]
++ #[test]
++ fn x11_studio_completion_does_not_accept_instant_or_wayland_leases() {
++ for (mode, wayland) in [
++ (cap_recording::RecordingMode::Instant, false),
++ (cap_recording::RecordingMode::Studio, true),
++ ] {
++ let state = x11_studio_restoring_fixture();
++ {
++ let mut inner = state.lock().unwrap();
++ let lease = inner.lease.as_mut().unwrap();
++ lease.mode = mode;
++ lease.wayland = wayland;
++ assert_eq!(inner.begin_x11_studio_restore_retry(true), None);
++ }
++ assert!(!finish_x11_studio_restoration(&state, 1, Ok(()), || {
++ panic!("another restoration path owns this shortcut")
++ }));
++ let inner = state.lock().unwrap();
++ assert!(inner.restored.is_none());
++ assert!(inner.lease.is_some());
}
-- .await;
-- assert_eq!(result.unwrap_err(), "pause acknowledgement failed");
}
-- #[tokio::test]
-- async fn repeated_studio_open_cap_keeps_the_recording_paused() {
-- for _ in 0..3 {
-- finish_main_controls(
-- Some(Phase::Paused),
-- None::<std::future::Ready<Result<(), String>>>,
-- async { panic!("an already paused recording must not be changed") },
-- )
-- .await
-- .unwrap();
-- }
++ #[cfg(target_os = "linux")]
++ #[test]
++ fn x11_studio_unregister_allows_the_f9_callback_to_lock_and_latch_stop() {
++ let state = x11_studio_restoring_fixture();
++ let (request_tx, request_rx) = std::sync::mpsc::channel();
++ let (reply_tx, reply_rx) = std::sync::mpsc::channel();
++ std::thread::scope(|scope| {
++ let callback_state = &state;
++ let callback = scope.spawn(move || {
++ request_rx.recv_timeout(Duration::from_secs(1)).unwrap();
++ let mut inner = callback_state.lock().unwrap();
++ assert!(inner.x11_cleanup.is_some());
++ assert!(inner.lease.as_ref().unwrap().registered_shortcut);
++ assert!(inner.reserve_x11_studio_cleanup(1, Ok(())).is_none());
++ assert!(inner.shortcut(true));
++ drop(inner);
++ reply_tx.send(()).unwrap();
++ });
++ assert!(finish_x11_studio_restoration(&state, 1, Ok(()), || {
++ request_tx.send(()).unwrap();
++ reply_rx
++ .recv_timeout(Duration::from_secs(1))
++ .map_err(|_| "F9 callback could not acquire restoration state".into())
++ }));
++ callback.join().unwrap();
++ });
++ let inner = state.lock().unwrap();
++ assert!(inner.x11_cleanup.is_none());
++ assert!(inner.lease.is_none());
++ assert_eq!(
++ inner.restored.as_ref().unwrap().restart_result(),
++ Err("Recording restart was cancelled by Stop".into())
++ );
+ }
+
- #[tokio::test]
- async fn studio_open_cap_rejects_pending_transitions_without_changing_capture() {
- for phase in [
- Phase::Starting,
- Phase::Pausing,
- Phase::Resuming,
- Phase::ResumeFailed,
- Phase::Restarting,
- Phase::Stopping,
- ] {
- let result = finish_main_controls(
- Some(phase),
- None::<std::future::Ready<Result<(), String>>>,
- async { panic!("a pending recording transition must not be changed") },
- )
- .await;
- assert_eq!(
- result.unwrap_err(),
- "Recording is changing state. Use Ctrl+Shift+F9 to stop."
- );
- }
++ #[cfg(target_os = "linux")]
++ #[test]
++ fn x11_studio_old_cleanup_completion_cannot_finish_a_retry() {
++ let state = x11_studio_restoring_fixture();
++ let mut inner = state.lock().unwrap();
++ let first = inner.reserve_x11_studio_cleanup(1, Ok(())).unwrap();
++ assert!(inner.reserve_x11_studio_cleanup(1, Ok(())).is_none());
++ assert!(!inner.complete_x11_studio_restoration(first, Err("unregister failed".into())));
++ assert_eq!(inner.begin_x11_studio_restore_retry(true), Some(1));
++ let retry = inner.reserve_x11_studio_cleanup(1, Ok(())).unwrap();
++ assert_ne!(first.sequence, retry.sequence);
++ assert!(!inner.complete_x11_studio_restoration(first, Ok(())));
++ assert!(inner.x11_cleanup == Some(retry));
++ assert!(inner.lease.as_ref().unwrap().registered_shortcut);
++ assert!(inner.complete_x11_studio_restoration(retry, Ok(())));
++ assert!(!inner.complete_x11_studio_restoration(retry, Ok(())));
++ assert_eq!(inner.generation, 2);
}
++ #[cfg(target_os = "linux")]
#[tokio::test]
- async fn studio_open_cap_rejects_pending_transitions_without_changing_capture() {
- for phase in [
- Phase::Starting,
- Phase::Pausing,
- Phase::Resuming,
- Phase::ResumeFailed,
- Phase::Restarting,
- Phase::Stopping,
- ] {
- let result = finish_main_controls(
- Some(phase),
- None::<std::future::Ready<Result<(), String>>>,
- async { panic!("a pending recording transition must not be changed") },
- )
- .await;
- assert_eq!(
- result.unwrap_err(),
- "Recording is changing state. Use Ctrl+Shift+F9 to stop."
- );
- async fn open_cap_keeps_preflight_visible_and_studio_pause_semantics() {
- finish_main_controls(
- Some(Phase::AwaitingShortcut),
- Some(async { panic!("preflight must not issue Stop") }),
- async { panic!("preflight must not issue Pause") },
- )
- .await
- .unwrap();
- finish_main_controls(
- Some(Phase::Recording),
- None::<std::future::Ready<Result<(), String>>>,
- async { Ok(()) },
- )
- .await
- .unwrap();
++ async fn x11_studio_pending_waiter_rejects_restart_after_error_f9_and_retry_success() {
++ let state = State {
++ inner: x11_studio_restoring_fixture(),
++ ..State::default()
++ };
++ let mut waiter = Box::pin(wait_for_restoration(&state, 1));
++ assert!(futures::poll!(&mut waiter).is_pending());
++ assert!(!finish_x11_studio_restoration(
++ &state.inner,
++ 1,
++ Err("window acknowledgement failed".into()),
++ || panic!("window failure must retain the Stop shortcut"),
++ ));
++ state.changed.notify_waiters();
++ {
++ let mut inner = state.inner.lock().unwrap();
++ assert_eq!(inner.begin_x11_studio_restore_retry(true), Some(1));
++ assert!(inner.restored.is_none());
++ assert!(inner.lease.as_ref().unwrap().stop_requested);
+ }
++ assert!(finish_x11_studio_restoration(
++ &state.inner,
++ 1,
++ Ok(()),
++ || Ok(())
++ ));
++ state.changed.notify_waiters();
++ assert_eq!(
++ waiter.await,
++ Err("Recording restart was cancelled by Stop".into())
++ );
}
- #[tokio::test]
- async fn open_cap_keeps_preflight_visible_and_studio_pause_semantics() {
- finish_main_controls(
- Some(Phase::AwaitingShortcut),
- Some(async { panic!("preflight must not issue Stop") }),
- async { panic!("preflight must not issue Pause") },
- )
- .await
- .unwrap();
- finish_main_controls(
- Some(Phase::Recording),
- None::<std::future::Ready<Result<(), String>>>,
- async { Ok(()) },
- )
- .await
- .unwrap();
- }
-
-- fn restoring() -> Inner {
++ fn fixture() -> Inner {
Inner {
-- generation: 7,
++ generation: 1,
++ stop_notice: None,
++ stop_notice_sequence: 0,
++ control_error: None,
++ restored: None,
++ #[cfg(target_os = "linux")]
++ x11_cleanup_sequence: 0,
++ #[cfg(target_os = "linux")]
++ x11_cleanup: None,
lease: Some(Lease {
-- mode: cap_recording::RecordingMode::Instant,
-- generation: 7,
-- phase: Phase::Restoring,
++ mode: cap_recording::RecordingMode::Studio,
++ generation: 1,
++ phase: Phase::AwaitingShortcut,
pressed: false,
stop_requested: false,
registered_shortcut: true,
@@@ -3873,689 -3575,687 +3682,882 @@@
recording_dir: None,
windows: Vec::new(),
}),
-- ..Inner::default()
}
}
#[test]
-- fn instant_restore_error_retains_lease_shortcut_and_error_until_successful_retry() {
-- let mut inner = restoring();
-- assert_eq!(
-- inner.complete_instant_restoration(7, Err("camera ack lost".into())),
-- None
-- );
-- assert_eq!(inner.snapshot().error.as_deref(), Some("camera ack lost"));
-- assert!(inner.lease.as_ref().unwrap().registered_shortcut);
-- assert_eq!(inner.generation, 7);
-- assert_eq!(inner.complete_instant_restoration(7, Ok(())), Some(true));
-- assert!(inner.lease.is_none());
-- assert_eq!(inner.generation, 8);
-- let receipt = inner.restored.as_ref().unwrap();
-- assert_eq!(receipt.generation, 7);
-- assert_eq!(receipt.restart_result(), Ok(()));
++ fn requires_delivered_press_then_release() {
++ let mut state = fixture();
++ assert!(state.shortcut(false));
++ assert_eq!(state.lease.as_ref().unwrap().phase, Phase::AwaitingShortcut);
++ assert!(state.shortcut(true));
++ assert_eq!(state.lease.as_ref().unwrap().phase, Phase::AwaitingShortcut);
++ assert!(state.shortcut(false));
++ assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Starting);
++ assert!(!state.lease.as_ref().unwrap().stop_requested);
++ assert!(state.shortcut(true));
++ assert!(state.lease.as_ref().unwrap().stop_requested);
}
#[test]
-- fn instant_stop_during_restoration_prevents_restart_after_successful_window_ack() {
-- let mut inner = restoring();
-- assert!(inner.shortcut(true));
-- assert_eq!(inner.complete_instant_restoration(7, Ok(())), Some(true));
-- assert!(inner.lease.is_none());
-- assert_eq!(inner.generation, 8);
-- assert!(inner.restored.as_ref().unwrap().restart_result().is_err());
++ fn delayed_reveal_cannot_cross_generation() {
++ let mut state = fixture();
++ assert!(state.may_reveal(1, "main"));
++ state.generation = 2;
++ state.lease = None;
++ assert!(!state.may_reveal(1, "main"));
++ assert!(!state.may_reveal(1, "camera"));
++ assert!(state.may_reveal(2, "main"));
}
#[test]
-- fn instant_stale_restore_receipt_cannot_clear_new_lease_or_error() {
-- let mut inner = restoring();
-- assert_eq!(inner.complete_instant_restoration(6, Ok(())), None);
-- assert!(inner.restored.is_none());
-- inner.lease.as_mut().unwrap().phase = Phase::Starting;
-- assert_eq!(inner.complete_instant_restoration(7, Ok(())), None);
-- assert!(inner.lease.as_ref().unwrap().registered_shortcut);
-- assert!(inner.restored.is_none());
- }
-}
-
-#[cfg(target_os = "linux")]
-thread_local! {
- static WAYLAND_WINDOWS: std::cell::RefCell<std::collections::HashMap<u32, Vec<gtk::ApplicationWindow>>> = std::cell::RefCell::new(std::collections::HashMap::new());
-}
-
-#[cfg(target_os = "linux")]
-pub(crate) fn wayland_generation(app: &AppHandle) -> Option<u32> {
- let state = app.try_state::<State>()?;
- let inner = state.inner.lock().unwrap();
- inner
- .lease
- .as_ref()
- .filter(|lease| lease.wayland)
- .map(|lease| lease.generation)
-}
++ fn wayland_requires_delivered_current_stop_input() {
++ let mut state = fixture();
++ let lease = state.lease.as_mut().unwrap();
++ lease.wayland = true;
++ assert!(!lease.accept_stop_input(None, true));
++ assert!(!lease.accept_stop_input(Some((2, StopRoute::Tray)), true));
++ assert!(!lease.accept_stop_input(Some((1, StopRoute::Portal)), false));
++ assert_eq!(lease.phase, Phase::AwaitingShortcut);
++ assert!(lease.accept_stop_input(Some((1, StopRoute::Portal)), true));
++ assert!(state.shortcut(true));
++ assert!(
++ !state
++ .lease
++ .as_mut()
++ .unwrap()
++ .accept_stop_input(Some((1, StopRoute::Tray)), false)
++ );
++ assert!(
++ state
++ .lease
++ .as_mut()
++ .unwrap()
++ .accept_stop_input(Some((1, StopRoute::Portal)), false)
++ );
++ assert!(state.shortcut(false));
++ assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Starting);
+ }
- }
-
- #[cfg(target_os = "linux")]
- thread_local! {
- static WAYLAND_WINDOWS: std::cell::RefCell<std::collections::HashMap<u32, Vec<gtk::ApplicationWindow>>> = std::cell::RefCell::new(std::collections::HashMap::new());
- }
--#[cfg(target_os = "linux")]
- pub(crate) fn wayland_generation(app: &AppHandle) -> Option<u32> {
- let state = app.try_state::<State>()?;
- let inner = state.inner.lock().unwrap();
- inner
-pub(crate) fn describe_wayland_stop(app: &AppHandle, generation: u32, description: String) {
- let state = app.state::<State>();
- let mut inner = state.inner.lock().unwrap();
- if let Some(lease) = inner
-- .lease
- .as_ref()
- .filter(|lease| lease.wayland)
- .map(|lease| lease.generation)
- }
- .as_mut()
- .filter(|lease| lease.generation == generation && lease.wayland)
- {
- lease.stop_description = Some(description);
++ #[test]
++ fn wayland_tray_activation_starts_and_next_activation_stops() {
++ let mut state = fixture();
++ state.lease.as_mut().unwrap().wayland = true;
++ for pressed in [true, false] {
++ assert!(
++ state
++ .lease
++ .as_mut()
++ .unwrap()
++ .accept_stop_input(Some((1, StopRoute::Tray)), pressed)
++ );
++ assert!(state.shortcut(pressed));
++ }
++ assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Starting);
++ state.lease.as_mut().unwrap().phase = Phase::Recording;
++ assert!(
++ state
++ .lease
++ .as_mut()
++ .unwrap()
++ .accept_stop_input(Some((1, StopRoute::Tray)), true)
++ );
++ assert!(state.shortcut(true));
++ assert!(state.lease.as_ref().unwrap().stop_requested);
+ }
- drop(inner);
- notify(app);
-}
- #[cfg(target_os = "linux")]
- pub(crate) fn describe_wayland_stop(app: &AppHandle, generation: u32, description: String) {
- let state = app.state::<State>();
- let mut inner = state.inner.lock().unwrap();
- if let Some(lease) = inner
- .lease
- .as_mut()
- .filter(|lease| lease.generation == generation && lease.wayland)
- {
- lease.stop_description = Some(description);
-async fn save_windows(app: &AppHandle, generation: u32) -> Result<Vec<SavedWindow>, String> {
- let (tx, rx) = tokio::sync::oneshot::channel();
- let handle = app.clone();
- app.run_on_main_thread(move || {
- let result = (|| {
- if !is_current(&handle, generation) {
- return Err("Recording preflight was superseded".to_string());
- }
- #[cfg(target_os = "linux")]
- if wayland_generation(&handle) == Some(generation) {
- install_wayland_window_guard(&handle)?;
- remember_wayland_windows(&handle, generation)?;
- }
- #[cfg(target_os = "linux")]
- let save_all = wayland_generation(&handle) == Some(generation);
- #[cfg(not(target_os = "linux"))]
- let save_all = false;
- let mut saved = Vec::new();
- for (label, window) in handle.webview_windows() {
- if save_all
- || matches!(
- label.parse::<CapWindowId>(),
- Ok(CapWindowId::Main | CapWindowId::Camera)
- )
- {
- #[cfg(target_os = "linux")]
- if wayland_generation(&handle) == Some(generation) {
- let gtk = window.gtk_window().map_err(|error| error.to_string())?;
- WAYLAND_WINDOWS.with_borrow_mut(|windows| {
- windows.entry(generation).or_default().push(gtk)
- });
- }
- saved.push(SavedWindow {
- label,
- native_id: native_id(&window)?,
- visible: window.is_visible().map_err(|error| error.to_string())?,
- });
- }
- }
- Ok(saved)
- })();
- let _ = tx.send(result);
- })
- .map_err(|error| error.to_string())?;
- tokio::time::timeout(Duration::from_secs(2), rx)
- .await
- .map_err(|_| "Timed out saving recording windows".to_string())?
- .map_err(|_| "Recording windows could not be saved".to_string())?
-}
++ #[test]
++ fn wayland_loss_cannot_start_or_silently_switch_control() {
++ let mut state = fixture();
++ let lease = state.lease.as_mut().unwrap();
++ lease.wayland = true;
++ assert!(!lease.lose_stop_route(StopRoute::Portal));
++ assert!(!lease.stop_requested);
++ assert!(!lease.accept_stop_input(Some((1, StopRoute::Portal)), true));
++ assert!(lease.accept_stop_input(Some((1, StopRoute::Tray)), true));
++ lease.phase = Phase::Recording;
++ assert!(lease.lose_stop_route(StopRoute::Tray));
++ assert!(lease.stop_requested);
++ assert!(!lease.accept_stop_input(Some((1, StopRoute::Tray)), true));
+ }
- drop(inner);
- notify(app);
- }
- async fn save_windows(app: &AppHandle, generation: u32) -> Result<Vec<SavedWindow>, String> {
- let (tx, rx) = tokio::sync::oneshot::channel();
- let handle = app.clone();
- app.run_on_main_thread(move || {
- let result = (|| {
- if !is_current(&handle, generation) {
- return Err("Recording preflight was superseded".to_string());
- }
- #[cfg(target_os = "linux")]
- if wayland_generation(&handle) == Some(generation) {
- install_wayland_window_guard(&handle)?;
- remember_wayland_windows(&handle, generation)?;
- }
- #[cfg(target_os = "linux")]
- let save_all = wayland_generation(&handle) == Some(generation);
- #[cfg(not(target_os = "linux"))]
- let save_all = false;
- let mut saved = Vec::new();
- for (label, window) in handle.webview_windows() {
- if save_all
- || matches!(
- label.parse::<CapWindowId>(),
- Ok(CapWindowId::Main | CapWindowId::Camera)
- )
- {
- #[cfg(target_os = "linux")]
- if wayland_generation(&handle) == Some(generation) {
- let gtk = window.gtk_window().map_err(|error| error.to_string())?;
- WAYLAND_WINDOWS.with_borrow_mut(|windows| {
- windows.entry(generation).or_default().push(gtk)
- });
- }
- saved.push(SavedWindow {
- label,
- native_id: native_id(&window)?,
- visible: window.is_visible().map_err(|error| error.to_string())?,
- });
- }
-fn set_native_visibility(window: &WebviewWindow, visible: bool) -> Result<(), String> {
- #[cfg(target_os = "linux")]
- {
- use gtk::prelude::*;
- let gtk = window.gtk_window().map_err(|error| error.to_string())?;
- // Tao queues GTK visibility changes even on the UI thread; this gate needs
- // the native change to complete before checking its acknowledgement.
- if visible {
- if cap_recording::screenshot::uses_wayland_portal() {
- gtk.show();
- } else {
- gtk.show_all();
-- }
- Ok(saved)
- })();
- let _ = tx.send(result);
- })
- .map_err(|error| error.to_string())?;
- tokio::time::timeout(Duration::from_secs(2), rx)
- .await
- .map_err(|_| "Timed out saving recording windows".to_string())?
- .map_err(|_| "Recording windows could not be saved".to_string())?
- }
- } else {
- gtk.hide();
- }
- if gtk.is_visible() != visible || (!visible && gtk.is_mapped()) {
- return Err("GTK did not acknowledge the recording window visibility change".into());
- }
- Ok(())
++ #[test]
++ fn wayland_both_missing_controls_cancel_visible_preflight() {
++ let mut state = fixture();
++ let lease = state.lease.as_mut().unwrap();
++ lease.wayland = true;
++ assert!(!lease.lose_stop_route(StopRoute::Tray));
++ assert!(!lease.lose_stop_route(StopRoute::Portal));
++ assert!(lease.stop_requested);
++ assert_eq!(lease.phase, Phase::AwaitingShortcut);
+ }
- #[cfg(not(target_os = "linux"))]
- {
- if visible {
- window.show()
- } else {
- window.hide()
+
- fn set_native_visibility(window: &WebviewWindow, visible: bool) -> Result<(), String> {
- #[cfg(target_os = "linux")]
- {
- use gtk::prelude::*;
- let gtk = window.gtk_window().map_err(|error| error.to_string())?;
- // Tao queues GTK visibility changes even on the UI thread; this gate needs
- // the native change to complete before checking its acknowledgement.
- if visible {
- gtk.show_all();
- } else {
- gtk.hide();
- }
- if gtk.is_visible() != visible || (!visible && gtk.is_mapped()) {
- return Err("GTK did not acknowledge the recording window visibility change".into());
- }
- Ok(())
++ #[test]
++ fn wayland_control_loss_during_start_is_retained_until_cleanup() {
++ let mut state = fixture();
++ let lease = state.lease.as_mut().unwrap();
++ lease.wayland = true;
++ lease.stop_route = Some(StopRoute::Tray);
++ lease.phase = Phase::Starting;
++ assert!(!lease.lose_stop_route(StopRoute::Tray));
++ assert!(lease.stop_requested);
++ assert_eq!(lease.phase, Phase::Starting);
+ }
- #[cfg(not(target_os = "linux"))]
- {
- if visible {
- window.show()
- } else {
- window.hide()
++
++ #[test]
++ fn only_acknowledged_pause_allows_main() {
++ let mut state = fixture();
++ for phase in [
++ Phase::Starting,
++ Phase::Recording,
++ Phase::Pausing,
++ Phase::Resuming,
++ Phase::Restarting,
++ Phase::Stopping,
++ ] {
++ state.lease.as_mut().unwrap().phase = phase;
++ assert!(!state.may_reveal(1, "main"));
++ assert!(!state.may_reveal(1, "camera"));
++ assert!(!state.may_reveal(1, "in-progress-recording"));
}
-- .map_err(|error| error.to_string())
++ state.lease.as_mut().unwrap().phase = Phase::Paused;
++ assert!(state.may_reveal(1, "main"));
++ assert!(!state.may_reveal(1, "camera"));
}
--}
--#[cfg(target_os = "linux")]
--async fn wayland_fence(app: &AppHandle, generation: u32, hidden: bool) -> Result<(), String> {
-- let (tx, rx) = tokio::sync::oneshot::channel();
-- let handle = app.clone();
-- app.run_on_main_thread(move || {
-- let display = (|| {
-- use gtk::prelude::*;
-- if !is_current(&handle, generation) {
-- return Err("Recording visibility fence was superseded".to_string());
-- }
-- let gtk = if let Some(window) = CapWindowId::Main.get(&handle) {
-- window.gtk_window().map_err(|error| error.to_string())?
-- } else if !hidden && phase(&handle) == Some(Phase::Restoring) {
-- WAYLAND_WINDOWS
-- .with_borrow(|windows| {
-- windows
-- .get(&generation)
-- .and_then(|windows| windows.first())
-- .cloned()
-- })
-- .ok_or("Retained recording display disappeared")?
-- } else {
-- return Err("Main recording window disappeared".into());
-- };
-- let display = gtk.display();
-- if display.type_().name() != "GdkWaylandDisplay" {
-- return Err(
-- "The recording window is not connected to the Wayland compositor".into(),
++ #[test]
++ fn instant_uses_capture_backend_without_loosening_studio_environment() {
++ use cap_recording::RecordingMode;
++ for strict_x11 in [false, true] {
++ assert!(capture_environment_is_x11(
++ RecordingMode::Instant,
++ strict_x11,
++ false
++ ));
++ assert!(!capture_environment_is_x11(
++ RecordingMode::Instant,
++ strict_x11,
++ true
++ ));
++ for uses_wayland_portal in [false, true] {
++ assert_eq!(
++ capture_environment_is_x11(
++ RecordingMode::Studio,
++ strict_x11,
++ uses_wayland_portal
++ ),
++ strict_x11
);
}
-- Ok(display)
-- })();
-- match display {
-- Ok(display) => wayland_ack::start(display, handle, generation, hidden, tx),
-- Err(error) => {
-- let _ = tx.send(Err(error));
-- }
}
-- })
-- .map_err(|error| error.to_string())?;
-- tokio::time::timeout(Duration::from_secs(3), rx)
-- .await
-- .map_err(|_| "Wayland visibility acknowledgement timed out".to_string())?
-- .map_err(|_| "Wayland visibility acknowledgement was lost".to_string())??;
-- if !is_current(app, generation) {
-- return Err("Recording visibility acknowledgement was superseded".into());
++ assert!(!x11_environment(true, false, None));
++ assert!(capture_environment_is_x11(
++ RecordingMode::Instant,
++ x11_environment(true, false, None),
++ false
++ ));
++ assert!(!x11_environment(true, true, Some("x11")));
++ assert!(capture_environment_is_x11(
++ RecordingMode::Instant,
++ x11_environment(true, true, Some("x11")),
++ false
++ ));
}
-- Ok(())
--}
--
--#[cfg(target_os = "linux")]
--mod wayland_ack {
-- use gtk::{gdk, prelude::*};
-- use std::{
-- cell::{Cell, RefCell},
-- ffi::c_void,
-- rc::Rc,
-- time::Duration,
-- };
-- use wayland_sys::{client::*, common::*};
-- type Reply = tokio::sync::oneshot::Sender<Result<(), String>>;
-- struct Pending {
-- callback: Cell<*mut wl_proxy>,
-- reply: RefCell<Option<Reply>>,
-- _display: gdk::Display,
-- app: tauri::AppHandle,
-- generation: u32,
-- hidden: bool,
-- }
-- impl Pending {
-- fn finish(&self, result: Result<(), String>) {
-- let callback = self.callback.replace(std::ptr::null_mut());
-- if !callback.is_null() {
-- unsafe {
-- (wayland_client_handle().wl_proxy_destroy)(callback);
-- }
++ #[test]
++ fn monitor_visibility_requires_x11_for_both_recording_modes() {
++ use cap_recording::{RecordingMode, screen_capture::ScreenCaptureTarget};
++ let display = ScreenCaptureTarget::Display {
++ id: "1".parse().unwrap(),
++ };
++ let area = ScreenCaptureTarget::Area {
++ screen: "1".parse().unwrap(),
++ bounds: scap_targets::bounds::LogicalBounds::new(
++ scap_targets::bounds::LogicalPosition::new(0.0, 0.0),
++ scap_targets::bounds::LogicalSize::new(100.0, 100.0),
++ ),
++ };
++ let window = ScreenCaptureTarget::Window {
++ id: "1".parse().unwrap(),
++ };
++ for mode in [RecordingMode::Studio, RecordingMode::Instant] {
++ for target in [&display, &area] {
++ assert_eq!(
++ validate_capture_visibility(mode, target, false, false, true),
++ Ok(true)
++ );
++ assert!(validate_capture_visibility(mode, target, false, false, false).is_err());
}
-- if let Some(reply) = self.reply.borrow_mut().take() {
-- let _ = reply.send(result);
++ for target in [&window, &ScreenCaptureTarget::CameraOnly] {
++ assert_eq!(
++ validate_capture_visibility(mode, target, false, false, true),
++ Ok(false)
++ );
++ assert_eq!(
++ validate_capture_visibility(mode, target, false, false, false),
++ Ok(false)
++ );
}
}
++ assert_eq!(
++ validate_capture_visibility(RecordingMode::Screenshot, &display, false, false, false),
++ Ok(false)
++ );
}
-- static CALLBACK: wl_interface = wl_interface {
-- name: c"wl_callback".as_ptr(),
-- version: 1,
-- request_count: 0,
-- requests: std::ptr::null(),
-- event_count: 1,
-- events: &wl_message {
-- name: c"done".as_ptr(),
-- signature: c"u".as_ptr(),
-- types: std::ptr::null(),
-- },
-- };
-- unsafe extern "C" fn dispatch(
-- _: *const c_void,
-- data: *mut c_void,
-- opcode: u32,
-- _: *const wl_message,
-- _: *const wl_argument,
-- ) -> i32 {
-- let pending = unsafe {
-- &*((wayland_client_handle().wl_proxy_get_user_data)(data.cast()).cast::<Pending>())
++
++ #[test]
++ fn window_camera_visibility_is_required_only_for_x11_instant() {
++ use cap_recording::{RecordingMode, screen_capture::ScreenCaptureTarget};
++ let target = ScreenCaptureTarget::Window {
++ id: "1".parse().unwrap(),
};
-- pending.finish(if opcode == 0 {
-- if pending.hidden {
-- super::verify_wayland_hidden(&pending.app, pending.generation)
-- } else {
-- super::verify_wayland_restored(&pending.app, pending.generation)
++ for mode in [
++ RecordingMode::Studio,
++ RecordingMode::Instant,
++ RecordingMode::Screenshot,
++ ] {
++ for camera in [false, true] {
++ for wayland in [false, true] {
++ let required = mode == RecordingMode::Instant && camera && !wayland;
++ assert_eq!(
++ validate_capture_visibility(mode, &target, camera, wayland, true),
++ Ok(required)
++ );
++ let unsupported =
++ validate_capture_visibility(mode, &target, camera, wayland, false);
++ if required {
++ assert!(unsupported.is_err());
++ } else {
++ assert_eq!(unsupported, Ok(false));
++ }
++ }
}
-- } else {
-- Err("Unexpected Wayland visibility acknowledgement".into())
-- });
-- 0
-- }
-- pub(super) fn start(
-- display: gdk::Display,
-- app: tauri::AppHandle,
-- generation: u32,
-- hidden: bool,
-- reply: Reply,
-- ) {
-- let Some(client) = wayland_client_option() else {
-- let _ = reply.send(Err("Wayland client library is unavailable".into()));
-- return;
-- };
-- let raw =
-- unsafe { gdk_wayland_sys::gdk_wayland_display_get_wl_display(display.as_ptr().cast()) }
-- .cast::<wl_display>();
-- if raw.is_null() {
-- let _ = reply.send(Err("Wayland display connection is unavailable".into()));
-- return;
-- }
-- let mut args = [wl_argument {
-- o: std::ptr::null(),
-- }];
-- let callback = unsafe {
-- (client.wl_proxy_marshal_array_constructor)(raw.cast(), 0, args.as_mut_ptr(), &CALLBACK)
-- };
-- if callback.is_null() {
-- let _ = reply.send(Err(
-- "Could not queue Wayland visibility acknowledgement".into()
- ));
- return;
- }
- let pending = Rc::new(Pending {
- callback: Cell::new(callback),
- reply: RefCell::new(Some(reply)),
- _display: display.clone(),
- app,
- generation,
- hidden,
- });
- let result = unsafe {
- (client.wl_proxy_add_dispatcher)(
- callback,
- dispatch,
- std::ptr::null(),
- Rc::as_ptr(&pending).cast_mut().cast(),
- )
- };
- if result != 0 {
- pending.finish(Err(
- "Could not subscribe to Wayland visibility acknowledgement".into(),
-- ));
-- return;
}
- let pending = Rc::new(Pending {
- callback: Cell::new(callback),
- reply: RefCell::new(Some(reply)),
- _display: display.clone(),
- app,
- generation,
- hidden,
- });
- let result = unsafe {
- (client.wl_proxy_add_dispatcher)(
- callback,
- dispatch,
- std::ptr::null(),
- Rc::as_ptr(&pending).cast_mut().cast(),
- )
- };
- if result != 0 {
- // GDK owns dispatch on this connection. The timeout retains listener data until
- // either the callback or timeout destroys the proxy, without reading GDK's queue.
- gtk::glib::timeout_add_local_once(Duration::from_secs(2), move || {
-- pending.finish(Err(
- "Could not subscribe to Wayland visibility acknowledgement".into(),
- ));
- return;
- "Wayland compositor did not acknowledge window visibility".into(),
- ))
- });
- display.flush();
+ }
-}
+
-#[cfg(target_os = "linux")]
-pub(crate) fn wayland_stop_lost(app: &AppHandle, generation: u32, route: StopRoute, error: String) {
- let state = app.state::<State>();
- let mut inner = state.inner.lock().unwrap();
- let Some(lease) = inner
- .lease
- .as_mut()
- .filter(|lease| lease.generation == generation && lease.wayland)
- else {
- return;
- };
- let stop = lease.lose_stop_route(route);
- if lease.stop_requested {
- lease.stop_error = Some(error);
- } else if route == StopRoute::Tray {
- lease.stop_description = Some("the portal shortcut shown by your desktop".into());
++ #[test]
++ fn refuses_wayland_and_ambiguous_sessions() {
++ assert!(x11_environment(true, false, Some("x11")));
++ assert!(!x11_environment(true, true, Some("x11")));
++ assert!(!x11_environment(true, false, Some("wayland")));
++ assert!(!x11_environment(true, false, None));
++ assert!(!x11_environment(false, false, Some("x11")));
+ }
- drop(inner);
- notify(app);
- if stop {
- let app = app.clone();
- drop(tauri::async_runtime::spawn(async move {
- if let Err(error) = crate::recording::stop_recording(app.clone(), app.state()).await {
- tracing::error!(%error, "Could not stop recording after losing its Stop control");
- }
- }));
++
++ #[test]
++ fn cancel_preflight_never_starts() {
++ let mut state = fixture();
++ assert!(state.queue_stop());
++ assert!(state.shortcut(true));
++ assert!(state.shortcut(false));
++ assert!(state.lease.as_ref().unwrap().stop_requested);
+ }
-}
+
-#[cfg(target_os = "linux")]
-fn verify_wayland_hidden(app: &AppHandle, generation: u32) -> Result<(), String> {
- use gtk::prelude::*;
- if !is_current(app, generation) || stop_requested(app, generation) {
- return Err("Recording hide acknowledgement was superseded or cancelled".into());
++ #[test]
++ fn stop_is_retained_through_start_restart_and_control_transitions() {
++ for phase in [Phase::Starting, Phase::Restarting, Phase::Pausing] {
++ let mut state = fixture();
++ state.lease.as_mut().unwrap().phase = phase;
++ assert!(state.queue_stop());
++ assert!(state.lease.as_ref().unwrap().stop_requested);
++ assert_eq!(state.lease.as_ref().unwrap().phase, phase);
+ }
- // GDK owns dispatch on this connection. The timeout retains listener data until
- // either the callback or timeout destroys the proxy, without reading GDK's queue.
- gtk::glib::timeout_add_local_once(Duration::from_secs(2), move || {
- pending.finish(Err(
- "Wayland compositor did not acknowledge window visibility".into(),
- ))
- });
- display.flush();
}
- }
- let main = CapWindowId::Main
- .get(app)
- .ok_or("Main recording window disappeared")?
- .gtk_window()
- .map_err(|error| error.to_string())?;
- let display = main.display();
- for window in wayland_application(app)?.windows() {
- if window.display() != display || window.is_visible() || window.is_mapped() {
- return Err("A Cap window is visible or uses another display connection".into());
- }
+
- #[cfg(target_os = "linux")]
- pub(crate) fn wayland_stop_lost(app: &AppHandle, generation: u32, route: StopRoute, error: String) {
- let state = app.state::<State>();
- let mut inner = state.inner.lock().unwrap();
- let Some(lease) = inner
- .lease
- .as_mut()
- .filter(|lease| lease.generation == generation && lease.wayland)
- else {
- return;
- };
- let stop = lease.lose_stop_route(route);
- let studio_stop = (lease.mode == cap_recording::RecordingMode::Studio
- && (stop || lease.stop_requested && lease.phase == Phase::Stopping))
- .then(|| lease.recording_dir.clone())
- .flatten();
- if lease.stop_requested {
- lease.stop_error = Some(error);
- } else if route == StopRoute::Tray {
- lease.stop_description = Some("the portal shortcut shown by your desktop".into());
++ #[test]
++ fn active_stop_claims_cleanup_once() {
++ let mut state = fixture();
++ state.lease.as_mut().unwrap().phase = Phase::Recording;
++ assert!(!state.queue_stop());
++ assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Stopping);
++ assert!(state.queue_stop());
++ assert!(state.lease.as_ref().unwrap().stop_requested);
}
- drop(inner);
- notify(app);
- if let Some(directory) = studio_stop {
- crate::recording::queue_clean_studio_stop(app, generation, directory);
- } else if stop {
- let app = app.clone();
- drop(tauri::async_runtime::spawn(async move {
- if let Err(error) = crate::recording::stop_recording(app.clone(), app.state()).await {
- tracing::error!(%error, "Could not stop recording after losing its Stop control");
- Ok(())
-}
+
-#[cfg(target_os = "linux")]
-fn verify_wayland_restored(app: &AppHandle, generation: u32) -> Result<(), String> {
- use gtk::prelude::*;
- for (saved, wanted) in wayland_restore_plan(app, generation, true)? {
- if saved.window.is_visible() != wanted || saved.window.is_mapped() != wanted {
- return Err("The compositor restore acknowledgement did not match Cap windows".into());
- }
++ #[test]
++ fn unconfirmed_resume_failure_keeps_main_hidden_and_stop_actionable() {
++ let mut state = fixture();
++ let dir = PathBuf::from("recording-a");
++ let lease = state.lease.as_mut().unwrap();
++ lease.recording_dir = Some(dir.clone());
++ lease.phase = Phase::Resuming;
++ assert!(state.complete_control(
++ 1,
++ &dir,
++ true,
++ &ControlOutcome::ActorFailed {
++ error: "actor transport failed".into(),
++ paused: false,
+ }
- }));
++ ));
++ assert_eq!(state.lease.as_ref().unwrap().phase, Phase::ResumeFailed);
++ assert!(state.shortcut(true));
++ assert!(state.lease.as_ref().unwrap().phase.can_stop());
++ assert!(!state.may_reveal(1, "main"));
++ assert!(!state.queue_stop());
++ assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Stopping);
}
- Ok(())
--}
- #[cfg(target_os = "linux")]
- fn verify_wayland_hidden(app: &AppHandle, generation: u32) -> Result<(), String> {
- use gtk::prelude::*;
- if !is_current(app, generation) || stop_requested(app, generation) {
- return Err("Recording hide acknowledgement was superseded or cancelled".into());
-fn wayland_blocks_mapping(phase: Phase) -> bool {
- !matches!(
- phase,
- Phase::AwaitingShortcut | Phase::Paused | Phase::Restoring
- )
-}
++ #[test]
++ fn old_control_acknowledgement_cannot_publish_into_new_recording() {
++ let mut state = fixture();
++ let lease = state.lease.as_mut().unwrap();
++ lease.phase = Phase::Pausing;
++ lease.recording_dir = Some(PathBuf::from("recording-b"));
++ lease.generation = 2;
++ state.generation = 2;
++ assert!(!state.complete_control(
++ 1,
++ std::path::Path::new("recording-a"),
++ false,
++ &ControlOutcome::Succeeded
++ ));
++ assert!(!state.complete_control(
++ 2,
++ std::path::Path::new("recording-a"),
++ false,
++ &ControlOutcome::Succeeded
++ ));
++ assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Pausing);
+ }
- let main = CapWindowId::Main
- .get(app)
- .ok_or("Main recording window disappeared")?
- .gtk_window()
- .map_err(|error| error.to_string())?;
- let display = main.display();
- for window in wayland_application(app)?.windows() {
- if window.display() != display || window.is_visible() || window.is_mapped() {
- return Err("A Cap window is visible or uses another display connection".into());
+
-#[cfg(any(target_os = "linux", test))]
-fn restore_floating_window(label: Option<&str>) -> bool {
- !matches!(
- label.and_then(|label| label.parse::<CapWindowId>().ok()),
- Some(
- CapWindowId::RecordingControls
- | CapWindowId::TargetSelectOverlay { .. }
- | CapWindowId::WindowCaptureOccluder { .. }
- | CapWindowId::CaptureArea
- )
- )
-}
++ #[test]
++ fn target_overlays_stay_hidden_even_during_preflight_and_pause() {
++ let mut state = fixture();
++ for phase in [
++ Phase::AwaitingShortcut,
++ Phase::Recording,
++ Phase::Paused,
++ Phase::Restarting,
++ Phase::Restoring,
++ ] {
++ state.lease.as_mut().unwrap().phase = phase;
++ assert!(!state.may_reveal(1, "target-select-overlay-1"));
+ }
+ }
- Ok(())
- }
--#[cfg(target_os = "linux")]
- fn verify_wayland_restored(app: &AppHandle, generation: u32) -> Result<(), String> {
- use gtk::prelude::*;
- for (saved, wanted) in wayland_restore_plan(app, generation, true)? {
- if saved.window.is_visible() != wanted || saved.window.is_mapped() != wanted {
- return Err("The compositor restore acknowledgement did not match Cap windows".into());
-#[derive(Clone)]
-struct RetainedWaylandWindow {
- window: gtk::Window,
- label: Option<String>,
- visible: bool,
- requested_during_stop: bool,
-}
++ #[test]
++ fn restore_preserves_hidden_camera_and_rejects_replaced_native_window() {
++ for visible in [false, true] {
++ let saved = SavedWindow {
++ label: "camera".into(),
++ native_id: 42,
++ visible,
++ };
++ assert_eq!(saved.visibility_for(42), Some(visible));
++ assert_eq!(saved.visibility_for(43), None);
+ }
+ }
- Ok(())
- }
-
- fn wayland_blocks_mapping(phase: Phase) -> bool {
- !matches!(
- phase,
- Phase::AwaitingShortcut | Phase::Paused | Phase::Restoring
- )
- }
-
- #[cfg(any(target_os = "linux", test))]
- fn restore_floating_window(label: Option<&str>) -> bool {
- !matches!(
- label.and_then(|label| label.parse::<CapWindowId>().ok()),
- Some(
- CapWindowId::RecordingControls
- | CapWindowId::TargetSelectOverlay { .. }
- | CapWindowId::WindowCaptureOccluder { .. }
- | CapWindowId::CaptureArea
- )
- )
- }
--#[cfg(target_os = "linux")]
- #[derive(Clone)]
- struct RetainedWaylandWindow {
- window: gtk::Window,
- label: Option<String>,
- visible: bool,
- requested_during_stop: bool,
-thread_local! {
- static WAYLAND_GUARD_APPLICATION: std::cell::RefCell<Option<gtk::glib::WeakRef<gtk::Application>>> = const { std::cell::RefCell::new(None) };
- static WAYLAND_GUARDED_WINDOWS: std::cell::RefCell<Vec<gtk::glib::WeakRef<gtk::Window>>> = const { std::cell::RefCell::new(Vec::new()) };
- static WAYLAND_CAPTURE_WINDOWS: std::cell::RefCell<std::collections::HashMap<u32, Vec<RetainedWaylandWindow>>> = std::cell::RefCell::new(std::collections::HashMap::new());
--}
++ #[test]
++ fn startup_failure_cannot_own_a_different_pending_recording() {
++ let mut state = fixture();
++ let old = PathBuf::from("failed-start-a");
++ let new = PathBuf::from("pending-start-b");
++ state.lease.as_mut().unwrap().phase = Phase::Starting;
++ state.lease.as_mut().unwrap().recording_dir = Some(old.clone());
++ assert_eq!(state.owner(&old), Some(1));
++ assert_eq!(state.owner(&new), None);
++ state.lease.as_mut().unwrap().recording_dir = Some(new.clone());
++ state.lease.as_mut().unwrap().generation = 2;
++ state.generation = 2;
++ assert_eq!(state.owner(&old), None);
++ assert_eq!(state.owner(&new), Some(2));
++ }
--#[cfg(target_os = "linux")]
- thread_local! {
- static WAYLAND_GUARD_APPLICATION: std::cell::RefCell<Option<gtk::glib::WeakRef<gtk::Application>>> = const { std::cell::RefCell::new(None) };
- static WAYLAND_GUARDED_WINDOWS: std::cell::RefCell<Vec<gtk::glib::WeakRef<gtk::Window>>> = const { std::cell::RefCell::new(Vec::new()) };
- static WAYLAND_CAPTURE_WINDOWS: std::cell::RefCell<std::collections::HashMap<u32, Vec<RetainedWaylandWindow>>> = std::cell::RefCell::new(std::collections::HashMap::new());
-fn wayland_application(app: &AppHandle) -> Result<gtk::Application, String> {
- use gtk::prelude::*;
- CapWindowId::Main
- .get(app)
- .ok_or("Main recording window disappeared")?
- .gtk_window()
- .map_err(|error| error.to_string())?
- .application()
- .ok_or("Recording GTK application disappeared".into())
--}
++ #[tokio::test]
++ async fn pending_pause_does_not_reveal_main_and_retains_queued_stop_after_ack() {
++ let state = std::sync::Arc::new(Mutex::new(fixture()));
++ let dir = PathBuf::from("recording-a");
++ {
++ let mut state = state.lock().unwrap();
++ let lease = state.lease.as_mut().unwrap();
++ lease.phase = Phase::Pausing;
++ lease.recording_dir = Some(dir.clone());
++ }
++ let (acknowledge, received) = tokio::sync::oneshot::channel();
++ let pending = {
++ let state = state.clone();
++ tokio::spawn(async move {
++ received.await.unwrap();
++ state
++ .lock()
++ .unwrap()
++ .complete_control(1, &dir, false, &ControlOutcome::Succeeded)
++ })
++ };
++ {
++ let mut state = state.lock().unwrap();
++ assert!(!state.may_reveal(1, "main"));
++ assert!(state.queue_stop());
++ }
++ acknowledge.send(()).unwrap();
++ assert!(pending.await.unwrap());
++ let mut state = state.lock().unwrap();
++ assert!(state.lease.as_ref().unwrap().stop_requested);
++ assert!(!state.queue_stop());
++ assert!(!state.may_reveal(1, "main"));
++ }
--#[cfg(target_os = "linux")]
- fn wayland_application(app: &AppHandle) -> Result<gtk::Application, String> {
-fn wayland_window_label(app: &AppHandle, native: &gtk::Window) -> Option<String> {
-- use gtk::prelude::*;
- CapWindowId::Main
- .get(app)
- .ok_or("Main recording window disappeared")?
- .gtk_window()
- .map_err(|error| error.to_string())?
- .application()
- .ok_or("Recording GTK application disappeared".into())
- app.webview_windows()
- .into_iter()
- .find_map(|(label, window)| {
- window
- .gtk_window()
- .ok()
- .filter(|window| window.upcast_ref::<gtk::Window>() == native)
- .map(|_| label)
- })
--}
++ #[tokio::test]
++ async fn stopped_owner_rejects_delayed_resume_acknowledgement() {
++ let state = std::sync::Arc::new(Mutex::new(fixture()));
++ let dir = PathBuf::from("recording-a");
++ {
++ let mut state = state.lock().unwrap();
++ let lease = state.lease.as_mut().unwrap();
++ lease.phase = Phase::Resuming;
++ lease.recording_dir = Some(dir.clone());
++ }
++ let (acknowledge, received) = tokio::sync::oneshot::channel();
++ let pending = {
++ let state = state.clone();
++ tokio::spawn(async move {
++ received.await.unwrap();
++ state
++ .lock()
++ .unwrap()
++ .complete_control(1, &dir, true, &ControlOutcome::Succeeded)
++ })
++ };
++ state.lock().unwrap().lease.as_mut().unwrap().phase = Phase::Restoring;
++ acknowledge.send(()).unwrap();
++ assert!(!pending.await.unwrap());
++ assert_eq!(
++ state.lock().unwrap().lease.as_ref().unwrap().phase,
++ Phase::Restoring
++ );
++ }
--#[cfg(target_os = "linux")]
- fn wayland_window_label(app: &AppHandle, native: &gtk::Window) -> Option<String> {
-fn remember_wayland_window(
- app: &AppHandle,
- generation: u32,
- window: &gtk::Window,
- during_stop: bool,
-) {
-- use gtk::prelude::*;
- app.webview_windows()
- .into_iter()
- .find_map(|(label, window)| {
- window
- .gtk_window()
- .ok()
- .filter(|window| window.upcast_ref::<gtk::Window>() == native)
- .map(|_| label)
- })
- }
- let label = wayland_window_label(app, window);
- WAYLAND_CAPTURE_WINDOWS.with_borrow_mut(|windows| {
- let windows = windows.entry(generation).or_default();
- if let Some(saved) = windows.iter_mut().find(|saved| saved.window == *window) {
- if during_stop {
- saved.requested_during_stop = true;
++ struct RunningControl {
++ state: std::sync::Arc<Mutex<Inner>>,
++ stages: tokio::sync::mpsc::UnboundedReceiver<&'static str>,
++ hide: Option<tokio::sync::oneshot::Sender<Result<(), String>>>,
++ change: Option<tokio::sync::oneshot::Sender<Result<(), String>>>,
++ paused: Option<tokio::sync::oneshot::Sender<bool>>,
++ reveal: Option<tokio::sync::oneshot::Sender<()>>,
++ result: tokio::task::JoinHandle<Result<(), String>>,
++ }
+
- #[cfg(target_os = "linux")]
- fn remember_wayland_window(
- app: &AppHandle,
- generation: u32,
- window: &gtk::Window,
- during_stop: bool,
- ) {
- use gtk::prelude::*;
- let label = wayland_window_label(app, window);
- WAYLAND_CAPTURE_WINDOWS.with_borrow_mut(|windows| {
- let windows = windows.entry(generation).or_default();
- if let Some(saved) = windows.iter_mut().find(|saved| saved.window == *window) {
- if during_stop {
- saved.requested_during_stop = true;
++ impl RunningControl {
++ fn start(resume: bool) -> Self {
++ let state = std::sync::Arc::new(Mutex::new(fixture()));
++ {
++ let mut inner = state.lock().unwrap();
++ let lease = inner.lease.as_mut().unwrap();
++ lease.phase = if resume {
++ Phase::Resuming
++ } else {
++ Phase::Pausing
++ };
++ lease.recording_dir = Some(PathBuf::from("recording-a"));
++ }
++ let (stages, observed) = tokio::sync::mpsc::unbounded_channel();
++ let (hide, hidden) = tokio::sync::oneshot::channel();
++ let (change, changed) = tokio::sync::oneshot::channel();
++ let (paused, acknowledged) = tokio::sync::oneshot::channel();
++ let (reveal, mapping) = tokio::sync::oneshot::channel();
++ let control_state = state.clone();
++ let result = tokio::spawn(async move {
++ let dir = PathBuf::from("recording-a");
++ ControlOperation {
++ resume,
++ generation: 1,
++ dir: &dir,
++ hide: async {
++ stages.send("hide").unwrap();
++ hidden.await.unwrap()
++ },
++ change: async {
++ stages.send("actor").unwrap();
++ changed.await.unwrap()
++ },
++ paused: async {
++ stages.send("confirm-paused").unwrap();
++ acknowledged.await.unwrap()
++ },
++ restore: async {
++ stages.send("queue-main").unwrap();
++ mapping.await.unwrap();
++ if control_state
++ .lock()
++ .unwrap()
++ .may_restore_paused_main(1, &dir)
++ {
++ stages.send("show-main").unwrap();
++ Ok(())
++ } else {
++ stages.send("suppress-main").unwrap();
++ Err("Recording changed before mapping".into())
++ }
++ },
++ stop: async {
++ stages.send("stop").unwrap();
++ assert!(!control_state.lock().unwrap().queue_stop());
++ Ok(())
++ },
++ notify: || stages.send("notify").unwrap(),
++ }
++ .run(&control_state)
++ .await
++ });
++ Self {
++ state,
++ stages: observed,
++ hide: Some(hide),
++ change: Some(change),
++ paused: Some(paused),
++ reveal: Some(reveal),
++ result,
}
-- } else {
-- windows.push(RetainedWaylandWindow {
-- window: window.clone(),
-- label,
-- visible: window.is_visible(),
-- requested_during_stop: during_stop,
++ }
++
++ async fn dispatch_stop(
++ &self,
++ ) -> (
++ tokio::sync::oneshot::Sender<()>,
++ tokio::task::JoinHandle<()>,
++ ) {
++ {
++ let mut inner = self.state.lock().unwrap();
++ assert!(inner.shortcut(true));
++ assert!(inner.lease.as_ref().unwrap().phase.can_stop());
++ assert!(!inner.queue_stop());
++ }
++ let (entered, delivered) = tokio::sync::oneshot::channel();
++ let (acknowledge, joined) = tokio::sync::oneshot::channel();
++ let state = self.state.clone();
++ let stop = tokio::spawn(async move {
++ entered.send(()).unwrap();
++ joined.await.unwrap();
++ let mut inner = state.lock().unwrap();
++ if inner.owner(std::path::Path::new("recording-a")) == Some(1)
++ && inner.lease.as_ref().unwrap().phase == Phase::Stopping
++ {
++ inner.lease.as_mut().unwrap().phase = Phase::Restoring;
++ }
});
++ tokio::time::timeout(Duration::from_secs(1), delivered)
++ .await
++ .unwrap()
++ .unwrap();
++ (acknowledge, stop)
}
-- });
--}
--#[cfg(target_os = "linux")]
--fn guard_wayland_window(app: &AppHandle, window: &gtk::Window) {
-- use gtk::prelude::*;
-- let already_guarded = WAYLAND_GUARDED_WINDOWS.with_borrow_mut(|windows| {
-- windows.retain(|window| window.upgrade().is_some());
-- if windows
-- .iter()
-- .any(|saved| saved.upgrade().as_ref() == Some(window))
++ async fn expect(&mut self, stage: &'static str) {
++ assert_eq!(
++ tokio::time::timeout(Duration::from_secs(1), self.stages.recv())
++ .await
++ .unwrap(),
++ Some(stage)
++ );
++ }
++
++ async fn finish(self) -> Result<(), String> {
++ tokio::time::timeout(Duration::from_secs(1), self.result)
++ .await
++ .unwrap()
++ .unwrap()
++ }
++ }
++
++ #[tokio::test]
++ async fn resume_hide_failure_restores_main_without_calling_actor() {
++ let mut run = RunningControl::start(true);
++ run.expect("hide").await;
++ run.hide
++ .take()
++ .unwrap()
++ .send(Err("partial unmap failed".into()))
++ .unwrap();
++ run.expect("notify").await;
++ run.expect("queue-main").await;
{
-- true
-- } else {
-- windows.push(window.downgrade());
-- false
++ let inner = run.state.lock().unwrap();
++ assert_eq!(inner.lease.as_ref().unwrap().phase, Phase::Paused);
++ assert!(!inner.may_reveal(1, "camera"));
++ assert!(!inner.may_reveal(1, "in-progress-recording"));
++ assert!(inner.lease.as_ref().unwrap().registered_shortcut);
}
-- });
-- if already_guarded {
-- return;
++ run.reveal.take().unwrap().send(()).unwrap();
++ run.expect("show-main").await;
++ assert_eq!(run.finish().await.unwrap_err(), "partial unmap failed");
}
-- let app = app.clone();
-- window.connect_map(move |window| {
-- let blocked = {
-- let state = app.state::<State>();
-- let inner = state.inner.lock().unwrap();
-- inner
-- .lease
-- .as_ref()
-- .filter(|lease| lease.wayland && wayland_blocks_mapping(lease.phase))
-- .map(|lease| (lease.generation, lease.phase == Phase::Stopping))
-- };
-- if let Some((generation, during_stop)) = blocked {
-- remember_wayland_window(&app, generation, window, during_stop);
-- // GTK's map default handler sends an empty Wayland commit with updates frozen
-- // until initial configure. This synchronous handler unmaps before that dispatch.
-- window.hide();
++
++ #[tokio::test]
++ async fn actor_resume_error_waits_for_quiescent_pause_ack_before_mapping() {
++ let mut run = RunningControl::start(true);
++ run.expect("hide").await;
++ run.hide.take().unwrap().send(Ok(())).unwrap();
++ run.expect("actor").await;
++ run.change
++ .take()
++ .unwrap()
++ .send(Err("segment setup failed".into()))
++ .unwrap();
++ run.expect("confirm-paused").await;
++ assert!(!run.state.lock().unwrap().may_reveal(1, "main"));
++ run.paused.take().unwrap().send(true).unwrap();
++ run.expect("notify").await;
++ run.expect("queue-main").await;
++ run.reveal.take().unwrap().send(()).unwrap();
++ run.expect("show-main").await;
++ assert_eq!(run.finish().await.unwrap_err(), "segment setup failed");
++ }
++
++ #[tokio::test]
++ async fn unknown_resume_error_does_not_map_and_stop_remains_executable() {
++ let mut run = RunningControl::start(true);
++ run.expect("hide").await;
++ run.hide.take().unwrap().send(Ok(())).unwrap();
++ run.expect("actor").await;
++ run.change
++ .take()
++ .unwrap()
++ .send(Err("transport failed".into()))
++ .unwrap();
++ run.expect("confirm-paused").await;
++ run.paused.take().unwrap().send(false).unwrap();
++ run.expect("notify").await;
++ let state = run.state.clone();
++ assert!(
++ run.finish()
++ .await
++ .unwrap_err()
++ .contains("pause could not be confirmed")
++ );
++ let mut state = state.lock().unwrap();
++ assert_eq!(state.lease.as_ref().unwrap().phase, Phase::ResumeFailed);
++ assert!(state.shortcut(true));
++ assert!(state.lease.as_ref().unwrap().phase.can_stop());
++ assert!(!state.may_reveal(1, "main"));
++ assert!(!state.queue_stop());
++ }
++
++ #[tokio::test]
++ async fn stop_during_hide_executes_before_resume_and_rejects_late_hide() {
++ for hidden in [Ok(()), Err("hide failed".into())] {
++ let mut run = RunningControl::start(true);
++ run.expect("hide").await;
++ let (ack, stopped) = run.dispatch_stop().await;
++ assert!(!run.result.is_finished());
++ ack.send(()).unwrap();
++ stopped.await.unwrap();
++ run.hide.take().unwrap().send(hidden).unwrap();
++ assert!(run.finish().await.unwrap_err().contains("changed during"));
}
-- });
--}
++ }
--#[cfg(target_os = "linux")]
--fn install_wayland_window_guard(app: &AppHandle) -> Result<(), String> {
-- use gtk::prelude::*;
-- let application = wayland_application(app)?;
-- let installed = WAYLAND_GUARD_APPLICATION
-- .with_borrow(|saved| saved.as_ref().and_then(gtk::glib::WeakRef::upgrade));
-- if let Some(installed) = installed {
-- if installed != application {
-- return Err("Recording GTK application identity changed".into());
++ #[tokio::test]
++ async fn stop_during_pause_confirmation_executes_without_waiting_for_it() {
++ for paused in [true, false] {
++ let mut run = RunningControl::start(true);
++ run.expect("hide").await;
++ run.hide.take().unwrap().send(Ok(())).unwrap();
++ run.expect("actor").await;
++ run.change
++ .take()
++ .unwrap()
++ .send(Err("setup failed".into()))
++ .unwrap();
++ run.expect("confirm-paused").await;
++ let (ack, stopped) = run.dispatch_stop().await;
++ assert!(!run.result.is_finished());
++ ack.send(()).unwrap();
++ stopped.await.unwrap();
++ run.paused.take().unwrap().send(paused).unwrap();
++ assert!(run.finish().await.unwrap_err().contains("changed during"));
}
-- return Ok(());
}
-- let handle = app.clone();
-- application.connect_window_added(move |_, window| guard_wayland_window(&handle, window));
-- for window in application.windows() {
-- guard_wayland_window(app, &window);
++
++ #[tokio::test]
++ async fn pending_resume_does_not_block_stop_and_late_result_cannot_publish() {
++ for resumed in [Ok(()), Err("cancelled setup".into())] {
++ let mut run = RunningControl::start(true);
++ run.expect("hide").await;
++ run.hide.take().unwrap().send(Ok(())).unwrap();
++ run.expect("actor").await;
++ let (ack, stopped) = run.dispatch_stop().await;
++ assert!(!run.result.is_finished());
++ assert_eq!(
++ run.state.lock().unwrap().lease.as_ref().unwrap().phase,
++ Phase::Stopping
++ );
++ ack.send(()).unwrap();
++ stopped.await.unwrap();
++ assert!(!run.result.is_finished());
++ let failed = resumed.is_err();
++ run.change.take().unwrap().send(resumed).unwrap();
++ if failed {
++ run.expect("confirm-paused").await;
++ run.paused.take().unwrap().send(true).unwrap();
++ }
++ let state = run.state.clone();
++ assert!(run.finish().await.unwrap_err().contains("changed during"));
++ let inner = state.lock().unwrap();
++ assert_eq!(inner.lease.as_ref().unwrap().phase, Phase::Restoring);
++ assert!(inner.snapshot().error.is_none());
++ }
}
-- WAYLAND_GUARD_APPLICATION.with_borrow_mut(|saved| *saved = Some(application.downgrade()));
-- Ok(())
--}
--#[cfg(target_os = "linux")]
--fn remember_wayland_windows(app: &AppHandle, generation: u32) -> Result<(), String> {
-- use gtk::prelude::*;
-- for window in wayland_application(app)?.windows() {
-- remember_wayland_window(app, generation, &window, false);
++ #[tokio::test]
++ async fn delayed_pause_confirmation_cannot_publish_to_new_owner() {
++ let mut run = RunningControl::start(true);
++ run.expect("hide").await;
++ run.hide.take().unwrap().send(Ok(())).unwrap();
++ run.expect("actor").await;
++ run.change
++ .take()
++ .unwrap()
++ .send(Err("setup failed".into()))
++ .unwrap();
++ run.expect("confirm-paused").await;
++ {
++ let mut inner = run.state.lock().unwrap();
++ inner.generation = 2;
++ let lease = inner.lease.as_mut().unwrap();
++ lease.generation = 2;
++ lease.recording_dir = Some(PathBuf::from("recording-b"));
++ }
++ run.paused.take().unwrap().send(true).unwrap();
++ let state = run.state.clone();
++ assert!(run.finish().await.unwrap_err().contains("changed during"));
++ assert_eq!(
++ state.lock().unwrap().lease.as_ref().unwrap().phase,
++ Phase::Resuming
++ );
}
-- Ok(())
--}
--#[cfg(target_os = "linux")]
--fn hide_wayland_windows(app: &AppHandle, generation: u32) -> Result<(), String> {
-- use gtk::prelude::*;
-- remember_wayland_windows(app, generation)?;
-- for window in wayland_application(app)?.windows() {
-- window.hide();
-- if window.is_visible() || window.is_mapped() {
-- return Err("GTK could not hide a Cap window".into());
++ #[tokio::test]
++ async fn delayed_main_mapping_rechecks_owner_phase_and_stop() {
++ for mutation in 0..4 {
++ let mut run = RunningControl::start(true);
++ run.expect("hide").await;
++ run.hide
++ .take()
++ .unwrap()
++ .send(Err("hide failed".into()))
++ .unwrap();
++ run.expect("notify").await;
++ run.expect("queue-main").await;
++ {
++ let mut inner = run.state.lock().unwrap();
++ match mutation {
++ 0 => {
++ inner.generation = 2;
++ inner.lease.as_mut().unwrap().generation = 2;
++ }
++ 1 => {
++ inner.lease.as_mut().unwrap().recording_dir =
++ Some(PathBuf::from("recording-b"))
++ }
++ 2 => inner.lease.as_mut().unwrap().phase = Phase::Resuming,
++ _ => inner.lease.as_mut().unwrap().stop_requested = true,
++ }
++ }
++ run.reveal.take().unwrap().send(()).unwrap();
++ run.expect("suppress-main").await;
++ assert!(
++ run.finish()
++ .await
++ .unwrap_err()
++ .contains("Could not restore controls")
++ );
}
}
-- Ok(())
--}
--#[cfg(target_os = "linux")]
--pub(crate) fn admit_wayland_window_creation(app: &AppHandle) -> Result<(), String> {
-- let state = app.state::<State>();
-- let inner = state.inner.lock().unwrap();
-- if inner.lease.as_ref().is_some_and(|lease| {
-- lease.wayland && wayland_blocks_mapping(lease.phase) && lease.phase != Phase::Stopping
-- }) {
-- return Err("Pause or stop recording before opening another Cap window".into());
++ #[tokio::test]
++ async fn ordinary_pause_and_successful_resume_never_use_failure_restore() {
++ for resume in [false, true] {
++ let mut run = RunningControl::start(resume);
++ if resume {
++ run.expect("hide").await;
++ run.hide.take().unwrap().send(Ok(())).unwrap();
++ }
++ run.expect("actor").await;
++ run.change.take().unwrap().send(Ok(())).unwrap();
++ run.expect("notify").await;
++ let state = run.state.clone();
++ assert!(run.finish().await.is_ok());
++ assert_eq!(
++ state.lock().unwrap().lease.as_ref().unwrap().phase,
++ if resume {
++ Phase::Recording
++ } else {
++ Phase::Paused
++ }
++ );
++ }
}
-- Ok(())
--}
--#[cfg(target_os = "linux")]
--fn wayland_restore_plan(
-- app: &AppHandle,
-- generation: u32,
-- require_inputs: bool,
--) -> Result<Vec<(RetainedWaylandWindow, bool)>, String> {
-- use gtk::prelude::*;
-- let saved_main = {
-- let state = app.state::<State>();
-- let inner = state.inner.lock().unwrap();
-- let lease = inner
-- .lease
-- .as_ref()
-- .filter(|lease| lease.generation == generation && lease.phase == Phase::Restoring)
-- .ok_or("Wayland restoration was superseded")?;
-- lease
-- .windows
-- .iter()
-- .find(|window| window.label == CapWindowId::Main.label())
-- .cloned()
-- };
-- let requested = if require_inputs {
-- Some(
-- app.state::<crate::RequestedInputsState>()
-- .ready_snapshot()?,
-- )
-- } else {
-- None
-- };
-- let retained = WAYLAND_CAPTURE_WINDOWS
-- .with_borrow(|windows| windows.get(&generation).cloned())
-- .ok_or("Retained Wayland windows disappeared")?;
-- let application = WAYLAND_GUARD_APPLICATION
-- .with_borrow(|saved| saved.as_ref().and_then(gtk::glib::WeakRef::upgrade))
-- .ok_or("Retained GTK application disappeared")?;
-- let current = application.windows();
-- let mut result = Vec::new();
-- for mut saved in retained {
-- let label = wayland_window_label(app, &saved.window);
-- let label_changed = saved.label.is_some() && saved.label != label;
-- if saved.label.is_none() {
-- saved.label = label;
-- }
-- let camera = saved
-- .label
-- .as_deref()
-- .is_some_and(|label| matches!(label.parse(), Ok(CapWindowId::Camera)));
-- let editor = saved
-- .label
-- .as_deref()
-- .is_some_and(|label| matches!(label.parse(), Ok(CapWindowId::Editor { .. })));
-- let mut wanted = (saved.visible || (editor && saved.requested_during_stop))
-- && restore_floating_window(saved.label.as_deref())
-- && (!camera
-- || requested
-- .as_ref()
-- .is_some_and(|snapshot| snapshot.camera.value.is_some()));
-- if saved.label.as_deref() == Some("main") {
-- wanted = saved_main.as_ref().is_some_and(|saved| saved.visible);
-- }
-- if wanted && label_changed {
-- return Err("A retained Cap window changed identity".into());
-- }
-- if wanted && !current.contains(&saved.window) {
-- return Err("A retained Cap window disappeared before restoration".into());
++ #[tokio::test]
++ async fn stale_hide_completion_never_invokes_actor_or_restores_main() {
++ for success in [false, true] {
++ let mut run = RunningControl::start(true);
++ run.expect("hide").await;
++ run.state.lock().unwrap().lease.as_mut().unwrap().phase = Phase::Restoring;
++ run.hide
++ .take()
++ .unwrap()
++ .send(if success {
++ Ok(())
++ } else {
++ Err("hide failed".into())
++ })
++ .unwrap();
++ assert!(run.finish().await.unwrap_err().contains("changed during"));
}
-- result.push((saved, wanted));
}
-- if requested.as_ref().is_some_and(|requested| {
-- !app.state::<crate::RequestedInputsState>()
-- .is_current(requested)
-- }) {
-- return Err("Requested inputs changed during Wayland restoration".into());
++
++ #[tokio::test]
++ async fn failed_pause_does_not_run_resume_probe_or_restore() {
++ let mut run = RunningControl::start(false);
++ run.expect("actor").await;
++ run.change
++ .take()
++ .unwrap()
++ .send(Err("pause failed".into()))
++ .unwrap();
++ run.expect("notify").await;
++ let state = run.state.clone();
++ assert_eq!(run.finish().await.unwrap_err(), "pause failed");
++ assert_eq!(
++ state.lock().unwrap().lease.as_ref().unwrap().phase,
++ Phase::Recording
++ );
++ assert!(!state.lock().unwrap().may_reveal(1, "main"));
}
-- Ok(result)
--}
--#[cfg(target_os = "linux")]
--fn restore_wayland_windows(
-- app: &AppHandle,
-- generation: u32,
-- main_only: bool,
--) -> Result<(), String> {
-- use gtk::prelude::*;
-- for (saved, wanted) in wayland_restore_plan(app, generation, !main_only)? {
-- if (saved.label.as_deref() == Some("main")) != main_only {
-- continue;
-- }
-- if wanted {
- saved.window.show_all();
- saved.window.show();
-- if saved.requested_during_stop
-- && saved
-- .label
-- .as_deref()
-- .is_some_and(|label| matches!(label.parse(), Ok(CapWindowId::Editor { .. })))
-- {
-- saved.window.present();
++ #[test]
++ fn control_error_survives_stop_and_release_but_not_a_new_owner() {
++ let mut inner = fixture();
++ let dir = PathBuf::from("recording-a");
++ inner.lease.as_mut().unwrap().recording_dir = Some(dir.clone());
++ inner.lease.as_mut().unwrap().phase = Phase::Resuming;
++ assert!(inner.complete_control(
++ 1,
++ &dir,
++ true,
++ &ControlOutcome::ActorFailed {
++ error: "capture setup failed".into(),
++ paused: false
}
-- } else {
-- saved.window.hide();
-- }
-- if saved.window.is_visible() != wanted || (!wanted && saved.window.is_mapped()) {
-- return Err("GTK did not acknowledge Cap window restoration".into());
-- }
++ ));
++ assert_eq!(
++ inner.snapshot().error.as_deref(),
++ Some("capture setup failed")
++ );
++ assert!(!inner.queue_stop());
++ assert_eq!(
++ inner.snapshot().error.as_deref(),
++ Some("capture setup failed")
++ );
++ inner.lease = None;
++ assert_eq!(
++ inner.snapshot().error.as_deref(),
++ Some("capture setup failed")
++ );
++ inner.generation = 2;
++ assert!(inner.snapshot().error.is_none());
}
-- Ok(())
}
diff --cc apps/desktop/src-tauri/src/export.rs
index a47696922,1f36a7a29..440cbdec8
--- a/apps/desktop/src-tauri/src/export.rs
+++ b/apps/desktop/src-tauri/src/export.rs
@@@ -22,9 -22,7 +22,9 @@@ use std::
atomic::{AtomicBool, AtomicUsize, Ordering},
},
};
+#[cfg(not(target_os = "linux"))]
use tauri::Manager;
- #[cfg(not(target_os = "linux"))]
++#[cfg(not(any(target_os = "linux", target_os = "macos")))]
use tauri_plugin_dialog::DialogExt;
use tokio::io::AsyncBufReadExt;
use tokio_util::sync::CancellationToken;
@@@ -181,13 -179,8 +181,36 @@@ impl ExportWorkerMode
#[derive(Clone)]
struct ExportProgress(tauri::ipc::Channel<FramesRendered>);
++#[derive(Debug, PartialEq, Eq)]
++enum ExportSaveDestination {
++ Selected(PathBuf),
++ #[cfg(any(target_os = "macos", test))]
++ Default,
++}
++
++#[cfg(any(target_os = "macos", test))]
++fn resolve_macos_export_destination(
++ result: Result<Option<PathBuf>, String>,
++) -> Option<ExportSaveDestination> {
++ match result {
++ Ok(path) => path.map(ExportSaveDestination::Selected),
++ Err(error) => {
++ warn!(
++ error,
++ "Save dialog unavailable; keeping the export in its project output folder"
++ );
++ Some(ExportSaveDestination::Default)
++ }
++ }
++}
++
struct ExportSaveDialogRequest {
+ #[cfg(not(target_os = "linux"))]
app: tauri::AppHandle,
+ #[cfg(target_os = "linux")]
+ parent: tauri::Window,
+ #[cfg(target_os = "linux")]
+ cancel_token: CancellationToken,
file_name: String,
file_type: String,
}
@@@ -537,10 -530,10 +560,51 @@@ async fn run_out_of_process_export_atte
mode: ExportWorkerMode,
cancel_token: CancellationToken,
) -> Result<PathBuf, String> {
++ use cap_utils::operation_diagnostics::{Field, Operation};
++ let mut diagnostic = Operation::start(
++ "export_worker",
++ &[
++ Field::identifier(
++ "resource",
++ cap_utils::operation_diagnostics::resource_id(project_path),
++ ),
++ Field::number("requested_fps", settings.fps() as u64),
++ Field::flag("software_safe", mode.is_software_safe()),
++ Field::flag(
++ "force_ffmpeg_decoder",
++ mode.force_ffmpeg_decoder(force_ffmpeg),
++ ),
++ ],
++ );
++ let result = run_out_of_process_export_attempt_inner(
++ project_path,
++ settings,
++ progress,
++ force_ffmpeg,
++ mode,
++ cancel_token,
++ &mut diagnostic,
++ )
++ .await;
++ diagnostic.finish(result.is_ok());
++ result
++}
++
++async fn run_out_of_process_export_attempt_inner(
++ project_path: &Path,
++ settings: &ExportSettings,
++ progress: ExportProgress,
++ force_ffmpeg: bool,
++ mode: ExportWorkerMode,
++ cancel_token: CancellationToken,
++ diagnostic: &mut cap_utils::operation_diagnostics::Operation,
++) -> Result<PathBuf, String> {
++ use cap_utils::operation_diagnostics::Field;
if cancel_token.is_cancelled() {
return Err("Export cancelled".to_string());
}
++ diagnostic.stage("resolving_worker");
let bin_path = resolve_exporter_binary()?;
let settings_json = serde_json::to_string(settings)
.map_err(|e| format!("Failed to serialize settings: {e}"))?;
@@@ -565,6 -558,6 +629,9 @@@
.stdout(Stdio::piped())
.stderr(Stdio::piped());
++ if let Ok(parent) = serde_json::to_string(&diagnostic.id()) {
++ command.env("CAP_DIAGNOSTIC_PARENT", parent);
++ }
command.arg("--progress-json");
if force_ffmpeg_decoder {
@@@ -586,6 -579,6 +653,10 @@@
)
})?;
++ if let Some(process_id) = child.id() {
++ diagnostic.field(Field::number("worker_process", process_id as u64));
++ }
++ diagnostic.stage("waiting_for_progress");
let stdout = child
.stdout
.take()
@@@ -597,6 -590,6 +668,7 @@@
let stderr_task = tokio::spawn(collect_exporter_stderr_tail(stderr));
let mut completed_path = None;
++ let mut next_diagnostic_frame = 0;
let mut stdout_lines = tokio::io::BufReader::new(stdout).lines();
while let Some(line) = tokio::select! {
@@@ -607,6 -600,6 +679,7 @@@
let _ = child.kill().await;
let _ = child.wait().await;
let _ = stderr_task.await;
++ diagnostic.stage("cancelled");
return Err("Export cancelled".to_string());
}
} {
@@@ -615,12 -608,12 +688,22 @@@
rendered_count,
total_frames,
}) => {
++ if rendered_count >= next_diagnostic_frame {
++ diagnostic.field(Field::number("rendered_frames", rendered_count as u64));
++ diagnostic.field(Field::number("expected_frames", total_frames as u64));
++ diagnostic.stage("rendering");
++ next_diagnostic_frame =
++ rendered_count.saturating_add((total_frames / 10).max(1));
++ }
if !progress_forwarder.send(rendered_count, total_frames) {
let _ = child.kill().await;
++ diagnostic.stage("cancelled");
return Err("Export cancelled".to_string());
}
}
Ok(ExportSidecarMessage::Completed { path }) => {
++ diagnostic.field(Field::flag("worker_reported_completion", true));
++ diagnostic.stage("waiting_for_worker_exit");
completed_path = Some(path);
}
Err(e) => {
@@@ -641,9 -634,9 +724,25 @@@
let _ = child.kill().await;
let _ = child.wait().await;
let _ = stderr_task.await;
++ diagnostic.stage("cancelled");
return Err("Export cancelled".to_string());
}
};
++ diagnostic.field(Field::flag("worker_exit_success", status.success()));
++ if let Some(code) = status.code() {
++ diagnostic.field(Field::number(
++ "worker_exit_code_bits",
++ u64::from(code as u32),
++ ));
++ }
++ #[cfg(unix)]
++ {
++ use std::os::unix::process::ExitStatusExt;
++ if let Some(signal) = status.signal() {
++ diagnostic.field(Field::number("worker_signal", signal as u64));
++ }
++ }
++ diagnostic.stage("worker_exited");
let stderr_tail = stderr_task.await.unwrap_or_default();
if !status.success() {
@@@ -676,6 -669,6 +775,9 @@@ async fn collect_exporter_stderr_tail(s
loop {
match lines.next_line().await {
Ok(Some(line)) => {
++ if cap_utils::operation_diagnostics::relay_worker_record(&line) {
++ continue;
++ }
if cfg!(debug_assertions) {
info!(line = %line, "Export worker stderr");
}
@@@ -1155,12 -1147,12 +1257,16 @@@ async fn export_video_to_file_inner
return Err("Save dialog cancelled".to_string());
};
-- info!(path = %save_path.display(), "Export save path selected");
--
let output_path =
export_video_inner(project_path, settings, editor, progress, cancel_token).await?;
-- copy_export_to_path(&output_path, &save_path).await?;
-- Ok(save_path)
++ match save_path {
++ ExportSaveDestination::Selected(path) => {
++ copy_export_to_path(&output_path, &path).await?;
++ Ok(path)
++ }
++ #[cfg(any(target_os = "macos", test))]
++ ExportSaveDestination::Default => Ok(output_path),
++ }
}
async fn export_video_inner(
@@@ -1275,18 -1267,10 +1381,18 @@@
}
async fn show_export_save_dialog(
- app: &tauri::AppHandle,
- file_name: String,
- file_type: String,
-) -> Result<Option<PathBuf>, String> {
+ request: ExportSaveDialogRequest,
- ) -> Result<Option<PathBuf>, String> {
++) -> Result<Option<ExportSaveDestination>, String> {
+ let ExportSaveDialogRequest {
+ #[cfg(not(target_os = "linux"))]
+ app,
+ #[cfg(target_os = "linux")]
+ parent,
+ #[cfg(target_os = "linux")]
+ cancel_token,
+ file_name,
+ file_type,
+ } = request;
info!(file_name, file_type, "Save file dialog requested");
let (name, extension) = match file_type.as_str() {
@@@ -1301,132 -1285,19 +1407,157 @@@
info!(file_name, name, extension, "Showing save file dialog");
+ #[cfg(target_os = "linux")]
- let result = show_linux_save_dialog(parent, cancel_token, file_name, name, extension).await;
- #[cfg(not(target_os = "linux"))]
++ let result = show_linux_save_dialog(parent, cancel_token, file_name, name, extension)
++ .await
++ .map(|path| path.map(ExportSaveDestination::Selected));
++ #[cfg(target_os = "macos")]
++ let result = Ok(resolve_macos_export_destination(
++ show_macos_save_dialog(&app, file_name, extension).await,
++ ));
++ #[cfg(not(any(target_os = "linux", target_os = "macos")))]
+ let result = {
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ app.dialog()
+ .file()
+ .set_title("Save File")
+ .set_file_name(file_name)
+ .add_filter(name, &[extension])
+ .save_file(move |path| {
+ let _ = tx.send(path.and_then(|p| p.as_path().map(PathBuf::from)));
+ });
- rx.await.map_err(|error| error.to_string())
++ rx.await
++ .map_err(|error| error.to_string())
++ .map(|path| path.map(ExportSaveDestination::Selected))
+ };
+ result.inspect(|result| {
+ info!(path = ?result, "Save file dialog completed");
+ })
+}
+
++#[cfg(target_os = "macos")]
++pub(crate) async fn show_macos_save_dialog(
++ app: &tauri::AppHandle,
++ file_name: String,
++ extension: &'static str,
++) -> Result<Option<PathBuf>, String> {
+ let (tx, rx) = tokio::sync::oneshot::channel();
- app.dialog()
- .file()
- .set_title("Save File")
- .set_file_name(file_name)
- .add_filter(name, &[extension])
- .save_file(move |path| {
- let _ = tx.send(path.and_then(|p| p.as_path().map(PathBuf::from)));
++ app.run_on_main_thread(move || {
++ crate::macos_save_panel::show(&file_name, &[extension], move |result| {
++ let _ = tx.send(result);
+ });
-
- rx.await.map_err(|e| e.to_string()).inspect(|result| {
- info!(path = ?result, "Save file dialog completed");
+ })
++ .map_err(|error| format!("Unable to show save dialog: {error}"))?;
++ rx.await
++ .map_err(|error| format!("Save dialog stopped before completing: {error}"))?
++}
++
+#[cfg(target_os = "linux")]
+pub(crate) async fn show_linux_save_dialog(
+ parent: tauri::Window,
+ cancel_token: CancellationToken,
+ file_name: String,
+ name: &'static str,
+ extension: &'static str,
+) -> Result<Option<PathBuf>, String> {
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ let window = parent.clone();
+ parent
+ .run_on_main_thread(move || {
+ use gtk::prelude::*;
+
+ let prepared = window
+ .gtk_window()
+ .map_err(|error| format!("Export window is unavailable: {error}"))
+ .map(|parent| parent.upcast::<gtk::Window>())
+ .and_then(|parent| {
+ create_linux_export_save_dialog(&parent, &file_name, name, extension)
+ .map(|dialog| (parent, dialog))
+ });
+ match prepared {
+ Ok((parent, dialog)) => {
+ run_linux_export_save_dialog(parent, dialog, cancel_token, tx);
+ }
+ Err(error) => {
+ let _ = tx.send(Err(error));
+ }
+ }
+ })
+ .map_err(|error| format!("Unable to show export save dialog: {error}"))?;
+ rx.await.map_err(|error| error.to_string())?
+}
+
+#[cfg(target_os = "linux")]
+fn create_linux_export_save_dialog(
+ parent: &gtk::Window,
+ file_name: &str,
+ filter_name: &str,
+ extension: &str,
+) -> Result<gtk::FileChooserNative, String> {
+ use gtk::prelude::*;
+
+ if parent.in_destruction() || !parent.is_mapped() {
+ return Err("Export window is no longer available".to_string());
+ }
+
+ // rfd's GTK backend discards its parent, so tiled compositors can clip the save controls.
+ let dialog = gtk::FileChooserNative::new(
+ Some("Save File"),
+ Some(parent),
+ gtk::FileChooserAction::Save,
+ None,
+ None,
+ );
+ dialog.set_do_overwrite_confirmation(true);
+ if !file_name.contains('\0') {
+ dialog.set_current_name(file_name);
+ }
+ let filter = gtk::FileFilter::new();
+ filter.set_name(Some(filter_name));
+ filter.add_pattern(&format!("*.{extension}"));
+ dialog.add_filter(filter);
+ Ok(dialog)
+}
+
+#[cfg(target_os = "linux")]
+fn run_linux_export_save_dialog(
+ parent: gtk::Window,
+ dialog: gtk::FileChooserNative,
+ cancel_token: CancellationToken,
+ mut result_tx: tokio::sync::oneshot::Sender<Result<Option<PathBuf>, String>>,
+) {
+ use gtk::prelude::*;
+
+ let (destroy_tx, destroyed) = tokio::sync::oneshot::channel();
+ let destroy_tx = std::cell::Cell::new(Some(destroy_tx));
+ let parent_destroyed = std::rc::Rc::new(std::cell::Cell::new(false));
+ let destroyed_flag = parent_destroyed.clone();
+ let destroy_handler = parent.connect_destroy(move |_| {
+ destroyed_flag.set(true);
+ if let Some(sender) = destroy_tx.take() {
+ let _ = sender.send(());
+ }
+ });
+ std::mem::drop(gtk::glib::MainContext::default().spawn_local(async move {
+ let result = tokio::select! {
+ biased;
+ _ = cancel_token.cancelled() => Err("Export cancelled".to_string()),
+ _ = result_tx.closed() => Err("Export cancelled".to_string()),
+ _ = destroyed => Err("Export window was closed".to_string()),
+ response = dialog.run_future() => {
+ Ok(if response == gtk::ResponseType::Accept {
+ dialog.filename()
+ } else {
+ None
+ })
+ }
+ };
+ if !parent_destroyed.get() {
+ parent.disconnect(destroy_handler);
+ }
+ dialog.destroy();
+ let _ = result_tx.send(result);
+ }));
}
async fn copy_export_to_path(src: &Path, dst: &Path) -> Result<(), String> {
@@@ -1875,108 -1756,39 +2016,167 @@@ mod tests
use super::*;
use tempfile::tempdir;
+ #[test]
- fn export_preview_projects_captions_after_a_cut() {
++ fn native_save_failure_uses_the_rendered_project_output() {
++ assert_eq!(
++ resolve_macos_export_destination(Err("NSSavePanel unavailable".to_string())),
++ Some(ExportSaveDestination::Default),
++ );
++ }
++
++ #[test]
++ fn cancelling_a_native_save_dialog_does_not_export() {
++ assert_eq!(resolve_macos_export_destination(Ok(None)), None);
++ }
++
++ #[test]
++ fn native_save_selection_keeps_the_requested_destination() {
++ let path = PathBuf::from("selected.mp4");
++ assert_eq!(
++ resolve_macos_export_destination(Ok(Some(path.clone()))),
++ Some(ExportSaveDestination::Selected(path)),
++ );
++ }
++
+ #[tokio::test]
+ async fn export_preview_reads_saved_caption_choice_after_stale_live_preview_update() {
+ for export_with_subtitles in [false, true] {
+ let dir = tempdir().unwrap();
+ let mut saved = cap_project::ProjectConfiguration {
+ captions: Some(cap_project::CaptionsData {
+ settings: cap_project::CaptionSettings {
+ enabled: true,
+ export_with_subtitles,
+ ..Default::default()
+ },
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+ saved.write(dir.path()).unwrap();
+ let (sender, receiver) = tokio::sync::watch::channel(saved.clone());
+ saved
+ .captions
+ .as_mut()
+ .unwrap()
+ .settings
+ .export_with_subtitles = !export_with_subtitles;
+ saved.captions.as_mut().unwrap().settings.enabled = false;
+ sender.send(saved).unwrap();
+
+ let preview = load_export_preview_config(dir.path().to_path_buf(), false)
+ .await
+ .unwrap();
+ let settings = preview.captions.unwrap().settings;
+ assert_eq!(settings.enabled, export_with_subtitles);
+ assert_eq!(settings.export_with_subtitles, export_with_subtitles);
+ assert!(
+ !receiver
+ .borrow()
+ .captions
+ .as_ref()
+ .unwrap()
+ .settings
+ .enabled
+ );
+ let persisted = cap_project::ProjectConfiguration::load(dir.path()).unwrap();
+ assert!(persisted.captions.as_ref().unwrap().settings.enabled);
+ }
+ }
+
+ #[tokio::test]
+ async fn export_preview_reports_missing_or_malformed_saved_config() {
+ let dir = tempdir().unwrap();
+ let missing = load_export_preview_config(dir.path().to_path_buf(), false)
+ .await
+ .unwrap_err();
+ assert!(missing.contains("Failed to read saved project config"));
+ std::fs::write(dir.path().join("project-config.json"), "{not valid json").unwrap();
+ let malformed = load_export_preview_config(dir.path().to_path_buf(), false)
+ .await
+ .unwrap_err();
+ assert!(malformed.contains("Failed to read saved project config"));
+ }
+
++ #[tokio::test]
++ async fn saved_export_preview_projects_captions_after_a_cut() {
+ let directory = tempdir().unwrap();
+ let mut meta: RecordingMeta = serde_json::from_value(serde_json::json!({
+ "pretty_name":"preview", "segments":[], "cursors":{}
+ }))
+ .unwrap();
+ meta.project_path = directory.path().to_path_buf();
+ let config: cap_project::ProjectConfiguration = serde_json::from_value(serde_json::json!({
+ "timeline": {
+ "segments":[
+ {"start":0.0,"end":5.0,"timescale":1.0},
+ {"start":6.0,"end":10.0,"timescale":1.0}
+ ], "zoomSegments":[]
+ },
+ "captions": {
+ "sourceTimed":true, "settings":{},
+ "segments":[{"id":"word","text":"retained","start":8.0,"end":8.5,"words":[]}]
+ }
+ }))
+ .unwrap();
+ config.write(directory.path()).unwrap();
- let mut preview = export_project_config(config.clone(), false);
++ let mut preview = load_export_preview_config(directory.path().to_path_buf(), false)
++ .await
++ .unwrap();
+ synchronize_preview_timing(&meta, &mut preview, &[10.0]);
+ let caption = &preview.timeline.as_ref().unwrap().caption_segments[0];
+ assert_eq!(caption.start, 7.0);
+ assert_eq!(caption.end, 7.5);
+ assert_eq!(caption.text, "retained");
- let mut cursor_only = export_project_config(config, true);
++ let mut cursor_only = load_export_preview_config(directory.path().to_path_buf(), true)
++ .await
++ .unwrap();
+ synchronize_preview_timing(&meta, &mut cursor_only, &[10.0]);
+ assert!(cursor_only.captions.is_none());
+ }
+
+ #[test]
+ fn export_preview_rejects_unloaded_incoming_and_outgoing_media() {
+ let medias = ["first", "second"];
+ assert_eq!(export_preview_media(&medias, 0).unwrap(), &"first");
+ assert_eq!(export_preview_media(&medias, 1).unwrap(), &"second");
+ assert!(export_preview_media(&medias, 2).is_err());
+ assert!(export_preview_media(&medias, u32::MAX).is_err());
+ assert!(export_preview_media::<()>(&[], 0).is_err());
+ }
+
+ #[test]
+ fn export_preview_caption_policy_preserves_editor_and_cursor_only_states() {
+ for enabled in [false, true] {
+ for export in [false, true] {
+ for cursor_only in [false, true] {
+ let editor = cap_project::ProjectConfiguration {
+ captions: Some(cap_project::CaptionsData {
+ settings: cap_project::CaptionSettings {
+ enabled,
+ export_with_subtitles: export,
+ ..Default::default()
+ },
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+ let original = serde_json::to_value(&editor).unwrap();
+ let preview = export_project_config(editor.clone(), cursor_only);
+ if cursor_only {
+ assert!(preview.captions.is_none());
+ } else {
+ assert_eq!(
+ preview.captions.unwrap().settings.enabled,
+ enabled && export
+ );
+ }
+ assert_eq!(serde_json::to_value(editor).unwrap(), original);
+ }
+ }
+ }
+ }
+
#[test]
fn export_estimates_use_source_duration_without_a_timeline() {
assert_eq!(
@@@ -2114,29 -1926,14 +2314,38 @@@ pub async fn generate_export_preview_fa
}
}
+async fn load_export_preview_config(
+ project_path: PathBuf,
+ cursor_only: bool,
+) -> Result<cap_project::ProjectConfiguration, String> {
+ tokio::task::spawn_blocking(move || {
+ cap_project::ProjectConfiguration::load(&project_path)
+ .map(|config| export_project_config(config, cursor_only))
+ .map_err(|error| {
+ format!("Failed to read saved project config for export preview: {error}")
+ })
+ })
+ .await
+ .map_err(|error| format!("Failed to load export preview config: {error}"))?
+}
+
+ fn synchronize_preview_timing(
+ meta: &RecordingMeta,
+ project: &mut cap_project::ProjectConfiguration,
+ display_durations: &[f64],
+ ) {
+ cap_project::synchronize_legacy_keyboard(meta, project);
+ cap_project::synchronize_captions(project, display_durations);
+ }
++
+fn export_preview_media<T>(medias: &[T], recording_clip: u32) -> Result<&T, String> {
+ medias.get(recording_clip as usize).ok_or_else(|| {
+ format!(
+ "Recording clip {recording_clip} is unavailable in this editor. Reopen the project before exporting."
+ )
+ })
+}
+
#[instrument(skip_all)]
async fn generate_export_preview_fast_inner(
editor: WindowEditorInstance,
@@@ -2152,8 -1949,26 +2361,24 @@@
let _preview_guard = ExportPreviewActiveGuard::try_new(&editor.export_preview_active)?;
- let project_config =
- let mut project_config = export_project_config(
- editor.project_config.1.borrow().clone(),
- settings.cursor_only,
- );
++ let mut project_config =
+ load_export_preview_config(editor.project_path.clone(), settings.cursor_only).await?;
+ let meta = editor.meta().clone();
+ let recordings = editor.recordings.clone();
+ let project_config = tokio::task::spawn_blocking(move || {
+ synchronize_preview_timing(
+ &meta,
+ &mut project_config,
+ &recordings
+ .segments
+ .iter()
+ .map(|segment| segment.display.duration)
+ .collect::<Vec<_>>(),
+ );
+ project_config
+ })
+ .await
+ .map_err(|error| format!("Failed to synchronize export preview timing: {error}"))?;
let transition_mapping = project_config.timeline.as_ref().and_then(|timeline| {
if timeline.transitions.is_empty() {
return None;
diff --cc apps/desktop/src-tauri/src/lib.rs
index d1f8f6fde,7e15f6962..6e07ad10b
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@@ -30,6 -30,6 +30,8 @@@ mod http_client
mod import;
pub mod linux_instant_camera;
mod logging;
++#[cfg(target_os = "macos")]
++mod macos_save_panel;
mod notifications;
mod panel_manager;
mod permissions;
@@@ -5172,7 -4574,7 +5158,9 @@@ fn screenshot_share_link_for_hash
}
async fn upgrade_required_result(app: &AppHandle) -> UploadResult {
-- let _ = ShowCapWindow::Upgrade.show(app).await;
++ if let Err(error) = open_pricing_page(app).await {
++ warn!(%error, "Failed to open pricing page");
++ }
UploadResult::UpgradeRequired
}
@@@ -5322,6 -4726,6 +5310,8 @@@ async fn save_file_dialog_inner
"gif" => ("GIF Image", "gif"),
"mov" => ("MOV Video", "mov"),
"screenshot" | "png" => ("PNG Image", "png"),
++ "srt" => ("SubRip Subtitle", "srt"),
++ "vtt" => ("WebVTT", "vtt"),
_ => {
warn!(file_type, "Invalid save file dialog type");
return Err("Invalid file type".to_string());
@@@ -5330,69 -4734,40 +5320,68 @@@
info!(file_name, name, extension, "Showing save file dialog");
- // Use `tokio::sync::oneshot` so the async runtime worker yields while the native dialog
- // is open instead of being parked by a synchronous `std::sync::mpsc` receive. The
- // previous version blocked a runtime worker for the lifetime of the dialog which, in
- // release builds with fewer/active workers, could starve other tasks and let an unrelated
- // exit event slip through before the export session guard incremented.
- let (tx, rx) = tokio::sync::oneshot::channel();
-
- app.dialog()
- .file()
- .set_title("Save File")
- .set_file_name(file_name)
- .add_filter(name, &[extension])
- .save_file(move |path| {
- let _ = tx.send(
- path.as_ref()
- .and_then(|p| p.as_path())
- .map(|p| p.to_string_lossy().to_string()),
- );
- });
+ #[cfg(target_os = "linux")]
- {
- use tauri_plugin_fs::FsExt;
-
- let path = export::show_linux_save_dialog(
- window.clone(),
- tokio_util::sync::CancellationToken::new(),
- file_name,
- name,
- extension,
- )
- .await?;
- if let Some(path) = &path {
- if let Some(scope) = window.try_fs_scope() {
- scope.allow_file(path).map_err(|error| error.to_string())?;
- }
- window
- .state::<tauri::scope::Scopes>()
- .allow_file(path)
- .map_err(|error| error.to_string())?;
- }
- Ok(path.map(|path| path.to_string_lossy().into_owned()))
- }
- #[cfg(not(target_os = "linux"))]
- {
++ let path = export::show_linux_save_dialog(
++ window.clone(),
++ tokio_util::sync::CancellationToken::new(),
++ file_name,
++ name,
++ extension,
++ )
++ .await?;
++ #[cfg(target_os = "macos")]
++ let path = export::show_macos_save_dialog(window.app_handle(), file_name, extension).await?;
++ #[cfg(not(any(target_os = "linux", target_os = "macos")))]
++ let path = {
+ use tauri_plugin_dialog::DialogExt;
+
+ let app = window.app_handle().clone();
+ // Use `tokio::sync::oneshot` so the async runtime worker yields while the native dialog
+ // is open instead of being parked by a synchronous `std::sync::mpsc` receive. The
+ // previous version blocked a runtime worker for the lifetime of the dialog which, in
+ // release builds with fewer/active workers, could starve other tasks and let an unrelated
+ // exit event slip through before the export session guard incremented.
+ let (tx, rx) = tokio::sync::oneshot::channel();
+
+ app.dialog()
+ .file()
+ .set_title("Save File")
+ .set_file_name(file_name)
+ .add_filter(name, &[extension])
+ .save_file(move |path| {
+ let _ = tx.send(
+ path.as_ref()
+ .and_then(|p| p.as_path())
- .map(|p| p.to_string_lossy().to_string()),
++ .map(std::path::PathBuf::from),
+ );
+ });
- match rx.await {
- Ok(result) => {
- info!(path = ?result, "Save file dialog completed");
- Ok(result)
+ match rx.await {
+ Ok(result) => {
+ info!(path = ?result, "Save file dialog completed");
- Ok(result)
++ result
+ }
+ Err(e) => {
+ warn!(error = %e, "Save file dialog failed");
+ notifications::send_notification(
+ &app,
+ notifications::NotificationType::VideoSaveFailed,
+ );
- Err(e.to_string())
++ return Err(e.to_string());
+ }
}
- Err(e) => {
- warn!(error = %e, "Save file dialog failed");
- notifications::send_notification(
- &app,
- notifications::NotificationType::VideoSaveFailed,
- );
- Err(e.to_string())
++ };
++ if let Some(path) = &path {
++ use tauri_plugin_fs::FsExt;
++ if let Some(scope) = window.try_fs_scope() {
++ scope.allow_file(path).map_err(|error| error.to_string())?;
+ }
++ window
++ .state::<tauri::scope::Scopes>()
++ .allow_file(path)
++ .map_err(|error| error.to_string())?;
}
++ Ok(path.map(|path| path.to_string_lossy().into_owned()))
}
#[derive(Serialize, specta::Type)]
@@@ -6005,11 -5380,11 +5994,21 @@@ async fn editor_delete_project
Ok(())
}
++async fn open_pricing_page(app: &AppHandle) -> Result<(), String> {
++ app.shell()
++ .open("https://cap.so/pricing?ref=desktop", None)
++ .map_err(|e| e.to_string())
++}
++
// keep this async otherwise opening windows may hang on windows
#[tauri::command]
#[specta::specta]
#[instrument(skip(app))]
async fn show_window(app: AppHandle, window: ShowCapWindow) -> Result<(), String> {
++ if matches!(window, ShowCapWindow::Upgrade) {
++ return open_pricing_page(&app).await;
++ }
++
if matches!(window, ShowCapWindow::Camera { .. }) {
let operation_lock = app.state::<CameraWindowOperationLock>();
let _operation_guard = operation_lock.lock().await;
@@@ -6481,6 -5856,6 +6480,7 @@@ fn specta_builder() -> tauri_specta::Bu
recording::delete_recording,
recording::take_screenshot,
recording::import_current_desktop_background,
++ recording::get_default_project_config,
recording::list_cameras,
recording::get_camera_formats,
recording::get_microphone_info,
@@@ -7097,6 -6456,6 +7097,7 @@@ pub async fn run(recording_logging_hand
let app = app.clone();
move |_| {
app.state::<MainWindowReadyState>().set_ready(true);
++ tracing::info!("Main window frontend ready");
gpu_context::prewarm_gpu();
tokio::task::spawn_blocking(cap_rendering::prewarm_fonts);
tokio::spawn(screenshot_editor::prewarm_screenshot_renderer());
@@@ -7135,16 -6494,16 +7136,20 @@@
tokio::spawn({
let app = app.clone();
async move {
-- if should_show_onboarding(&app) {
-- println!("Showing onboarding");
-- let _ = ShowCapWindow::Onboarding.show(&app).await;
++ let startup_window = if should_show_onboarding(&app) {
++ ShowCapWindow::Onboarding
} else {
-- println!("Showing main window");
-- let _ = ShowCapWindow::Main {
++ ShowCapWindow::Main {
init_target_mode: None,
}
-- .show(&app)
-- .await;
++ };
++ match startup_window.show(&app).await {
++ Ok(window) => {
++ tracing::info!(label = window.label(), "Startup window created");
++ }
++ Err(error) => {
++ tracing::error!(%error, "Failed to open startup window");
++ }
}
}
});
diff --cc apps/desktop/src-tauri/src/logging.rs
index 9e64d19d9,9e64d19d9..8551885d6
--- a/apps/desktop/src-tauri/src/logging.rs
+++ b/apps/desktop/src-tauri/src/logging.rs
@@@ -7,35 -7,35 +7,8 @@@ use cap_recording::diagnostics::
StorageInfo,
};
use serde::Serialize;
--use std::{fs, path::PathBuf};
--use tauri::{AppHandle, Manager};
--async fn get_latest_log_file(app: &AppHandle) -> Option<PathBuf> {
-- let logs_dir = app
-- .state::<ArcLock<crate::App>>()
-- .read()
-- .await
-- .logs_dir
-- .clone();
--
-- let entries = fs::read_dir(&logs_dir).ok()?;
-- let mut log_files: Vec<_> = entries
-- .filter_map(|entry| {
-- let entry = entry.ok()?;
-- let path = entry.path();
-- if path.is_file() && path.file_name()?.to_str()?.contains("cap-desktop.log") {
-- let metadata = fs::metadata(&path).ok()?;
-- let modified = metadata.modified().ok()?;
-- Some((path, modified))
-- } else {
-- None
-- }
-- })
-- .collect();
--
-- log_files.sort_by_key(|b| std::cmp::Reverse(b.1));
-- log_files.first().map(|(path, _)| path.clone())
--}
++use tauri::{AppHandle, Manager};
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
@@@ -196,49 -196,49 +169,21 @@@ pub async fn upload_log_file(app: &AppH
upload_log_file_inner(app, None).await
}
--/// `report` is the optional diagnostic report JSON. With `None` the request is
--/// byte-identical to the log upload that has always shipped.
pub(crate) async fn upload_log_file_inner(
app: &AppHandle,
report: Option<String>,
) -> Result<(), String> {
-- let log_file = get_latest_log_file(app).await.ok_or("No log file found")?;
--
-- let metadata =
-- fs::metadata(&log_file).map_err(|e| format!("Failed to read log file metadata: {e}"))?;
-- let file_size = metadata.len();
--
-- const MAX_SIZE: u64 = 1024 * 1024;
--
-- let log_content = if file_size > MAX_SIZE {
-- let content =
-- fs::read_to_string(&log_file).map_err(|e| format!("Failed to read log file: {e}"))?;
--
-- let header = format!(
-- "⚠️ Log file truncated (original size: {file_size} bytes, showing last ~1MB)\n\n"
-- );
-- let max_content_size = (MAX_SIZE as usize) - header.len();
--
-- if content.len() > max_content_size {
-- // Walk forward to a char boundary first: slicing a String at an
-- // arbitrary byte offset panics, and logs carry multi-byte text
-- // (device names, paths).
-- let mut start_pos = content.len() - max_content_size;
-- while start_pos < content.len() && !content.is_char_boundary(start_pos) {
-- start_pos += 1;
-- }
-- let truncated = &content[start_pos..];
-- if let Some(newline_pos) = truncated.find('\n') {
-- format!("{}{}", header, &truncated[newline_pos + 1..])
-- } else {
-- format!("{header}{truncated}")
-- }
-- } else {
-- content
-- }
-- } else {
-- fs::read_to_string(&log_file).map_err(|e| format!("Failed to read log file: {e}"))?
-- };
++ let logs_dir = app
++ .state::<ArcLock<crate::App>>()
++ .read()
++ .await
++ .logs_dir
++ .clone();
++ let log_bundle = tokio::task::spawn_blocking(move || {
++ cap_utils::log_upload::collect(&logs_dir, "cap-desktop.log")
++ })
++ .await
++ .map_err(|_| "Log collection could not finish".to_string())?;
let app_data_dir = app
.path()
@@@ -255,8 -255,8 +200,28 @@@
)
};
-- let diagnostics = collect_diagnostics_for_upload(&recordings_dir, &app_data_dir, is_recording);
++ let diagnostics = tokio::task::spawn_blocking(move || {
++ collect_diagnostics_for_upload(&recordings_dir, &app_data_dir, is_recording)
++ })
++ .await
++ .ok();
let diagnostics_json = serde_json::to_string(&diagnostics).unwrap_or_else(|_| "{}".to_string());
++ let context = serde_json::json!({
++ "schemaVersion": 1,
++ "app": {
++ "flavor": "tauri",
++ "version": env!("CARGO_PKG_VERSION"),
++ "os": std::env::consts::OS,
++ "binaryArchitecture": std::env::consts::ARCH,
++ "debugBuild": cfg!(debug_assertions),
++ "sourceRevision": option_env!("CAP_BUILD_REVISION"),
++ "sourceDirty": option_env!("CAP_BUILD_DIRTY").and_then(|value| value.parse::<bool>().ok()),
++ },
++ "operations": cap_utils::operation_diagnostics::snapshot(),
++ "logCoverage": &log_bundle,
++ "environmentCollectedAt": "upload_time",
++ "mediaIncluded": false,
++ });
// Everything leaving the machine goes through the redactor. Logs record
// whole URLs on failure (reqwest's Display and Debug both append the URL),
@@@ -264,14 -264,14 +229,23 @@@
// live write credential for up to an hour.
use cap_recording::log_redaction::scrub_log_text;
++ let upload = cap_utils::log_upload::prepare_upload(
++ log_bundle,
++ context,
++ Some(&diagnostics_json),
++ report.as_deref(),
++ scrub_log_text,
++ );
let mut form = reqwest::multipart::Form::new()
-- .text("log", scrub_log_text(&log_content))
++ .text("log", upload.log)
.text("os", std::env::consts::OS)
.text("version", env!("CARGO_PKG_VERSION"))
-- .text("diagnostics", scrub_log_text(&diagnostics_json));
--
-- if let Some(report) = report {
-- form = form.text("report", scrub_log_text(&report));
++ .text("context", upload.context);
++ if let Some(diagnostics) = upload.diagnostics {
++ form = form.text("diagnostics", diagnostics);
++ }
++ if let Some(report) = upload.report {
++ form = form.text("report", report);
}
let response = app
diff --cc apps/desktop/src-tauri/src/macos_save_panel.rs
index 000000000,000000000..c975b5d4c
new file mode 100644
--- /dev/null
+++ b/apps/desktop/src-tauri/src/macos_save_panel.rs
@@@ -1,0 -1,0 +1,108 @@@
++use block2::RcBlock;
++use objc2::rc::Retained;
++use objc2::{ClassType, MainThreadMarker, msg_send};
++use objc2_app_kit::{NSApplication, NSModalResponseCancel, NSModalResponseOK, NSSavePanel};
++use objc2_foundation::{NSArray, NSString};
++use std::cell::RefCell;
++use std::path::PathBuf;
++
++fn response_result(response: isize, path: Option<PathBuf>) -> Result<Option<PathBuf>, String> {
++ match response {
++ value if value == NSModalResponseCancel => Ok(None),
++ value if value == NSModalResponseOK => path
++ .map(Some)
++ .ok_or_else(|| "The save dialog did not return a file path".to_string()),
++ _ => Err("The save dialog could not be displayed".to_string()),
++ }
++}
++
++pub fn show(
++ file_name: &str,
++ extensions: &[&str],
++ completion: impl FnOnce(Result<Option<PathBuf>, String>) + 'static,
++) {
++ let Some(mtm) = MainThreadMarker::new() else {
++ completion(Err(
++ "The save dialog must run on the main thread".to_string()
++ ));
++ return;
++ };
++
++ // AppKit can return nil here even when the bundle signature is valid (Cap #2163).
++ let panel: Option<Retained<NSSavePanel>> =
++ unsafe { msg_send![NSSavePanel::class(), savePanel] };
++ let Some(panel) = panel else {
++ completion(Err("The save dialog is unavailable".to_string()));
++ return;
++ };
++
++ unsafe {
++ panel.setCanCreateDirectories(true);
++ panel.setTitle(Some(&NSString::from_str("Save File")));
++ panel.setNameFieldStringValue(&NSString::from_str(file_name));
++ if !extensions.is_empty() {
++ let extensions: Vec<_> = extensions
++ .iter()
++ .map(|extension| NSString::from_str(extension))
++ .collect();
++ let extensions = NSArray::from_retained_slice(&extensions);
++ let _: () = msg_send![&*panel, setAllowedFileTypes: &*extensions];
++ }
++ }
++
++ let completion = RefCell::new(Some(completion));
++ let callback_panel = panel.clone();
++ let callback = RcBlock::new(move |response: isize| {
++ let Some(completion) = completion.borrow_mut().take() else {
++ return;
++ };
++ let path = if response == NSModalResponseOK {
++ unsafe { callback_panel.URL() }
++ .and_then(|url| unsafe { url.path() })
++ .map(|path| PathBuf::from(path.to_string()))
++ } else {
++ None
++ };
++ callback_panel.orderOut(None);
++ completion(response_result(response, path));
++ });
++ let app = NSApplication::sharedApplication(mtm);
++ let parent = app.keyWindow().or_else(|| unsafe { app.mainWindow() });
++ unsafe {
++ if let Some(parent) = parent {
++ panel.beginSheetModalForWindow_completionHandler(&parent, &callback);
++ } else {
++ panel.beginWithCompletionHandler(&callback);
++ }
++ }
++}
++
++#[cfg(test)]
++mod tests {
++ use super::*;
++ use objc2_app_kit::NSModalResponseAbort;
++
++ #[test]
++ fn explicit_cancel_does_not_become_a_dialog_failure() {
++ assert_eq!(response_result(NSModalResponseCancel, None), Ok(None));
++ }
++
++ #[test]
++ fn native_failure_is_distinct_from_explicit_cancel() {
++ assert!(response_result(NSModalResponseAbort, None).is_err());
++ }
++
++ #[test]
++ fn accepted_dialog_requires_a_destination() {
++ assert!(response_result(NSModalResponseOK, None).is_err());
++ }
++
++ #[test]
++ fn accepted_dialog_preserves_the_selected_destination() {
++ let path = PathBuf::from("/tmp/My Export.mov");
++ assert_eq!(
++ response_result(NSModalResponseOK, Some(path.clone())),
++ Ok(Some(path))
++ );
++ }
++}
diff --cc apps/desktop/src-tauri/src/main.rs
index 4b9e9b0da,ac7a169f6..b3113b658
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@@ -103,16 -103,16 +103,40 @@@ fn main()
path
};
- // Ensure logs directory exists
- std::fs::create_dir_all(&logs_dir).unwrap_or_else(|e| {
- eprintln!("Failed to create logs directory: {e}");
- });
-
- let info_file_appender = tracing_appender::rolling::daily(&logs_dir, "cap-desktop.log");
- let (info_file_writer, _info_logger_guard) = tracing_appender::non_blocking(info_file_appender);
-
- let errors_file_appender =
- tracing_appender::rolling::daily(&logs_dir, "cap-desktop-errors.log");
+ let (info_file_writer, _info_logger_guard) =
+ match create_log_appender(&logs_dir, "cap-desktop.log") {
+ Some(appender) => {
- let (writer, guard) = tracing_appender::non_blocking(appender);
++ let (writer, guard) = tracing_appender::non_blocking(
++ cap_utils::diagnostic_writer::DiagnosticWriter::new(
++ appender,
++ &logs_dir,
++ "cap-desktop.log",
++ ),
++ );
++ let queue_errors = writer.error_counter();
++ cap_utils::operation_diagnostics::install_queue_loss_counter(move || {
++ queue_errors.dropped_lines()
++ });
++ let diagnostic_writer = writer.clone();
++ cap_utils::operation_diagnostics::install_sink(
++ cap_utils::operation_diagnostics::AppInfo {
++ flavor: "tauri",
++ version: env!("CARGO_PKG_VERSION"),
++ source_revision: option_env!("CAP_BUILD_REVISION"),
++ debug_build: cfg!(debug_assertions),
++ source_dirty: option_env!("CAP_BUILD_DIRTY").map(|value| value == "true"),
++ },
++ move |bytes| {
++ use std::io::Write;
++ let _ = diagnostic_writer.clone().write_all(bytes);
++ },
++ );
+ (Some(writer), Some(guard))
+ }
+ None => (None, None),
+ };
+
+ let errors_file_appender = create_log_appender(&logs_dir, "cap-desktop-errors.log");
let (otel_layer, _tracer) = if cfg!(debug_assertions) {
use opentelemetry::trace::TracerProvider;
@@@ -191,30 -191,7 +215,35 @@@
.thread_stack_size(TOKIO_WORKER_THREAD_STACK_SIZE)
.build()
.expect("Failed to build multi threaded tokio runtime")
-- .block_on(cap_desktop_lib::run(handle, logs_dir));
++ .block_on(async move {
++ drop(tokio::spawn(
++ cap_utils::operation_diagnostics::run_checkpoints(),
++ ));
++ cap_desktop_lib::run(handle, logs_dir).await;
++ });
+}
+
+fn create_log_appender(
+ directory: &std::path::Path,
+ prefix: &str,
+) -> Option<tracing_appender::rolling::RollingFileAppender> {
+ use std::io::Write;
+
+ match tracing_appender::rolling::RollingFileAppender::builder()
+ .rotation(tracing_appender::rolling::Rotation::DAILY)
+ .filename_prefix(prefix)
+ .build(directory)
+ {
+ Ok(appender) => Some(appender),
+ Err(error) => {
+ let _ = writeln!(
+ std::io::stderr(),
+ "Could not open {prefix} in {}: {error}; console logging remains enabled",
+ directory.display()
+ );
+ None
+ }
+ }
}
fn install_panic_hook(logs_dir: std::path::PathBuf) {
diff --cc apps/desktop/src-tauri/src/recording.rs
index 7b2db68f8,e743e56a3..3ce7c6fcb
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@@ -6605,6 -5179,6 +6599,24 @@@ fn apply_screen_recording_presentation_
}
}
++pub fn default_project_config() -> ProjectConfiguration {
++ let mut config = ProjectConfiguration::default();
++
++ apply_screen_recording_presentation_defaults(&mut config, None, false, None);
++
++ if config.background.rounding <= f64::EPSILON {
++ config.background.rounding = DEFAULT_SCREEN_RECORDING_BACKGROUND_ROUNDING_PERCENT;
++ }
++
++ config
++}
++
++#[tauri::command]
++#[specta::specta]
++pub fn get_default_project_config() -> ProjectConfiguration {
++ default_project_config()
++}
++
pub fn needs_fragment_remux(recording_dir: &Path, meta: &StudioRecordingMeta) -> bool {
let StudioRecordingMeta::MultipleSegments { inner, .. } = meta else {
return false;
@@@ -7251,6 -5810,6 +7263,21 @@@ mod tests
assert!(config.background.border.is_none());
}
++ #[test]
++ fn default_project_config_matches_screen_recording_presentation() {
++ let config = default_project_config();
++ let spring = cap_project::ScreenMovementSpring::default();
++
++ assert_eq!(config.background.padding, 10.0);
++ assert_eq!(
++ config.background.rounding,
++ DEFAULT_SCREEN_RECORDING_BACKGROUND_ROUNDING_PERCENT
++ );
++ assert_eq!(config.screen_movement_spring.stiffness, spring.stiffness);
++ assert_eq!(config.screen_movement_spring.damping, spring.damping);
++ assert_eq!(config.screen_movement_spring.mass, spring.mass);
++ }
++
#[test]
fn classifies_unsolicited_pipeline_completion_as_unexpected_stop() {
let disposition = classify_actor_done_result(Ok::<(), anyhow::Error>(()), true);
diff --cc apps/desktop/src-tauri/src/windows.rs
index 27ba686cc,dfe3ad5f4..92ba119ad
--- a/apps/desktop/src-tauri/src/windows.rs
+++ b/apps/desktop/src-tauri/src/windows.rs
@@@ -3303,6 -2919,6 +3303,13 @@@ impl ShowCapWindow
.theme(theme)
.devtools(cfg!(debug_assertions));
++ #[cfg(all(target_os = "macos", debug_assertions))]
++ if matches!(id, CapWindowId::Main) {
++ // Main stays hidden until its frontend mounts; WebKit must finish loading Vite first.
++ builder = builder
++ .background_throttling(tauri::utils::config::BackgroundThrottlingPolicy::Disabled);
++ }
++
if !id.is_transparent() {
let is_dark = match theme {
Some(tauri::Theme::Dark) => true,
diff --cc apps/desktop/src/components/Mode.tsx
index c12e80547,c12e80547..a09746c30
--- a/apps/desktop/src/components/Mode.tsx
+++ b/apps/desktop/src/components/Mode.tsx
@@@ -32,7 -32,7 +32,7 @@@ const MODE_BUTTONS: ModeButtonConfig[]
mode: "studio",
label: "Studio mode",
description:
-- "Records at the highest quality for local rendering later. Opens the Cap editor when you're done.",
++ "Saves to your computer and opens the editor when you stop. Choose recording quality in settings.",
settingsSection: "studio-quality",
icon: (p) => <IconCapFilmCut {...p} />,
iconClass: "size-[0.9rem] invert dark:invert-0",
@@@ -64,7 -64,7 +64,7 @@@ const Mode = (props: ModeProps) =>
try {
localStorage.setItem("cap.settings.scrollToSection", section);
} catch {}
-- await commands.showWindow({ Settings: { page: "general" } });
++ await commands.showWindow({ Settings: { page: "quality" } });
await events.requestScrollToSettingsSection.emit({ section });
};
diff --cc apps/desktop/src/components/Toggle.tsx
index 43e8d2250,43e8d2250..e1d7b0359
--- a/apps/desktop/src/components/Toggle.tsx
+++ b/apps/desktop/src/components/Toggle.tsx
@@@ -3,7 -3,7 +3,7 @@@ import { cva } from "cva"
import { type ComponentProps, splitProps } from "solid-js";
const toggleControlStyles = cva(
-- "cap-toggle rounded-full bg-gray-6 data-disabled:bg-gray-3 data-checked:bg-blue-500 transition-[background-color,box-shadow]",
++ "cap-toggle rounded-full bg-ed-ctl-active data-disabled:bg-ed-ctl data-checked:bg-ed-accent transition-[background-color,box-shadow]",
{
variants: {
size: {
diff --cc apps/desktop/src/routes/(window-chrome)/new-main/TargetCard.tsx
index e42bb4690,c01e68f75..33ffdbb5e
--- a/apps/desktop/src/routes/(window-chrome)/new-main/TargetCard.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/new-main/TargetCard.tsx
@@@ -1,6 -1,6 +1,6 @@@
import { ProgressCircle } from "@cap/ui-solid";
import { convertFileSrc } from "@tauri-apps/api/core";
--import { ask, save } from "@tauri-apps/plugin-dialog";
++import { ask } from "@tauri-apps/plugin-dialog";
import { remove } from "@tauri-apps/plugin-fs";
import * as shell from "@tauri-apps/plugin-shell";
import { cx } from "cva";
@@@ -243,15 -243,15 +243,10 @@@ export default function TargetCard(prop
const screenshot = screenshotTarget();
if (!screenshot) return;
try {
-- const path = await save({
-- defaultPath: `${screenshot.pretty_name}.png`,
-- filters: [
-- {
-- name: "Image",
-- extensions: ["png"],
-- },
-- ],
-- });
++ const path = await commands.saveFileDialog(
++ `${screenshot.pretty_name}.png`,
++ "png",
++ );
if (!path) return;
await commands.copyFileToPath(screenshot.path, path);
toast.success("Screenshot saved");
diff --cc apps/desktop/src/routes/(window-chrome)/new-main/index.tsx
index 0a0019c9c,92e44288a..54b90dc08
--- a/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx
@@@ -2910,12 -2821,12 +2910,10 @@@ function Page()
try {
await commands.stopRecording();
} catch (error) {
- if (stopRequest === request) {
- stopErrorRequest = request;
- setStopError(error instanceof Error ? error.message : String(error));
- }
- } finally {
- if (stopRequest === request) resetStopRequest();
+ await dialog.message(
- `Failed to stop recording: ${
- error instanceof Error ? error.message : String(error)
- }`,
++ error instanceof Error ? error.message : String(error),
+ { title: "Stop Recording", kind: "error" },
+ );
}
},
}));
diff --cc apps/desktop/src/routes/(window-chrome)/onboarding.tsx
index cc6a1bf26,cc6a1bf26..8ef45a586
--- a/apps/desktop/src/routes/(window-chrome)/onboarding.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/onboarding.tsx
@@@ -1075,7 -1075,7 +1075,7 @@@ function FaqStep(props: { active: boole
out our{" "}
<button
type="button"
-- onClick={() => shell.open("https://cap.so/pricing")}
++ onClick={() => shell.open("https://cap.so/pricing?ref=desktop")}
class="text-blue-10 hover:text-blue-11 underline underline-offset-2"
>
pricing plans
@@@ -1115,7 -1115,7 +1115,7 @@@
<button
type="button"
-- onClick={() => shell.open("https://cap.so/pricing")}
++ onClick={() => shell.open("https://cap.so/pricing?ref=desktop")}
class={cx(
"flex items-center gap-1.5 text-[13px] text-blue-10 hover:text-blue-11 transition-all duration-500 delay-200",
visible() ? "opacity-100" : "opacity-0",
diff --cc apps/desktop/src/routes/(window-chrome)/settings.tsx
index ea3edf9dd,ea3edf9dd..b7c592ade
--- a/apps/desktop/src/routes/(window-chrome)/settings.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings.tsx
@@@ -200,6 -200,6 +200,11 @@@ export default function Settings(props
name: "General",
icon: IconCapSettings,
},
++ {
++ href: "quality",
++ name: "Recording quality",
++ icon: IconCapFilmCut,
++ },
{
href: "hotkeys",
name: "Shortcuts",
@@@ -237,7 -237,7 +242,7 @@@
},
{
href: "license",
-- name: "License",
++ name: "Plan & license",
icon: IconLucideGift,
},
{
diff --cc apps/desktop/src/routes/(window-chrome)/settings/general.tsx
index a0f663657,a0f663657..7b953b98d
--- a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
@@@ -16,7 -16,7 +16,6 @@@ import
createResource,
createSignal,
For,
-- onCleanup,
onMount,
Show,
} from "solid-js";
@@@ -46,7 -46,7 +45,6 @@@ import
type MainWindowRecordingStartBehaviour,
type PostDeletionBehaviour,
type PostStudioRecordingBehaviour,
-- type StudioRecordingQuality,
type UpdateChannel,
type WindowExclusion,
} from "~/utils/tauri";
@@@ -128,8 -128,8 +126,6 @@@ const MAX_FPS_OPTIONS =
const DEFAULT_PROJECT_NAME_TEMPLATE =
"{target_name} ({target_kind}) {date} {time}";
--const FREE_INSTANT_MODE_MAX_RESOLUTION = 1280;
--const PRO_INSTANT_MODE_MAX_RESOLUTION = 1920;
export default function GeneralSettings() {
const [stores] = createResource(() =>
@@@ -237,71 -237,71 +233,11 @@@ function Inner(props:
] = createSignal(
props.initialRecordingStartSafety.confirmBeforeRecordingWithoutMicrophone,
);
-- const auth = authStore.createQuery();
-- const hasCapPro = createMemo(() => {
-- const plan = auth.data?.plan;
-- return !!plan && (plan.upgraded || plan.manual);
-- });
-- const instantModeMaxResolution = createMemo(() =>
-- hasCapPro()
-- ? (settings.instantModeMaxResolution ?? PRO_INSTANT_MODE_MAX_RESOLUTION)
-- : FREE_INSTANT_MODE_MAX_RESOLUTION,
-- );
createEffect(() => {
setSettings(reconcile(deriveGeneralSettings(props.initialStore)));
});
-- let scrollContainerRef: HTMLDivElement | undefined;
--
-- const scrollToSection = (section: string) => {
-- try {
-- localStorage.removeItem("cap.settings.scrollToSection");
-- } catch {}
-- const attempt = (remaining: number) => {
-- const target = document.getElementById(`settings-section-${section}`);
-- const container = scrollContainerRef;
-- if (!target || !container) {
-- if (remaining > 0) {
-- window.setTimeout(() => attempt(remaining - 1), 50);
-- }
-- return;
-- }
-- const containerRect = container.getBoundingClientRect();
-- const targetRect = target.getBoundingClientRect();
-- const offset =
-- targetRect.top - containerRect.top + container.scrollTop - 8;
-- container.scrollTo({ top: offset, behavior: "smooth" });
-- target.classList.add("settings-section-pulse");
-- window.setTimeout(() => {
-- target.classList.remove("settings-section-pulse");
-- }, 1600);
-- };
-- attempt(10);
-- };
--
-- onMount(() => {
-- commands
-- .updateAuthPlan()
-- .then(() => auth.refetch())
-- .catch(console.error);
--
-- let pending: string | null = null;
-- try {
-- pending = localStorage.getItem("cap.settings.scrollToSection");
-- } catch {}
-- if (pending) {
-- scrollToSection(pending);
-- }
--
-- const unlisten = events.requestScrollToSettingsSection.listen((event) => {
-- scrollToSection(event.payload.section);
-- });
-- onCleanup(() => {
-- unlisten.then((cb) => cb()).catch(() => {});
-- });
-- });
--
const [windows, { refetch: refetchWindows }] = createResource(
async () => {
// Fetch windows with a small delay to avoid blocking initial render
@@@ -465,7 -465,7 +401,6 @@@
| MainWindowRecordingStartBehaviour
| PostStudioRecordingBehaviour
| PostDeletionBehaviour
-- | StudioRecordingQuality
| number,
>(props: {
label: string;
@@@ -509,10 -509,10 +444,7 @@@
};
return (
-- <div
-- ref={scrollContainerRef}
-- class="cap-settings-page flex flex-col h-full custom-scroll"
-- >
++ <div class="cap-settings-page flex flex-col h-full custom-scroll">
<SettingsPageContent>
<AppearanceSection
currentTheme={settings.theme ?? "system"}
@@@ -553,25 -553,25 +485,6 @@@
</Section>
)}
-- <CapProSection
-- hasCapPro={hasCapPro()}
-- instantResolution={instantModeMaxResolution()}
-- onInstantResolutionChange={(value) =>
-- handleChange("instantModeMaxResolution", value)
-- }
-- autoOpenShareableLinks={!settings.disableAutoOpenLinks}
-- onAutoOpenShareableLinksChange={(v) =>
-- handleChange("disableAutoOpenLinks", !v)
-- }
-- />
--
-- <QualitySection
-- studioQuality={settings.studioRecordingQuality ?? "balanced"}
-- onStudioQualityChange={(value) =>
-- handleChange("studioRecordingQuality", value)
-- }
-- />
--
<Section
title="Recording"
description="Behaviour while you record and after you stop."
@@@ -969,51 -969,51 +882,6 @@@ function UpdatesSection(props:
);
}
--type StudioQualityTier = {
-- value: StudioRecordingQuality;
-- label: string;
-- summary: string;
-- bestFor: string;
--};
--
--const STUDIO_QUALITY_TIERS: StudioQualityTier[] = [
-- {
-- value: "compatibility",
-- label: "Compatibility",
-- summary: "Lower bitrate to keep older or low-power machines smooth.",
-- bestFor: "Older Intel Macs, 8GB MacBook Air, weaker laptops.",
-- },
-- {
-- value: "balanced",
-- label: "Balanced",
-- summary: "Sharp footage with sensible CPU and disk usage.",
-- bestFor: "Most modern Macs and PCs with 16GB+ RAM.",
-- },
-- {
-- value: "ultra",
-- label: "Ultra",
-- summary: "Maximum detail for color-graded, large-display edits.",
-- bestFor: "M-series Pro/Max, discrete GPUs, 32GB+ RAM, NVMe.",
-- },
--];
--
--type InstantResolutionTier = {
-- value: number;
-- label: string;
-- summary: string;
--};
--
--const INSTANT_RESOLUTION_TIERS: InstantResolutionTier[] = [
-- { value: 1280, label: "720p", summary: "Smallest size, low bandwidth." },
-- {
-- value: 1920,
-- label: "1080p",
-- summary: "Recommended. Sharp on most networks.",
-- },
-- { value: 2560, label: "1440p", summary: "More detail for desktop content." },
-- { value: 3840, label: "4K", summary: "Max clarity. Needs fast upload." },
--];
--
function SegmentedControl<T extends string | number>(props: {
value: T;
onChange: (value: T) => void;
@@@ -1044,177 -1044,177 +912,6 @@@
);
}
--function StudioQualitySubsection(props: {
-- value: StudioRecordingQuality;
-- onChange: (value: StudioRecordingQuality) => void;
--}) {
-- const currentTier = createMemo(
-- () =>
-- STUDIO_QUALITY_TIERS.find((t) => t.value === props.value) ??
-- STUDIO_QUALITY_TIERS[1],
-- );
--
-- return (
-- <div
-- id="settings-section-studio-quality"
-- class="flex flex-col gap-3 px-4 py-4"
-- >
-- <div class="flex justify-between items-start gap-4">
-- <div class="flex flex-col gap-0.5 min-w-0">
-- <p class="text-[13px] text-gray-12">Studio mode</p>
-- <p class="text-xs leading-snug text-gray-10">
-- Encoder profile for local Studio recordings.
-- </p>
-- </div>
-- <SegmentedControl
-- value={props.value}
-- onChange={props.onChange}
-- options={STUDIO_QUALITY_TIERS.map((tier) => ({
-- value: tier.value,
-- label: tier.label,
-- }))}
-- />
-- </div>
-- <div class="flex flex-col gap-1.5 px-3 py-2.5 rounded-lg bg-gray-3">
-- <p class="text-xs text-gray-12">{currentTier().summary}</p>
-- <p class="text-[11px] text-gray-10 leading-snug">
-- <span class="text-gray-11">Best for:</span> {currentTier().bestFor}
-- </p>
-- </div>
-- </div>
-- );
--}
--
--function InstantQualitySetting(props: {
-- hasCapPro: boolean;
-- value: number;
-- onChange: (value: number) => void;
--}) {
-- const effectiveValue = createMemo(() =>
-- props.hasCapPro ? props.value : FREE_INSTANT_MODE_MAX_RESOLUTION,
-- );
-- const currentTier = createMemo(
-- () =>
-- INSTANT_RESOLUTION_TIERS.find((t) => t.value === effectiveValue()) ??
-- INSTANT_RESOLUTION_TIERS[0],
-- );
-- const handleResolutionClick = async (value: number) => {
-- if (props.hasCapPro || value === FREE_INSTANT_MODE_MAX_RESOLUTION) {
-- props.onChange(value);
-- return;
-- }
--
-- toast.custom(
-- (t) => (
-- <div class="flex gap-3 items-center px-4 py-3 rounded-xl border shadow-lg bg-gray-1 border-gray-4 text-gray-12">
-- <p class="text-sm">
-- Upgrade to Cap Pro to record Instant Mode videos above 720p.
-- </p>
-- <button
-- type="button"
-- class="px-2.5 py-1 text-xs font-medium rounded-lg transition-colors bg-blue-9 text-white hover:bg-blue-10"
-- onClick={() => {
-- toast.dismiss(t.id);
-- void commands.showWindow("Upgrade");
-- }}
-- >
-- Upgrade
-- </button>
-- </div>
-- ),
-- { duration: 6000 },
-- );
-- };
--
-- return (
-- <SettingItem
-- id="settings-section-instant-quality"
-- label="Instant Mode quality"
-- description={
-- props.hasCapPro
-- ? "Choose the maximum upload resolution for Instant recordings."
-- : "Instant recordings are locked to 720p. Cap Pro unlocks higher resolutions."
-- }
-- >
-- <div class="flex flex-col items-end gap-1.5">
-- <div class="inline-flex p-0.5 rounded-lg border border-gray-3 bg-gray-3">
-- <For each={INSTANT_RESOLUTION_TIERS}>
-- {(tier) => {
-- const isSelected = () => effectiveValue() === tier.value;
-- return (
-- <button
-- type="button"
-- onClick={() => void handleResolutionClick(tier.value)}
-- class={cx(
-- "px-3 py-1 text-xs font-medium rounded-md transition-[background-color,color,box-shadow]",
-- isSelected()
-- ? "bg-gray-1 text-gray-12 shadow-sm"
-- : "text-gray-10 hover:text-gray-12",
-- )}
-- >
-- {tier.label}
-- </button>
-- );
-- }}
-- </For>
-- </div>
-- <p class="text-[11px] leading-snug text-right text-gray-10">
-- {currentTier().summary}
-- </p>
-- </div>
-- </SettingItem>
-- );
--}
--
--function CapProSection(props: {
-- hasCapPro: boolean;
-- instantResolution: number;
-- onInstantResolutionChange: (value: number) => void;
-- autoOpenShareableLinks: boolean;
-- onAutoOpenShareableLinksChange: (value: boolean) => void;
--}) {
-- return (
-- <Section
-- title="Cap Pro"
-- description="Settings available with a Cap Pro license."
-- pro
-- >
-- <SectionRows>
-- <InstantQualitySetting
-- hasCapPro={props.hasCapPro}
-- value={props.instantResolution}
-- onChange={props.onInstantResolutionChange}
-- />
-- <ToggleSettingItem
-- label="Auto-open shareable links"
-- description="Open the share link in your browser as soon as the upload finishes."
-- value={props.autoOpenShareableLinks}
-- onChange={props.onAutoOpenShareableLinksChange}
-- />
-- </SectionRows>
-- </Section>
-- );
--}
--
--function QualitySection(props: {
-- studioQuality: StudioRecordingQuality;
-- onStudioQualityChange: (value: StudioRecordingQuality) => void;
--}) {
-- return (
-- <Section
-- title="Quality"
-- description="Pick the right profile for local Studio recordings."
-- >
-- <SectionCard>
-- <StudioQualitySubsection
-- value={props.studioQuality}
-- onChange={props.onStudioQualityChange}
-- />
-- </SectionCard>
-- </Section>
-- );
--}
--
function ServerURLSetting(props: {
value: string;
defaultValue: string;
diff --cc apps/desktop/src/routes/(window-chrome)/settings/license.tsx
index 85c64a7e8,85c64a7e8..0148a284e
--- a/apps/desktop/src/routes/(window-chrome)/settings/license.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings/license.tsx
@@@ -5,91 -5,91 +5,184 @@@ import type { ClientInferResponseBody
import {
createResource,
createSignal,
-- Match,
++ onMount,
Show,
Suspense,
-- Switch,
} from "solid-js";
--import { generalSettingsStore } from "~/store";
++import { authStore, generalSettingsStore } from "~/store";
++import { openPricingPage } from "~/utils/pricing";
import { createLicenseQuery } from "~/utils/queries";
--import { createRive } from "~/utils/rive";
import { commands } from "~/utils/tauri";
import { licenseApiClient } from "~/utils/web-api";
--import PricingRive from "../../../assets/rive/pricing.riv";
import { Input } from "../../editor/ui";
--
++import { Section, SectionCard, SettingsPageContent } from "./Setting";
export default function Page() {
const license = createLicenseQuery();
++ const auth = authStore.createQuery();
const queryClient = useQueryClient();
++ const refreshPlan = createMutation(() => ({
++ mutationFn: async () => {
++ await commands.updateAuthPlan();
++ await Promise.all([auth.refetch(), license.refetch()]);
++ },
++ }));
++ onMount(() => refreshPlan.mutate());
return (
-- <div class="cap-settings-page flex relative flex-col gap-3 items-center p-4 mx-auto h-full custom-scroll">
-- <Switch fallback={<CommercialLicensePurchase />}>
-- <Match when={license.data?.type === "pro" && license.data}>
-- <div class="flex justify-center items-center w-full h-screen">
-- <div class="flex flex-col items-center p-6 mx-auto space-y-3 w-full max-w-md text-white rounded-3xl border bg-gray-2 border-gray-3">
-- <div class="flex flex-col gap-2 items-center">
-- <h3 class="text-2xl font-medium text-gray-12">
-- Cap Pro License
-- </h3>
-- </div>
-- <p class="text-center text-gray-11">
-- Your account is upgraded to{" "}
-- <span class="font-semibold text-blue-500">Cap Pro</span> and
-- already includes a commercial license.
-- </p>
-- </div>
-- </div>
-- </Match>
-- <Match when={license.data?.type === "commercial" && license.data}>
-- {(license) => (
-- <div class="p-8 mx-auto mt-6 w-full max-w-[700px] text-white rounded-xl border border-gray-3 bg-gray-2">
-- <div class="space-y-6">
-- <div class="flex flex-col gap-2 items-center mb-4 text-center">
-- <span class="text-2xl text-green-400 fa fa-briefcase" />
-- <h3 class="text-2xl font-medium text-gray-12">
-- Commercial License
-- </h3>
-- </div>
-- <div>
-- <label class="block mb-2 text-sm text-gray-12">
-- License Key
-- </label>
-- <pre class="overflow-x-auto p-3 font-mono text-xs rounded-lg border border-gray-4 text-gray-9 bg-gray-3">
-- {license().licenseKey}
-- </pre>
-- </div>
-- <Show when={license().expiryDate}>
-- {(expiry) => (
-- <div class="space-y-1">
-- <label class="text-sm text-gray-12">Expires</label>
-- <p class="text-gray-10">
-- {new Date(expiry()).toLocaleDateString()}
++ <div class="cap-settings-page h-full overflow-y-auto custom-scroll">
++ <SettingsPageContent>
++ <Section
++ title="Plan & license"
++ description="Your Cap plan and desktop license, in one place."
++ />
++ <Show when={license.isPending}>
++ <p class="text-xs text-gray-10">Loading your plan…</p>
++ </Show>
++ <Show when={license.isError}>
++ <SectionCard padded>
++ <p class="mb-3 text-xs text-gray-10">Couldn't load your plan.</p>
++ <Button
++ size="sm"
++ variant="gray"
++ onClick={() => void license.refetch()}
++ >
++ Try again
++ </Button>
++ </SectionCard>
++ </Show>
++ <Show when={license.data}>
++ {(current) => (
++ <>
++ <Section title="Your plan">
++ <SectionCard padded>
++ <p class="text-lg font-semibold text-gray-12">
++ {current().type === "pro"
++ ? "Cap Pro"
++ : current().type === "commercial"
++ ? "Desktop License"
++ : "Cap Free"}
++ </p>
++ <p class="mt-1 text-xs leading-relaxed text-gray-10">
++ {current().type === "pro"
++ ? "Your account includes cloud sharing, Pro features and a desktop license for commercial use."
++ : current().type === "commercial"
++ ? "Your desktop license covers commercial recording and editing. Cap Pro adds cloud sharing and collaboration features."
++ : "Record and edit locally for personal use. Choose a paid plan for commercial use or more cloud features."}
++ </p>
++ <Show when={auth.data}>
++ <Button
++ class="mt-3"
++ size="sm"
++ variant="gray"
++ disabled={refreshPlan.isPending}
++ onClick={() => refreshPlan.mutate()}
++ >
++ {refreshPlan.isPending ? "Checking…" : "Refresh plan"}
++ </Button>
++ <Show when={refreshPlan.isError}>
++ <p class="mt-2 text-xs text-gray-10">
++ Couldn't refresh your plan. Please try again.
</p>
-- </div>
++ </Show>
++ </Show>
++ <Show when={!auth.data}>
++ <p class="mt-3 text-xs leading-relaxed text-gray-10">
++ Already have Cap Pro? Sign in with your account from the
++ sidebar.
++ </p>
++ </Show>
++ </SectionCard>
++ </Section>
++ <Section
++ title="Explore plans"
++ description="Compare current pricing and everything included on our website."
++ >
++ <SectionCard padded>
++ <div class="space-y-3 text-xs leading-relaxed text-gray-10">
++ <p>
++ <span class="font-medium text-gray-12">
++ Desktop License
++ </span>{" "}
++ · Commercial use of the desktop recorder and editor.
++ </p>
++ <p>
++ <span class="font-medium text-gray-12">Cap Pro</span> · A
++ desktop license, plus cloud sharing, AI features and
++ collaboration.
++ </p>
++ <Button
++ size="sm"
++ variant="dark"
++ onClick={() => void openPricingPage()}
++ >
++ View plans & pricing ↗
++ </Button>
++ <p>Opens cap.so/pricing in your browser.</p>
++ </div>
++ </SectionCard>
++ </Section>
++ <Show when={current().type !== "pro"}>
++ <Show
++ when={license.data?.type === "commercial" && license.data}
++ fallback={
++ <LicenseKeyActivate
++ onActivated={(value) => {
++ generalSettingsStore
++ .set({
++ commercialLicense: {
++ licenseKey: value.licenseKey,
++ expiryDate: value.expiryDate ?? null,
++ activatedOn: Date.now(),
++ refresh: value.refresh,
++ },
++ })
++ .then(() =>
++ queryClient.refetchQueries({
++ queryKey: ["licenseQuery"],
++ }),
++ );
++ }}
++ />
++ }
++ >
++ {(commercial) => (
++ <Section title="Desktop license">
++ <SectionCard padded>
++ <p class="mb-2 text-xs text-gray-10">License key</p>
++ <pre class="overflow-x-auto p-3 text-xs rounded-lg bg-gray-3 text-gray-11">
++ {commercial().licenseKey}
++ </pre>
++ <Show when={commercial().expiryDate}>
++ {(expiry) => (
++ <p class="mt-3 text-xs text-gray-10">
++ Expires {new Date(expiry()).toLocaleDateString()}
++ </p>
++ )}
++ </Show>
++ <Button
++ class="mt-4"
++ size="sm"
++ variant="destructive"
++ onClick={async () => {
++ await generalSettingsStore.set({
++ commercialLicense: undefined,
++ });
++ await queryClient.refetchQueries({
++ queryKey: ["licenseQuery"],
++ });
++ }}
++ >
++ Deactivate license
++ </Button>
++ </SectionCard>
++ </Section>
)}
</Show>
-- <div class="my-6 h-px bg-gray-4" />
-- <div class="flex flex-col items-center">
-- <Button
-- variant="destructive"
-- onClick={() => {
-- generalSettingsStore.set({
-- commercialLicense: undefined,
-- });
-- queryClient.refetchQueries({
-- queryKey: ["licenseQuery"],
-- });
-- }}
-- >
-- Deactivate License
-- </Button>
-- </div>
-- </div>
-- </div>
++ </Show>
++ </>
)}
-- </Match>
-- </Switch>
++ </Show>
++ </SettingsPageContent>
</div>
);
}
@@@ -176,140 -176,140 +269,3 @@@ function LicenseKeyActivate(props:
</Suspense>
);
}
--
--type CommercialLicenseType = "yearly" | "lifetime";
--function CommercialLicensePurchase() {
-- const queryClient = useQueryClient();
--
-- const [_type, _setType] = createSignal<CommercialLicenseType>("yearly");
--
-- const [isCommercialAnnual, setIsCommercialAnnual] = createSignal(true);
--
-- const { rive: CommercialRive, RiveComponent: Commercial } = createRive(
-- () => ({
-- src: PricingRive,
-- autoplay: true,
-- artboard: "commercial",
-- animations: ["card-stack"],
-- }),
-- );
--
-- const openCommercialCheckout = createMutation(() => ({
-- mutationFn: async () => {
-- const resp = await licenseApiClient.createCommercialCheckoutUrl({
-- body: { type: isCommercialAnnual() ? "yearly" : "lifetime" },
-- });
--
-- if (resp.status === 200) {
-- commands.openExternalLink(resp.body.url);
-- }
-- },
-- }));
--
-- return (
-- <>
-- <div class="w-full max-w-[700px] rounded-xl shadow-xs bg-gray-2">
-- <div class="flex flex-col md:flex-row">
-- {/* Left Column */}
-- <div
-- onMouseEnter={() => {
-- const riveInstance = CommercialRive();
-- if (riveInstance) {
-- // Stop any current animations first
-- riveInstance.stop();
-- // Play the enter animation
-- riveInstance.play("cards");
-- }
-- }}
-- onMouseLeave={() => {
-- const riveInstance = CommercialRive();
-- if (riveInstance) {
-- // Stop any current animations first
-- riveInstance.stop();
-- // Play the leave animation
-- riveInstance.play("card-stack");
-- }
-- }}
-- class="flex flex-col gap-4 items-center p-5 rounded-t-xl border md:rounded-tr-none md:rounded-tl-xl md:rounded-bl-xl border-gray-4 md:w-1/2 bg-gray-3"
-- >
-- <Commercial class="w-[200px]" />
-- <div class="space-y-1 text-center">
-- <h3 class="text-2xl font-medium tracking-tight leading-5">
-- Commercial License
-- </h3>
-- <p class="mt-2 text-sm text-(--text-tertiary)">
-- For commercial use
-- </p>
-- </div>
-- <div class="flex flex-col justify-center items-center mt-5">
-- <h3 class="text-4xl leading-6">
-- {isCommercialAnnual() ? "$29" : "$58"}
-- <span class="text-gray-11 text-[16px]">.00 /</span>
-- </h3>
-- <p class="text-[16px] font-medium text-gray-11">
-- {isCommercialAnnual() ? "billed annually" : "one-time payment"}
-- </p>
-- </div>
-- <div
-- onClick={() => setIsCommercialAnnual((v) => !v)}
-- class="px-3 py-2 text-center rounded-full border border-transparent transition-all duration-200 w-fit bg-gray-5 hover:border-gray-400"
-- >
-- <p class="text-xs text-gray-12">
-- Switch to {isCommercialAnnual() ? "lifetime" : "yearly"}:{" "}
-- <span class="font-medium">
-- {isCommercialAnnual() ? "$58" : "$29"}
-- </span>
-- </p>
-- </div>
-- <Button
-- onClick={() => openCommercialCheckout.mutate()}
-- disabled={openCommercialCheckout.isPending}
-- variant="dark"
-- class="w-full rounded-full! mt-10 h-[48px]! text-lg font-medium"
-- size="lg"
-- >
-- {openCommercialCheckout.isPending
-- ? "Loading..."
-- : "Purchase License"}
-- </Button>
-- </div>
--
-- {/* Right Column */}
-- <div class="flex flex-col gap-4 justify-center items-center p-5 rounded-t-none rounded-b-xl border border-t-0 md:border-t md:border-l-0 md:rounded-bl-none md:rounded-tr-xl md:rounded-br-xl md:w-1/2 border-gray-3">
-- <ul class="flex flex-col gap-2 list-none">
-- {[
-- "Commercial Use of Cap Recorder + Editor",
-- "Community Support",
-- "Local-only features",
-- "Perpetual license option",
-- ].map((feature) => (
-- <li class="flex justify-start items-center">
-- <div class="flex justify-center items-center p-0 m-0 w-6 h-6">
-- <IconLucideCheck class="w-4 h-4 text-(--text-primary)" />
-- </div>
-- <span class="ml-1 text-[0.9rem] text-(--text-primary)">
-- {feature}
-- </span>
-- </li>
-- ))}
-- </ul>
-- </div>
-- </div>
-- </div>
--
-- <LicenseKeyActivate
-- onActivated={async (value) => {
-- await generalSettingsStore.set({
-- commercialLicense: {
-- activatedOn: Date.now(),
-- expiryDate: value.expiryDate ?? null,
-- refresh: value.refresh,
-- licenseKey: value.licenseKey,
-- },
-- });
-- await queryClient.refetchQueries({ queryKey: ["licenseQuery"] });
-- }}
-- />
-- </>
-- );
--}
diff --cc apps/desktop/src/routes/(window-chrome)/settings/quality.tsx
index 000000000,000000000..920b17d57
new file mode 100644
--- /dev/null
+++ b/apps/desktop/src/routes/(window-chrome)/settings/quality.tsx
@@@ -1,0 -1,0 +1,325 @@@
++import { Button } from "@cap/ui-solid";
++import { cx } from "cva";
++import {
++ createMemo,
++ createSignal,
++ For,
++ onCleanup,
++ onMount,
++ Show,
++} from "solid-js";
++import toast from "solid-toast";
++import { authStore, generalSettingsStore } from "~/store";
++import {
++ deriveGeneralSettings,
++ type GeneralSettingsStore,
++} from "~/utils/general-settings";
++import { openPricingPage } from "~/utils/pricing";
++import { commands, events, type StudioRecordingQuality } from "~/utils/tauri";
++import {
++ Section,
++ SectionCard,
++ SectionRows,
++ SettingsPageContent,
++ ToggleSettingItem,
++} from "./Setting";
++
++const STUDIO_OPTIONS = [
++ {
++ value: "balanced",
++ label: "Balanced",
++ description:
++ "Clear, detailed recordings with a practical file size. Best for everyday use.",
++ },
++ {
++ value: "compatibility",
++ label: "Smaller files",
++ description:
++ "Uses less disk space. Can reduce detail, especially when recording with a camera.",
++ },
++ {
++ value: "ultra",
++ label: "Maximum detail",
++ description:
++ "Preserves more detail for demanding edits. Creates larger files and needs more disk space.",
++ },
++] satisfies {
++ value: StudioRecordingQuality;
++ label: string;
++ description: string;
++}[];
++
++const INSTANT_OPTIONS = [
++ {
++ value: 1280,
++ label: "720p",
++ description: "Smaller uploads. Good for quick updates.",
++ },
++ {
++ value: 1920,
++ label: "1080p",
++ description:
++ "Clear text and a practical upload size. Recommended with Cap Pro.",
++ },
++ {
++ value: 2560,
++ label: "1440p",
++ description: "More detail for larger screens. Takes longer to upload.",
++ },
++ {
++ value: 3840,
++ label: "4K",
++ description:
++ "The most detail and largest uploads. Best with a fast connection.",
++ },
++];
++
++export default function RecordingQualitySettings() {
++ const store = generalSettingsStore.createQuery();
++ const auth = authStore.createQuery();
++ const settings = createMemo(() => deriveGeneralSettings(store.data));
++ const studioQuality = createMemo(
++ () => settings().studioRecordingQuality ?? "balanced",
++ );
++ const hasCapPro = createMemo(
++ () => !!(auth.data?.plan?.upgraded || auth.data?.plan?.manual),
++ );
++ const [saving, setSaving] = createSignal(false);
++ const instantResolution = createMemo(() =>
++ hasCapPro() ? (settings().instantModeMaxResolution ?? 1920) : 1280,
++ );
++ const instantDescription = createMemo(
++ () =>
++ INSTANT_OPTIONS.find((option) => option.value === instantResolution())
++ ?.description,
++ );
++ let scrollContainer: HTMLDivElement | undefined;
++ let scrollTimer: ReturnType<typeof setTimeout> | undefined;
++
++ const scrollToSection = (section: string) => {
++ if (section !== "studio-quality" && section !== "instant-quality") return;
++ clearTimeout(scrollTimer);
++ const attempt = (remaining: number) => {
++ const target = document.getElementById(`settings-section-${section}`);
++ if (!target || !scrollContainer) {
++ if (remaining > 0)
++ scrollTimer = setTimeout(() => attempt(remaining - 1), 50);
++ return;
++ }
++ scrollContainer.scrollTo({
++ top:
++ target.getBoundingClientRect().top -
++ scrollContainer.getBoundingClientRect().top +
++ scrollContainer.scrollTop -
++ 16,
++ behavior: "smooth",
++ });
++ };
++ attempt(10);
++ };
++
++ onMount(() => {
++ commands
++ .updateAuthPlan()
++ .then(() => auth.refetch())
++ .catch(console.error);
++ try {
++ const section = localStorage.getItem("cap.settings.scrollToSection");
++ localStorage.removeItem("cap.settings.scrollToSection");
++ if (section) scrollToSection(section);
++ } catch {}
++ const unlisten = events.requestScrollToSettingsSection.listen((event) =>
++ scrollToSection(event.payload.section),
++ );
++ onCleanup(() => {
++ clearTimeout(scrollTimer);
++ unlisten.then((cleanup) => cleanup()).catch(console.error);
++ });
++ });
++
++ const save = async <K extends keyof GeneralSettingsStore>(
++ key: K,
++ value: GeneralSettingsStore[K],
++ ) => {
++ if (saving()) return;
++ setSaving(true);
++ try {
++ await generalSettingsStore.set({ [key]: value });
++ await store.refetch();
++ } catch {
++ toast.error("Couldn't save your recording settings. Please try again.");
++ } finally {
++ setSaving(false);
++ }
++ };
++
++ return (
++ <div
++ ref={scrollContainer}
++ class="cap-settings-page h-full overflow-y-auto custom-scroll"
++ >
++ <SettingsPageContent>
++ <Section
++ title="Recording quality"
++ description="Choose how new recordings look and how much space they use."
++ />
++ <Show when={store.isPending}>
++ <p class="text-xs text-gray-10">Loading recording settings…</p>
++ </Show>
++ <Show when={store.isError}>
++ <SectionCard padded>
++ <p class="mb-3 text-xs text-gray-10">
++ Couldn't load your recording settings.
++ </p>
++ <Button
++ size="sm"
++ variant="gray"
++ onClick={() => void store.refetch()}
++ >
++ Try again
++ </Button>
++ </SectionCard>
++ </Show>
++ <Show when={!store.isPending && !store.isError}>
++ <div id="settings-section-studio-quality">
++ <Section
++ title="Studio"
++ description="Saved to your computer, ready to edit. All three quality options are available on every plan."
++ >
++ <SectionCard padded>
++ <div
++ class="flex flex-col gap-2"
++ role="group"
++ aria-label="Studio recording quality"
++ >
++ <For each={STUDIO_OPTIONS}>
++ {(option) => (
++ <button
++ type="button"
++ aria-pressed={studioQuality() === option.value}
++ disabled={saving()}
++ onClick={() =>
++ void save("studioRecordingQuality", option.value)
++ }
++ class={cx(
++ "flex items-start gap-3 p-3 rounded-lg border text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-9 disabled:opacity-60",
++ studioQuality() === option.value
++ ? "border-blue-9 bg-blue-3"
++ : "border-gray-4 hover:bg-gray-3",
++ )}
++ >
++ <span
++ class={cx(
++ "mt-0.5 size-4 shrink-0 rounded-full border flex items-center justify-center",
++ studioQuality() === option.value
++ ? "border-blue-9"
++ : "border-gray-7",
++ )}
++ >
++ <Show when={studioQuality() === option.value}>
++ <span class="size-2 rounded-full bg-blue-9" />
++ </Show>
++ </span>
++ <span class="flex flex-col gap-1">
++ <span class="flex items-center gap-2 text-[13px] font-medium text-gray-12">
++ {option.label}
++ <Show when={option.value === "balanced"}>
++ <span class="rounded px-1.5 py-0.5 text-[10px] font-medium text-blue-11 bg-blue-4">
++ Recommended
++ </span>
++ </Show>
++ </span>
++ <span class="text-xs leading-relaxed text-gray-10">
++ {option.description}
++ </span>
++ </span>
++ </button>
++ )}
++ </For>
++ </div>
++ <p class="mt-3 text-xs leading-relaxed text-gray-10">
++ These options affect the original recording. Choose your final
++ export resolution and file size in the editor.
++ </p>
++ </SectionCard>
++ </Section>
++ </div>
++ <div id="settings-section-instant-quality">
++ <Section
++ title="Instant"
++ description="Uploads while you record, so your share link is ready when you stop."
++ >
++ <SectionCard padded>
++ <p class="mb-3 text-[13px] font-medium text-gray-12">
++ Maximum resolution
++ </p>
++ <div
++ class="grid grid-cols-4 gap-2"
++ role="group"
++ aria-label="Instant recording resolution"
++ >
++ <For each={INSTANT_OPTIONS}>
++ {(option) => (
++ <button
++ type="button"
++ aria-pressed={instantResolution() === option.value}
++ disabled={
++ saving() ||
++ auth.isPending ||
++ (!hasCapPro() && option.value > 1280)
++ }
++ onClick={() =>
++ void save("instantModeMaxResolution", option.value)
++ }
++ class={cx(
++ "flex flex-col items-center justify-center gap-1 py-2.5 rounded-lg border text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-9 disabled:cursor-default",
++ instantResolution() === option.value
++ ? "border-blue-9 bg-blue-3 text-gray-12"
++ : "border-gray-4 text-gray-10 enabled:hover:bg-gray-3",
++ )}
++ >
++ {option.label}
++ <Show when={!hasCapPro() && option.value > 1280}>
++ <span class="text-[9px] text-gray-10">Pro</span>
++ </Show>
++ </button>
++ )}
++ </For>
++ </div>
++ <p class="mt-3 text-xs leading-relaxed text-gray-10">
++ {instantDescription()} Resolution is limited by the screen or
++ area you record.
++ </p>
++ <Show when={!auth.isPending && !hasCapPro()}>
++ <div class="flex flex-col items-start gap-3 mt-4 pt-4 border-t border-gray-4">
++ <p class="text-xs leading-relaxed text-gray-11">
++ 720p is included. Cap Pro unlocks 1080p, 1440p and 4K for
++ Instant recordings.
++ </p>
++ <Button
++ size="sm"
++ variant="gray"
++ onClick={() => void openPricingPage()}
++ >
++ View plans ↗
++ </Button>
++ </div>
++ </Show>
++ </SectionCard>
++ </Section>
++ </div>
++ <Section title="Sharing">
++ <SectionRows>
++ <ToggleSettingItem
++ label="Open share links automatically"
++ description="Open the link in your browser when an upload finishes."
++ value={!settings().disableAutoOpenLinks}
++ onChange={(value) => void save("disableAutoOpenLinks", !value)}
++ />
++ </SectionRows>
++ </Section>
++ </Show>
++ </SettingsPageContent>
++ </div>
++ );
++}
diff --cc apps/desktop/src/routes/(window-chrome)/upgrade.tsx
index a1ba1be70,a1ba1be70..ed5c1361b
--- a/apps/desktop/src/routes/(window-chrome)/upgrade.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/upgrade.tsx
@@@ -1,601 -1,601 +1,30 @@@
import { Button } from "@cap/ui-solid";
--import { createMutation, useQueryClient } from "@tanstack/solid-query";
--import { getCurrentWindow, Window } from "@tauri-apps/api/window";
--import { type Accessor, createResource, createSignal, Show } from "solid-js";
--import { generalSettingsStore } from "~/store";
--import { getPresentmentCurrencySymbol } from "~/utils/currency";
--import { getProPlanId } from "~/utils/plans";
--import { createLicenseQuery } from "~/utils/queries";
--import { createRive } from "~/utils/rive";
++import { getCurrentWindow } from "@tauri-apps/api/window";
++import { createSignal, onMount, Show } from "solid-js";
import { commands } from "~/utils/tauri";
--import { apiClient, licenseApiClient, protectedHeaders } from "~/utils/web-api";
--import PricingRive from "../../assets/rive/pricing.riv";
--import { authStore } from "../../store";
--
--import { Dialog, DialogContent, Input } from "../editor/ui";
--
--const proFeatures = [
-- "Commercial License Included",
-- "Unlimited cloud storage & Shareable links",
-- "Connect custom S3 storage bucket",
-- "Advanced teams features",
-- "Unlimited views",
-- "Password protected videos",
-- "Advanced analytics",
-- "Priority support",
--];
--
--import { RuntimeLoader } from "@rive-app/canvas";
--import riveWASMResource from "@rive-app/canvas/rive.wasm?url";
--import { createSignInMutation } from "~/utils/auth";
--
--RuntimeLoader.setWasmUrl(riveWASMResource);
--
--export default function Page() {
-- const [isProAnnual, setIsProAnnual] = createSignal(true);
-- const [isCommercialAnnual, setIsCommercialAnnual] = createSignal(true);
-- const [upgradeComplete, _setUpgradeComplete] = createSignal(false);
-- const [loading, setLoading] = createSignal(false);
-- const signIn = createSignInMutation();
-- const license = createLicenseQuery();
-- const [openLicenseDialog, setOpenLicenseDialog] = createSignal(false);
-- const [currencySymbol] = createResource(getPresentmentCurrencySymbol);
-- // Both plans are billed in the same presentment currency.
-- const symbol = () => currencySymbol() ?? "$";
--
-- const resetLicense = createMutation(() => ({
-- mutationFn: async () => {
-- const generalSettings = await generalSettingsStore.get();
-- if (
-- !generalSettings?.instanceId ||
-- !license.data ||
-- license.data.type !== "commercial"
-- ) {
-- throw new Error("No instance ID or valid commercial license found");
-- }
--
-- const resp = await licenseApiClient.activateCommercialLicense({
-- headers: {
-- licensekey: license.data.licenseKey,
-- instanceid: generalSettings.instanceId,
-- },
-- body: { reset: true },
-- });
--
-- if (resp.status !== 200) {
-- if (
-- typeof resp.body === "object" &&
-- resp.body &&
-- "message" in resp.body
-- )
-- throw resp.body.message;
-- throw new Error(String(resp.body));
-- }
-- },
-- onSuccess: async () => {
-- await generalSettingsStore.set({
-- commercialLicense: undefined,
-- });
-- license.refetch();
-- },
-- }));
--
-- const openCheckoutInExternalBrowser = async () => {
-- console.log("Opening checkout in external browser");
-- setLoading(true);
++export default function UpgradeRedirect() {
++ const [failed, setFailed] = createSignal(false);
++ const openPricing = async () => {
++ setFailed(false);
try {
-- const auth = await authStore.get();
--
-- console.log({ auth });
-- if (!auth) {
-- console.log("No auth found, starting sign in flow");
-- await signIn.mutateAsync(new AbortController());
-- }
--
-- const planId = getProPlanId(isProAnnual() ? "yearly" : "monthly");
-- console.log("Getting checkout URL for plan:", planId);
-- const response = await apiClient.desktop.getProSubscribeURL({
-- body: { priceId: planId },
-- headers: await protectedHeaders(),
-- });
--
-- if (response.status === 200) {
-- console.log("Opening checkout URL in external browser");
-- commands.openExternalLink(response.body.url);
-- console.log("Minimizing upgrade window");
-- const window = await Window.getByLabel("upgrade");
-- if (window) await window.minimize();
-- } else {
-- console.error("Failed to get checkout URL, status:", response.status);
-- }
-- } catch (error) {
-- console.error("Error getting checkout URL:", error);
-- } finally {
-- setLoading(false);
++ await commands.showWindow("Upgrade");
++ await getCurrentWindow().close();
++ } catch {
++ setFailed(true);
}
};
-- const openCommercialCheckout = createMutation(() => ({
-- mutationFn: async () => {
-- const resp = await licenseApiClient.createCommercialCheckoutUrl({
-- body: { type: isCommercialAnnual() ? "yearly" : "lifetime" },
-- });
--
-- if (resp.status === 200) {
-- console.log("Opening checkout URL in external browser");
-- commands.openExternalLink(resp.body.url);
-- console.log("Minimizing upgrade window");
-- const window = await Window.getByLabel("upgrade");
-- if (window) {
-- await window.minimize();
-- }
-- } else {
-- throw resp.body;
-- }
-- },
-- }));
--
-- // onMount(async () => {
-- // console.log("Component mounted");
-- // const unsubscribeDeepLink = await onOpenUrl(async (urls) => {
-- // console.log("Deep link received:", urls);
-- // const isDevMode = import.meta.env.VITE_ENVIRONMENT === "development";
-- // if (isDevMode) {
-- // console.log("In dev mode, ignoring deep link");
-- // return;
-- // }
--
-- // for (const url of urls) {
-- // if (!url.includes("token=")) {
-- // console.log("URL does not contain token, skipping");
-- // return;
-- // }
--
-- // console.log("Processing auth URL");
-- // const urlObject = new URL(url);
-- // const token = urlObject.searchParams.get("token");
-- // const user_id = urlObject.searchParams.get("user_id");
-- // const expires = Number(urlObject.searchParams.get("expires"));
--
-- // if (!token || !expires || !user_id) {
-- // console.error("Invalid signin params");
-- // throw new Error("Invalid signin params");
-- // }
--
-- // console.log("Setting auth store with new credentials");
-- // const existingAuth = await authStore.get();
-- // await authStore.set({
-- // token,
-- // user_id,
-- // expires,
-- // plan: {
-- // upgraded: false,
-- // last_checked: 0,
-- // manual: existingAuth?.plan?.manual ?? false,
-- // },
-- // });
--
-- // console.log("Identifying user in analytics");
-- // identifyUser(user_id);
-- // console.log("Tracking sign in event");
-- // trackEvent("user_signed_in", { platform: "desktop" });
--
-- // console.log("Reopening upgrade window");
-- // await commands.showWindow("Upgrade");
--
-- // console.log("Waiting for window to be ready");
-- // await new Promise((resolve) => setTimeout(resolve, 500));
--
-- // console.log("Getting upgrade window reference");
-- // const upgradeWindow = await Window.getByLabel("upgrade");
-- // if (upgradeWindow) {
-- // try {
-- // console.log("Setting focus on upgrade window");
-- // await upgradeWindow.show();
-- // await upgradeWindow.setFocus();
-- // } catch (e) {
-- // console.error("Failed to focus upgrade window:", e);
-- // }
-- // }
--
-- // console.log("Getting checkout URL");
-- // const planId = getProPlanId(isProAnnual() ? "yearly" : "monthly");
-- // const response = await apiClient.desktop.getProSubscribeURL({
-- // body: { priceId: planId },
-- // headers: await protectedHeaders(),
-- // });
--
-- // if (response.status === 200) {
-- // console.log("Opening checkout URL in external browser");
-- // commands.openExternalLink(response.body.url);
-- // console.log("Minimizing upgrade window");
-- // if (upgradeWindow) {
-- // await upgradeWindow.minimize();
-- // }
-- // }
-- // }
-- // });
--
-- // onCleanup(() => {
-- // console.log("Cleaning up deep link listener");
-- // unsubscribeDeepLink();
-- // });
--
-- // console.log("Setting up upgrade status check interval");
-- // const interval = setInterval(async () => {
-- // console.log("Checking upgrade status");
-- // const result = await commands.checkUpgradedAndUpdate();
-- // if (result) {
-- // console.log("Upgrade complete");
-- // setUpgradeComplete(true);
-- // }
-- // }, 5000);
-- // onCleanup(() => {
-- // console.log("Cleaning up upgrade status check interval");
-- // clearInterval(interval);
-- // });
-- // });
--
-- const { rive: CommercialRive, RiveComponent: Commercial } = createRive(
-- () => ({
-- src: PricingRive,
-- autoplay: true,
-- artboard: "commercial",
-- animations: ["card-stack"],
-- }),
-- );
--
-- const { rive: ProRive, RiveComponent: Pro } = createRive(() => ({
-- src: PricingRive,
-- autoplay: true,
-- artboard: "pro",
-- animations: ["items-coming-in"],
-- }));
++ onMount(() => void openPricing());
return (
-- <div class="flex relative flex-col justify-center items-center p-5 mx-auto w-full h-full">
-- {upgradeComplete() && (
-- <div class="flex justify-center items-center h-full bg-opacity-75">
-- <div class="relative z-10 p-6 text-center bg-white rounded-lg shadow-lg">
-- <h2 class="mb-4 text-2xl font-bold">Upgrade complete</h2>
-- <p class="mb-4 text-sm text-gray-10">
-- You can now close this window - thank you for upgrading!
-- </p>
-- <Button
-- onClick={() => {
-- console.log("Closing window after upgrade");
-- const window = getCurrentWindow();
-- window.close();
-- }}
-- variant="primary"
-- size="lg"
-- >
-- Close window
-- </Button>
-- </div>
-- </div>
-- )}
-- {!upgradeComplete() &&
-- (license.data?.type === "commercial" ? (
-- <div class="p-8 mx-auto w-full max-w-[700px] rounded-xl border shadow-xs bg-gray-2 border-gray-3">
-- <div class="space-y-6">
-- <div class="flex flex-col items-center mb-6 text-center">
-- <h3 class="text-2xl font-medium">Commercial License</h3>
-- <p class="text-sm text-gray-11">
-- Your license details for Cap commercial use
-- </p>
-- </div>
--
-- <div class="space-y-6">
-- <div>
-- <label class="block mb-2 text-sm text-gray-12">
-- License Key
-- </label>
-- <p class="overflow-x-auto p-3 font-mono text-xs whitespace-pre-wrap break-all rounded-lg border border-gray-4 text-gray-9 bg-gray-3">
-- {license.data.licenseKey}
-- </p>
-- </div>
--
-- <Show when={license.data.expiryDate}>
-- {(expiryDate) => (
-- <div class="space-y-1">
-- <label class="text-sm text-gray-12">Expires</label>
-- <p class="text-gray-10">
-- {new Date(expiryDate()).toLocaleDateString(undefined, {
-- year: "numeric",
-- month: "long",
-- day: "numeric",
-- })}
-- </p>
-- </div>
-- )}
-- </Show>
--
-- <div class="flex flex-col items-center pt-6 border-t border-gray-3">
-- <Button
-- variant="destructive"
-- disabled={resetLicense.isPending}
-- onClick={() => {
-- resetLicense.mutate();
-- }}
-- >
-- {resetLicense.isPending
-- ? "Deactivating..."
-- : "Deactivate License"}
-- </Button>
-- </div>
-- </div>
-- </div>
-- </div>
-- ) : (
-- <>
-- <div class="text-center">
-- <h1 class="text-4xl md:text-4xl mb-6 tracking-[-.05em] font-medium text-(--text-primary)">
-- Early Adopter Pricing
-- </h1>
-- </div>
-- <div class="flex gap-4 w-full">
-- <div
-- onMouseEnter={() => {
-- const riveInstance = CommercialRive();
-- if (riveInstance) {
-- // Stop any current animations first
-- riveInstance.stop();
-- // Play the enter animation
-- riveInstance.play("cards");
-- }
-- }}
-- onMouseLeave={() => {
-- const riveInstance = CommercialRive();
-- if (riveInstance) {
-- // Stop any current animations first
-- riveInstance.stop();
-- // Play the leave animation
-- riveInstance.play("card-stack");
-- }
-- }}
-- class="flex flex-col flex-1 justify-between p-3 h-[700px ] bg-gray-3 rounded-2xl border border-gray-3 shadow-xs text-card-foreground md:p-3"
-- >
-- <div class="space-y-5">
-- <div class="flex flex-col gap-6 items-center">
-- <Commercial class="w-[250px]" />
-- <div class="space-y-1 text-center">
-- <h3 class="text-2xl font-medium tracking-tight leading-5">
-- Commercial License
-- </h3>
-- <p class="mt-2 text-sm text-(--text-tertiary)">
-- For commercial use
-- </p>
-- </div>
-- <div class="flex flex-col justify-center items-center">
-- <h3 class="text-4xl leading-6">
-- {symbol()}
-- {isCommercialAnnual() ? "29" : "58"}
-- <span class="text-gray-11 text-[16px]">.00 /</span>
-- </h3>
-- {isCommercialAnnual() && (
-- <p class="text-[16px] font-medium text-gray-11">
-- billed annually
-- </p>
-- )}
-- {!isCommercialAnnual() && (
-- <p class="text-[16px] font-medium text-gray-11">
-- one-time payment
-- </p>
-- )}
-- </div>
-- <div
-- onClick={() => setIsCommercialAnnual((v) => !v)}
-- class="px-3 py-2 text-center rounded-full border border-transparent transition-all duration-200 bg-gray-5 hover:border-gray-400"
-- >
-- <p class="text-xs text-gray-12">
-- Switch to {isCommercialAnnual() ? "lifetime" : "yearly"}
-- :{" "}
-- <span class="font-medium">
-- {`${symbol()}${isCommercialAnnual() ? "58" : "29"}`}
-- </span>
-- </p>
-- </div>
-- <ul class="flex flex-col gap-2 justify-center list-none">
-- {[
-- "Commercial Use of Cap Recorder + Editor",
-- "Community Support",
-- "Local-only features",
-- "Perpetual license option",
-- ].map((feature) => (
-- <li class="flex justify-start items-center">
-- <div class="flex justify-center items-center p-0 m-0 w-6 h-6">
-- <IconLucideCheck class="w-4 h-4 text-(--text-primary)" />
-- </div>
-- <span class="ml-1 text-[0.9rem] text-(--text-primary)">
-- {feature}
-- </span>
-- </li>
-- ))}
-- </ul>
-- </div>
-- </div>
-- <ActivateLicenseDialog
-- open={openLicenseDialog}
-- onOpenChange={setOpenLicenseDialog}
-- />
-- <div class="flex flex-col gap-4 items-center">
-- <Button
-- onClick={() => openCommercialCheckout.mutate()}
-- disabled={openCommercialCheckout.isPending}
-- variant="dark"
-- class="w-full rounded-full! h-[48px]! text-lg font-medium"
-- size="lg"
-- >
-- {openCommercialCheckout.isPending
-- ? "Loading..."
-- : "Purchase License"}
-- </Button>
-- <p
-- onClick={() => setOpenLicenseDialog(true)}
-- class="mb-2 text-sm transition-colors text-gray-11 hover:text-gray-12"
-- >
-- Already have a license key?
-- </p>
-- </div>
-- </div>
--
-- {/* Cap Pro */}
-- <div
-- onMouseEnter={() => {
-- const riveInstance = ProRive();
-- if (riveInstance) {
-- // Stop any current animations first
-- riveInstance.stop();
-- // Play the enter animation
-- riveInstance.play("items-coming-out");
-- }
-- }}
-- onMouseLeave={() => {
-- const riveInstance = ProRive();
-- if (riveInstance) {
-- // Stop any current animations first
-- riveInstance.stop();
-- // Play the leave animation
-- riveInstance.play("items-coming-in");
-- }
-- }}
-- class="grow p-3 h-[700px] flex-1 bg-gray-12 rounded-2xl border shadow-xs text-card-foreground md:p-3"
-- >
-- <div class="flex flex-col justify-between space-y-5 h-full">
-- <div class="flex flex-col gap-6 items-center px-6">
-- <Pro class="w-[250px]" />
-- <div class="space-y-1 text-center">
-- <h3 class="text-2xl font-medium tracking-tight leading-5 text-gray-1">
-- Cap Pro
-- </h3>
-- <p class="text-[0.875rem] text-gray-9">
-- For professional use and teams.
-- </p>
-- </div>
-- <div class="flex flex-col justify-center items-center">
-- <h3 class="text-4xl leading-6 text-gray-1">
-- {symbol()}
-- {isProAnnual() ? "8.16" : "12"}
-- <span class="text-gray-10 text-[16px]">.00 /</span>
-- </h3>
-- {isProAnnual() && (
-- <p class="text-[16px] font-medium text-gray-9">
-- per user, billed annually
-- </p>
-- )}
-- {!isProAnnual() && (
-- <p class="text-[16px] font-medium text-gray-9">
-- per user, billed monthly
-- </p>
-- )}
-- </div>
-- <div
-- onClick={() => setIsProAnnual((v) => !v)}
-- class="px-3 py-2 text-center bg-blue-500 rounded-full border border-transparent transition-all duration-200 hover:border-blue-400"
-- >
-- <p class="text-xs text-solid-white">
-- Switch to {isProAnnual() ? "monthly" : "yearly"}:{" "}
-- <span class="font-medium">
-- {isProAnnual()
-- ? `${symbol()}12 per user, billed monthly`
-- : `${symbol()}8.16 per user, billed annually`}
-- </span>
-- </p>
-- </div>
-- <ul class="flex flex-col gap-2 justify-center list-none">
-- {proFeatures.map((feature) => (
-- <li class="flex justify-start items-center text-gray-1">
-- <div class="flex justify-center items-center p-0 m-0 size-4">
-- <IconLucideCheck class="size-4" />
-- </div>
-- <span class="ml-2 text-[0.9rem]">{feature}</span>
-- </li>
-- ))}
-- </ul>
-- </div>
-- <Button
-- variant="blue"
-- class="rounded-full! text-lg! w-full mx-auto"
-- onClick={openCheckoutInExternalBrowser}
-- >
-- {loading() ? "Loading..." : "Upgrade to Cap Pro"}
-- </Button>
-- </div>
-- </div>
-- </div>
-- </>
-- ))}
++ <div class="flex flex-col items-center justify-center gap-3 h-full text-gray-12">
++ <Show when={failed()} fallback={<p>Opening pricing in your browser…</p>}>
++ <p>Couldn't open your browser. Visit cap.so/pricing to view plans.</p>
++ <Button variant="gray" onClick={() => void openPricing()}>
++ Try again
++ </Button>
++ </Show>
</div>
);
}
--
--interface Props {
-- open: Accessor<boolean>;
-- onOpenChange: (open: boolean) => void;
--}
--
--const ActivateLicenseDialog = ({ open, onOpenChange }: Props) => {
-- const [licenseKey, setLicenseKey] = createSignal("");
-- const queryClient = useQueryClient();
--
-- const activateLicenseKey = createMutation(() => ({
-- mutationFn: async (vars: { licenseKey: string }) => {
-- const generalSettings = await generalSettingsStore.get();
-- if (!generalSettings?.instanceId) {
-- throw new Error("No instance ID found");
-- }
-- const resp = await licenseApiClient.activateCommercialLicense({
-- headers: {
-- licensekey: vars.licenseKey,
-- instanceid: generalSettings.instanceId,
-- },
-- body: { reset: false },
-- });
--
-- if (resp.status === 200)
-- return { ...resp.body, licenseKey: vars.licenseKey };
-- if (typeof resp.body === "object" && resp.body && "message" in resp.body)
-- throw resp.body.message;
-- throw new Error(String(resp.body));
-- },
-- onSuccess: async (value) => {
-- await generalSettingsStore.set({
-- commercialLicense: {
-- activatedOn: Date.now(),
-- expiryDate: value.expiryDate ?? null,
-- refresh: value.refresh,
-- licenseKey: value.licenseKey,
-- },
-- });
-- await queryClient.refetchQueries({ queryKey: ["licenseQuery"] });
-- },
-- }));
-- return (
-- <Dialog.Root open={open()} onOpenChange={onOpenChange}>
-- <DialogContent
-- title="Activate License"
-- confirm={
-- <Dialog.ConfirmButton
-- disabled={activateLicenseKey.isPending}
-- onClick={() =>
-- activateLicenseKey.mutate({
-- licenseKey: licenseKey(),
-- })
-- }
-- >
-- Activate
-- </Dialog.ConfirmButton>
-- }
-- >
-- <Input
-- class="mt-2"
-- placeholder="Enter license key..."
-- value={licenseKey()}
-- onInput={(e) => setLicenseKey(e.currentTarget.value)}
-- />
-- </DialogContent>
-- </Dialog.Root>
-- );
--};
diff --cc apps/desktop/src/routes/editor/AnimatedGradientEditor.tsx
index 910586401,910586401..3e653f0f3
--- a/apps/desktop/src/routes/editor/AnimatedGradientEditor.tsx
+++ b/apps/desktop/src/routes/editor/AnimatedGradientEditor.tsx
@@@ -6,7 -6,7 +6,6 @@@ import
createSignal,
For,
Index,
-- type JSX,
onCleanup,
Show,
} from "solid-js";
@@@ -33,7 -33,7 +32,7 @@@ import
import { BrandColorsDropdown } from "./BrandColorsDropdown";
import { hexToRgb, RgbInput } from "./color-utils";
import { useEditorContext } from "./context";
--import { Field, Input, Slider, Subfield } from "./ui";
++import { EditorButton, Field, Input, Section, Slider } from "./ui";
const MAX_STOPS = 5;
const MIN_STOPS = 2;
@@@ -118,44 -118,44 +117,18 @@@ function largestGapPosition(stops: Stop
return position;
}
--function HeaderButton(props: {
-- icon: JSX.Element;
-- label: string;
-- title?: string;
-- disabled?: boolean;
-- pressed?: boolean;
-- onClick: () => void;
--}) {
-- return (
-- <button
-- type="button"
-- title={props.title}
-- aria-pressed={props.pressed}
-- disabled={props.disabled}
-- class={cx(
-- "flex h-7 items-center gap-1 rounded-md px-2 text-xs transition-colors hover:bg-gray-3 hover:text-gray-12 disabled:opacity-40 disabled:hover:bg-transparent",
-- props.pressed ? "bg-gray-3 text-gray-12" : "text-gray-11",
-- )}
-- onClick={props.onClick}
-- >
-- <span class="[&>svg]:size-3.5">{props.icon}</span>
-- {props.label}
-- </button>
-- );
--}
--
function ControlRow(props: {
control: AnimatedGradientControl;
value: number;
onChange: (value: number) => void;
}) {
return (
-- <div class="flex items-center gap-3">
-- <span class="w-24 shrink-0 truncate text-xs text-gray-11">
-- {props.control.label}
-- </span>
++ <Field
++ inline
++ name={props.control.label}
++ value={controlValue(props.control, props.value)}
++ >
<Slider
-- class="min-w-0 flex-1"
value={[props.value]}
minValue={props.control.min}
maxValue={props.control.max}
@@@ -164,10 -164,10 +137,7 @@@
aria-label={props.control.label}
onChange={([next]) => props.onChange(next)}
/>
-- <span class="w-10 shrink-0 text-right text-xs text-gray-11 tabular-nums">
-- {controlValue(props.control, props.value)}
-- </span>
-- </div>
++ </Field>
);
}
@@@ -394,26 -394,26 +364,29 @@@ export function AnimatedGradientEditor(
};
const swatchClass =
-- "aspect-square w-full rounded-lg ring-offset-2 ring-offset-gray-200 transition-all duration-200 hover:scale-105 hover:opacity-80";
++ "aspect-square w-full rounded-lg ring-offset-2 ring-offset-ed-card transition-all duration-200 hover:scale-105 hover:opacity-80";
return (
<Show when={config()}>
{(current) => (
-- <div class="flex flex-col gap-5">
++ <div class="flex flex-col gap-3.5">
<Show when={error()}>
<p role="alert" class="text-xs text-red-11">
{error()}
</p>
</Show>
-- <Field
++ <Section
name="Presets"
-- value={
-- <HeaderButton
-- icon={<IconLucideSave />}
-- label="Save"
++ action={
++ <EditorButton
++ size="sm"
++ leftIcon={<IconLucideSave />}
title="Save the current gradient"
-- pressed={saveOpen()}
++ aria-pressed={saveOpen()}
++ class={
++ saveOpen() ? "bg-ed-ctl-hover text-ed-text-1" : undefined
++ }
disabled={
saving() ||
library.isPending ||
@@@ -421,7 -421,7 +394,9 @@@
savedPresets().length >= MAX_SAVED
}
onClick={() => (saveOpen() ? closeSave() : setSaveOpen(true))}
-- />
++ >
++ Save
++ </EditorButton>
}
>
<div class="flex flex-col gap-3">
@@@ -433,7 -433,7 +408,7 @@@
disabled={randomizing()}
class={cx(
swatchClass,
-- "flex items-center justify-center border border-dashed border-gray-8 bg-gray-2 text-gray-10 disabled:opacity-50",
++ "flex items-center justify-center border border-dashed border-ed-line-strong bg-ed-ctl text-ed-text-3 disabled:opacity-50",
)}
onClick={() => void randomize()}
>
@@@ -447,7 -447,7 +422,9 @@@
aria-label={preset.name}
aria-pressed={isSelected(preset)}
class={swatchClass}
-- classList={{ "ring-2 ring-gray-500": isSelected(preset) }}
++ classList={{
++ "ring-2 ring-ed-accent": isSelected(preset),
++ }}
style={{ background: palettePreview(preset.config) }}
onClick={() => applyConfig(preset.config)}
/>
@@@ -479,7 -479,7 +456,7 @@@
/>
<button
type="button"
-- class="h-8 rounded-lg bg-gray-3 px-3 text-xs font-medium text-gray-12 transition-colors hover:bg-gray-4 disabled:opacity-40"
++ class="h-8 rounded-[7px] bg-ed-ctl px-3 text-[12px] font-medium text-ed-text-1 outline-hidden transition-colors duration-150 hover:bg-ed-ctl-hover disabled:opacity-40"
disabled={!presetName().trim() || saving()}
onClick={() => void savePreset()}
>
@@@ -488,7 -488,7 +465,7 @@@
<button
type="button"
aria-label="Cancel"
-- class="rounded-md p-1.5 text-gray-10 transition-colors hover:bg-gray-3 hover:text-gray-12"
++ class="rounded-md p-1.5 text-ed-text-3 outline-hidden transition-colors duration-150 hover:bg-ed-ctl-hover hover:text-ed-text-1"
onClick={closeSave}
>
<IconLucideX class="size-3.5" />
@@@ -496,7 -496,7 +473,7 @@@
</div>
</Show>
<Show when={savedPresets().length > 0}>
-- <span class="text-[11px] text-gray-10">Saved</span>
++ <span class="text-[11px] text-ed-text-3">Saved</span>
<div class="grid grid-cols-7 gap-2">
<For each={savedPresets()}>
{(preset) => (
@@@ -508,7 -508,7 +485,7 @@@
aria-pressed={isSelected(preset)}
class={swatchClass}
classList={{
-- "ring-2 ring-gray-500": isSelected(preset),
++ "ring-2 ring-ed-accent": isSelected(preset),
}}
style={{ background: palettePreview(preset.config) }}
onClick={() => applyConfig(preset.config)}
@@@ -519,7 -519,7 +496,7 @@@
title="Delete"
aria-label={`Delete ${preset.name}`}
disabled={deletingId() !== null}
-- class="absolute -top-1.5 -right-1.5 flex size-5 items-center justify-center rounded-full bg-gray-12 text-gray-1 shadow-sm transition-colors hover:bg-red-11 disabled:opacity-40"
++ class="absolute -top-1.5 -right-1.5 flex size-5 items-center justify-center rounded-full bg-ed-text-1 text-ed-card shadow-ed-card outline-hidden transition-colors duration-150 hover:bg-red-11 hover:text-white disabled:opacity-40"
onClick={() => void deletePreset(preset.id)}
>
<IconLucideX class="size-3" />
@@@ -531,22 -531,22 +508,24 @@@
</div>
</Show>
</div>
-- </Field>
++ </Section>
-- <div class="w-full border-t border-dashed border-gray-5" />
++ <div class="w-full border-t border-ed-line" />
-- <Field
++ <Section
name="Colours"
-- value={
-- <HeaderButton
-- icon={<IconLucidePlus />}
-- label="Add"
++ action={
++ <EditorButton
++ size="sm"
++ leftIcon={<IconLucidePlus />}
title="Add a colour"
disabled={current().colorStops.length >= MAX_STOPS}
onClick={() =>
addStop(largestGapPosition(current().colorStops))
}
-- />
++ >
++ Add
++ </EditorButton>
}
>
<div class="flex flex-col gap-3">
@@@ -572,7 -572,7 +551,7 @@@
}}
>
<div
-- class="absolute inset-0 rounded-lg border border-gray-5"
++ class="absolute inset-0 rounded-lg border border-ed-line"
style={{ background: palettePreview(current()) }}
/>
<Index each={current().colorStops}>
@@@ -584,8 -584,8 +563,10 @@@
aria-label={`Colour ${index + 1}`}
aria-pressed={selected()}
class={cx(
-- "absolute top-1/2 flex -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full p-0.5 shadow-md outline-hidden transition-[width,height] focus-visible:ring-2 focus-visible:ring-blue-9",
-- selected() ? "size-6 bg-blue-9" : "size-5 bg-white",
++ "absolute top-1/2 flex -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full p-0.5 shadow-md outline-hidden transition-[width,height] focus-visible:ring-2 focus-visible:ring-ed-accent",
++ selected()
++ ? "size-6 bg-ed-accent"
++ : "size-5 bg-white",
)}
style={{ left: `${stop().position}%` }}
onPointerDown={(event) => {
@@@ -651,7 -651,7 +632,7 @@@
})
}
/>
-- <span class="ml-auto text-xs text-gray-11 tabular-nums">
++ <span class="ml-auto text-[11px] text-ed-text-3 tabular-nums">
{Math.round(stop().position)}%
</span>
<button
@@@ -659,7 -659,7 +640,7 @@@
title="Remove colour"
aria-label={`Remove colour ${stopIndex() + 1}`}
disabled={current().colorStops.length <= MIN_STOPS}
-- class="rounded-md p-1.5 text-gray-10 transition-colors hover:bg-gray-3 hover:text-gray-12 disabled:opacity-30 disabled:hover:bg-transparent"
++ class="rounded-md p-1.5 text-ed-text-3 outline-hidden transition-colors duration-150 hover:bg-ed-ctl-hover hover:text-ed-text-1 disabled:opacity-30 disabled:hover:bg-transparent"
onClick={() => removeStop(stopIndex())}
>
<IconLucideTrash2 class="size-3.5" />
@@@ -681,58 -681,58 +662,58 @@@
)}
</Show>
</div>
-- </Field>
++ </Section>
-- <div class="w-full border-t border-dashed border-gray-5" />
++ <div class="w-full border-t border-ed-line" />
<Show when={motionControl()}>
{(control) => (
-- <Subfield name="Motion" class="gap-4">
-- <div class="flex min-w-0 flex-1 items-center gap-3">
-- <Slider
-- class="min-w-0 flex-1"
-- value={[current()[MOTION_KEY]]}
-- minValue={control().min}
-- maxValue={control().max}
-- step={control().step}
-- formatTooltip={(value) => controlValue(control(), value)}
-- aria-label="Motion speed"
-- onChange={([next]) =>
-- updateConfig((value) => {
-- value[MOTION_KEY] = next;
-- })
-- }
-- />
-- <span class="w-10 shrink-0 text-right text-xs text-gray-11 tabular-nums">
-- {controlValue(control(), current()[MOTION_KEY])}
-- </span>
-- </div>
-- </Subfield>
++ <Field
++ inline
++ name="Motion"
++ value={controlValue(control(), current()[MOTION_KEY])}
++ >
++ <Slider
++ value={[current()[MOTION_KEY]]}
++ minValue={control().min}
++ maxValue={control().max}
++ step={control().step}
++ formatTooltip={(value) => controlValue(control(), value)}
++ aria-label="Motion speed"
++ onChange={([next]) =>
++ updateConfig((value) => {
++ value[MOTION_KEY] = next;
++ })
++ }
++ />
++ </Field>
)}
</Show>
-- <div class="w-full border-t border-dashed border-gray-5" />
++ <div class="w-full border-t border-ed-line" />
<KCollapsible open={fineTuneOpen()} onOpenChange={setFineTuneOpen}>
-- <div class="flex items-center">
-- <KCollapsible.Trigger class="group flex flex-1 items-center gap-1.5 text-sm font-medium text-gray-12 outline-hidden">
++ <div class="flex items-center min-h-[22px]">
++ <KCollapsible.Trigger class="group flex flex-1 items-center gap-1.5 text-[12px] font-medium text-ed-text-2 transition-colors duration-150 hover:text-ed-text-1 outline-hidden">
Fine-tune
-- <IconCapChevronDown class="size-3.5 text-gray-10 transition-transform duration-200 group-data-expanded:rotate-180" />
++ <IconCapChevronDown class="size-3.5 text-ed-text-3 transition-transform duration-200 group-data-expanded:rotate-180" />
</KCollapsible.Trigger>
<Show when={fineTuneOpen()}>
-- <HeaderButton
-- icon={<IconLucideRotateCcw />}
-- label="Reset"
++ <EditorButton
++ size="sm"
++ leftIcon={<IconLucideRotateCcw />}
title="Reset fine-tune settings"
onClick={resetFineTune}
-- />
++ >
++ Reset
++ </EditorButton>
</Show>
</div>
<KCollapsible.Content class="overflow-hidden opacity-0 transition-opacity animate-collapsible-up data-expanded:animate-collapsible-down data-expanded:opacity-100">
<div class="flex flex-col gap-3 pt-4">
<div
role="tablist"
-- class="grid grid-cols-4 gap-1 rounded-lg border border-gray-3 bg-gray-2 p-1"
++ class="flex flex-row rounded-lg bg-ed-ctl p-0.5"
>
<For each={groups()}>
{(group) => (
@@@ -741,10 -741,10 +722,10 @@@
role="tab"
aria-selected={activeGroup()?.name === group.name}
class={cx(
-- "rounded-md py-1 text-xs font-medium transition-colors",
++ "flex flex-1 justify-center items-center h-[26px] px-1 rounded-md text-[11.5px] font-medium whitespace-nowrap border-0 outline-hidden transition-colors duration-200",
activeGroup()?.name === group.name
-- ? "bg-gray-5 text-gray-12"
-- : "text-gray-10 hover:text-gray-12",
++ ? "bg-ed-card text-ed-text-1 shadow-[0_1px_2px_rgba(0,0,0,.12),0_0_0_.5px_rgba(0,0,0,.06)] dark:bg-white/11 dark:shadow-none"
++ : "text-ed-text-2 hover:text-ed-text-1",
)}
onClick={() => setGroupName(group.name)}
>
@@@ -753,7 -753,7 +734,7 @@@
)}
</For>
</div>
-- <div class="flex flex-col gap-1">
++ <div class="flex flex-col">
<For each={activeGroup()?.controls ?? []}>
{(control) => (
<ControlRow
diff --cc apps/desktop/src/routes/editor/AspectRatioSelect.tsx
index fe558038c,fe558038c..55337994e
--- a/apps/desktop/src/routes/editor/AspectRatioSelect.tsx
+++ b/apps/desktop/src/routes/editor/AspectRatioSelect.tsx
@@@ -47,7 -47,7 +47,7 @@@ function AspectRatioSelect()
: ASPECT_RATIOS[props.item.rawValue].name}
<Show when={item()}>
{(item) => (
-- <span class="text-gray-11">
++ <span class="text-ed-text-3">
{"⋅"}
{item().ratio[0]}:{item().ratio[1]}
</span>
@@@ -60,18 -60,18 +60,17 @@@
</MenuItem>
);
}}
-- placement="top-start"
++ placement="bottom-start"
>
<EditorButton<typeof KSelect.Trigger>
as={KSelect.Trigger}
-- class="w-28"
++ variant="text"
leftIcon={<IconCapLayout />}
rightIcon={
<KSelect.Icon>
<IconCapChevronDown />
</KSelect.Icon>
}
-- rightIconEnd={true}
>
<KSelect.Value<AspectRatio | "auto">>
{(state) => {
@@@ -79,7 -79,7 +78,7 @@@
const option = state.selectedOption();
return option === "auto" ? "Auto" : ASPECT_RATIOS[option].name;
};
-- return <>{text()}</>;
++ return <span class="max-[1200px]:hidden">{text()}</span>;
}}
</KSelect.Value>
</EditorButton>
diff --cc apps/desktop/src/routes/editor/BrandColorsDropdown.tsx
index f3da4a21c,f3da4a21c..9e160c483
--- a/apps/desktop/src/routes/editor/BrandColorsDropdown.tsx
+++ b/apps/desktop/src/routes/editor/BrandColorsDropdown.tsx
@@@ -18,7 -18,7 +18,7 @@@ export function BrandColorsDropdown(pro
<KDropdownMenu.Trigger
disabled={props.disabled}
class={cx(
-- "flex h-8 w-full items-center gap-2 rounded-lg border border-gray-3 bg-gray-2 px-2 text-sm text-gray-12 transition-colors hover:border-gray-4 hover:bg-gray-3 disabled:pointer-events-none disabled:opacity-50",
++ "flex h-8 w-full items-center gap-2 rounded-[7px] bg-ed-ctl px-2 text-[13px] text-ed-text-1 outline-hidden transition-colors duration-150 hover:bg-ed-ctl-hover data-expanded:bg-ed-ctl-hover disabled:pointer-events-none disabled:opacity-50",
props.class,
)}
>
@@@ -27,7 -27,7 +27,7 @@@
<For each={props.swatches.slice(0, 4)}>
{(swatch) => (
<span
-- class="size-4 rounded-full border border-gray-1"
++ class="size-4 rounded-full border border-ed-card"
style={{
"background-color": swatch.color,
"box-shadow": `inset 0 0 0 1px ${getColorPreviewBorderColor(
@@@ -38,7 -38,7 +38,7 @@@
)}
</For>
</span>
-- <IconCapChevronDown class="size-4 shrink-0 text-gray-10" />
++ <IconCapChevronDown class="size-3.5 shrink-0 text-ed-text-3" />
</KDropdownMenu.Trigger>
<KDropdownMenu.Portal>
<PopperContent<typeof KDropdownMenu.Content>
@@@ -62,7 -62,7 +62,7 @@@
}}
/>
<span class="min-w-0 flex-1 truncate">{swatch.label}</span>
-- <span class="text-xs text-gray-10 tabular-nums">
++ <span class="text-[11px] text-ed-text-3 tabular-nums">
{swatch.color}
</span>
</DropdownItem>
diff --cc apps/desktop/src/routes/editor/CanvasElementsOverlay.tsx
index 7fa417c99,c33f04d9e..d14bab3fd
--- a/apps/desktop/src/routes/editor/CanvasElementsOverlay.tsx
+++ b/apps/desktop/src/routes/editor/CanvasElementsOverlay.tsx
@@@ -291,7 -253,7 +291,7 @@@ export function CanvasElementsOverlay(p
const select = (type: "display" | "camera") =>
batch(() => {
setEditorState("canvasSelection", { type });
-- setEditorState("timeline", "selection", null);
++ if (!selectedStyle()) setEditorState("timeline", "selection", null);
});
// Selecting a timeline segment drops the canvas selection (and vice versa
@@@ -667,14 -621,14 +667,17 @@@
});
return (
-- <div class="absolute inset-0 pointer-events-none">
++ <div class="absolute inset-0 isolate pointer-events-none">
<Show when={overlayVisible()}>
-- <Show when={selection()}>
++ <Show when={selection() || editorState.timeline.selection}>
<div
class="absolute inset-0 pointer-events-auto"
onMouseDown={(e) => {
if (e.button !== 0) return;
-- setEditorState("canvasSelection", null);
++ batch(() => {
++ setEditorState("canvasSelection", null);
++ setEditorState("timeline", "selection", null);
++ });
}}
/>
</Show>
diff --cc apps/desktop/src/routes/editor/CaptionsTab.tsx
index a1efaa89f,a1efaa89f..ea3d58c0e
--- a/apps/desktop/src/routes/editor/CaptionsTab.tsx
+++ b/apps/desktop/src/routes/editor/CaptionsTab.tsx
@@@ -58,17 -58,17 +58,23 @@@ import
TEXT_WEIGHT_OPTIONS,
} from "./text-style";
import {
++ EditorButton,
Field,
Input,
MenuItem,
MenuItemList,
PopperContent,
++ Section,
++ SectionLabel,
Slider,
Subfield,
topLeftAnimateClasses,
topSlideAnimateClasses,
} from "./ui";
++const selectTriggerClass =
++ "flex flex-row gap-1.5 items-center px-2 h-7 max-w-full rounded-[7px] text-[13px] transition-colors outline-hidden bg-ed-ctl text-ed-text-1 hover:bg-ed-ctl-hover focus-visible:ring-1 focus-visible:ring-ed-accent disabled:text-ed-text-3";
++
interface ModelOption {
name: string;
label: string;
@@@ -763,132 -763,132 +769,323 @@@ export function CaptionsTab(props:
);
return (
-- <Field name="Captions" icon={<IconCapMessageBubble />} badge="Beta">
-- <div class="flex flex-col gap-4">
-- <div class="space-y-6 transition-all duration-200">
-- <div class="space-y-4">
-- <Subfield name="Model" class="items-start">
-- <KSelect<string>
-- options={availableModelOptions().map((model) => model.name)}
-- value={selectedModel()}
-- onChange={(value: string | null) => {
-- if (value) setSelectedModel(value);
-- }}
-- itemComponent={(props) => {
-- const model = availableModelOptions().find(
-- (option) => option.name === props.item.rawValue,
-- );
++ <div class="flex flex-col gap-3.5">
++ <div class="flex flex-row gap-2 items-center min-h-[22px]">
++ <SectionLabel name="Captions" />
++ <span class="px-1.5 py-0.5 text-[10px] font-medium rounded-full bg-ed-ctl text-ed-text-2">
++ Beta
++ </span>
++ </div>
-- return (
-- <MenuItem<typeof KSelect.Item>
-- as={KSelect.Item}
-- item={props.item}
-- >
-- <div class="flex w-full items-center gap-3">
-- <div class="min-w-0 flex-1">
-- <div class="flex items-center gap-1.5 text-gray-12">
-- <KSelect.ItemLabel class="truncate font-medium">
-- {model?.label ?? props.item.rawValue}
-- </KSelect.ItemLabel>
-- <Show when={model}>
-- <Tooltip openDelay={0} content={model?.modelName}>
-- <button
-- type="button"
-- class="flex shrink-0 text-gray-9 transition-colors hover:text-gray-12"
-- onPointerDown={(event) =>
-- event.stopPropagation()
-- }
-- onClick={(event) => event.stopPropagation()}
-- >
-- <IconLucideInfo class="size-3.5" />
-- </button>
-- </Tooltip>
-- </Show>
-- </div>
-- <Show when={model}>
-- <div class="truncate text-xs text-gray-11">
-- {model?.description}
-- </div>
-- </Show>
-- </div>
++ <div class="flex flex-col gap-2">
++ <Field name="Model">
++ <KSelect<string>
++ options={availableModelOptions().map((model) => model.name)}
++ value={selectedModel()}
++ onChange={(value: string | null) => {
++ if (value) setSelectedModel(value);
++ }}
++ itemComponent={(props) => {
++ const model = availableModelOptions().find(
++ (option) => option.name === props.item.rawValue,
++ );
++
++ return (
++ <MenuItem<typeof KSelect.Item>
++ as={KSelect.Item}
++ item={props.item}
++ >
++ <div class="flex gap-3 items-center w-full">
++ <div class="flex-1 min-w-0">
++ <div class="flex gap-1.5 items-center text-ed-text-1">
++ <KSelect.ItemLabel class="font-medium truncate">
++ {model?.label ?? props.item.rawValue}
++ </KSelect.ItemLabel>
<Show when={model}>
-- <span class="shrink-0 text-[10px] text-gray-10">
-- {model?.size}
-- </span>
++ <Tooltip openDelay={0} content={model?.modelName}>
++ <button
++ type="button"
++ class="flex shrink-0 transition-colors text-ed-text-3 hover:text-ed-text-1"
++ onPointerDown={(event) => event.stopPropagation()}
++ onClick={(event) => event.stopPropagation()}
++ >
++ <IconLucideInfo class="size-3.5" />
++ </button>
++ </Tooltip>
</Show>
</div>
-- </MenuItem>
-- );
-- }}
-- >
-- <KSelect.Trigger class="flex min-w-0 flex-row items-center gap-2 rounded-lg border border-gray-3 bg-gray-2 px-3 py-2 text-sm text-gray-12 transition-colors hover:border-gray-4 hover:bg-gray-3 focus:border-blue-9 focus:ring-1 focus:ring-blue-9">
-- <div class="min-w-0 flex-1 text-left">
-- <div class="flex items-center gap-1.5">
-- <span class="truncate font-medium">
-- {selectedModelOption()?.label || "Select a model"}
-- </span>
-- <Show when={selectedModelOption()}>
-- <Tooltip
-- openDelay={0}
-- content={selectedModelOption()?.modelName}
-- >
-- <button
-- type="button"
-- class="flex shrink-0 text-gray-9 transition-colors hover:text-gray-12"
-- onPointerDown={(event) => event.stopPropagation()}
-- onClick={(event) => event.stopPropagation()}
-- >
-- <IconLucideInfo class="size-3.5" />
-- </button>
-- </Tooltip>
++ <Show when={model}>
++ <div class="text-[11px] truncate text-ed-text-2">
++ {model?.description}
++ </div>
</Show>
</div>
-- <Show when={selectedModelOption()}>
-- <div class="truncate text-xs text-gray-11">
-- {selectedModelOption()?.description}
-- </div>
++ <Show when={model}>
++ <span class="shrink-0 text-[10px] text-ed-text-3">
++ {model?.size}
++ </span>
</Show>
</div>
++ </MenuItem>
++ );
++ }}
++ >
++ <KSelect.Trigger class="flex flex-row gap-2 items-center px-2.5 py-1.5 w-full min-w-0 rounded-lg transition-colors outline-hidden bg-ed-ctl text-ed-text-1 hover:bg-ed-ctl-hover focus-visible:ring-1 focus-visible:ring-ed-accent">
++ <div class="flex-1 min-w-0 text-left">
++ <div class="flex gap-1.5 items-center">
++ <span class="text-[13px] font-medium truncate">
++ {selectedModelOption()?.label || "Select a model"}
++ </span>
<Show when={selectedModelOption()}>
-- <span class="shrink-0 text-[10px] text-gray-10">
-- {selectedModelOption()?.size}
-- </span>
++ <Tooltip
++ openDelay={0}
++ content={selectedModelOption()?.modelName}
++ >
++ <button
++ type="button"
++ class="flex shrink-0 transition-colors text-ed-text-3 hover:text-ed-text-1"
++ onPointerDown={(event) => event.stopPropagation()}
++ onClick={(event) => event.stopPropagation()}
++ >
++ <IconLucideInfo class="size-3.5" />
++ </button>
++ </Tooltip>
</Show>
-- <KSelect.Icon>
-- <IconCapChevronDown class="size-4 shrink-0 transform transition-transform data-expanded:rotate-180" />
-- </KSelect.Icon>
-- </KSelect.Trigger>
-- <KSelect.Portal>
-- <PopperContent<typeof KSelect.Content>
-- as={KSelect.Content}
-- class={topLeftAnimateClasses}
++ </div>
++ <Show when={selectedModelOption()}>
++ <div class="text-[11px] truncate text-ed-text-2">
++ {selectedModelOption()?.description}
++ </div>
++ </Show>
++ </div>
++ <Show when={selectedModelOption()}>
++ <span class="shrink-0 text-[10px] text-ed-text-3">
++ {selectedModelOption()?.size}
++ </span>
++ </Show>
++ <KSelect.Icon>
++ <IconCapChevronDown class="shrink-0 size-3.5 transition-transform transform text-ed-text-3 data-expanded:rotate-180" />
++ </KSelect.Icon>
++ </KSelect.Trigger>
++ <KSelect.Portal>
++ <PopperContent<typeof KSelect.Content>
++ as={KSelect.Content}
++ class={topLeftAnimateClasses}
++ >
++ <MenuItemList<typeof KSelect.Listbox> as={KSelect.Listbox} />
++ </PopperContent>
++ </KSelect.Portal>
++ </KSelect>
++ </Field>
++
++ <Show when={!supportsParakeetTranscription()}>
++ <p class="text-[11px] leading-relaxed text-ed-text-3">
++ Parakeet caption models are unavailable on Intel Macs. Whisper
++ models remain available.
++ </p>
++ </Show>
++
++ <p class="text-[11px] leading-relaxed text-ed-text-3">
++ One time download to your system. All captions are stored locally.
++ </p>
++
++ <Field name="Language" inline>
++ <KSelect<string>
++ options={LANGUAGE_OPTIONS.map((l) => l.code)}
++ value={selectedLanguage()}
++ onChange={(value: string | null) => {
++ if (value) setSelectedLanguage(value);
++ }}
++ itemComponent={(props) => (
++ <MenuItem<typeof KSelect.Item>
++ as={KSelect.Item}
++ item={props.item}
++ >
++ <KSelect.ItemLabel class="flex-1">
++ {
++ LANGUAGE_OPTIONS.find((l) => l.code === props.item.rawValue)
++ ?.label
++ }
++ </KSelect.ItemLabel>
++ </MenuItem>
++ )}
++ >
++ <KSelect.Trigger class={selectTriggerClass}>
++ <KSelect.Value<string> class="truncate">
++ {(state) => {
++ const language = LANGUAGE_OPTIONS.find(
++ (l) => l.code === state.selectedOption(),
++ );
++ return <span>{language?.label || "Select a language"}</span>;
++ }}
++ </KSelect.Value>
++ <KSelect.Icon>
++ <IconCapChevronDown class="shrink-0 size-3.5 transition-transform transform text-ed-text-3 data-expanded:rotate-180" />
++ </KSelect.Icon>
++ </KSelect.Trigger>
++ <KSelect.Portal>
++ <PopperContent<typeof KSelect.Content>
++ as={KSelect.Content}
++ class={topLeftAnimateClasses}
++ >
++ <MenuItemList<typeof KSelect.Listbox>
++ class="overflow-y-auto max-h-48"
++ as={KSelect.Listbox}
++ />
++ </PopperContent>
++ </KSelect.Portal>
++ </KSelect>
++ </Field>
++
++ <Show
++ when={downloadedModels().includes(selectedModel())}
++ fallback={
++ <div class="flex flex-col gap-2">
++ <Button
++ class="flex gap-2 justify-center items-center w-full"
++ onClick={downloadModel}
++ disabled={isDownloading()}
++ >
++ <Show
++ when={isDownloading()}
++ fallback={
++ <>
++ <IconLucideDownload class="size-4" />
++ Download{" "}
++ {
++ availableModelOptions().find(
++ (m) => m.name === selectedModel(),
++ )?.label
++ }{" "}
++ Model
++ </>
++ }
++ >
++ {`Downloading ${
++ downloadingModelOption()?.label ?? "model"
++ }... ${downloadPercent()}%`}
++ </Show>
++ </Button>
++ <Show when={isDownloading()}>
++ <div class="flex flex-col gap-1.5">
++ <div
++ class="overflow-hidden w-full h-1.5 rounded-full bg-ed-ctl"
++ role="progressbar"
++ aria-valuemin="0"
++ aria-valuemax="100"
++ aria-valuenow={downloadPercent()}
>
-- <MenuItemList<typeof KSelect.Listbox>
-- as={KSelect.Listbox}
++ <div
++ class="h-1.5 rounded-full transition-all duration-300 bg-ed-accent"
++ style={{
++ width: `${clampDownloadProgress(downloadProgress())}%`,
++ }}
/>
-- </PopperContent>
-- </KSelect.Portal>
-- </KSelect>
-- </Subfield>
++ </div>
++ <p class="text-[11px] leading-relaxed text-ed-text-3">
++ {downloadMessage() ||
++ "Keep Cap open while the model downloads. Editor reloads will reconnect automatically."}
++ </p>
++ </div>
++ </Show>
++ </div>
++ }
++ >
++ <div class="flex flex-col gap-2">
++ <Show when={hasAudio()}>
++ <Button
++ onClick={generateCaptions}
++ disabled={isGenerating() || deletingModel() !== null}
++ class="w-full"
++ >
++ {isGenerating()
++ ? "Generating..."
++ : hasCaptions()
++ ? "Regenerate Captions"
++ : "Generate Captions"}
++ </Button>
++ </Show>
++ <div class="flex gap-2 justify-between items-center text-[11px] text-ed-text-3">
++ <span class="flex gap-1.5 items-center min-w-0">
++ <IconCapCircleCheck class="shrink-0 size-3.5 text-ed-text-3" />
++ <span class="truncate">
++ {selectedModelOption()?.label ?? "Caption"} model downloaded
++ </span>
++ </span>
++ <EditorButton
++ size="sm"
++ leftIcon={<IconLucideTrash2 />}
++ onClick={deleteModel}
++ disabled={
++ isGenerating() ||
++ isDownloading() ||
++ deletingModel() === selectedModel()
++ }
++ >
++ {deletingModel() === selectedModel() ? "Deleting..." : "Delete"}
++ </EditorButton>
++ </div>
++ </div>
++ </Show>
++ </div>
++
++ <div class="w-full border-t border-ed-line" />
-- <Show when={!supportsParakeetTranscription()}>
-- <p class="text-xs text-gray-10">
-- Parakeet caption models are unavailable on Intel Macs. Whisper
-- models remain available.
-- </p>
++ <div
++ class={cx(
++ "flex flex-col gap-3.5",
++ !hasCaptions() && "opacity-50 pointer-events-none",
++ )}
++ >
++ <Section name="Style">
++ <div class="grid grid-cols-2 gap-2">
++ <For each={CAPTION_STYLE_PRESETS}>
++ {(preset) => (
++ <button
++ type="button"
++ title={preset.description}
++ onClick={() => applyCaptionPreset(preset)}
++ disabled={!hasCaptions()}
++ class={cx(
++ "flex flex-col gap-1.5 p-1.5 text-left rounded-lg transition-shadow",
++ selectedPresetId() === preset.id
++ ? "ring-2 ring-ed-accent ring-offset-2 ring-offset-ed-card"
++ : "ring-1 ring-ed-line hover:ring-ed-line-strong",
++ )}
++ >
++ <CaptionPresetPreview preset={preset} />
++ <span class="px-0.5 text-[11px] font-medium text-ed-text-1">
++ {preset.label}
++ </span>
++ </button>
++ )}
++ </For>
++ <Show when={selectedPresetId() === "custom"}>
++ <div class="flex flex-col gap-1.5 p-1.5 text-left rounded-lg ring-2 ring-ed-accent ring-offset-2 ring-offset-ed-card">
++ <div class="flex justify-center items-center h-12 text-[11px] rounded-md bg-ed-card-2 text-ed-text-3">
++ Custom
++ </div>
++ <span class="px-0.5 text-[11px] font-medium text-ed-text-1">
++ Custom
++ </span>
++ </div>
</Show>
++ </div>
++ </Section>
-- <p class="text-xs leading-relaxed text-gray-10">
-- One time download to your system. All captions are stored locally.
-- </p>
++ <div class="w-full border-t border-ed-line" />
-- <Subfield name="Language">
++ <Section name="Font settings">
++ <div class="flex flex-col gap-2">
++ <Field name="Font Family" inline>
<KSelect<string>
-- options={LANGUAGE_OPTIONS.map((l) => l.code)}
-- value={selectedLanguage()}
-- onChange={(value: string | null) => {
-- if (value) setSelectedLanguage(value);
++ options={FONT_OPTIONS.map((f) => f.value)}
++ value={getSetting("font")}
++ onChange={(value) => {
++ if (value === null) return;
++ updateCaptionSetting("font", value);
}}
++ disabled={!hasCaptions()}
itemComponent={(props) => (
<MenuItem<typeof KSelect.Item>
as={KSelect.Item}
@@@ -896,27 -896,27 +1093,24 @@@
>
<KSelect.ItemLabel class="flex-1">
{
-- LANGUAGE_OPTIONS.find(
-- (l) => l.code === props.item.rawValue,
++ FONT_OPTIONS.find(
++ (f) => f.value === props.item.rawValue,
)?.label
}
</KSelect.ItemLabel>
</MenuItem>
)}
>
-- <KSelect.Trigger class="flex flex-row items-center h-9 px-3 gap-2 border rounded-lg border-gray-3 bg-gray-2 w-full text-gray-12 text-sm hover:border-gray-4 hover:bg-gray-3 focus:border-blue-9 focus:ring-1 focus:ring-blue-9 transition-colors">
-- <KSelect.Value<string> class="flex-1 text-left truncate">
-- {(state) => {
-- const language = LANGUAGE_OPTIONS.find(
-- (l) => l.code === state.selectedOption(),
-- );
-- return (
-- <span>{language?.label || "Select a language"}</span>
-- );
-- }}
++ <KSelect.Trigger class={selectTriggerClass}>
++ <KSelect.Value<string> class="truncate">
++ {(state) =>
++ FONT_OPTIONS.find(
++ (f) => f.value === state.selectedOption(),
++ )?.label
++ }
</KSelect.Value>
<KSelect.Icon>
-- <IconCapChevronDown class="size-4 shrink-0 transform transition-transform data-expanded:rotate-180" />
++ <IconCapChevronDown class="shrink-0 size-3.5 text-ed-text-3" />
</KSelect.Icon>
</KSelect.Trigger>
<KSelect.Portal>
@@@ -925,387 -925,387 +1119,292 @@@
class={topLeftAnimateClasses}
>
<MenuItemList<typeof KSelect.Listbox>
-- class="max-h-48 overflow-y-auto"
++ class="overflow-y-auto max-h-48"
as={KSelect.Listbox}
/>
</PopperContent>
</KSelect.Portal>
</KSelect>
-- </Subfield>
--
-- <div class="pt-2">
-- <Show
-- when={downloadedModels().includes(selectedModel())}
-- fallback={
-- <div class="space-y-2">
-- <Button
-- class="w-full flex items-center justify-center gap-2"
-- onClick={downloadModel}
-- disabled={isDownloading()}
-- >
-- <Show
-- when={isDownloading()}
-- fallback={
-- <>
-- <IconLucideDownload class="size-4" />
-- Download{" "}
-- {
-- availableModelOptions().find(
-- (m) => m.name === selectedModel(),
-- )?.label
-- }{" "}
-- Model
-- </>
-- }
-- >
-- {`Downloading ${
-- downloadingModelOption()?.label ?? "model"
-- }... ${downloadPercent()}%`}
-- </Show>
-- </Button>
-- <Show when={isDownloading()}>
-- <div class="space-y-1.5">
-- <div
-- class="w-full bg-gray-3 rounded-full h-1.5 overflow-hidden"
-- role="progressbar"
-- aria-valuemin="0"
-- aria-valuemax="100"
-- aria-valuenow={downloadPercent()}
-- >
-- <div
-- class="bg-blue-9 h-1.5 rounded-full transition-all duration-300"
-- style={{
-- width: `${clampDownloadProgress(downloadProgress())}%`,
-- }}
-- />
-- </div>
-- <p class="text-xs leading-relaxed text-gray-10">
-- {downloadMessage() ||
-- "Keep Cap open while the model downloads. Editor reloads will reconnect automatically."}
-- </p>
-- </div>
-- </Show>
-- </div>
++ </Field>
++
++ <Field name="Size" inline>
++ <Slider
++ value={[getSetting("size")]}
++ onChange={(v) => updateCaptionSetting("size", v[0])}
++ minValue={12}
++ maxValue={100}
++ step={1}
++ disabled={!hasCaptions()}
++ />
++ </Field>
++
++ <Field name="Uppercase" inline>
++ <Toggle
++ checked={getSetting("uppercase")}
++ onChange={(checked) =>
++ updateCaptionSetting("uppercase", checked)
}
-- >
-- <div class="space-y-2">
-- <Show when={hasAudio()}>
-- <Button
-- onClick={generateCaptions}
-- disabled={isGenerating() || deletingModel() !== null}
-- class="w-full"
-- >
-- {isGenerating()
-- ? "Generating..."
-- : hasCaptions()
-- ? "Regenerate Captions"
-- : "Generate Captions"}
-- </Button>
-- </Show>
-- <div class="flex items-center justify-between gap-2 text-xs text-gray-10">
-- <span class="flex min-w-0 items-center gap-1.5">
-- <IconCapCircleCheck class="size-3.5 shrink-0 text-gray-9" />
-- <span class="truncate">
-- {selectedModelOption()?.label ?? "Caption"} model
-- downloaded
-- </span>
-- </span>
-- <Button
-- variant="gray"
-- size="sm"
-- class="shrink-0 gap-1.5 px-2"
-- onClick={deleteModel}
-- disabled={
-- isGenerating() ||
-- isDownloading() ||
-- deletingModel() === selectedModel()
-- }
-- >
-- <IconLucideTrash2 class="size-3.5" />
-- {deletingModel() === selectedModel()
-- ? "Deleting..."
-- : "Delete"}
-- </Button>
-- </div>
-- </div>
-- </Show>
-- </div>
-- </div>
++ disabled={!hasCaptions()}
++ />
++ </Field>
-- <div
-- class={cx(
-- "space-y-4",
-- !hasCaptions() && "opacity-50 pointer-events-none",
-- )}
-- >
-- <Field name="Style" icon={<IconCapMessageBubble />}>
-- <div class="grid grid-cols-2 gap-2">
-- <For each={CAPTION_STYLE_PRESETS}>
-- {(preset) => (
-- <button
-- type="button"
-- title={preset.description}
-- onClick={() => applyCaptionPreset(preset)}
-- disabled={!hasCaptions()}
-- class={cx(
-- "flex flex-col gap-1.5 rounded-lg border p-1.5 text-left transition-colors",
-- selectedPresetId() === preset.id
-- ? "border-blue-9 ring-1 ring-blue-9"
-- : "border-gray-3 hover:border-gray-5",
-- )}
-- >
-- <CaptionPresetPreview preset={preset} />
-- <span class="px-0.5 text-xs font-medium text-gray-12">
-- {preset.label}
-- </span>
-- </button>
-- )}
-- </For>
-- <Show when={selectedPresetId() === "custom"}>
-- <div class="flex flex-col gap-1.5 rounded-lg border border-blue-9 p-1.5 text-left ring-1 ring-blue-9">
-- <div class="flex h-12 items-center justify-center rounded-md bg-gray-2 text-xs text-gray-10">
-- Custom
-- </div>
-- <span class="px-0.5 text-xs font-medium text-gray-12">
-- Custom
-- </span>
-- </div>
-- </Show>
-- </div>
++ <Field name="Active Word Highlight" inline>
++ <Toggle
++ checked={getSetting("activeWordHighlight")}
++ onChange={(checked) =>
++ updateCaptionSetting("activeWordHighlight", checked)
++ }
++ disabled={!hasCaptions()}
++ />
</Field>
++ <p class="text-[11px] leading-relaxed text-ed-text-3">
++ This is the first version of captions in Cap. Active word
++ highlighting may be inaccurate in some situations. We're working
++ on a fix for this and it will be released in upcoming versions.
++ </p>
-- <Field name="Font Settings" icon={<IconCapMessageBubble />}>
-- <div class="space-y-3">
-- <div class="flex flex-col gap-2">
-- <span class="text-gray-11 text-sm">Font Family</span>
-- <KSelect<string>
-- options={FONT_OPTIONS.map((f) => f.value)}
-- value={getSetting("font")}
-- onChange={(value) => {
-- if (value === null) return;
-- updateCaptionSetting("font", value);
-- }}
-- disabled={!hasCaptions()}
-- itemComponent={(props) => (
-- <MenuItem<typeof KSelect.Item>
-- as={KSelect.Item}
-- item={props.item}
-- >
-- <KSelect.ItemLabel class="flex-1">
-- {
-- FONT_OPTIONS.find(
-- (f) => f.value === props.item.rawValue,
-- )?.label
-- }
-- </KSelect.ItemLabel>
-- </MenuItem>
-- )}
-- >
-- <KSelect.Trigger class="w-full flex items-center justify-between rounded-lg px-3 py-2 bg-gray-2 border border-gray-3 text-gray-12 hover:border-gray-4 hover:bg-gray-3 focus:border-blue-9 focus:ring-1 focus:ring-blue-9 transition-colors">
-- <KSelect.Value<string>>
-- {(state) =>
-- FONT_OPTIONS.find(
-- (f) => f.value === state.selectedOption(),
++ <Show when={getSetting("activeWordHighlight")}>
++ <Field name="Highlight Style" inline>
++ <KSelect<string>
++ options={CAPTION_HIGHLIGHT_STYLE_OPTIONS.map((o) => o.value)}
++ value={getSetting("highlightStyle")}
++ onChange={(value) => {
++ if (value === null) return;
++ updateCaptionSetting(
++ "highlightStyle",
++ value as CaptionHighlightStyle,
++ );
++ }}
++ disabled={!hasCaptions()}
++ itemComponent={(itemProps) => (
++ <MenuItem<typeof KSelect.Item>
++ as={KSelect.Item}
++ item={itemProps.item}
++ >
++ <KSelect.ItemLabel class="flex-1">
++ {
++ CAPTION_HIGHLIGHT_STYLE_OPTIONS.find(
++ (o) => o.value === itemProps.item.rawValue,
)?.label
}
-- </KSelect.Value>
-- <KSelect.Icon>
-- <IconCapChevronDown />
-- </KSelect.Icon>
-- </KSelect.Trigger>
-- <KSelect.Portal>
-- <PopperContent<typeof KSelect.Content>
-- as={KSelect.Content}
-- class={topLeftAnimateClasses}
-- >
-- <MenuItemList<typeof KSelect.Listbox>
-- class="max-h-48 overflow-y-auto"
-- as={KSelect.Listbox}
-- />
-- </PopperContent>
-- </KSelect.Portal>
-- </KSelect>
-- </div>
--
-- <div class="flex flex-col gap-2">
-- <span class="text-gray-11 text-sm">Size</span>
-- <Slider
-- value={[getSetting("size")]}
-- onChange={(v) => updateCaptionSetting("size", v[0])}
-- minValue={12}
-- maxValue={100}
-- step={1}
-- disabled={!hasCaptions()}
-- />
-- </div>
--
-- <div class="flex items-center justify-between">
-- <span class="text-gray-11 text-sm">Uppercase</span>
-- <Toggle
-- checked={getSetting("uppercase")}
-- onChange={(checked) =>
-- updateCaptionSetting("uppercase", checked)
-- }
-- disabled={!hasCaptions()}
-- />
-- </div>
--
-- <div class="flex flex-col gap-2">
-- <div class="flex items-center justify-between">
-- <span class="text-gray-11 text-sm">
-- Active Word Highlight
-- </span>
-- <Toggle
-- checked={getSetting("activeWordHighlight")}
-- onChange={(checked) =>
-- updateCaptionSetting("activeWordHighlight", checked)
++ </KSelect.ItemLabel>
++ </MenuItem>
++ )}
++ >
++ <KSelect.Trigger class={selectTriggerClass}>
++ <KSelect.Value<string> class="truncate">
++ {(state) =>
++ CAPTION_HIGHLIGHT_STYLE_OPTIONS.find(
++ (o) => o.value === state.selectedOption(),
++ )?.label
}
-- disabled={!hasCaptions()}
-- />
-- </div>
-- <p class="text-xs text-gray-10">
-- This is the first version of captions in Cap. Active word
-- highlighting may be inaccurate in some situations. We're
-- working on a fix for this and it will be released in
-- upcoming versions.
-- </p>
-- </div>
--
-- <Show when={getSetting("activeWordHighlight")}>
-- <div class="flex flex-col gap-2">
-- <span class="text-gray-11 text-sm">Highlight Style</span>
-- <KSelect<string>
-- options={CAPTION_HIGHLIGHT_STYLE_OPTIONS.map(
-- (o) => o.value,
-- )}
-- value={getSetting("highlightStyle")}
-- onChange={(value) => {
-- if (value === null) return;
-- updateCaptionSetting(
-- "highlightStyle",
-- value as CaptionHighlightStyle,
-- );
-- }}
-- disabled={!hasCaptions()}
-- itemComponent={(itemProps) => (
-- <MenuItem<typeof KSelect.Item>
-- as={KSelect.Item}
-- item={itemProps.item}
-- >
-- <KSelect.ItemLabel class="flex-1">
-- {
-- CAPTION_HIGHLIGHT_STYLE_OPTIONS.find(
-- (o) => o.value === itemProps.item.rawValue,
-- )?.label
-- }
-- </KSelect.ItemLabel>
-- </MenuItem>
-- )}
++ </KSelect.Value>
++ <KSelect.Icon>
++ <IconCapChevronDown class="shrink-0 size-3.5 text-ed-text-3" />
++ </KSelect.Icon>
++ </KSelect.Trigger>
++ <KSelect.Portal>
++ <PopperContent<typeof KSelect.Content>
++ as={KSelect.Content}
++ class={topLeftAnimateClasses}
>
-- <KSelect.Trigger class="w-full flex items-center justify-between rounded-lg px-3 py-2 bg-gray-2 border border-gray-3 text-gray-12 hover:border-gray-4 hover:bg-gray-3 focus:border-blue-9 focus:ring-1 focus:ring-blue-9 transition-colors">
-- <KSelect.Value<string>>
-- {(state) =>
-- CAPTION_HIGHLIGHT_STYLE_OPTIONS.find(
-- (o) => o.value === state.selectedOption(),
-- )?.label
-- }
-- </KSelect.Value>
-- <KSelect.Icon>
-- <IconCapChevronDown />
-- </KSelect.Icon>
-- </KSelect.Trigger>
-- <KSelect.Portal>
-- <PopperContent<typeof KSelect.Content>
-- as={KSelect.Content}
-- class={topLeftAnimateClasses}
-- >
-- <MenuItemList<typeof KSelect.Listbox>
-- as={KSelect.Listbox}
-- />
-- </PopperContent>
-- </KSelect.Portal>
-- </KSelect>
-- </div>
-- </Show>
++ <MenuItemList<typeof KSelect.Listbox>
++ as={KSelect.Listbox}
++ />
++ </PopperContent>
++ </KSelect.Portal>
++ </KSelect>
++ </Field>
++ </Show>
-- <div class="flex flex-col gap-2">
-- <span class="text-gray-11 text-sm">Text Color</span>
-- <HexColorInput
-- value={getSetting("color")}
-- brandColorSwatches={props.brandColorSwatches}
-- onChange={(value) => updateCaptionSetting("color", value)}
-- />
-- </div>
-- </div>
++ <Field name="Text Color">
++ <HexColorInput
++ value={getSetting("color")}
++ brandColorSwatches={props.brandColorSwatches}
++ onChange={(value) => updateCaptionSetting("color", value)}
++ />
++ </Field>
++ </div>
++ </Section>
++
++ <div class="w-full border-t border-ed-line" />
++
++ <Section name="Background settings">
++ <div class="flex flex-col gap-2">
++ <Field name="Background Color">
++ <HexColorInput
++ value={getSetting("backgroundColor")}
++ brandColorSwatches={props.brandColorSwatches}
++ onChange={(value) =>
++ updateCaptionSetting("backgroundColor", value)
++ }
++ />
</Field>
-- <Field name="Background Settings" icon={<IconCapMessageBubble />}>
-- <div class="space-y-3">
-- <div class="flex flex-col gap-2">
-- <span class="text-gray-11 text-sm">Background Color</span>
-- <HexColorInput
-- value={getSetting("backgroundColor")}
-- brandColorSwatches={props.brandColorSwatches}
-- onChange={(value) =>
-- updateCaptionSetting("backgroundColor", value)
++ <Field name="Background Opacity" inline>
++ <Slider
++ value={[getSetting("backgroundOpacity")]}
++ onChange={(v) =>
++ updateCaptionSetting("backgroundOpacity", v[0])
++ }
++ minValue={0}
++ maxValue={100}
++ step={1}
++ disabled={!hasCaptions()}
++ />
++ </Field>
++ </div>
++ </Section>
++
++ <div class="w-full border-t border-ed-line" />
++
++ <div class="flex flex-col gap-2">
++ <Field name="Position" inline>
++ <KSelect<string>
++ options={CAPTION_POSITION_OPTIONS.map((p) => p.value)}
++ value={getSetting("position")}
++ onChange={(value) => {
++ if (value === null) return;
++ updateCaptionPosition(value);
++ }}
++ disabled={!hasCaptions()}
++ itemComponent={(props) => (
++ <MenuItem<typeof KSelect.Item>
++ as={KSelect.Item}
++ item={props.item}
++ >
++ <KSelect.ItemLabel class="flex-1">
++ {
++ CAPTION_POSITION_OPTIONS.find(
++ (p) => p.value === props.item.rawValue,
++ )?.label
}
++ </KSelect.ItemLabel>
++ </MenuItem>
++ )}
++ >
++ <KSelect.Trigger class={selectTriggerClass}>
++ <KSelect.Value<string> class="truncate">
++ {(state) => (
++ <span>
++ {
++ CAPTION_POSITION_OPTIONS.find(
++ (p) => p.value === state.selectedOption(),
++ )?.label
++ }
++ </span>
++ )}
++ </KSelect.Value>
++ <KSelect.Icon>
++ <IconCapChevronDown class="shrink-0 size-3.5 text-ed-text-3" />
++ </KSelect.Icon>
++ </KSelect.Trigger>
++ <KSelect.Portal>
++ <PopperContent<typeof KSelect.Content>
++ as={KSelect.Content}
++ class={topLeftAnimateClasses}
++ >
++ <MenuItemList<typeof KSelect.Listbox> as={KSelect.Listbox} />
++ </PopperContent>
++ </KSelect.Portal>
++ </KSelect>
++ </Field>
++
++ <Field name="Font Weight" inline>
++ <KSelect
++ options={TEXT_WEIGHT_OPTIONS}
++ optionValue="value"
++ optionTextValue="label"
++ value={{
++ label: "Custom",
++ value: getSetting("fontWeight"),
++ }}
++ onChange={(value) => {
++ if (!value) return;
++ updateCaptionSetting("fontWeight", value.value);
++ }}
++ disabled={!hasCaptions()}
++ itemComponent={(selectItemProps) => (
++ <MenuItem<typeof KSelect.Item>
++ as={KSelect.Item}
++ item={selectItemProps.item}
++ >
++ <KSelect.ItemLabel class="flex-1">
++ {selectItemProps.item.rawValue.label}
++ </KSelect.ItemLabel>
++ <KSelect.ItemIndicator class="ml-auto text-ed-accent">
++ <IconCapCircleCheck />
++ </KSelect.ItemIndicator>
++ </MenuItem>
++ )}
++ >
++ <KSelect.Trigger class={selectTriggerClass}>
++ <KSelect.Value<{
++ label: string;
++ value: number;
++ }> class="truncate">
++ {(state) =>
++ state.selectedOption()?.label ??
++ getTextWeightLabel(getSetting("fontWeight"))
++ }
++ </KSelect.Value>
++ <KSelect.Icon>
++ <IconCapChevronDown class="shrink-0 size-3.5 transition-transform transform text-ed-text-3 data-expanded:rotate-180" />
++ </KSelect.Icon>
++ </KSelect.Trigger>
++ <KSelect.Portal>
++ <PopperContent<typeof KSelect.Content>
++ as={KSelect.Content}
++ class={cx(topSlideAnimateClasses, "z-50")}
++ >
++ <MenuItemList<typeof KSelect.Listbox>
++ class="overflow-y-auto max-h-40"
++ as={KSelect.Listbox}
/>
-- </div>
++ </PopperContent>
++ </KSelect.Portal>
++ </KSelect>
++ </Field>
++ </div>
-- <div class="flex flex-col gap-2">
-- <span class="text-gray-11 text-sm">Background Opacity</span>
-- <Slider
-- value={[getSetting("backgroundOpacity")]}
-- onChange={(v) =>
-- updateCaptionSetting("backgroundOpacity", v[0])
-- }
-- minValue={0}
-- maxValue={100}
-- step={1}
-- disabled={!hasCaptions()}
-- />
-- </div>
-- </div>
-- </Field>
++ <div class="w-full border-t border-ed-line" />
-- <Field name="Position" icon={<IconCapMessageBubble />}>
++ <Section name="Animation">
++ <div class="flex flex-col gap-2">
++ <Field name="Animation Style" inline>
<KSelect<string>
-- options={CAPTION_POSITION_OPTIONS.map((p) => p.value)}
-- value={getSetting("position")}
++ options={CAPTION_ANIMATION_OPTIONS.map((o) => o.value)}
++ value={getSetting("animation")}
onChange={(value) => {
if (value === null) return;
-- updateCaptionPosition(value);
++ updateCaptionSetting("animation", value as CaptionAnimation);
}}
disabled={!hasCaptions()}
-- itemComponent={(props) => (
++ itemComponent={(itemProps) => (
<MenuItem<typeof KSelect.Item>
as={KSelect.Item}
-- item={props.item}
++ item={itemProps.item}
>
<KSelect.ItemLabel class="flex-1">
{
-- CAPTION_POSITION_OPTIONS.find(
-- (p) => p.value === props.item.rawValue,
++ CAPTION_ANIMATION_OPTIONS.find(
++ (o) => o.value === itemProps.item.rawValue,
)?.label
}
</KSelect.ItemLabel>
</MenuItem>
)}
>
-- <KSelect.Trigger class="w-full flex items-center justify-between rounded-lg px-3 py-2 bg-gray-2 border border-gray-3 text-gray-12 hover:border-gray-4 hover:bg-gray-3 focus:border-blue-9 focus:ring-1 focus:ring-blue-9 transition-colors">
-- <KSelect.Value<string>>
-- {(state) => (
-- <span>
-- {
-- CAPTION_POSITION_OPTIONS.find(
-- (p) => p.value === state.selectedOption(),
-- )?.label
-- }
-- </span>
-- )}
++ <KSelect.Trigger class={selectTriggerClass}>
++ <KSelect.Value<string> class="truncate">
++ {(state) =>
++ CAPTION_ANIMATION_OPTIONS.find(
++ (o) => o.value === state.selectedOption(),
++ )?.label
++ }
</KSelect.Value>
<KSelect.Icon>
-- <IconCapChevronDown />
++ <IconCapChevronDown class="shrink-0 size-3.5 text-ed-text-3" />
</KSelect.Icon>
</KSelect.Trigger>
<KSelect.Portal>
@@@ -1321,243 -1321,243 +1420,126 @@@
</KSelect>
</Field>
-- <Field name="Animation" icon={<IconCapMessageBubble />}>
-- <div class="space-y-3">
-- <div class="flex flex-col gap-2">
-- <span class="text-gray-11 text-sm">Animation Style</span>
-- <KSelect<string>
-- options={CAPTION_ANIMATION_OPTIONS.map((o) => o.value)}
-- value={getSetting("animation")}
-- onChange={(value) => {
-- if (value === null) return;
-- updateCaptionSetting(
-- "animation",
-- value as CaptionAnimation,
-- );
-- }}
-- disabled={!hasCaptions()}
-- itemComponent={(itemProps) => (
-- <MenuItem<typeof KSelect.Item>
-- as={KSelect.Item}
-- item={itemProps.item}
-- >
-- <KSelect.ItemLabel class="flex-1">
-- {
-- CAPTION_ANIMATION_OPTIONS.find(
-- (o) => o.value === itemProps.item.rawValue,
-- )?.label
-- }
-- </KSelect.ItemLabel>
-- </MenuItem>
-- )}
-- >
-- <KSelect.Trigger class="w-full flex items-center justify-between rounded-lg px-3 py-2 bg-gray-2 border border-gray-3 text-gray-12 hover:border-gray-4 hover:bg-gray-3 focus:border-blue-9 focus:ring-1 focus:ring-blue-9 transition-colors">
-- <KSelect.Value<string>>
-- {(state) =>
-- CAPTION_ANIMATION_OPTIONS.find(
-- (o) => o.value === state.selectedOption(),
-- )?.label
-- }
-- </KSelect.Value>
-- <KSelect.Icon>
-- <IconCapChevronDown />
-- </KSelect.Icon>
-- </KSelect.Trigger>
-- <KSelect.Portal>
-- <PopperContent<typeof KSelect.Content>
-- as={KSelect.Content}
-- class={topLeftAnimateClasses}
-- >
-- <MenuItemList<typeof KSelect.Listbox>
-- as={KSelect.Listbox}
-- />
-- </PopperContent>
-- </KSelect.Portal>
-- </KSelect>
-- </div>
-- <div class="flex flex-col gap-2">
-- <span class="text-gray-11 text-sm">Highlight Color</span>
-- <HexColorInput
-- value={getSetting("highlightColor")}
-- brandColorSwatches={props.brandColorSwatches}
-- onChange={(value) =>
-- updateCaptionSetting("highlightColor", value)
++ <Field name="Highlight Color">
++ <HexColorInput
++ value={getSetting("highlightColor")}
++ brandColorSwatches={props.brandColorSwatches}
++ onChange={(value) =>
++ updateCaptionSetting("highlightColor", value)
++ }
++ />
++ </Field>
++
++ <Field
++ name="Fade Duration"
++ inline
++ value={`${(getSetting("fadeDuration") * 1000).toFixed(0)}ms`}
++ >
++ <Slider
++ value={[getSetting("fadeDuration") * 100]}
++ onChange={(v) =>
++ updateCaptionSetting("fadeDuration", v[0] / 100)
++ }
++ minValue={0}
++ maxValue={50}
++ step={1}
++ disabled={!hasCaptions()}
++ />
++ </Field>
++ </div>
++ </Section>
++
++ <div class="w-full border-t border-ed-line" />
++
++ <Section name="Export options">
++ <Field name="Export with Subtitles" inline>
++ <Toggle
++ checked={getSetting("exportWithSubtitles")}
++ onChange={(checked) =>
++ updateCaptionSetting("exportWithSubtitles", checked)
++ }
++ disabled={!hasCaptions()}
++ />
++ </Field>
++ </Section>
++ </div>
++
++ <Show
++ when={
++ editorState.timeline.selection?.type === "caption" &&
++ editorState.timeline.selection.indices.length === 1
++ }
++ >
++ <div class="w-full border-t border-ed-line" />
++ <Section name="Selected caption override">
++ <Show when={selectedCaptionSegment()}>
++ {(seg) => (
++ <div class="flex flex-col gap-1">
++ <Subfield name="Start Time">
++ <Input
++ type="number"
++ value={seg().start.toFixed(2)}
++ step="0.1"
++ min={0}
++ onChange={(e) =>
++ updateSelectedCaption((segment) => {
++ segment.start = Number.parseFloat(e.target.value);
++ })
}
/>
-- </div>
-- <div class="flex flex-col gap-2">
-- <span class="text-gray-11 text-sm">Fade Duration</span>
++ </Subfield>
++ <Subfield name="End Time">
++ <Input
++ type="number"
++ value={seg().end.toFixed(2)}
++ step="0.1"
++ min={seg().start}
++ onChange={(e) =>
++ updateSelectedCaption((segment) => {
++ segment.end = Number.parseFloat(e.target.value);
++ })
++ }
++ />
++ </Subfield>
++ <Subfield name="Caption Text">
++ <Input
++ type="text"
++ value={seg().text}
++ onChange={(e) =>
++ updateSelectedCaption((segment) => {
++ segment.text = e.target.value;
++ segment.words = syncCaptionWordsWithText(
++ e.target.value,
++ segment.words,
++ segment.start,
++ segment.end,
++ );
++ })
++ }
++ />
++ </Subfield>
++ <Subfield name="Fade Duration Override">
<Slider
-- value={[getSetting("fadeDuration") * 100]}
++ class="flex-1"
++ value={[
++ (seg().fadeDurationOverride ??
++ getSetting("fadeDuration")) * 100,
++ ]}
onChange={(v) =>
-- updateCaptionSetting("fadeDuration", v[0] / 100)
++ updateSelectedCaption((segment) => {
++ segment.fadeDurationOverride = v[0] / 100;
++ })
}
minValue={0}
maxValue={50}
step={1}
-- disabled={!hasCaptions()}
/>
-- <span class="text-xs text-gray-11 text-right">
-- {(getSetting("fadeDuration") * 1000).toFixed(0)}ms
-- </span>
-- </div>
++ </Subfield>
</div>
-- </Field>
--
-- <Field name="Font Weight" icon={<IconCapMessageBubble />}>
-- <KSelect
-- options={TEXT_WEIGHT_OPTIONS}
-- optionValue="value"
-- optionTextValue="label"
-- value={{
-- label: "Custom",
-- value: getSetting("fontWeight"),
-- }}
-- onChange={(value) => {
-- if (!value) return;
-- updateCaptionSetting("fontWeight", value.value);
-- }}
-- disabled={!hasCaptions()}
-- itemComponent={(selectItemProps) => (
-- <MenuItem<typeof KSelect.Item>
-- as={KSelect.Item}
-- item={selectItemProps.item}
-- >
-- <KSelect.ItemLabel class="flex-1">
-- {selectItemProps.item.rawValue.label}
-- </KSelect.ItemLabel>
-- <KSelect.ItemIndicator class="ml-auto text-blue-9">
-- <IconCapCircleCheck />
-- </KSelect.ItemIndicator>
-- </MenuItem>
-- )}
-- >
-- <KSelect.Trigger class="flex w-full items-center justify-between rounded-md border border-gray-3 bg-gray-2 px-3 py-2 text-sm text-gray-12 transition-colors hover:border-gray-4 hover:bg-gray-3 focus:border-blue-9 focus:outline-hidden focus:ring-1 focus:ring-blue-9">
-- <KSelect.Value<{
-- label: string;
-- value: number;
-- }> class="truncate">
-- {(state) =>
-- state.selectedOption()?.label ??
-- getTextWeightLabel(getSetting("fontWeight"))
-- }
-- </KSelect.Value>
-- <KSelect.Icon>
-- <IconCapChevronDown class="size-4 shrink-0 transform transition-transform data-expanded:rotate-180 text-(--gray-500)" />
-- </KSelect.Icon>
-- </KSelect.Trigger>
-- <KSelect.Portal>
-- <PopperContent<typeof KSelect.Content>
-- as={KSelect.Content}
-- class={cx(topSlideAnimateClasses, "z-50")}
-- >
-- <MenuItemList<typeof KSelect.Listbox>
-- class="overflow-y-auto max-h-40"
-- as={KSelect.Listbox}
-- />
-- </PopperContent>
-- </KSelect.Portal>
-- </KSelect>
-- </Field>
--
-- <Field name="Export Options" icon={<IconCapMessageBubble />}>
-- <Subfield name="Export with Subtitles">
-- <Toggle
-- checked={getSetting("exportWithSubtitles")}
-- onChange={(checked) =>
-- updateCaptionSetting("exportWithSubtitles", checked)
-- }
-- disabled={!hasCaptions()}
-- />
-- </Subfield>
-- </Field>
-- </div>
--
-- <Show
-- when={
-- editorState.timeline.selection?.type === "caption" &&
-- editorState.timeline.selection.indices.length === 1
-- }
-- >
-- {(() => {
-- return (
-- <Field
-- name="Selected Caption Override"
-- icon={<IconCapMessageBubble />}
-- >
-- <Show when={selectedCaptionSegment()}>
-- {(seg) => (
-- <div class="space-y-3">
-- <Subfield name="Start Time">
-- <Input
-- type="number"
-- value={seg().start.toFixed(2)}
-- step="0.1"
-- min={0}
-- onChange={(e) =>
-- updateSelectedCaption((segment) => {
-- segment.start = Number.parseFloat(
-- e.target.value,
-- );
-- })
-- }
-- />
-- </Subfield>
-- <Subfield name="End Time">
-- <Input
-- type="number"
-- value={seg().end.toFixed(2)}
-- step="0.1"
-- min={seg().start}
-- onChange={(e) =>
-- updateSelectedCaption((segment) => {
-- segment.end = Number.parseFloat(e.target.value);
-- })
-- }
-- />
-- </Subfield>
-- <Subfield name="Caption Text">
-- <Input
-- type="text"
-- value={seg().text}
-- onChange={(e) =>
-- updateSelectedCaption((segment) => {
-- segment.text = e.target.value;
-- segment.words = syncCaptionWordsWithText(
-- e.target.value,
-- segment.words,
-- segment.start,
-- segment.end,
-- );
-- })
-- }
-- />
-- </Subfield>
-- <Subfield name="Fade Duration Override">
-- <Slider
-- value={[
-- (seg().fadeDurationOverride ??
-- getSetting("fadeDuration")) * 100,
-- ]}
-- onChange={(v) =>
-- updateSelectedCaption((segment) => {
-- segment.fadeDurationOverride = v[0] / 100;
-- })
-- }
-- minValue={0}
-- maxValue={50}
-- step={1}
-- />
-- </Subfield>
-- </div>
-- )}
-- </Show>
-- </Field>
-- );
-- })()}
++ )}
</Show>
-- </div>
-- </div>
-- </Field>
++ </Section>
++ </Show>
++ </div>
);
}
diff --cc apps/desktop/src/routes/editor/ClipsSidebar.tsx
index c8e91cbd1,e64bdc55a..549f926e5
--- a/apps/desktop/src/routes/editor/ClipsSidebar.tsx
+++ b/apps/desktop/src/routes/editor/ClipsSidebar.tsx
@@@ -59,8 -59,15 +59,11 @@@ import
rippleTimelineTrack,
transitionsAfterClipMove,
} from "./clip-transitions";
-import {
- type EditorTimelineSegment,
- serializeProjectConfiguration,
- useEditorContext,
-} from "./context";
+import { type EditorTimelineSegment, useEditorContext } from "./context";
import { getExistingRecordingPickerOptions } from "./existing-recording-picker";
+ import { rippleKeyboardTrack } from "./keyboard-timing";
+ import { scaleKeyframeTimes } from "./three-d";
+ import { effectiveToOutput, holdWindows } from "./timeline-holds";
import { Input } from "./ui";
const findCamera = (cameras: CameraInfo[], id?: DeviceOrModelID | null) => {
@@@ -666,9 -674,11 +671,13 @@@ function ClipsSidebarInner(props: { ope
timeline.transitions = timeline.transitions.filter(
(candidate) => candidate.segmentIndex !== transition.segmentIndex,
);
+ const camera3dSegments = timeline.camera3dSegments ?? [];
+ const previousCamera3dDurations = camera3dSegments.map(
+ (segment) => segment.end - segment.start,
+ );
for (const track of [
+ timeline.styleSegments,
+ timeline.imageSegments,
timeline.zoomSegments,
timeline.sceneSegments ?? [],
timeline.maskSegments,
@@@ -790,16 -813,16 +812,16 @@@
return (
<div
class={cx(
-- "flex flex-col flex-1 min-h-0 rounded-xl border bg-gray-1 dark:bg-gray-2 border-gray-3 overflow-hidden",
++ "flex overflow-hidden flex-col flex-1 min-h-0 rounded-xl bg-ed-card shadow-ed-card",
props.class,
)}
>
<button
type="button"
onClick={backToEditor}
-- class="flex flex-none gap-2 items-center px-4 w-full h-16 text-sm font-medium border-b transition-colors text-gray-12 border-gray-3 hover:bg-gray-3"
++ class="flex flex-none gap-2 items-center px-4 w-full h-[46px] text-[13px] font-medium border-b transition-colors text-ed-text-1 border-ed-line hover:bg-ed-ctl"
>
-- <IconCapMoveLeft class="size-4 text-gray-11" />
++ <IconCapMoveLeft class="size-4 text-ed-text-2" />
Back to editor
</button>
diff --cc apps/desktop/src/routes/editor/ColorCorrectionSection.tsx
index f80918bdd,f80918bdd..f01f53e79
--- a/apps/desktop/src/routes/editor/ColorCorrectionSection.tsx
+++ b/apps/desktop/src/routes/editor/ColorCorrectionSection.tsx
@@@ -3,9 -3,9 +3,6 @@@ import { cx } from "cva"
import { createSignal, For, Show } from "solid-js";
import { produce } from "solid-js/store";
import { Toggle } from "~/components/Toggle";
--import IconLucideGrip from "~icons/lucide/grip";
--import IconLucideMousePointer2 from "~icons/lucide/mouse-pointer-2";
--import IconLucideSlidersHorizontal from "~icons/lucide/sliders-horizontal";
import {
COLOR_CORRECTION_PRESETS,
COLOR_PRESET_CUSTOM,
@@@ -16,7 -16,7 +13,7 @@@
type ColorPresetDefinition,
} from "./colorCorrection";
import { useEditorContext } from "./context";
--import { Field, Slider } from "./ui";
++import { Field, Section, Slider } from "./ui";
const ADJUST_SLIDERS: {
key: keyof ColorCorrectionValues;
@@@ -123,10 -123,10 +120,7 @@@ export function ColorCorrectionSection(
return (
<>
-- <Field
-- name="Color Correction"
-- icon={<IconLucideSlidersHorizontal class="size-4" />}
-- >
++ <Section name="Color correction">
<div class="grid grid-cols-3 gap-2">
<For each={COLOR_CORRECTION_PRESETS}>
{(preset) => (
@@@ -135,22 -135,22 +129,22 @@@
title={preset.description}
onClick={() => applyPreset(preset)}
class={cx(
-- "flex flex-col gap-1.5 rounded-lg border p-1.5 text-left transition-colors",
++ "flex flex-col gap-1.5 rounded-lg p-1.5 text-left transition-shadow duration-150",
grade().preset === preset.id
-- ? "border-blue-9 ring-1 ring-blue-9"
-- : "border-gray-3 hover:border-gray-5",
++ ? "ring-2 ring-ed-accent ring-offset-2 ring-offset-ed-card"
++ : "ring-1 ring-ed-line hover:ring-ed-line-strong",
)}
>
<ColorPresetPreview preset={preset} />
-- <span class="px-0.5 text-xs font-medium text-gray-12">
++ <span class="px-0.5 text-[11px] text-ed-text-2">
{preset.label}
</span>
</button>
)}
</For>
</div>
-- </Field>
-- <Field name="Grain" icon={<IconLucideGrip class="size-4" />}>
++ </Section>
++ <Field inline name="Grain" value={`${(grade().grain * 100).toFixed(1)}%`}>
<Slider
value={[grade().grain * 100]}
onChange={(v) => setValue("grain", v[0] / 100, true)}
@@@ -161,30 -161,30 +155,30 @@@
/>
</Field>
<Show when={props.target === "screen"}>
-- <Field
-- name="Apply to cursor"
-- icon={<IconLucideMousePointer2 class="size-4" />}
-- value={
-- <Toggle
-- checked={project.colorCorrection.gradeCursor}
-- onChange={(gradeCursor) =>
-- setProject("colorCorrection", "gradeCursor", gradeCursor)
-- }
-- />
-- }
-- />
++ <Field inline name="Apply to cursor">
++ <Toggle
++ checked={project.colorCorrection.gradeCursor}
++ onChange={(gradeCursor) =>
++ setProject("colorCorrection", "gradeCursor", gradeCursor)
++ }
++ />
++ </Field>
</Show>
<div class="w-full">
<KCollapsible open={adjustOpen()} onOpenChange={handleAdjustToggle}>
-- <KCollapsible.Trigger class="flex gap-1 items-center w-full text-sm font-medium text-left group text-gray-12 hover:text-gray-10 transition duration-200 outline-hidden">
++ <KCollapsible.Trigger class="flex gap-1 items-center w-full text-[12px] font-medium text-left group text-ed-text-2 hover:text-ed-text-1 transition-colors duration-200 outline-hidden">
Fine-tune colors
-- <IconCapChevronDown class="transition-transform duration-200 size-5 group-data-expanded:rotate-180" />
++ <IconCapChevronDown class="transition-transform duration-200 size-3.5 text-ed-text-3 group-data-expanded:rotate-180" />
</KCollapsible.Trigger>
<KCollapsible.Content class="overflow-hidden opacity-0 transition-opacity animate-collapsible-up data-expanded:animate-collapsible-down data-expanded:opacity-100">
-- <div class="mt-4 space-y-6 font-medium">
++ <div class="flex flex-col mt-2">
<For each={ADJUST_SLIDERS}>
{(slider) => (
-- <Field name={slider.label}>
++ <Field
++ inline
++ name={slider.label}
++ value={`${Math.round(grade()[slider.key] * 100).toFixed(1)}%`}
++ >
<Slider
value={[Math.round(grade()[slider.key] * 100)]}
onChange={(v) =>
diff --cc apps/desktop/src/routes/editor/ConfigSidebar.tsx
index 19fdf51d9,a58f3f13d..0411325bf
--- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx
+++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
@@@ -33,7 -33,7 +33,6 @@@ import
createSignal,
For,
Index,
-- type JSX,
lazy,
on,
onCleanup,
@@@ -46,10 -46,10 +45,6 @@@
import { createStore, produce } from "solid-js/store";
import { Dynamic } from "solid-js/web";
import toast from "solid-toast";
--import colorBg from "~/assets/illustrations/color.webp";
--import gradientBg from "~/assets/illustrations/gradient.webp";
--import imageBg from "~/assets/illustrations/image.webp";
--import transparentBg from "~/assets/illustrations/transparent.webp";
import { Toggle } from "~/components/Toggle";
import { animatedGradientsStore, generalSettingsStore } from "~/store";
import { listSystemFonts } from "~/utils/fonts";
@@@ -90,23 -90,23 +85,11 @@@ import IconLucideColumns2 from "~icons/
import IconLucideEyeOff from "~icons/lucide/eye-off";
import IconLucideFlipHorizontal2 from "~icons/lucide/flip-horizontal-2";
import IconLucideFlipVertical2 from "~icons/lucide/flip-vertical-2";
--import IconLucideGrid from "~icons/lucide/grid";
--import IconLucideImageOff from "~icons/lucide/image-off";
import IconLucideItalic from "~icons/lucide/italic";
import IconLucideKeyboard from "~icons/lucide/keyboard";
--import IconLucideLaptop from "~icons/lucide/laptop";
import IconLucideMonitor from "~icons/lucide/monitor";
--import IconLucideMoon from "~icons/lucide/moon";
--import IconLucideMoveRight from "~icons/lucide/move-right";
--import IconLucideMusic from "~icons/lucide/music";
--import IconLucidePalette from "~icons/lucide/palette";
--import IconLucideRabbit from "~icons/lucide/rabbit";
--import IconLucideSparkles from "~icons/lucide/sparkles";
--import IconLucideTimer from "~icons/lucide/timer";
--import IconLucideType from "~icons/lucide/type";
import IconLucideVideo from "~icons/lucide/video";
--import IconLucideVolume2 from "~icons/lucide/volume-2";
--import IconLucideWind from "~icons/lucide/wind";
++import IconLucideX from "~icons/lucide/x";
import {
AnimatedGradientEditor,
copyAnimatedGradientConfig,
@@@ -182,9 -176,9 +165,10 @@@ import
CAMERA3D_BLUR_MODE_SEEDS,
CAMERA3D_BOKEH_MAX_STRENGTH,
CAMERA3D_LIMITS,
-- CAMERA3D_MIN_SHOT_DURATION,
CAMERA3D_RESET_POSE,
++ CAMERA3D_SCENE_DESCRIPTIONS,
CAMERA3D_SCENES,
++ CAMERA3D_STARTER_SCENES,
CAMERA3D_TRANSITION_LIMITS,
type Camera3DAnglePreset,
type Camera3DBlurMode,
@@@ -196,10 -190,10 +180,12 @@@
type Camera3DPropertyKey,
type Camera3DScene,
type Camera3DSegment,
++ type Camera3DSetup,
camera3DPosesEqual,
camera3dBlurLimit,
cssPreviewTransform,
defaultCamera3DBlur,
++ findCamera3DScene,
flipCamera3DSegment,
getEndPose,
getMotionEasing,
@@@ -218,6 -212,6 +204,8 @@@ import
MenuItem,
MenuItemList,
PopperContent,
++ Section,
++ SectionLabel,
Slider,
Subfield,
topSlideAnimateClasses,
@@@ -245,21 -239,21 +233,10 @@@ const BACKGROUND_SOURCES =
none: "None",
} satisfies Record<BackgroundSourceTab, string>;
--const BACKGROUND_ICONS = {
-- wallpaper: imageBg,
-- image: transparentBg,
-- color: colorBg,
-- gradient: gradientBg,
-- animatedGradient: gradientBg,
--} satisfies Record<BackgroundSource["type"], string>;
--
--const BACKGROUND_SOURCES_ROW_ONE = [
++const BACKGROUND_SOURCE_TABS = [
"desktop",
"wallpaper",
"image",
--] satisfies Array<BackgroundSourceTab>;
--
--const BACKGROUND_SOURCES_ROW_TWO = [
"color",
"gradient",
"animatedGradient",
@@@ -439,6 -433,6 +416,9 @@@ type CursorPresetValues =
const DEFAULT_MOTION_BLUR = 1.0;
++const formatVolumeDb = (value: number) =>
++ value <= -30 ? "Muted" : `${value > 0 ? "+" : ""}${value.toFixed(1)} dB`;
++
const CURSOR_ANIMATION_STYLE_OPTIONS = [
{
value: "slow",
@@@ -604,21 -578,10 +584,41 @@@ function ConfigSidebarContent()
// multi-select); it must not swap the sidebar away from the current tab.
const sidebarSelection = () => {
const selection = editorState.timeline.selection;
- return selection && selection.type !== "clip" ? selection : null;
+ return selection && selection.type !== "clip" && selection.type !== "style"
+ ? selection
+ : null;
};
+ createEffect(() => {
+ if (
+ selectedStyle() &&
+ state.selectedTab !== "background" &&
+ state.selectedTab !== "camera" &&
+ state.selectedTab !== "cursor"
+ )
+ setState("selectedTab", "background");
+ });
let scrollRef!: HTMLDivElement;
++ let selectionScrollRef!: HTMLDivElement;
++ let previousStyle: number | null = null;
++ createEffect(() => {
++ const index = editorState.styleEditIndex;
++ if (index !== previousStyle) {
++ previousStyle = index;
++ scrollRef?.scrollTo({ top: 0 });
++ }
++ });
++ let previousSelection = "";
++ createEffect(() => {
++ const selection = sidebarSelection();
++ const key = selection
++ ? `${selection.type}:${"indices" in selection ? selection.indices.join(",") : selection.index}`
++ : "";
++ if (key !== previousSelection) {
++ previousSelection = key;
++ selectionScrollRef?.scrollTo({ top: 0 });
++ }
++ });
return (
<KTabs
@@@ -629,10 -592,9 +629,9 @@@
? undefined
: state.selectedTab
}
-- class="flex flex-col min-h-0 shrink-0 flex-1 max-w-104 overflow-hidden rounded-xl z-10 bg-gray-1 dark:bg-gray-2 border border-gray-3"
++ class="flex overflow-hidden z-10 flex-col flex-1 min-h-0 max-w-104 rounded-xl shrink-0 bg-ed-card shadow-ed-card"
>
- <StyleSegmentConfig />
-- <KTabs.List class="flex overflow-hidden sticky top-0 z-60 flex-row items-center h-16 text-lg border-b border-gray-3 shrink-0 bg-gray-1 dark:bg-gray-2">
++ <KTabs.List class="flex sticky top-0 z-60 flex-row justify-around items-center px-2.5 h-[46px] border-b border-ed-line shrink-0 bg-ed-card">
<For
each={[
{ id: TAB_IDS.background, icon: IconCapImage },
@@@ -669,12 -625,12 +668,17 @@@
{(item) => (
<KTabs.Trigger
value={item.id}
-- class={cx(
-- "flex relative z-10 flex-1 justify-center items-center px-4 py-2 transition-colors group disabled:opacity-50 focus:outline-hidden",
-- sidebarSelection()
-- ? "text-gray-11"
-- : "text-gray-11 data-selected:text-gray-12",
-- )}
++ aria-label={
++ item.id === "background"
++ ? "Background"
++ : item.id.charAt(0).toUpperCase() + item.id.slice(1)
++ }
++ title={
++ item.id === "background"
++ ? "Background"
++ : item.id.charAt(0).toUpperCase() + item.id.slice(1)
++ }
++ class="flex justify-center items-center w-10 h-[30px] rounded-[9px] transition-colors shrink-0 outline-hidden focus-visible:ring-1 focus-visible:ring-ed-accent text-ed-text-2 hover:bg-ed-ctl hover:text-ed-text-1 data-selected:bg-ed-ctl-hover data-selected:text-ed-text-1 disabled:text-ed-text-3 disabled:opacity-60 disabled:hover:bg-transparent"
onClick={() => {
// Clear any active selection first
if (sidebarSelection()) {
@@@ -696,38 -652,38 +700,17 @@@
}}
disabled={item.disabled}
>
-- <div
-- class={cx(
-- "flex justify-center relative border-transparent border z-10 items-center rounded-md size-9 transition will-change-transform",
-- state.selectedTab !== item.id &&
-- "group-hover:border-gray-300 group-disabled:border-none",
-- )}
-- >
-- <Dynamic component={item.icon} />
-- </div>
++ <Dynamic component={item.icon} class="size-4" />
</KTabs.Trigger>
)}
</For>
--
-- {/** Center the indicator with the icon */}
-- <Show
-- when={
-- !sidebarSelection() &&
-- editorState.timeline.audioPicker === null &&
-- editorState.timeline.camera3dSetup === null
-- }
-- >
-- <KTabs.Indicator class="absolute top-0 left-0 w-full h-full transition-transform duration-200 ease-in-out pointer-events-none will-change-transform">
-- <div class="absolute top-1/2 left-1/2 rounded-lg transform -translate-x-1/2 -translate-y-1/2 bg-gray-3 will-change-transform size-9" />
-- </KTabs.Indicator>
-- </Show>
</KTabs.List>
<div
ref={scrollRef}
style={{
"--margin-top-scroll": "5px",
}}
-- class="custom-scroll overflow-x-hidden overflow-y-scroll text-[0.875rem] flex-1 min-h-0"
++ class="custom-scroll overscroll-contain overflow-x-hidden overflow-y-auto text-[0.875rem] flex-1 min-h-0"
classList={{
hidden:
!!sidebarSelection() ||
@@@ -736,6 -692,6 +719,7 @@@
editorState.timeline.camera3dSetup !== null,
}}
>
++ <StyleSegmentConfig />
<BackgroundConfig
scrollRef={scrollRef}
brandColorSwatches={brandColorSwatches()}
@@@ -743,12 -699,12 +727,9 @@@
<CameraConfig scrollRef={scrollRef} />
<KTabs.Content
value="audio"
-- class="flex flex-col flex-1 gap-6 p-4 min-h-0"
++ class="flex flex-col flex-1 gap-3.5 pt-3.5 px-4 pb-4 min-h-0"
>
-- <Field
-- name="Audio Controls"
-- icon={<IconLucideVolume2 class="size-4" />}
-- >
++ <Section name="Audio">
<Subfield name="Mute Audio">
<Toggle
checked={project.audio.mute}
@@@ -779,18 -735,18 +760,18 @@@
</MenuItem>
)}
>
-- <KSelect.Trigger class="flex flex-row gap-2 items-center px-2 w-full h-8 rounded-lg transition-colors bg-gray-3 disabled:text-gray-11">
++ <KSelect.Trigger class="flex flex-row gap-1.5 items-center px-2 w-full h-[26px] rounded-[7px] transition-colors bg-ed-ctl hover:bg-ed-ctl-hover outline-hidden disabled:text-ed-text-3">
<KSelect.Value<{
name: string;
value: StereoMode;
-- }> class="flex-1 text-sm text-left truncate text-(--gray-500) font-normal">
++ }> class="flex-1 text-[12px] text-left truncate text-ed-text-1 font-normal">
{(state) => <span>{state.selectedOption().name}</span>}
</KSelect.Value>
<KSelect.Icon<ValidComponent>
as={(props) => (
<IconCapChevronDown
{...props}
-- class="size-4 shrink-0 transform transition-transform data-expanded:rotate-180 text-(--gray-500)"
++ class="size-3.5 shrink-0 transform transition-transform data-expanded:rotate-180 text-ed-text-3"
/>
)}
/>
@@@ -822,11 -778,11 +803,12 @@@
<Toggle disabled />
</Subfield>
</ComingSoonTooltip> */}
-- </Field>
++ </Section>
{meta().hasMicrophone && (
<Field
++ inline
name="Microphone Volume"
-- icon={<IconCapMicrophone class="size-4" />}
++ value={formatVolumeDb(project.audio.micVolumeDb ?? 0)}
>
<Slider
disabled={project.audio.mute}
@@@ -843,8 -799,8 +825,9 @@@
)}
{meta().hasSystemAudio && (
<Field
++ inline
name="System Audio Volume"
-- icon={<IconLucideMonitor class="size-4" />}
++ value={formatVolumeDb(project.audio.systemVolumeDb ?? 0)}
>
<Slider
disabled={project.audio.mute}
@@@ -863,173 -819,169 +846,175 @@@
</KTabs.Content>
<KTabs.Content
value="cursor"
-- class="flex flex-col flex-1 gap-6 p-4 min-h-0"
++ class="flex flex-col flex-1 gap-3.5 pt-3.5 px-4 pb-4 min-h-0"
>
- <Field
- name="Show cursor"
- value={
+ <StyleGroupToggle group="cursor" />
+ <Show
+ when={!selectedStyle() || selectedStyle()?.overrides.cursor != null}
+ >
- <Field
- name="Show cursor"
- value={
- <Toggle
- checked={!project.cursor.hide}
- onChange={(v) => {
- setProject("cursor", "hide", !v);
- }}
- />
- }
- />
++ <Field inline name="Show cursor">
+ <Toggle
+ checked={!project.cursor.hide}
+ onChange={(v) => {
+ setProject("cursor", "hide", !v);
+ }}
+ />
- }
- />
- <Show when={!project.cursor.hide}>
- <CursorStylePicker />
- <Field name="Size" icon={<IconCapEnlarge />}>
- <Slider
- value={[project.cursor.size]}
- onChange={(v) => setProject("cursor", "size", v[0])}
- minValue={20}
- maxValue={300}
- step={1}
- />
- </Field>
- <Field name="Tilt" icon={<IconLucideRotate3d class="size-4" />}>
- <Slider
- value={[project.cursor.rotationAmount ?? 0.15]}
- onChange={(v) => setProject("cursor", "rotationAmount", v[0])}
- minValue={0}
- maxValue={1}
- step={0.01}
- formatTooltip={(value) => `${Math.round(value * 100)}%`}
- />
+ </Field>
- <CursorRippleSection />
- <Field
- name="Hide When Idle"
- icon={<IconLucideTimer class="size-4" />}
- value={
+ <Show when={!project.cursor.hide}>
+ <CursorStylePicker />
- <Field name="Size" icon={<IconCapEnlarge />}>
++ <Field
++ inline
++ name="Size"
++ value={`${Math.round(project.cursor.size)}%`}
++ >
+ <Slider
+ value={[project.cursor.size]}
+ onChange={(v) => setProject("cursor", "size", v[0])}
+ minValue={20}
+ maxValue={300}
+ step={1}
+ />
+ </Field>
- <Field name="Tilt" icon={<IconLucideRotate3d class="size-4" />}>
++ <Field
++ inline
++ name="Tilt"
++ value={`${Math.round(
++ (project.cursor.rotationAmount ?? 0.15) * 100,
++ )}%`}
++ >
+ <Slider
+ value={[project.cursor.rotationAmount ?? 0.15]}
+ onChange={(v) => setProject("cursor", "rotationAmount", v[0])}
+ minValue={0}
+ maxValue={1}
+ step={0.01}
+ formatTooltip={(value) => `${Math.round(value * 100)}%`}
+ />
+ </Field>
+ <CursorRippleSection />
- <Field
- name="Hide When Idle"
- icon={<IconLucideTimer class="size-4" />}
- value={
- <Toggle
- checked={project.cursor.hideWhenIdle}
- onChange={(value) =>
- setProject("cursor", "hideWhenIdle", value)
- }
- />
- }
- />
++ <Field inline name="Hide When Idle">
+ <Toggle
- checked={project.cursor.hideWhenIdle}
- onChange={(value) =>
- setProject("cursor", "hideWhenIdle", value)
- }
++ checked={!project.cursor.hide}
++ onChange={(v) => {
++ setProject("cursor", "hide", !v);
++ }}
+ />
- }
- />
- <Show when={project.cursor.hideWhenIdle}>
- <Subfield name="Inactivity Delay" class="gap-4 items-center">
- <div class="flex flex-1 gap-3 items-center">
++ </Field>
+ <Show when={project.cursor.hideWhenIdle}>
- <Subfield name="Inactivity Delay" class="gap-4 items-center">
- <div class="flex flex-1 gap-3 items-center">
- <Slider
- class="flex-1"
- value={[cursorIdleDelay()]}
- onChange={(v) => {
- const rounded = clampIdleDelay(v[0]);
- setProject("cursor", "hideWhenIdleDelay", rounded);
- }}
- minValue={0.5}
- maxValue={5}
- step={0.1}
- formatTooltip={(value) => `${value.toFixed(1)}s`}
- />
- <span class="w-12 text-xs text-right text-gray-11">
- {cursorIdleDelay().toFixed(1)}s
- </span>
- </div>
- </Subfield>
++ <Field
++ inline
++ name="Inactivity Delay"
++ value={`${cursorIdleDelay().toFixed(1)}s`}
++ >
+ <Slider
- class="flex-1"
+ value={[cursorIdleDelay()]}
+ onChange={(v) => {
+ const rounded = clampIdleDelay(v[0]);
+ setProject("cursor", "hideWhenIdleDelay", rounded);
+ }}
+ minValue={0.5}
+ maxValue={5}
+ step={0.1}
+ formatTooltip={(value) => `${value.toFixed(1)}s`}
+ />
- <span class="w-12 text-xs text-right text-gray-11">
- {cursorIdleDelay().toFixed(1)}s
- </span>
- </div>
- </Subfield>
- </Show>
- <Field
- name="Cursor Movement Style"
- icon={<IconLucideRabbit class="size-4" />}
- >
- <RadioGroup
- class="flex flex-col gap-2"
- value={project.cursor.animationStyle}
- onChange={(value) =>
- applyCursorStylePreset(value as CursorAnimationStyle)
- }
- >
- {CURSOR_ANIMATION_STYLE_OPTIONS.map((option) => (
- <RadioGroup.Item
- value={option.value}
- class="rounded-lg border border-gray-3 transition-colors data-checked:border-blue-8 data-checked:bg-blue-3/40"
- >
- <RadioGroup.ItemInput class="sr-only" />
- <RadioGroup.ItemLabel class="flex items-start gap-3 p-3">
- <RadioGroup.ItemControl class="mt-1 size-4 rounded-full border border-gray-7 data-checked:border-blue-9 data-checked:bg-blue-9" />
- <div class="flex flex-col text-left">
- <span class="text-sm font-medium text-gray-12">
- {option.label}
- </span>
- <span class="text-xs text-gray-11">
- {option.description}
- </span>
- </div>
- </RadioGroup.ItemLabel>
- </RadioGroup.Item>
- ))}
- </RadioGroup>
- </Field>
- <KCollapsible open={!project.cursor.raw}>
- <Field
- name="Smooth Movement"
- icon={<IconHugeiconsEaseCurveControlPoints />}
- value={
++ </Field>
+ </Show>
- <Field
- name="Cursor Movement Style"
- icon={<IconLucideRabbit class="size-4" />}
- >
++ <Field name="Cursor Movement Style">
+ <RadioGroup
+ class="flex flex-col gap-2"
+ value={project.cursor.animationStyle}
+ onChange={(value) =>
+ applyCursorStylePreset(value as CursorAnimationStyle)
+ }
+ >
+ {CURSOR_ANIMATION_STYLE_OPTIONS.map((option) => (
+ <RadioGroup.Item
+ value={option.value}
+ class="rounded-lg border border-gray-3 transition-colors data-checked:border-blue-8 data-checked:bg-blue-3/40"
+ >
+ <RadioGroup.ItemInput class="sr-only" />
+ <RadioGroup.ItemLabel class="flex items-start gap-3 p-3">
+ <RadioGroup.ItemControl class="mt-1 size-4 rounded-full border border-gray-7 data-checked:border-blue-9 data-checked:bg-blue-9" />
+ <div class="flex flex-col text-left">
- <span class="text-sm font-medium text-gray-12">
++ <span class="text-[13px] font-medium text-ed-text-1">
+ {option.label}
+ </span>
- <span class="text-xs text-gray-11">
++ <span class="text-[11px] text-ed-text-3">
+ {option.description}
+ </span>
+ </div>
+ </RadioGroup.ItemLabel>
+ </RadioGroup.Item>
+ ))}
+ </RadioGroup>
+ </Field>
+ <KCollapsible open={!project.cursor.raw}>
- <Field
- name="Smooth Movement"
- icon={<IconHugeiconsEaseCurveControlPoints />}
- value={
- <Toggle
- checked={!project.cursor.raw}
- onChange={(value) => {
- setProject("cursor", "raw", !value);
- }}
- />
- }
- />
++ <Field inline name="Smooth Movement">
+ <Toggle
- checked={!project.cursor.raw}
- onChange={(value) => {
- setProject("cursor", "raw", !value);
- }}
++ checked={project.cursor.hideWhenIdle}
++ onChange={(value) =>
++ setProject("cursor", "hideWhenIdle", value)
++ }
+ />
- }
- />
- <KCollapsible.Content class="overflow-hidden border-b opacity-0 transition-opacity border-gray-3 animate-collapsible-up data-expanded:animate-collapsible-down data-expanded:opacity-100">
- {/* if Content has padding or margin the animation doesn't look as good */}
- <div class="flex flex-col gap-4 pt-4 pb-6">
- <Field name="Tension">
- <Slider
- value={[project.cursor.tension]}
- onChange={(v) => setCursorPhysics("tension", v[0])}
- minValue={1}
- maxValue={600}
- step={1}
- />
- </Field>
- <Field name="Friction">
- <Slider
- value={[project.cursor.friction]}
- onChange={(v) => setCursorPhysics("friction", v[0])}
- minValue={0}
- maxValue={200}
- step={0.1}
- />
- </Field>
- <Field name="Mass">
- <Slider
- value={[project.cursor.mass]}
- onChange={(v) => setCursorPhysics("mass", v[0])}
- minValue={0.1}
- maxValue={15}
- step={0.01}
- />
- </Field>
- </div>
- </KCollapsible.Content>
- </KCollapsible>
- <Show when={!isExplicitCursorFamily(project.cursor.type)}>
- <Field
- name="High Quality SVG Cursors"
- icon={<IconLucideSparkles />}
- value={
++ </Field>
+ <KCollapsible.Content class="overflow-hidden border-b opacity-0 transition-opacity border-gray-3 animate-collapsible-up data-expanded:animate-collapsible-down data-expanded:opacity-100">
+ {/* if Content has padding or margin the animation doesn't look as good */}
- <div class="flex flex-col gap-4 pt-4 pb-6">
- <Field name="Tension">
++ <div class="flex flex-col gap-1 pt-2 pb-4">
++ <Field
++ inline
++ name="Tension"
++ value={Math.round(project.cursor.tension)}
++ >
+ <Slider
+ value={[project.cursor.tension]}
+ onChange={(v) => setCursorPhysics("tension", v[0])}
+ minValue={1}
+ maxValue={600}
+ step={1}
+ />
+ </Field>
- <Field name="Friction">
++ <Field
++ inline
++ name="Friction"
++ value={project.cursor.friction.toFixed(1)}
++ >
+ <Slider
+ value={[project.cursor.friction]}
+ onChange={(v) => setCursorPhysics("friction", v[0])}
+ minValue={0}
+ maxValue={200}
+ step={0.1}
+ />
+ </Field>
- <Field name="Mass">
++ <Field
++ inline
++ name="Mass"
++ value={project.cursor.mass.toFixed(2)}
++ >
+ <Slider
+ value={[project.cursor.mass]}
+ onChange={(v) => setCursorPhysics("mass", v[0])}
+ minValue={0.1}
+ maxValue={15}
+ step={0.01}
+ />
+ </Field>
+ </div>
+ </KCollapsible.Content>
+ </KCollapsible>
+ <Show when={!isExplicitCursorFamily(project.cursor.type)}>
- <Field
- name="High Quality SVG Cursors"
- icon={<IconLucideSparkles />}
- value={
- <Toggle
- checked={project.cursor.useSvg ?? true}
- onChange={(value) => {
- setProject("cursor", "useSvg", value);
- }}
- />
- }
- />
++ <Field inline name="High Quality SVG Cursors">
+ <Toggle
+ checked={project.cursor.useSvg ?? true}
+ onChange={(value) => {
+ setProject("cursor", "useSvg", value);
+ }}
+ />
- }
- />
++ </Field>
+ </Show>
</Show>
- </Show>
- {/* <Field name="Animation Style" icon={<IconLucideRabbit />}>
+ {/* <Field name="Animation Style" icon={<IconLucideRabbit />}>
<RadioGroup
defaultValue="regular"
value={project.cursor.animationStyle}
@@@ -1074,20 -1026,19 +1059,23 @@@
))}
</RadioGroup>
</Field> */}
+ </Show>
</KTabs.Content>
-- <KTabs.Content value="hotkeys" class="flex flex-1 p-4 min-h-0">
-- <Field name="Hotkeys" icon={<IconCapHotkeys />}>
++ <KTabs.Content
++ value="hotkeys"
++ class="flex flex-1 pt-3.5 px-4 pb-4 min-h-0"
++ >
++ <Section name="Hotkeys">
<ComingSoonTooltip>
<Subfield name="Show hotkeys">
<Toggle disabled />
</Subfield>
</ComingSoonTooltip>
-- </Field>
++ </Section>
</KTabs.Content>
<KTabs.Content
value={TAB_IDS.captions}
-- class="flex flex-col flex-1 gap-6 p-4 min-h-0"
++ class="flex flex-col flex-1 gap-3.5 pt-3.5 px-4 pb-4 min-h-0"
>
<Suspense>
<CaptionsTab brandColorSwatches={brandColorSwatches()} />
@@@ -1095,16 -1046,16 +1083,21 @@@
</KTabs.Content>
<KTabs.Content
value={TAB_IDS.keyboard}
-- class="flex flex-col flex-1 gap-6 p-4 min-h-0"
++ class="flex flex-col flex-1 gap-3.5 pt-3.5 px-4 pb-4 min-h-0"
>
<KeyboardTab brandColorSwatches={brandColorSwatches()} />
</KTabs.Content>
</div>
<div
++ ref={selectionScrollRef}
style={{
"--margin-top-scroll": "5px",
++ "overflow-y": editorState.timeline.camera3dSetup
++ ? "hidden"
++ : undefined,
++ padding: editorState.timeline.camera3dSetup ? "0" : undefined,
}}
-- class="custom-scroll p-4 top-16 left-0 right-0 bottom-0 text-[0.875rem] space-y-4 bg-gray-1 dark:bg-gray-2 z-50"
++ class="custom-scroll min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-contain pt-3.5 px-4 pb-4 text-[0.875rem] space-y-3.5 bg-ed-card z-50"
classList={{
hidden:
!sidebarSelection() &&
@@@ -1228,7 -1167,7 +1221,7 @@@
>
Done
</EditorButton>
-- <span class="text-sm text-gray-10">
++ <span class="text-[12px] text-ed-text-2">
{value().segments.length} caption{" "}
{value().segments.length === 1
? "segment"
@@@ -1250,7 -1189,7 +1243,7 @@@
</div>
<For each={value().segments}>
{(item) => (
-- <div class="p-4 rounded-lg border border-gray-200">
++ <div class="p-3.5 rounded-xl bg-ed-card-2">
<CaptionSegmentConfig
segment={item.segment}
segmentIndex={item.index}
@@@ -1301,7 -1240,7 +1294,7 @@@
>
Done
</EditorButton>
-- <span class="text-sm text-gray-10">
++ <span class="text-[12px] text-ed-text-2">
{value().segments.length} keyboard{" "}
{value().segments.length === 1
? "segment"
@@@ -1323,7 -1262,7 +1316,7 @@@
</div>
<For each={value().segments}>
{(item) => (
-- <div class="p-4 rounded-lg border border-gray-200">
++ <div class="p-3.5 rounded-xl bg-ed-card-2">
<KeyboardSegmentConfig
segment={item.segment}
segmentIndex={item.index}
@@@ -1368,7 -1307,7 +1361,7 @@@
>
Done
</EditorButton>
-- <span class="text-sm text-gray-10">
++ <span class="text-[12px] text-ed-text-2">
{value().segments.length} text{" "}
{value().segments.length === 1
? "segment"
@@@ -1390,7 -1329,7 +1383,7 @@@
</div>
<For each={value().segments}>
{(item) => (
-- <div class="p-4 rounded-lg border border-gray-200">
++ <div class="p-3.5 rounded-xl bg-ed-card-2">
<TextSegmentConfig
segment={item.segment}
segmentIndex={item.index}
@@@ -1440,7 -1379,7 +1433,7 @@@
>
Done
</EditorButton>
-- <span class="text-sm text-gray-10">
++ <span class="text-[12px] text-ed-text-2">
{value().segments.length} audio{" "}
{value().segments.length === 1
? "segment"
@@@ -1462,7 -1401,7 +1455,7 @@@
</div>
<For each={value().segments}>
{(item) => (
-- <div class="p-4 rounded-lg border border-gray-200">
++ <div class="p-3.5 rounded-xl bg-ed-card-2">
<AudioSegmentConfig
segment={item.segment}
segmentIndex={item.index}
@@@ -1507,7 -1446,7 +1500,7 @@@
>
Done
</EditorButton>
-- <span class="text-sm text-gray-10">
++ <span class="text-[12px] text-ed-text-2">
{value().segments.length} mask{" "}
{value().segments.length === 1
? "segment"
@@@ -1529,7 -1468,7 +1522,7 @@@
</div>
<For each={value().segments}>
{(item) => (
-- <div class="p-4 rounded-lg border border-gray-200">
++ <div class="p-3.5 rounded-xl bg-ed-card-2">
<MaskSegmentConfig
segment={item.segment}
segmentIndex={item.index}
@@@ -1590,7 -1529,7 +1583,7 @@@
>
Done
</EditorButton>
-- <span class="text-sm text-gray-10 whitespace-nowrap">
++ <span class="text-[12px] text-ed-text-2 whitespace-nowrap">
{selectionLabel()}
</span>
<Show
@@@ -1598,7 -1537,7 +1591,7 @@@
>
<button
type="button"
-- class="text-sm font-medium whitespace-nowrap text-blue-11 hover:underline outline-hidden focus-visible:underline"
++ class="text-[12px] font-medium whitespace-nowrap text-ed-accent hover:underline outline-hidden focus-visible:underline"
onClick={() =>
setEditorState("timeline", "selection", {
type: "zoom",
@@@ -1633,7 -1572,7 +1626,7 @@@
>
<For each={value().segments}>
{(item) => (
-- <div class="p-4 rounded-lg border border-gray-200">
++ <div class="p-3.5 rounded-xl bg-ed-card-2">
<ZoomSegmentConfig
segment={item.segment}
segmentIndex={item.index}
@@@ -1682,7 -1621,7 +1675,7 @@@
>
Done
</EditorButton>
-- <span class="text-sm text-gray-10">
++ <span class="text-[12px] text-ed-text-2">
{value().segments.length} 3D{" "}
{value().segments.length === 1
? "segment"
@@@ -1708,7 -1647,7 +1701,7 @@@
}
>
{(item) => (
-- <div class="p-4 rounded-lg border border-gray-200">
++ <div class="p-3.5 rounded-xl bg-ed-card-2">
<Camera3DSegmentConfig
segment={item().segment}
segmentIndex={item().index}
@@@ -1761,7 -1700,7 +1754,7 @@@
>
Done
</EditorButton>
-- <span class="text-sm text-gray-10">
++ <span class="text-[12px] text-ed-text-2">
{value().segments.length} scene{" "}
{value().segments.length === 1
? "segment"
@@@ -2164,71 -2103,71 +2157,6 @@@ function BackgroundConfig(props:
}
};
-- const renderBackgroundSourceIcon = (item: BackgroundSourceTab) => {
-- if (item === "animatedGradient") {
-- return <IconLucideSparkles class="size-3.5" />;
-- }
-- if (item === "none") {
-- return <IconLucideImageOff class="size-3.5" />;
-- }
--
-- if (item === "gradient") {
-- const source = project.background.source;
-- const angle = source.type === "gradient" ? source.angle : 90;
-- const fromColor =
-- source.type === "gradient" ? source.from : DEFAULT_GRADIENT_FROM;
-- const toColor =
-- source.type === "gradient" ? source.to : DEFAULT_GRADIENT_TO;
-- return (
-- <div
-- class="size-3.5 rounded-sm"
-- style={{
-- background: `linear-gradient(${angle}deg, rgb(${fromColor}), rgb(${toColor}))`,
-- }}
-- />
-- );
-- }
--
-- if (item === "color") {
-- const source = project.background.source;
-- const backgroundColor =
-- source.type === "color" ? source.value : hexToRgb(BACKGROUND_COLORS[9]);
-- return (
-- <div
-- class="size-3.5 rounded-[5px]"
-- style={{ "background-color": `rgb(${backgroundColor})` }}
-- />
-- );
-- }
--
-- let imageSrc: string =
-- item === "desktop" ? imageBg : BACKGROUND_ICONS[item];
-- const source = project.background.source;
-- if (item === "image" && source.type === "image" && source.path) {
-- const convertedPath = convertFileSrc(source.path);
-- if (convertedPath) imageSrc = convertedPath;
-- } else if (item === "desktop") {
-- const desktopBackground = currentDesktopBackground();
-- if (desktopBackground) imageSrc = desktopBackground.url;
-- } else if (
-- item === "wallpaper" &&
-- source.type === "wallpaper" &&
-- source.path
-- ) {
-- const selected = selectedWallpaper();
-- if (selected?.thumbnailUrl) imageSrc = selected.thumbnailUrl;
-- }
--
-- return (
-- <img
-- loading="eager"
-- alt={BACKGROUND_SOURCES[item]}
-- class="size-3.5 rounded-sm"
-- src={imageSrc}
-- />
-- );
-- };
--
const BackgroundSourceTrigger = (props: {
item: BackgroundSourceTab;
class?: string;
@@@ -2242,11 -2181,11 +2170,10 @@@
animatedGradientLibrary.isError)
}
class={cx(
-- "z-10 flex justify-center items-center gap-1.5 py-2.5 px-2 text-xs whitespace-nowrap text-gray-11 rounded-[10px] border transition-colors duration-200 outline-hidden data-selected:border-gray-3 data-selected:bg-gray-3 data-selected:text-gray-12 not-data-selected:hover:border-gray-7 disabled:opacity-40 peer",
++ "flex flex-1 justify-center items-center h-[26px] px-1 text-[11.5px] font-medium whitespace-nowrap text-ed-text-2 rounded-md border-0 transition-colors duration-200 outline-hidden data-selected:bg-ed-card data-selected:text-ed-text-1 data-selected:shadow-[0_1px_2px_rgba(0,0,0,.12),0_0_0_.5px_rgba(0,0,0,.06)] dark:data-selected:bg-white/11 dark:data-selected:shadow-none not-data-selected:hover:text-ed-text-1 disabled:opacity-40",
props.class,
)}
>
-- {renderBackgroundSourceIcon(props.item)}
{BACKGROUND_SOURCES[props.item]}
</KTabs.Trigger>
);
@@@ -2286,179 -2225,213 +2213,190 @@@
});
};
++ const selectBackgroundSourceTab = (v: string) => {
++ const tab = v as BackgroundSourceTab;
++ if (
++ tab === "animatedGradient" &&
++ (!animatedGradientCatalog.data ||
++ animatedGradientLibrary.isPending ||
++ animatedGradientLibrary.isError)
++ )
++ return;
++ const fromNone = backgroundSourceTab() === "none";
++ if (tab === "none") {
++ batch(() => {
++ const source = project.background.source;
++ if (source.type === "animatedGradient") {
++ lastAnimatedGradient = copyAnimatedGradientConfig(source.config);
++ pendingGradientPreference = {
++ lastUsed: lastAnimatedGradient,
++ selected: false,
++ };
++ setProject("background", "source", {
++ type: "color",
++ value: [255, 255, 255],
++ alpha: 255,
++ });
++ }
++ setBackgroundSourceTab(tab);
++ setProject("background", "padding", 0);
++ setProject("background", "rounding", 0);
++ });
++ return;
++ }
++ setBackgroundSourceTab(tab);
++ if (tab === "desktop") {
++ const desktopBackground = currentDesktopBackground();
++ if (desktopBackground) {
++ ensureBackgroundPresentation(fromNone);
++ setWallpaperSource(desktopBackground.rawPath);
++ }
++ return;
++ }
++ ensureBackgroundPresentation(fromNone);
++ switch (tab) {
++ case "animatedGradient": {
++ const config =
++ lastAnimatedGradient ??
++ animatedGradientLibrary.data?.lastUsed ??
++ animatedGradientCatalog.data?.defaultConfig;
++ if (!config) return;
++ setProject("background", "source", {
++ type: "animatedGradient",
++ config: copyAnimatedGradientConfig(config),
++ });
++ break;
++ }
++ case "image": {
++ setProject("background", "source", {
++ type: "image",
++ path:
++ project.background.source.type === "image"
++ ? project.background.source.path
++ : null,
++ });
++ break;
++ }
++ case "color": {
++ setProject("background", "source", {
++ type: "color",
++ value:
++ project.background.source.type === "color"
++ ? project.background.source.value
++ : DEFAULT_GRADIENT_FROM,
++ });
++ break;
++ }
++ case "gradient": {
++ setProject("background", "source", {
++ type: "gradient",
++ from:
++ project.background.source.type === "gradient"
++ ? project.background.source.from
++ : DEFAULT_GRADIENT_FROM,
++ to:
++ project.background.source.type === "gradient"
++ ? project.background.source.to
++ : DEFAULT_GRADIENT_TO,
++ angle:
++ project.background.source.type === "gradient"
++ ? project.background.source.angle
++ : 90,
++ });
++ break;
++ }
++ case "wallpaper": {
++ const path =
++ project.background.source.type === "wallpaper" &&
++ !isCurrentDesktopBackgroundPath(project.background.source.path)
++ ? project.background.source.path
++ : null;
++ setProject("background", "source", {
++ type: "wallpaper",
++ path,
++ });
++ break;
++ }
++ }
++ };
++
return (
-- <KTabs.Content value={TAB_IDS.background} class="flex flex-col gap-6 p-4">
- <Field icon={<IconCapImage class="size-4" />} name="Background Image">
- <KTabs
- value={backgroundSourceTab()}
- onChange={(v) => {
- const tab = v as BackgroundSourceTab;
- if (
- tab === "animatedGradient" &&
- (!animatedGradientCatalog.data ||
- animatedGradientLibrary.isPending ||
- animatedGradientLibrary.isError)
- )
- return;
- const fromNone = backgroundSourceTab() === "none";
- if (tab === "none") {
- batch(() => {
- const source = project.background.source;
- if (source.type === "animatedGradient") {
- lastAnimatedGradient = copyAnimatedGradientConfig(
- source.config,
- );
- pendingGradientPreference = {
- lastUsed: lastAnimatedGradient,
- selected: false,
- };
- setProject("background", "source", {
- type: "color",
- value: [255, 255, 255],
- alpha: 255,
- });
- }
- setBackgroundSourceTab(tab);
- setProject("background", "padding", 0);
- setProject("background", "rounding", 0);
- });
- return;
- }
- setBackgroundSourceTab(tab);
- if (tab === "desktop") {
- const desktopBackground = currentDesktopBackground();
- if (desktopBackground) {
- ensureBackgroundPresentation(fromNone);
- setWallpaperSource(desktopBackground.rawPath);
- }
- return;
- }
- ensureBackgroundPresentation(fromNone);
- switch (tab) {
- case "animatedGradient": {
- const config =
- lastAnimatedGradient ??
- animatedGradientLibrary.data?.lastUsed ??
- animatedGradientCatalog.data?.defaultConfig;
- if (!config) return;
- setProject("background", "source", {
- type: "animatedGradient",
- config: copyAnimatedGradientConfig(config),
- });
- break;
- }
- case "image": {
- setProject("background", "source", {
- type: "image",
- path:
- project.background.source.type === "image"
- ? project.background.source.path
- : null,
- });
- break;
- }
- case "color": {
- setProject("background", "source", {
- type: "color",
- value:
- project.background.source.type === "color"
- ? project.background.source.value
- : DEFAULT_GRADIENT_FROM,
- });
- break;
- }
- case "gradient": {
- setProject("background", "source", {
- type: "gradient",
- from:
- project.background.source.type === "gradient"
- ? project.background.source.from
- : DEFAULT_GRADIENT_FROM,
- to:
- project.background.source.type === "gradient"
- ? project.background.source.to
- : DEFAULT_GRADIENT_TO,
- angle:
- project.background.source.type === "gradient"
- ? project.background.source.angle
- : 90,
- });
- break;
- }
- case "wallpaper": {
- const path =
- project.background.source.type === "wallpaper" &&
- !isCurrentDesktopBackgroundPath(
- project.background.source.path,
- )
- ? project.background.source.path
- : null;
- setProject("background", "source", {
- type: "wallpaper",
- path,
- });
- break;
++ <KTabs.Content
++ value={TAB_IDS.background}
++ class="flex flex-col gap-3.5 pt-3.5 px-4 pb-4"
++ >
+ <StyleGroupToggle group="background" />
+ <Show
+ when={!selectedStyle() || selectedStyle()?.overrides.background != null}
+ >
- <Field icon={<IconCapImage class="size-4" />} name="Background Image">
++ <Section
++ name="Background"
++ action={
++ <EditorButton
++ size="sm"
++ leftIcon={<IconLucideX />}
++ class={
++ backgroundSourceTab() === "none"
++ ? "bg-ed-ctl-hover text-ed-text-1"
++ : undefined
+ }
- }
- }}
++ onClick={() => selectBackgroundSourceTab("none")}
++ >
++ None
++ </EditorButton>
++ }
+ >
- <KTabs.List class="flex relative flex-col gap-2">
- <div class="flex flex-row gap-2 items-center">
- <For each={BACKGROUND_SOURCES_ROW_ONE}>
- {(item) => (
- <BackgroundSourceTrigger item={item} class="flex-1" />
- )}
- </For>
- </div>
- <div class="flex flex-row gap-2 items-center">
- <For each={BACKGROUND_SOURCES_ROW_TWO}>
- {(item) => (
- <BackgroundSourceTrigger item={item} class="flex-1" />
- )}
- </For>
- </div>
- <BackgroundSourceTrigger
- item="none"
- class="w-full not-data-selected:border-gray-5"
- />
- </KTabs.List>
- <Show
- when={
- animatedGradientCatalog.isError || animatedGradientLibrary.isError
- }
+ <KTabs
+ value={backgroundSourceTab()}
- onChange={(v) => {
- const tab = v as BackgroundSourceTab;
- if (
- tab === "animatedGradient" &&
- (!animatedGradientCatalog.data ||
- animatedGradientLibrary.isPending ||
- animatedGradientLibrary.isError)
- )
- return;
- const fromNone = backgroundSourceTab() === "none";
- if (tab === "none") {
- batch(() => {
- const source = project.background.source;
- if (source.type === "animatedGradient") {
- lastAnimatedGradient = copyAnimatedGradientConfig(
- source.config,
- );
- pendingGradientPreference = {
- lastUsed: lastAnimatedGradient,
- selected: false,
- };
- setProject("background", "source", {
- type: "color",
- value: [255, 255, 255],
- alpha: 255,
- });
- }
- setBackgroundSourceTab(tab);
- setProject("background", "padding", 0);
- setProject("background", "rounding", 0);
- });
- return;
- }
- setBackgroundSourceTab(tab);
- if (tab === "desktop") {
- const desktopBackground = currentDesktopBackground();
- if (desktopBackground) {
- ensureBackgroundPresentation(fromNone);
- setWallpaperSource(desktopBackground.rawPath);
- }
- return;
- }
- ensureBackgroundPresentation(fromNone);
- switch (tab) {
- case "animatedGradient": {
- const config =
- lastAnimatedGradient ??
- animatedGradientLibrary.data?.lastUsed ??
- animatedGradientCatalog.data?.defaultConfig;
- if (!config) return;
- setProject("background", "source", {
- type: "animatedGradient",
- config: copyAnimatedGradientConfig(config),
- });
- break;
- }
- case "image": {
- setProject("background", "source", {
- type: "image",
- path:
- project.background.source.type === "image"
- ? project.background.source.path
- : null,
- });
- break;
- }
- case "color": {
- setProject("background", "source", {
- type: "color",
- value:
- project.background.source.type === "color"
- ? project.background.source.value
- : DEFAULT_GRADIENT_FROM,
- });
- break;
- }
- case "gradient": {
- setProject("background", "source", {
- type: "gradient",
- from:
- project.background.source.type === "gradient"
- ? project.background.source.from
- : DEFAULT_GRADIENT_FROM,
- to:
- project.background.source.type === "gradient"
- ? project.background.source.to
- : DEFAULT_GRADIENT_TO,
- angle:
- project.background.source.type === "gradient"
- ? project.background.source.angle
- : 90,
- });
- break;
- }
- case "wallpaper": {
- const path =
- project.background.source.type === "wallpaper" &&
- !isCurrentDesktopBackgroundPath(
- project.background.source.path,
- )
- ? project.background.source.path
- : null;
- setProject("background", "source", {
- type: "wallpaper",
- path,
- });
- break;
- }
- }
- }}
++ onChange={selectBackgroundSourceTab}
>
- <KTabs.List class="flex relative flex-col gap-2">
- <div class="flex flex-row gap-2 items-center">
- <For each={BACKGROUND_SOURCES_ROW_ONE}>
- {(item) => (
- <BackgroundSourceTrigger item={item} class="flex-1" />
- )}
- </For>
- </div>
- <div class="flex flex-row gap-2 items-center">
- <For each={BACKGROUND_SOURCES_ROW_TWO}>
- {(item) => (
- <BackgroundSourceTrigger item={item} class="flex-1" />
- )}
- </For>
- </div>
- <BackgroundSourceTrigger
- item="none"
- class="w-full not-data-selected:border-gray-5"
- <div class="mt-2 flex items-center justify-between gap-2 text-xs">
- <span role="alert" class="text-red-11">
- Could not load animated gradients.
- </span>
- <button
- type="button"
- class="text-gray-12 underline"
- onClick={() => {
- void animatedGradientCatalog.refetch();
- void animatedGradientLibrary.refetch();
- }}
- >
- Retry
- </button>
- </div>
- </Show>
- {/** Dashed divider */}
- <div class="my-5 w-full border-t border-dashed border-gray-5" />
- <KTabs.Content value="desktop">
++ <KTabs.List class="flex flex-row gap-0.5 p-0.5 rounded-lg bg-ed-ctl">
++ <For each={BACKGROUND_SOURCE_TABS}>
++ {(item) => <BackgroundSourceTrigger item={item} />}
++ </For>
++ {/* Kobalte resets a Tabs value that matches no trigger to the
++ first tab (and fires onChange), which would silently replace
++ a "None" background. The None action lives on the section
++ header, so the tab itself stays registered but hidden. */}
++ <KTabs.Trigger
++ value="none"
++ aria-hidden="true"
++ tabIndex={-1}
++ class="sr-only"
+ />
+ </KTabs.List>
<Show
- when={currentDesktopBackground()}
- fallback={
- <div class="flex flex-col gap-3 items-center justify-center p-6 w-full rounded-lg border border-dashed bg-gray-2 border-gray-5">
- <IconLucideMonitor class="size-6 text-gray-11" />
- <span class="text-[13px] text-center text-gray-12">
- Use the wallpaper from your desktop
- </span>
- <EditorButton
- onClick={importDesktopBackground}
- disabled={importingDesktopBackground()}
- leftIcon={<IconLucideMonitor />}
- >
- {importingDesktopBackground()
- ? "Importing..."
- : "Import desktop background"}
- </EditorButton>
- </div>
+ when={
+ animatedGradientCatalog.isError ||
+ animatedGradientLibrary.isError
}
>
- {(photo) => (
- <div class="flex flex-col gap-3">
- <button
- type="button"
- onClick={() => {
- setWallpaperSource(photo().rawPath);
- ensureBackgroundPresentation();
- }}
- class={cx(
- "overflow-hidden relative w-full h-48 rounded-lg border transition group",
- project.background.source.type === "wallpaper" &&
- project.background.source.path === photo().rawPath
- ? "border-blue-9 ring-2 ring-blue-9"
- : "border-gray-5 hover:border-gray-7",
- )}
- >
- <img
- src={photo().url}
- loading="eager"
- class="object-cover w-full h-full"
- alt={photo().label ?? getCurrentDesktopBackgroundLabel()}
- />
- <span class="flex absolute right-2 bottom-2 justify-center items-center w-7 h-7 rounded-full text-white/95 bg-black/55 backdrop-blur-sm">
- <IconLucideMonitor class="size-4" />
+ <div class="mt-2 flex items-center justify-between gap-2 text-xs">
+ <span role="alert" class="text-red-11">
+ Could not load animated gradients.
+ </span>
+ <button
+ type="button"
+ class="text-gray-12 underline"
+ onClick={() => {
+ void animatedGradientCatalog.refetch();
+ void animatedGradientLibrary.refetch();
+ }}
+ >
+ Retry
+ </button>
+ </div>
+ </Show>
- {/** Dashed divider */}
- <div class="my-5 w-full border-t border-dashed border-gray-5" />
++ <div class="my-3.5 w-full border-t border-ed-line" />
+ <KTabs.Content value="desktop">
+ <Show
+ when={currentDesktopBackground()}
+ fallback={
- <div class="flex flex-col gap-3 items-center justify-center p-6 w-full rounded-lg border border-dashed bg-gray-2 border-gray-5">
- <IconLucideMonitor class="size-6 text-gray-11" />
- <span class="text-[13px] text-center text-gray-12">
++ <div class="flex flex-col gap-3 items-center justify-center p-6 w-full rounded-xl border border-dashed bg-ed-card-2 border-ed-line-strong">
++ <IconLucideMonitor class="size-6 text-ed-text-3" />
++ <span class="text-[13px] text-center text-ed-text-1">
+ Use the wallpaper from your desktop
</span>
- </button>
- <div class="flex justify-end">
<EditorButton
onClick={importDesktopBackground}
disabled={importingDesktopBackground()}
@@@ -2466,323 -2439,278 +2404,323 @@@
>
{importingDesktopBackground()
? "Importing..."
- : "Re-import"}
+ : "Import desktop background"}
</EditorButton>
</div>
- </div>
- )}
- </Show>
- </KTabs.Content>
- <KTabs.Content value="wallpaper">
- {/** Background Tabs */}
- <KTabs class="overflow-hidden relative" value={backgroundTab()}>
- <KTabs.List
- ref={setBackgroundRef}
- class="flex overflow-x-auto overscroll-contain relative z-10 flex-row gap-2 items-center mb-3 text-xs hide-scroll"
- style={{
- "-webkit-mask-image": `linear-gradient(to right, transparent, black ${
- scrollX() > 0 ? "24px" : "0"
- }, black calc(100% - ${
- reachedEndOfScroll() ? "0px" : "24px"
- }), transparent)`,
-
- "mask-image": `linear-gradient(to right, transparent, black ${
- scrollX() > 0 ? "24px" : "0"
- }, black calc(100% - ${
- reachedEndOfScroll() ? "0px" : "24px"
- }), transparent);`,
- }}
+ }
>
- <For each={Object.entries(BACKGROUND_THEMES)}>
- {([key, value]) => (
- <>
- <KTabs.Trigger
- onClick={() =>
- setBackgroundTab(
- key as keyof typeof BACKGROUND_THEMES,
- )
+ {(photo) => (
+ <div class="flex flex-col gap-3">
+ <button
+ type="button"
+ onClick={() => {
+ setWallpaperSource(photo().rawPath);
+ ensureBackgroundPresentation();
+ }}
+ class={cx(
- "overflow-hidden relative w-full h-48 rounded-lg border transition group",
++ "overflow-hidden relative w-full h-48 rounded-lg transition group",
+ project.background.source.type === "wallpaper" &&
+ project.background.source.path === photo().rawPath
- ? "border-blue-9 ring-2 ring-blue-9"
- : "border-gray-5 hover:border-gray-7",
++ ? "ring-2 ring-ed-accent ring-offset-2 ring-offset-ed-card"
++ : "ring-1 ring-ed-line hover:ring-ed-line-strong",
+ )}
+ >
+ <img
+ src={photo().url}
+ loading="eager"
+ class="object-cover w-full h-full"
+ alt={
+ photo().label ?? getCurrentDesktopBackgroundLabel()
}
- value={key}
- class="flex relative z-10 flex-1 justify-center items-center px-4 py-2 bg-transparent rounded-lg border transition-colors duration-200 text-gray-11 not-data-selected:hover:border-gray-7 data-selected:bg-gray-3 data-selected:border-gray-3 group data-selected:text-gray-12 disabled:opacity-50 focus:outline-hidden"
+ />
+ <span class="flex absolute right-2 bottom-2 justify-center items-center w-7 h-7 rounded-full text-white/95 bg-black/55 backdrop-blur-sm">
+ <IconLucideMonitor class="size-4" />
+ </span>
+ </button>
+ <div class="flex justify-end">
+ <EditorButton
+ onClick={importDesktopBackground}
+ disabled={importingDesktopBackground()}
+ leftIcon={<IconLucideMonitor />}
>
- {value}
- </KTabs.Trigger>
- </>
- )}
- </For>
- </KTabs.List>
- </KTabs>
- {/** End of Background Tabs */}
- <KRadioGroup
- value={
- project.background.source.type === "wallpaper"
- ? (selectedWallpaper()?.url ?? undefined)
- : undefined
- }
- onChange={(photoUrl) => {
- try {
- const wallpaper = wallpaperOptions().find(
- (w) => w.url === photoUrl,
- );
- if (!wallpaper) return;
+ {importingDesktopBackground()
+ ? "Importing..."
+ : "Re-import"}
+ </EditorButton>
+ </div>
+ </div>
+ )}
+ </Show>
+ </KTabs.Content>
+ <KTabs.Content value="wallpaper">
+ {/** Background Tabs */}
+ <KTabs class="overflow-hidden relative" value={backgroundTab()}>
+ <KTabs.List
+ ref={setBackgroundRef}
+ class="flex overflow-x-auto overscroll-contain relative z-10 flex-row gap-2 items-center mb-3 text-xs hide-scroll"
+ style={{
+ "-webkit-mask-image": `linear-gradient(to right, transparent, black ${
+ scrollX() > 0 ? "24px" : "0"
+ }, black calc(100% - ${
+ reachedEndOfScroll() ? "0px" : "24px"
+ }), transparent)`,
+
+ "mask-image": `linear-gradient(to right, transparent, black ${
+ scrollX() > 0 ? "24px" : "0"
+ }, black calc(100% - ${
+ reachedEndOfScroll() ? "0px" : "24px"
+ }), transparent);`,
+ }}
+ >
+ <For each={Object.entries(BACKGROUND_THEMES)}>
+ {([key, value]) => (
+ <>
+ <KTabs.Trigger
+ onClick={() =>
+ setBackgroundTab(
+ key as keyof typeof BACKGROUND_THEMES,
+ )
+ }
+ value={key}
- class="flex relative z-10 flex-1 justify-center items-center px-4 py-2 bg-transparent rounded-lg border transition-colors duration-200 text-gray-11 not-data-selected:hover:border-gray-7 data-selected:bg-gray-3 data-selected:border-gray-3 group data-selected:text-gray-12 disabled:opacity-50 focus:outline-hidden"
++ class="flex relative z-10 flex-1 justify-center items-center px-2.5 h-6 text-[12px] font-medium bg-transparent rounded-[7px] border-0 transition-colors duration-200 text-ed-text-2 not-data-selected:hover:text-ed-text-1 data-selected:bg-ed-ctl-hover group data-selected:text-ed-text-1 disabled:opacity-50 focus:outline-hidden"
+ >
+ {value}
+ </KTabs.Trigger>
+ </>
+ )}
+ </For>
+ </KTabs.List>
+ </KTabs>
+ {/** End of Background Tabs */}
+ <KRadioGroup
+ value={
+ project.background.source.type === "wallpaper"
+ ? (selectedWallpaper()?.url ?? undefined)
+ : undefined
+ }
+ onChange={(photoUrl) => {
+ try {
+ const wallpaper = wallpaperOptions().find(
+ (w) => w.url === photoUrl,
+ );
+ if (!wallpaper) return;
- // Get the raw path without any URL prefixes
+ // Get the raw path without any URL prefixes
- setWallpaperSource(wallpaper.rawPath);
+ setWallpaperSource(wallpaper.rawPath);
- ensureBackgroundPresentation();
- } catch (_err) {
- toast.error("Failed to set wallpaper");
- }
- }}
- class="grid grid-cols-7 gap-2 h-auto"
- >
+ ensureBackgroundPresentation();
+ } catch (_err) {
+ toast.error("Failed to set wallpaper");
+ }
+ }}
- class="grid grid-cols-7 gap-2 h-auto"
++ class="grid grid-cols-6 gap-1.5 h-auto"
+ >
+ <Show
+ when={!wallpapers.loading}
+ fallback={
- <div class="flex col-span-7 justify-center items-center h-32 text-gray-11">
++ <div class="flex col-span-6 justify-center items-center h-32 text-ed-text-2">
+ <div class="flex flex-col gap-2 items-center">
+ <div class="w-6 h-6 rounded-full border-2 animate-spin border-gray-5 border-t-blue-400" />
+ <span>Loading wallpapers...</span>
+ </div>
+ </div>
+ }
+ >
- <For each={filteredWallpapers().slice(0, 21)}>
++ <For each={filteredWallpapers().slice(0, 18)}>
+ {(photo) => (
+ <KRadioGroup.Item
+ value={photo.url}
- class="relative aspect-square group"
++ class="relative h-[34px] group"
+ >
+ <KRadioGroup.ItemInput class="peer" />
- <KRadioGroup.ItemControl class="overflow-hidden w-full h-full rounded-lg transition not-data-checked:ring-offset-1 not-data-checked:ring-offset-gray-200 not-data-checked:hover:ring-1 not-data-checked:hover:ring-gray-400 data-checked:ring-2 data-checked:ring-gray-500 data-checked:ring-offset-2 data-checked:ring-offset-gray-200">
++ <KRadioGroup.ItemControl class="overflow-hidden w-full h-full rounded-md transition not-data-checked:hover:ring-1 not-data-checked:hover:ring-ed-line-strong data-checked:ring-2 data-checked:ring-ed-accent data-checked:ring-offset-2 data-checked:ring-offset-ed-card">
+ <img
+ src={photo.thumbnailUrl}
+ loading="eager"
+ class="object-cover w-full h-full"
+ alt="Wallpaper option"
+ />
+ </KRadioGroup.ItemControl>
+ </KRadioGroup.Item>
+ )}
+ </For>
- <Collapsible class="col-span-7">
++ <Collapsible class="col-span-6">
+ <Collapsible.Content class="animate-in slide-in-from-top-2 fade-in">
- <div class="grid grid-cols-7 gap-2">
++ <div class="grid grid-cols-6 gap-1.5">
+ <For each={filteredWallpapers()}>
+ {(photo) => (
+ <KRadioGroup.Item
+ value={photo.url}
- class="relative aspect-square group"
++ class="relative h-[34px] group"
+ >
+ <KRadioGroup.ItemInput class="peer" />
- <KRadioGroup.ItemControl class="overflow-hidden w-full h-full rounded-lg border border-gray-5 data-checked:border-blue-9 data-checked:ring-2 data-checked:ring-blue-9 peer-focus-visible:border-2 peer-focus-visible:border-blue-9">
++ <KRadioGroup.ItemControl class="overflow-hidden w-full h-full rounded-md transition data-checked:ring-2 data-checked:ring-ed-accent data-checked:ring-offset-2 data-checked:ring-offset-ed-card">
+ <img
+ src={photo.thumbnailUrl}
+ alt="Wallpaper option"
+ class="object-cover w-full h-full"
+ loading="lazy"
+ />
+ </KRadioGroup.ItemControl>
+ </KRadioGroup.Item>
+ )}
+ </For>
+ </div>
+ </Collapsible.Content>
+ </Collapsible>
+ </Show>
+ </KRadioGroup>
+ </KTabs.Content>
+ <KTabs.Content value="image">
<Show
- when={!wallpapers.loading}
+ when={
+ project.background.source.type === "image" &&
+ project.background.source.path
+ }
fallback={
- <div class="flex col-span-7 justify-center items-center h-32 text-gray-11">
- <div class="flex flex-col gap-2 items-center">
- <div class="w-6 h-6 rounded-full border-2 animate-spin border-gray-5 border-t-blue-400" />
- <span>Loading wallpapers...</span>
- </div>
- </div>
+ <button
+ type="button"
+ onClick={() => fileInput.click()}
- class="p-6 bg-gray-2 text-[13px] w-full rounded-lg border border-gray-5 border-dashed flex flex-col items-center justify-center gap-2 hover:bg-gray-3 transition-colors duration-100"
++ class="p-6 bg-ed-card-2 text-[13px] w-full rounded-xl border border-ed-line-strong border-dashed flex flex-col items-center justify-center gap-2 hover:bg-ed-ctl transition-colors duration-100"
+ >
- <IconCapImage class="text-gray-11 size-6" />
- <span class="text-gray-12">
++ <IconCapImage class="text-ed-text-3 size-6" />
++ <span class="text-ed-text-1">
+ Click to select or drag and drop image
+ </span>
+ </button>
}
>
- <For each={filteredWallpapers().slice(0, 21)}>
- {(photo) => (
- <KRadioGroup.Item
- value={photo.url}
- class="relative aspect-square group"
- >
- <KRadioGroup.ItemInput class="peer" />
- <KRadioGroup.ItemControl class="overflow-hidden w-full h-full rounded-lg transition not-data-checked:ring-offset-1 not-data-checked:ring-offset-gray-200 not-data-checked:hover:ring-1 not-data-checked:hover:ring-gray-400 data-checked:ring-2 data-checked:ring-gray-500 data-checked:ring-offset-2 data-checked:ring-offset-gray-200">
- <img
- src={photo.thumbnailUrl}
- loading="eager"
- class="object-cover w-full h-full"
- alt="Wallpaper option"
- />
- </KRadioGroup.ItemControl>
- </KRadioGroup.Item>
- )}
- </For>
- <Collapsible class="col-span-7">
- <Collapsible.Content class="animate-in slide-in-from-top-2 fade-in">
- <div class="grid grid-cols-7 gap-2">
- <For each={filteredWallpapers()}>
- {(photo) => (
- <KRadioGroup.Item
- value={photo.url}
- class="relative aspect-square group"
- >
- <KRadioGroup.ItemInput class="peer" />
- <KRadioGroup.ItemControl class="overflow-hidden w-full h-full rounded-lg border border-gray-5 data-checked:border-blue-9 data-checked:ring-2 data-checked:ring-blue-9 peer-focus-visible:border-2 peer-focus-visible:border-blue-9">
- <img
- src={photo.thumbnailUrl}
- alt="Wallpaper option"
- class="object-cover w-full h-full"
- loading="lazy"
- />
- </KRadioGroup.ItemControl>
- </KRadioGroup.Item>
- )}
- </For>
+ {(source) => (
+ <div class="overflow-hidden relative w-full h-48 rounded-md border border-gray-3 group">
+ <img
+ src={convertFileSrc(source())}
+ class="object-cover w-full h-full"
+ alt="Selected background"
+ />
+ <div class="absolute top-2 right-2">
+ <button
+ type="button"
+ onClick={() =>
+ setProject("background", "source", {
+ type: "image",
+ path: null,
+ })
+ }
+ class="p-2 text-white rounded-full transition-colors bg-black/50 hover:bg-black/70"
+ >
+ <IconCapCircleX class="w-4 h-4" />
+ </button>
</div>
- </Collapsible.Content>
- </Collapsible>
- </Show>
- </KRadioGroup>
- </KTabs.Content>
- <KTabs.Content value="image">
- <Show
- when={
- project.background.source.type === "image" &&
- project.background.source.path
- }
- fallback={
- <button
- type="button"
- onClick={() => fileInput.click()}
- class="p-6 bg-gray-2 text-[13px] w-full rounded-lg border border-gray-5 border-dashed flex flex-col items-center justify-center gap-2 hover:bg-gray-3 transition-colors duration-100"
- >
- <IconCapImage class="text-gray-11 size-6" />
- <span class="text-gray-12">
- Click to select or drag and drop image
- </span>
- </button>
- }
- >
- {(source) => (
- <div class="overflow-hidden relative w-full h-48 rounded-md border border-gray-3 group">
- <img
- src={convertFileSrc(source())}
- class="object-cover w-full h-full"
- alt="Selected background"
- />
- <div class="absolute top-2 right-2">
- <button
- type="button"
- onClick={() =>
- setProject("background", "source", {
- type: "image",
- path: null,
- })
- }
- class="p-2 text-white rounded-full transition-colors bg-black/50 hover:bg-black/70"
- >
- <IconCapCircleX class="w-4 h-4" />
- </button>
</div>
- </div>
- )}
- </Show>
- <input
- type="file"
- ref={fileInput}
- class="hidden"
- accept={BACKGROUND_IMAGE_ACCEPT}
- onChange={async (e) => {
- const file = e.currentTarget.files?.[0];
- if (!file) return;
-
- const extension = getValidBackgroundImageExtension(file);
- if (!extension) {
- toast.error("Invalid image file type");
- return;
- }
+ )}
+ </Show>
+ <input
+ type="file"
+ ref={fileInput}
+ class="hidden"
+ accept={BACKGROUND_IMAGE_ACCEPT}
+ onChange={async (e) => {
+ const file = e.currentTarget.files?.[0];
+ if (!file) return;
+
+ const extension = getValidBackgroundImageExtension(file);
+ if (!extension) {
+ toast.error("Invalid image file type");
+ return;
+ }
- try {
- const fileName = `bg-${Date.now()}-${file.name}`;
- const arrayBuffer = await file.arrayBuffer();
- const uint8Array = new Uint8Array(arrayBuffer);
+ try {
+ const fileName = `bg-${Date.now()}-${file.name}`;
+ const arrayBuffer = await file.arrayBuffer();
+ const uint8Array = new Uint8Array(arrayBuffer);
- const fullPath = `${await appDataDir()}/${fileName}`;
+ const fullPath = `${await appDataDir()}/${fileName}`;
- await writeFile(fileName, uint8Array, {
- baseDir: BaseDirectory.AppData,
- });
+ await writeFile(fileName, uint8Array, {
+ baseDir: BaseDirectory.AppData,
+ });
- setProject("background", "source", {
- type: "image",
- path: fullPath,
- });
- } catch (_err) {
- toast.error("Failed to save image");
+ setProject("background", "source", {
+ type: "image",
+ path: fullPath,
+ });
+ } catch (_err) {
+ toast.error("Failed to save image");
+ }
+ }}
+ />
+ </KTabs.Content>
+ <KTabs.Content value="color">
+ <Show
+ when={
+ project.background.source.type === "color" &&
+ project.background.source
}
- }}
- />
- </KTabs.Content>
- <KTabs.Content value="color">
- <Show
- when={
- project.background.source.type === "color" &&
- project.background.source
- }
- >
- <div class="flex flex-col flex-wrap gap-3">
- <div class="flex flex-col gap-2">
- <RgbInput
- value={
- project.background.source.type === "color"
- ? project.background.source.value
- : [0, 0, 0]
- }
- onChange={(value) => {
- setProject("background", "source", {
- type: "color",
- value,
- });
- }}
- />
- <BrandColorsDropdown
- swatches={props.brandColorSwatches}
- onSelect={setColorBackgroundSource}
- />
- </div>
+ >
+ <div class="flex flex-col flex-wrap gap-3">
+ <div class="flex flex-col gap-2">
+ <RgbInput
+ value={
+ project.background.source.type === "color"
+ ? project.background.source.value
+ : [0, 0, 0]
+ }
+ onChange={(value) => {
+ setProject("background", "source", {
+ type: "color",
+ value,
+ });
+ }}
+ />
+ <BrandColorsDropdown
+ swatches={props.brandColorSwatches}
+ onSelect={setColorBackgroundSource}
+ />
+ </div>
- <div class="flex flex-wrap gap-2">
- <For each={BACKGROUND_COLORS}>
- {(color) => (
- <label class="relative">
- <input
- type="radio"
- class="sr-only peer"
- name="colorPicker"
- onChange={(e) => {
- if (!e.target.checked) return;
-
- const rgbValue = hexToRgb(color);
- if (!rgbValue) return;
-
- const [r, g, b, a] = rgbValue;
- colorBackground = {
- type: "color",
- value: [r, g, b],
- alpha: a,
- };
-
- setProject("background", "source", colorBackground);
- }}
- />
- <div
- class="rounded-lg transition-all duration-200 size-8 hover:peer-checked:opacity-100 peer-hover:opacity-70 peer-checked:ring-2 peer-checked:ring-gray-500 peer-checked:ring-offset-2 peer-checked:ring-offset-gray-200"
- style={{
- background:
- color === "#00000000"
- ? CHECKERED_BUTTON_BACKGROUND
- : color,
- }}
- />
- </label>
- )}
- </For>
- </div>
- {/* <Tooltip content="Add custom color">
+ <div class="flex flex-wrap gap-2">
+ <For each={BACKGROUND_COLORS}>
+ {(color) => (
+ <label class="relative">
+ <input
+ type="radio"
+ class="sr-only peer"
+ name="colorPicker"
+ onChange={(e) => {
+ if (!e.target.checked) return;
+
+ const rgbValue = hexToRgb(color);
+ if (!rgbValue) return;
+
+ const [r, g, b, a] = rgbValue;
+ colorBackground = {
+ type: "color",
+ value: [r, g, b],
+ alpha: a,
+ };
+
+ setProject(
+ "background",
+ "source",
+ colorBackground,
+ );
+ }}
+ />
+ <div
- class="rounded-lg transition-all duration-200 size-8 hover:peer-checked:opacity-100 peer-hover:opacity-70 peer-checked:ring-2 peer-checked:ring-gray-500 peer-checked:ring-offset-2 peer-checked:ring-offset-gray-200"
++ class="rounded-lg transition-all duration-200 size-8 hover:peer-checked:opacity-100 peer-hover:opacity-70 peer-checked:ring-2 peer-checked:ring-ed-accent peer-checked:ring-offset-2 peer-checked:ring-offset-ed-card"
+ style={{
+ background:
+ color === "#00000000"
+ ? CHECKERED_BUTTON_BACKGROUND
+ : color,
+ }}
+ />
+ </label>
+ )}
+ </For>
+ </div>
+ {/* <Tooltip content="Add custom color">
<button
class="flex justify-center items-center w-6 h-6 rounded-lg border border-gray-400 border-dashed text-gray-12 hover:border-gray-500"
onClick={() => {
@@@ -2795,185 -2723,154 +2733,205 @@@
+
</button>
</Tooltip> */}
- </div>
- </Show>
- </KTabs.Content>
- <KTabs.Content value="gradient">
- <GradientEditor brandColorSwatches={props.brandColorSwatches} />
- </KTabs.Content>
- <KTabs.Content value="animatedGradient">
- <AnimatedGradientEditor
- brandColorSwatches={props.brandColorSwatches}
- />
- </KTabs.Content>
- </KTabs>
- </Field>
+ </div>
+ </Show>
+ </KTabs.Content>
+ <KTabs.Content value="gradient">
+ <GradientEditor brandColorSwatches={props.brandColorSwatches} />
+ </KTabs.Content>
+ <KTabs.Content value="animatedGradient">
+ <AnimatedGradientEditor
+ brandColorSwatches={props.brandColorSwatches}
+ />
+ </KTabs.Content>
+ </KTabs>
- </Field>
++ </Section>
- <Field name="Background Blur" icon={<IconCapBgBlur />}>
- <Field name="Background Blur" icon={<IconCapBgBlur />}>
- <Slider
- value={[project.background.blur]}
- onChange={(v) => setProject("background", "blur", v[0])}
- minValue={0}
- maxValue={100}
- step={0.1}
- formatTooltip="%"
- />
- </Field>
- {/** Dashed divider */}
- <div class="w-full border-t border-gray-300 border-dashed" />
- <Field name="Padding" icon={<IconCapPadding class="size-4" />}>
- <Slider
- value={[project.background.padding]}
- onChange={(v) => setBackgroundDimension("padding", v[0])}
- minValue={0}
- maxValue={40}
- step={0.1}
- formatTooltip="%"
- />
++ <div class="w-full border-t border-ed-line" />
++ <SectionLabel name="Layout" />
++ <Field
++ inline
++ name="Blur"
++ value={`${project.background.blur.toFixed(1)}%`}
++ >
+ <Slider
+ value={[project.background.blur]}
+ onChange={(v) => setProject("background", "blur", v[0])}
+ minValue={0}
+ maxValue={100}
+ step={0.1}
+ formatTooltip="%"
+ />
+ </Field>
- {/** Dashed divider */}
- <div class="w-full border-t border-gray-300 border-dashed" />
- <Field name="Padding" icon={<IconCapPadding class="size-4" />}>
++ <Field
++ inline
++ name="Padding"
++ value={`${project.background.padding.toFixed(1)}%`}
++ >
+ <Slider
+ value={[project.background.padding]}
+ onChange={(v) => setBackgroundDimension("padding", v[0])}
+ minValue={0}
+ maxValue={40}
+ step={0.1}
+ formatTooltip="%"
+ />
- <Show when={project.background.displayPosition}>
- <div class="flex justify-between items-center mt-3">
- <span class="text-xs text-gray-11">
- Custom screen position (dragged on canvas)
- </span>
- <EditorButton
- onClick={() =>
- setProject("background", "displayPosition", null)
- }
- >
- Reset
- </EditorButton>
- </div>
- </Show>
+ </Field>
- <Field name="Rounded Corners" icon={<IconCapCorners class="size-4" />}>
- <div class="flex flex-col gap-3">
- <Slider
- value={[project.background.rounding]}
- onChange={(v) => setBackgroundDimension("rounding", v[0])}
- minValue={0}
- maxValue={100}
- step={0.1}
- formatTooltip="%"
- />
- <CornerStyleSelect
- label="Corner Style"
- value={project.background.roundingType}
- onChange={(value) =>
- setProject("background", "roundingType", value)
- }
- />
+ <Show when={project.background.displayPosition}>
- <div class="flex justify-between items-center mt-3">
- <span class="text-xs text-gray-11">
++ <div class="flex gap-2 justify-between items-center">
++ <span class="text-[11px] text-ed-text-3">
+ Custom screen position (dragged on canvas)
+ </span>
+ <EditorButton
++ size="sm"
+ onClick={() => setProject("background", "displayPosition", null)}
+ >
+ Reset
+ </EditorButton>
</div>
+ </Show>
- </Field>
- <Field name="Rounded Corners" icon={<IconCapCorners class="size-4" />}>
- <div class="flex flex-col gap-3">
++ <Field
++ inline
++ name="Corners"
++ value={`${project.background.rounding.toFixed(1)}%`}
++ >
+ <Slider
- value={[project.background.rounding]}
- onChange={(v) => setBackgroundDimension("rounding", v[0])}
++ value={[project.background.blur]}
++ onChange={(v) => setProject("background", "blur", v[0])}
+ minValue={0}
+ maxValue={100}
+ step={0.1}
+ formatTooltip="%"
+ />
++ </Field>
++ <Field inline name="Corner Style">
+ <CornerStyleSelect
- label="Corner Style"
+ value={project.background.roundingType}
+ onChange={(value) =>
+ setProject("background", "roundingType", value)
+ }
+ />
- </div>
- </Field>
- <Field name="Motion Blur" icon={<IconLucideWind class="size-4" />}>
- <Slider
- value={[
- project.screenMotionBlur ??
- project.cursor.motionBlur ??
- DEFAULT_MOTION_BLUR,
- ]}
- onChange={(v) => {
- const value = v[0] ?? 0;
- batch(() => {
- setProject("cursor", "motionBlur", value);
- setProject("screenMotionBlur", value);
- });
- }}
- minValue={0}
- maxValue={1}
- step={0.01}
- formatTooltip={(value) => `${Math.round(value * 100)}%`}
- />
- </Field>
- <Field
- name="Border"
- icon={<IconCapSettings class="size-4" />}
- value={
+ </Field>
+ <Show when={!selectedStyle()}>
- <Field name="Motion Blur" icon={<IconLucideWind class="size-4" />}>
++ <Field
++ inline
++ name="Motion Blur"
++ value={`${Math.round(
++ (project.screenMotionBlur ??
++ project.cursor.motionBlur ??
++ DEFAULT_MOTION_BLUR) * 100,
++ )}%`}
++ >
+ <Slider
+ value={[
+ project.screenMotionBlur ??
+ project.cursor.motionBlur ??
+ DEFAULT_MOTION_BLUR,
+ ]}
+ onChange={(v) => {
+ const value = v[0] ?? 0;
+ batch(() => {
+ setProject("cursor", "motionBlur", value);
+ setProject("screenMotionBlur", value);
+ });
+ }}
+ minValue={0}
+ maxValue={1}
+ step={0.01}
+ formatTooltip={(value) => `${Math.round(value * 100)}%`}
+ />
+ </Field>
+ </Show>
- <Field
- name="Border"
- icon={<IconCapSettings class="size-4" />}
- value={
- <Toggle
- checked={project.background.border?.enabled ?? false}
- onChange={(enabled) => {
- const prev = project.background.border ?? {
- enabled: false,
- width: 5.0,
- color: [0, 0, 0],
- opacity: 50.0,
- };
-
- if (props.scrollRef && enabled) {
- setTimeout(
- () =>
- props.scrollRef.scrollTo({
- top: props.scrollRef.scrollHeight,
- behavior: "smooth",
- }),
- 100,
- );
- }
++ <Field inline name="Border">
+ <Toggle
+ checked={project.background.border?.enabled ?? false}
+ onChange={(enabled) => {
+ const prev = project.background.border ?? {
+ enabled: false,
+ width: 5.0,
+ color: [0, 0, 0],
+ opacity: 50.0,
+ };
+
+ if (props.scrollRef && enabled) {
+ setTimeout(
+ () =>
+ props.scrollRef.scrollTo({
+ top: props.scrollRef.scrollHeight,
+ behavior: "smooth",
+ }),
+ 100,
+ );
+ }
- setProject("background", "border", {
- ...prev,
- enabled,
- });
- }}
- />
- }
- />
+ setProject("background", "border", {
+ ...prev,
+ enabled,
+ });
+ }}
+ />
- }
- />
- <KCollapsible open={project.background.border?.enabled ?? false}>
- <KCollapsible.Content class="overflow-hidden opacity-0 transition-opacity animate-collapsible-up data-expanded:animate-collapsible-down data-expanded:opacity-100">
- <div class="flex flex-col gap-6 pb-6">
- <Field name="Border Width" icon={<IconCapEnlarge class="size-4" />}>
- <Slider
- value={[project.background.border?.width ?? 5.0]}
- onChange={(v) =>
- setProject("background", "border", {
- ...(project.background.border ?? {
- enabled: true,
- width: 5.0,
- color: [0, 0, 0],
- opacity: 50.0,
- }),
- width: v[0],
- })
- }
- minValue={1}
- maxValue={20}
- step={0.1}
- formatTooltip="px"
- />
- </Field>
- <Field name="Border Color" icon={<IconCapImage class="size-4" />}>
- <div class="flex flex-col gap-2">
- <RgbInput
- value={project.background.border?.color ?? [0, 0, 0]}
- onChange={(color) =>
++ </Field>
+ <KCollapsible open={project.background.border?.enabled ?? false}>
+ <KCollapsible.Content class="overflow-hidden opacity-0 transition-opacity animate-collapsible-up data-expanded:animate-collapsible-down data-expanded:opacity-100">
- <div class="flex flex-col gap-6 pb-6">
++ <div class="flex flex-col gap-2 pb-4">
+ <Field
++ inline
+ name="Border Width"
- icon={<IconCapEnlarge class="size-4" />}
++ value={`${(project.background.border?.width ?? 5).toFixed(
++ 1,
++ )}px`}
+ >
+ <Slider
+ value={[project.background.border?.width ?? 5.0]}
+ onChange={(v) =>
+ setProject("background", "border", {
+ ...(project.background.border ?? {
+ enabled: true,
+ width: 5.0,
+ color: [0, 0, 0],
+ opacity: 50.0,
+ }),
+ width: v[0],
+ })
+ }
+ minValue={1}
+ maxValue={20}
+ step={0.1}
+ formatTooltip="px"
+ />
+ </Field>
- <Field name="Border Color" icon={<IconCapImage class="size-4" />}>
++ <Field name="Border Color">
+ <div class="flex flex-col gap-2">
+ <RgbInput
+ value={project.background.border?.color ?? [0, 0, 0]}
+ onChange={(color) =>
+ setProject("background", "border", {
+ ...(project.background.border ?? {
+ enabled: true,
+ width: 5.0,
+ color: [0, 0, 0],
+ opacity: 50.0,
+ }),
+ color,
+ })
+ }
+ />
+ <BrandColorsDropdown
+ swatches={props.brandColorSwatches}
+ onSelect={setBackgroundBorderColor}
+ />
+ </div>
+ </Field>
+ <Field
++ inline
+ name="Border Opacity"
- icon={<IconCapShadow class="size-4" />}
++ value={`${(project.background.border?.opacity ?? 50).toFixed(
++ 1,
++ )}%`}
+ >
+ <Slider
+ value={[project.background.border?.opacity ?? 50.0]}
+ onChange={(v) =>
setProject("background", "border", {
...(project.background.border ?? {
enabled: true,
@@@ -2981,172 -2878,194 +2939,179 @@@
color: [0, 0, 0],
opacity: 50.0,
}),
- color,
+ opacity: v[0],
})
}
+ minValue={0}
+ maxValue={100}
+ step={0.1}
+ formatTooltip="%"
/>
- <BrandColorsDropdown
- swatches={props.brandColorSwatches}
- onSelect={setBackgroundBorderColor}
- />
- </div>
- </Field>
- <Field
- name="Border Opacity"
- icon={<IconCapShadow class="size-4" />}
- >
- <Slider
- value={[project.background.border?.opacity ?? 50.0]}
- onChange={(v) =>
- setProject("background", "border", {
- ...(project.background.border ?? {
- enabled: true,
- width: 5.0,
- color: [0, 0, 0],
- opacity: 50.0,
- }),
- opacity: v[0],
- })
- }
- minValue={0}
- maxValue={100}
- step={0.1}
- formatTooltip="%"
- />
- </Field>
- </div>
- </KCollapsible.Content>
- </KCollapsible>
- <Field
- name="MacBook notch"
- icon={<IconLucideLaptop class="size-4" />}
- value={
+ </Field>
+ </div>
+ </KCollapsible.Content>
+ </KCollapsible>
- <Field
- name="MacBook notch"
- icon={<IconLucideLaptop class="size-4" />}
- value={
- <Toggle
- checked={project.background.notch?.enabled ?? false}
- onChange={(enabled) =>
- setProject("background", "notch", {
- ...(project.background.notch ?? UNPLACED_NOTCH),
- enabled,
- })
- }
- />
- }
- />
++ <Field inline name="MacBook notch">
+ <Toggle
+ checked={project.background.notch?.enabled ?? false}
+ onChange={(enabled) =>
+ setProject("background", "notch", {
+ ...(project.background.notch ?? UNPLACED_NOTCH),
+ enabled,
+ })
+ }
+ />
- }
- />
- <KCollapsible open={project.background.notch?.enabled ?? false}>
- <KCollapsible.Content class="overflow-hidden opacity-0 transition-opacity animate-collapsible-up data-expanded:animate-collapsible-down data-expanded:opacity-100">
- <div class="flex flex-col gap-6 pb-6">
- <p class="text-xs text-gray-11">
- Draws a MacBook notch over the recording. Recordings made on a Mac
- with a notch use their own measurements; otherwise start from the
- size below and adjust to match.
- </p>
- <For
- each={
- [
- { key: "width", name: "Notch Width", max: 0.4 },
- { key: "height", name: "Notch Height", max: 0.15 },
- { key: "x", name: "Notch Position", max: 1 },
- ] as const
- }
- >
- {(field) => (
- <Field
- name={field.name}
- icon={<IconCapEnlarge class="size-4" />}
- >
- <Slider
- value={[
- field.key === "x"
- ? Math.min(
- project.background.notch?.x ??
- editorInstance.notchBase.x,
- notchXMax(),
- )
- : (project.background.notch?.[field.key] ??
- editorInstance.notchBase[field.key]),
- ]}
- onChange={(v) => {
- const base = editorInstance.notchBase;
- const prev = project.background.notch ?? UNPLACED_NOTCH;
- const next: NotchConfiguration = {
- ...prev,
- enabled: true,
- };
- if (field.key === "x") {
- next.x = Math.min(v[0], notchXMax());
- } else {
- next[field.key] = v[0];
- }
++ </Field>
+ <KCollapsible open={project.background.notch?.enabled ?? false}>
+ <KCollapsible.Content class="overflow-hidden opacity-0 transition-opacity animate-collapsible-up data-expanded:animate-collapsible-down data-expanded:opacity-100">
- <div class="flex flex-col gap-6 pb-6">
- <p class="text-xs text-gray-11">
++ <div class="flex flex-col gap-2 pb-4">
++ <p class="text-[11px] text-ed-text-3">
+ Draws a MacBook notch over the recording. Recordings made on a
+ Mac with a notch use their own measurements; otherwise start
+ from the size below and adjust to match.
+ </p>
+ <For
+ each={
+ [
+ { key: "width", name: "Notch Width", max: 0.4 },
+ { key: "height", name: "Notch Height", max: 0.15 },
+ { key: "x", name: "Notch Position", max: 1 },
+ ] as const
+ }
+ >
- {(field) => (
- <Field
- name={field.name}
- icon={<IconCapEnlarge class="size-4" />}
- >
- <Slider
- value={[
- field.key === "x"
- ? Math.min(
- project.background.notch?.x ??
- editorInstance.notchBase.x,
- notchXMax(),
- )
- : (project.background.notch?.[field.key] ??
- editorInstance.notchBase[field.key]),
- ]}
- onChange={(v) => {
- const base = editorInstance.notchBase;
- const prev = project.background.notch ?? UNPLACED_NOTCH;
- const next: NotchConfiguration = {
- ...prev,
- enabled: true,
- };
- if (field.key === "x") {
- next.x = Math.min(v[0], notchXMax());
- } else {
- next[field.key] = v[0];
- }
++ {(field) => {
++ const notchValue = () =>
++ field.key === "x"
++ ? Math.min(
++ project.background.notch?.x ??
++ editorInstance.notchBase.x,
++ notchXMax(),
++ )
++ : (project.background.notch?.[field.key] ??
++ editorInstance.notchBase[field.key]);
- if (field.key === "width") {
- // Resize about the centre rather than dragging the
- // left edge along with the width.
- const centre =
- (prev.x ?? base.x) + (prev.width ?? base.width) / 2;
- next.x = Math.min(
- Math.max(centre - v[0] / 2, 0),
- 1 - v[0],
- );
- }
- if (field.key === "width") {
- // Resize about the centre rather than dragging the
- // left edge along with the width.
- const centre =
- (prev.x ?? base.x) + (prev.width ?? base.width) / 2;
- next.x = Math.min(
- Math.max(centre - v[0] / 2, 0),
- 1 - v[0],
- );
- }
++ return (
++ <Field
++ inline
++ name={field.name}
++ value={`${(notchValue() * 100).toFixed(1)}%`}
++ >
++ <Slider
++ value={[notchValue()]}
++ onChange={(v) => {
++ const base = editorInstance.notchBase;
++ const prev =
++ project.background.notch ?? UNPLACED_NOTCH;
++ const next: NotchConfiguration = {
++ ...prev,
++ enabled: true,
++ };
++ if (field.key === "x") {
++ next.x = Math.min(v[0], notchXMax());
++ } else {
++ next[field.key] = v[0];
++ }
- setProject("background", "notch", next);
- }}
- minValue={0}
- maxValue={field.key === "x" ? notchXMax() : field.max}
- step={0.001}
- formatTooltip={(value) => `${(value * 100).toFixed(1)}%`}
- />
- </Field>
- )}
- setProject("background", "notch", next);
- }}
- minValue={0}
- maxValue={field.key === "x" ? notchXMax() : field.max}
- step={0.001}
- formatTooltip={(value) => `${(value * 100).toFixed(1)}%`}
- />
- </Field>
- )}
- </For>
- </div>
- </KCollapsible.Content>
- </KCollapsible>
- <Field name="Shadow" icon={<IconCapShadow class="size-4" />}>
- <Slider
- value={[project.background.shadow ?? 0]}
- onChange={(v) => {
- batch(() => {
- setProject("background", "shadow", v[0]);
- // Initialize advanced shadow settings if they don't exist and shadow is enabled
- if (v[0] > 0 && !project.background.advancedShadow) {
- setProject("background", "advancedShadow", {
- size: 50,
- opacity: 18,
- blur: 50,
- });
- }
- });
- }}
- minValue={0}
- maxValue={100}
- step={0.1}
- formatTooltip="%"
- />
++ if (field.key === "width") {
++ // Resize about the centre rather than dragging the
++ // left edge along with the width.
++ const centre =
++ (prev.x ?? base.x) +
++ (prev.width ?? base.width) / 2;
++ next.x = Math.min(
++ Math.max(centre - v[0] / 2, 0),
++ 1 - v[0],
++ );
++ }
+
++ setProject("background", "notch", next);
++ }}
++ minValue={0}
++ maxValue={field.key === "x" ? notchXMax() : field.max}
++ step={0.001}
++ formatTooltip={(value) =>
++ `${(value * 100).toFixed(1)}%`
++ }
++ />
++ </Field>
++ );
++ }}
+ </For>
+ </div>
+ </KCollapsible.Content>
+ </KCollapsible>
- <Field name="Shadow" icon={<IconCapShadow class="size-4" />}>
++ <Field
++ inline
++ name="Shadow"
++ value={`${(project.background.shadow ?? 0).toFixed(1)}%`}
++ >
+ <Slider
+ value={[project.background.shadow ?? 0]}
+ onChange={(v) => {
+ batch(() => {
+ setProject("background", "shadow", v[0]);
+ // Initialize advanced shadow settings if they don't exist and shadow is enabled
+ if (v[0] > 0 && !project.background.advancedShadow) {
+ setProject("background", "advancedShadow", {
+ size: 50,
+ opacity: 18,
+ blur: 50,
+ });
+ }
+ });
+ }}
+ minValue={0}
+ maxValue={100}
+ step={0.1}
+ formatTooltip="%"
+ />
-
- <ShadowSettings
- scrollRef={props.scrollRef}
- size={{
- value: [project.background.advancedShadow?.size ?? 50],
- onChange: (v) => {
- setProject("background", "advancedShadow", {
- ...(project.background.advancedShadow ?? {
- size: 50,
- opacity: 18,
- blur: 50,
- }),
- size: v[0],
- });
- },
- }}
- opacity={{
- value: [project.background.advancedShadow?.opacity ?? 18],
- onChange: (v) => {
- setProject("background", "advancedShadow", {
- ...(project.background.advancedShadow ?? {
- size: 50,
- opacity: 18,
- blur: 50,
- }),
- opacity: v[0],
- });
- },
- }}
- blur={{
- value: [project.background.advancedShadow?.blur ?? 50],
- onChange: (v) => {
- setProject("background", "advancedShadow", {
- ...(project.background.advancedShadow ?? {
- size: 50,
- opacity: 18,
- blur: 50,
- }),
- blur: v[0],
- });
- },
- }}
- />
+ </Field>
+ <ShadowSettings
+ scrollRef={props.scrollRef}
+ size={{
+ value: [project.background.advancedShadow?.size ?? 50],
+ onChange: (v) => {
+ setProject("background", "advancedShadow", {
+ ...(project.background.advancedShadow ?? {
+ size: 50,
+ opacity: 18,
+ blur: 50,
+ }),
+ size: v[0],
+ });
+ },
+ }}
+ opacity={{
+ value: [project.background.advancedShadow?.opacity ?? 18],
+ onChange: (v) => {
+ setProject("background", "advancedShadow", {
+ ...(project.background.advancedShadow ?? {
+ size: 50,
+ opacity: 18,
+ blur: 50,
+ }),
+ opacity: v[0],
+ });
+ },
+ }}
+ blur={{
+ value: [project.background.advancedShadow?.blur ?? 50],
+ onChange: (v) => {
+ setProject("background", "advancedShadow", {
+ ...(project.background.advancedShadow ?? {
+ size: 50,
+ opacity: 18,
+ blur: 50,
+ }),
+ blur: v[0],
+ });
+ },
+ }}
+ />
- </Field>
- <ColorCorrectionSection target="screen" scrollRef={props.scrollRef} />
- {/* <ComingSoonTooltip>
+ <Show when={!selectedStyle()}>
+ <ColorCorrectionSection target="screen" scrollRef={props.scrollRef} />
+ </Show>
+ {/* <ComingSoonTooltip>
<Field name="Inset" icon={<IconCapInset />}>
<Slider
disabled
@@@ -3175,339 -3093,332 +3140,349 @@@ function CameraConfig(props: { scrollRe
return (
<KTabs.Content
value={TAB_IDS.camera}
-- class="flex flex-col flex-1 gap-6 p-4 min-h-0"
++ class="flex flex-col flex-1 gap-3.5 pt-3.5 px-4 pb-4 min-h-0"
>
- <Field icon={<IconCapCamera class="size-4" />} name="Camera">
- <div class="flex flex-col gap-6">
- <div>
- <Subfield name="Position" />
- <KRadioGroup
- value={cameraPositionValue()}
- onChange={(v) => {
- const [x, y] = v.split(":");
- const xPosition = CAMERA_X_POSITIONS.find(
- (position) => position === x,
- );
- const yPosition = CAMERA_Y_POSITIONS.find(
- (position) => position === y,
- );
- if (!xPosition || !yPosition) return;
- batch(() => {
- setProject("camera", "position", {
- x: xPosition,
- y: yPosition,
- });
- setProject("camera", "manualPosition", null);
- });
- }}
- class="mt-3 rounded-lg border border-gray-3 bg-gray-2 w-full h-30 relative"
- >
- <For
- each={[
- { x: "left", y: "top" } as const,
- { x: "center", y: "top" } as const,
- { x: "right", y: "top" } as const,
- { x: "left", y: "bottom" } as const,
- { x: "center", y: "bottom" } as const,
- { x: "right", y: "bottom" } as const,
- ]}
- >
- {(item) => {
- const itemValue = `${item.x}:${item.y}`;
- const selected = () => cameraPositionValue() === itemValue;
- return (
- <RadioGroup.Item value={itemValue}>
- <RadioGroup.ItemInput class="peer" />
- <RadioGroup.ItemControl
- class={cx(
- "size-6 shrink-0 rounded-md absolute flex justify-center items-center focus-visible:outline-solid focus-visible:outline-2 focus-visible:outline-blue-9 focus-visible:outline-offset-2 peer-focus-visible:outline-solid peer-focus-visible:outline-2 peer-focus-visible:outline-blue-9 peer-focus-visible:outline-offset-2 transition-colors duration-100",
- selected() ? "bg-blue-9" : "bg-gray-5",
- item.x === "left"
- ? "left-2"
- : item.x === "right"
- ? "right-2"
- : "left-1/2 transform -translate-x-1/2",
- item.y === "top" ? "top-2" : "bottom-2",
- )}
- >
- <div class="size-2 shrink-0 bg-solid-white rounded-full" />
- </RadioGroup.ItemControl>
- </RadioGroup.Item>
+ <StyleGroupToggle group="camera" />
+ <Show
+ when={!selectedStyle() || selectedStyle()?.overrides.camera != null}
+ >
- <Field icon={<IconCapCamera class="size-4" />} name="Camera">
- <div class="flex flex-col gap-6">
++ <Section name="Camera">
++ <div class="flex flex-col gap-2">
+ <div>
+ <Subfield name="Position" />
+ <KRadioGroup
+ value={cameraPositionValue()}
+ onChange={(v) => {
+ const [x, y] = v.split(":");
+ const xPosition = CAMERA_X_POSITIONS.find(
+ (position) => position === x,
);
- }}
- </For>
- </KRadioGroup>
- <Show when={project.camera.manualPosition}>
- <div class="flex justify-between items-center mt-3">
- <span class="text-xs text-gray-11">
- Custom position (dragged on canvas)
- </span>
- <EditorButton
- onClick={() => setProject("camera", "manualPosition", null)}
- >
- Reset
- </EditorButton>
- </div>
- </Show>
- </div>
- <Subfield name="Hide Camera">
- <Toggle
- checked={project.camera.hide}
- onChange={(hide) => setProject("camera", "hide", hide)}
- />
- </Subfield>
- <Subfield name="Mirror Camera">
- <Toggle
- checked={project.camera.mirror}
- onChange={(mirror) => setProject("camera", "mirror", mirror)}
- />
- </Subfield>
- <Subfield name="Background Blur">
- <KSelect<{ name: string; value: BackgroundBlurMode }>
- options={[
- { name: "Off", value: "off" },
- { name: "Light Blur", value: "light" },
- { name: "Heavy Blur", value: "heavy" },
- ]}
- optionValue="value"
- optionTextValue="name"
- value={
- (
- [
- { name: "Off", value: "off" },
- { name: "Light Blur", value: "light" },
- { name: "Heavy Blur", value: "heavy" },
- ] as const
- ).find(
- (v) =>
- v.value === (project.camera.backgroundBlur?.mode ?? "off"),
- ) ?? { name: "Off", value: "off" }
- }
- onChange={(v) => {
- if (v)
- setProject("camera", "backgroundBlur", {
- mode: v.value,
+ const yPosition = CAMERA_Y_POSITIONS.find(
+ (position) => position === y,
+ );
+ if (!xPosition || !yPosition) return;
+ batch(() => {
+ setProject("camera", "position", {
+ x: xPosition,
+ y: yPosition,
+ });
+ setProject("camera", "manualPosition", null);
});
- }}
- disallowEmptySelection
- itemComponent={(props) => (
- <MenuItem<typeof KSelect.Item>
- as={KSelect.Item}
- item={props.item}
- >
- <KSelect.ItemLabel class="flex-1">
- {props.item.rawValue.name}
- </KSelect.ItemLabel>
- </MenuItem>
- )}
- >
- <KSelect.Trigger class="flex flex-row gap-2 items-center px-2 w-full h-8 rounded-lg transition-colors bg-gray-3 disabled:text-gray-11">
- <KSelect.Value<{
- name: string;
- value: string;
- }> class="flex-1 text-sm text-left truncate text-(--gray-500) font-normal">
- {(state) => <span>{state.selectedOption().name}</span>}
- </KSelect.Value>
- <KSelect.Icon<ValidComponent>
- as={(iconProps) => (
- <IconCapChevronDown
- {...iconProps}
- class="size-4 shrink-0 transform transition-transform data-expanded:rotate-180 text-(--gray-500)"
- />
- )}
- />
- </KSelect.Trigger>
- <KSelect.Portal>
- <PopperContent<typeof KSelect.Content>
- as={KSelect.Content}
- class={cx(topSlideAnimateClasses, "z-50")}
+ }}
- class="mt-3 rounded-lg border border-gray-3 bg-gray-2 w-full h-30 relative"
++ class="mt-1 rounded-xl bg-ed-card-2 w-full h-30 relative"
+ >
+ <For
+ each={[
+ { x: "left", y: "top" } as const,
+ { x: "center", y: "top" } as const,
+ { x: "right", y: "top" } as const,
+ { x: "left", y: "bottom" } as const,
+ { x: "center", y: "bottom" } as const,
+ { x: "right", y: "bottom" } as const,
+ ]}
>
- <MenuItemList<typeof KSelect.Listbox>
- class="overflow-y-auto max-h-32"
- as={KSelect.Listbox}
+ {(item) => {
+ const itemValue = `${item.x}:${item.y}`;
+ const selected = () => cameraPositionValue() === itemValue;
+ return (
+ <RadioGroup.Item value={itemValue}>
+ <RadioGroup.ItemInput class="peer" />
+ <RadioGroup.ItemControl
+ class={cx(
+ "size-6 shrink-0 rounded-md absolute flex justify-center items-center focus-visible:outline-solid focus-visible:outline-2 focus-visible:outline-blue-9 focus-visible:outline-offset-2 peer-focus-visible:outline-solid peer-focus-visible:outline-2 peer-focus-visible:outline-blue-9 peer-focus-visible:outline-offset-2 transition-colors duration-100",
- selected() ? "bg-blue-9" : "bg-gray-5",
++ selected() ? "bg-ed-accent" : "bg-ed-ctl-active",
+ item.x === "left"
+ ? "left-2"
+ : item.x === "right"
+ ? "right-2"
+ : "left-1/2 transform -translate-x-1/2",
+ item.y === "top" ? "top-2" : "bottom-2",
+ )}
+ >
+ <div class="size-2 shrink-0 bg-solid-white rounded-full" />
+ </RadioGroup.ItemControl>
+ </RadioGroup.Item>
+ );
+ }}
+ </For>
+ </KRadioGroup>
+ <Show when={project.camera.manualPosition}>
+ <div class="flex justify-between items-center mt-3">
- <span class="text-xs text-gray-11">
++ <span class="text-[11px] text-ed-text-3">
+ Custom position (dragged on canvas)
+ </span>
+ <EditorButton
+ onClick={() => setProject("camera", "manualPosition", null)}
+ >
+ Reset
+ </EditorButton>
+ </div>
+ </Show>
+ </div>
+ <Subfield name="Hide Camera">
+ <Toggle
+ checked={project.camera.hide}
+ onChange={(hide) => setProject("camera", "hide", hide)}
+ />
+ </Subfield>
+ <Subfield name="Mirror Camera">
+ <Toggle
+ checked={project.camera.mirror}
+ onChange={(mirror) => setProject("camera", "mirror", mirror)}
+ />
+ </Subfield>
+ <Subfield name="Background Blur">
+ <KSelect<{ name: string; value: BackgroundBlurMode }>
+ options={[
+ { name: "Off", value: "off" },
+ { name: "Light Blur", value: "light" },
+ { name: "Heavy Blur", value: "heavy" },
+ ]}
+ optionValue="value"
+ optionTextValue="name"
+ value={
+ (
+ [
+ { name: "Off", value: "off" },
+ { name: "Light Blur", value: "light" },
+ { name: "Heavy Blur", value: "heavy" },
+ ] as const
+ ).find(
+ (v) =>
+ v.value ===
+ (project.camera.backgroundBlur?.mode ?? "off"),
+ ) ?? { name: "Off", value: "off" }
+ }
+ onChange={(v) => {
+ if (v)
+ setProject("camera", "backgroundBlur", {
+ mode: v.value,
+ });
+ }}
+ disallowEmptySelection
+ itemComponent={(props) => (
+ <MenuItem<typeof KSelect.Item>
+ as={KSelect.Item}
+ item={props.item}
+ >
+ <KSelect.ItemLabel class="flex-1">
+ {props.item.rawValue.name}
+ </KSelect.ItemLabel>
+ </MenuItem>
+ )}
+ >
- <KSelect.Trigger class="flex flex-row gap-2 items-center px-2 w-full h-8 rounded-lg transition-colors bg-gray-3 disabled:text-gray-11">
++ <KSelect.Trigger class="flex flex-row gap-1.5 items-center px-2 w-full h-[26px] rounded-[7px] transition-colors bg-ed-ctl hover:bg-ed-ctl-hover outline-hidden disabled:text-ed-text-3">
+ <KSelect.Value<{
+ name: string;
+ value: string;
- }> class="flex-1 text-sm text-left truncate text-(--gray-500) font-normal">
++ }> class="flex-1 text-[12px] text-left truncate text-ed-text-1 font-normal">
+ {(state) => <span>{state.selectedOption().name}</span>}
+ </KSelect.Value>
+ <KSelect.Icon<ValidComponent>
+ as={(iconProps) => (
+ <IconCapChevronDown
+ {...iconProps}
- class="size-4 shrink-0 transform transition-transform data-expanded:rotate-180 text-(--gray-500)"
++ class="size-3.5 shrink-0 transform transition-transform data-expanded:rotate-180 text-ed-text-3"
+ />
+ )}
/>
- </PopperContent>
- </KSelect.Portal>
- </KSelect>
- </Subfield>
- <Subfield name="Shape">
- <KSelect<{ name: string; value: CameraShape }>
- options={CAMERA_SHAPES}
- optionValue="value"
- optionTextValue="name"
- value={CAMERA_SHAPES.find(
- (v) => v.value === project.camera.shape,
- )}
- onChange={(v) => {
- if (v) setProject("camera", "shape", v.value);
- }}
- disallowEmptySelection
- itemComponent={(props) => (
- <MenuItem<typeof KSelect.Item>
- as={KSelect.Item}
- item={props.item}
- >
- <KSelect.ItemLabel class="flex-1">
- {props.item.rawValue.name}
- </KSelect.ItemLabel>
- </MenuItem>
- )}
- >
- <KSelect.Trigger class="flex flex-row gap-2 items-center px-2 w-full h-8 rounded-lg transition-colors bg-gray-3 disabled:text-gray-11">
- <KSelect.Value<{
- name: string;
- value: StereoMode;
- }> class="flex-1 text-sm text-left truncate text-(--gray-500) font-normal">
- {(state) => <span>{state.selectedOption().name}</span>}
- </KSelect.Value>
- <KSelect.Icon<ValidComponent>
- as={(props) => (
- <IconCapChevronDown
- {...props}
- class="size-4 shrink-0 transform transition-transform data-expanded:rotate-180 text-(--gray-500)"
+ </KSelect.Trigger>
+ <KSelect.Portal>
+ <PopperContent<typeof KSelect.Content>
+ as={KSelect.Content}
+ class={cx(topSlideAnimateClasses, "z-50")}
+ >
+ <MenuItemList<typeof KSelect.Listbox>
+ class="overflow-y-auto max-h-32"
+ as={KSelect.Listbox}
/>
- )}
- />
- </KSelect.Trigger>
- <KSelect.Portal>
- <PopperContent<typeof KSelect.Content>
- as={KSelect.Content}
- class={cx(topSlideAnimateClasses, "z-50")}
- >
- <MenuItemList<typeof KSelect.Listbox>
- class="overflow-y-auto max-h-32"
- as={KSelect.Listbox}
+ </PopperContent>
+ </KSelect.Portal>
+ </KSelect>
+ </Subfield>
+ <Subfield name="Shape">
+ <KSelect<{ name: string; value: CameraShape }>
+ options={CAMERA_SHAPES}
+ optionValue="value"
+ optionTextValue="name"
+ value={CAMERA_SHAPES.find(
+ (v) => v.value === project.camera.shape,
+ )}
+ onChange={(v) => {
+ if (v) setProject("camera", "shape", v.value);
+ }}
+ disallowEmptySelection
+ itemComponent={(props) => (
+ <MenuItem<typeof KSelect.Item>
+ as={KSelect.Item}
+ item={props.item}
+ >
+ <KSelect.ItemLabel class="flex-1">
+ {props.item.rawValue.name}
+ </KSelect.ItemLabel>
+ </MenuItem>
+ )}
+ >
- <KSelect.Trigger class="flex flex-row gap-2 items-center px-2 w-full h-8 rounded-lg transition-colors bg-gray-3 disabled:text-gray-11">
++ <KSelect.Trigger class="flex flex-row gap-1.5 items-center px-2 w-full h-[26px] rounded-[7px] transition-colors bg-ed-ctl hover:bg-ed-ctl-hover outline-hidden disabled:text-ed-text-3">
+ <KSelect.Value<{
+ name: string;
+ value: StereoMode;
- }> class="flex-1 text-sm text-left truncate text-(--gray-500) font-normal">
++ }> class="flex-1 text-[12px] text-left truncate text-ed-text-1 font-normal">
+ {(state) => <span>{state.selectedOption().name}</span>}
+ </KSelect.Value>
+ <KSelect.Icon<ValidComponent>
+ as={(props) => (
+ <IconCapChevronDown
+ {...props}
- class="size-4 shrink-0 transform transition-transform data-expanded:rotate-180 text-(--gray-500)"
++ class="size-3.5 shrink-0 transform transition-transform data-expanded:rotate-180 text-ed-text-3"
+ />
+ )}
/>
- </PopperContent>
- </KSelect.Portal>
- </KSelect>
- </Subfield>
+ </KSelect.Trigger>
+ <KSelect.Portal>
+ <PopperContent<typeof KSelect.Content>
+ as={KSelect.Content}
+ class={cx(topSlideAnimateClasses, "z-50")}
+ >
+ <MenuItemList<typeof KSelect.Listbox>
+ class="overflow-y-auto max-h-32"
+ as={KSelect.Listbox}
+ />
+ </PopperContent>
+ </KSelect.Portal>
+ </KSelect>
+ </Subfield>
- {/* <Subfield name="Use Camera Aspect Ratio">
+ {/* <Subfield name="Use Camera Aspect Ratio">
<Toggle
checked={project.camera.use_camera_aspect}
onChange={(v) => setProject("camera", "use_camera_aspect", v)}
/>
</Subfield> */}
- </div>
- </Field>
- {/** Dashed divider */}
- <div class="w-full border-t border-dashed border-gray-5" />
- <Field name="Size" icon={<IconCapEnlarge class="size-4" />}>
- <Slider
- value={[project.camera.size]}
- onChange={(v) => setProject("camera", "size", v[0])}
- minValue={20}
- maxValue={80}
- step={0.1}
- formatTooltip="%"
- />
- </Field>
- <Field name="Size During Zoom" icon={<IconCapEnlarge class="size-4" />}>
- <Slider
- value={[project.camera.zoomSize ?? 60]}
- onChange={(v) => setProject("camera", "zoomSize", v[0])}
- minValue={10}
- maxValue={60}
- step={0.1}
- formatTooltip="%"
- />
- </Field>
- <Subfield name="Keep original size during zoom">
- <Toggle
- checked={
- (project.camera.scaleDuringZoom ??
- DEFAULT_CAMERA_SCALE_DURING_ZOOM) >= 1
- }
- onChange={(keep) =>
- setProject(
- "camera",
- "scaleDuringZoom",
- keep ? 1 : DEFAULT_CAMERA_SCALE_DURING_ZOOM,
- )
- }
- />
- </Subfield>
- <Field name="Rounded Corners" icon={<IconCapCorners class="size-4" />}>
- <div class="flex flex-col gap-3">
+ </div>
- </Field>
- {/** Dashed divider */}
- <div class="w-full border-t border-dashed border-gray-5" />
- <Field name="Size" icon={<IconCapEnlarge class="size-4" />}>
++ </Section>
++ <div class="w-full border-t border-ed-line" />
++ <Field inline name="Size" value={`${project.camera.size.toFixed(1)}%`}>
+ <Slider
+ value={[project.camera.size]}
+ onChange={(v) => setProject("camera", "size", v[0])}
+ minValue={20}
+ maxValue={80}
+ step={0.1}
+ formatTooltip="%"
+ />
+ </Field>
- <Field name="Size During Zoom" icon={<IconCapEnlarge class="size-4" />}>
++ <Field
++ inline
++ name="Size During Zoom"
++ value={`${(project.camera.zoomSize ?? 60).toFixed(1)}%`}
++ >
<Slider
- value={[project.camera.rounding ?? 0]}
- onChange={(v) => setProject("camera", "rounding", v[0])}
- minValue={0}
- maxValue={100}
+ value={[project.camera.zoomSize ?? 60]}
+ onChange={(v) => setProject("camera", "zoomSize", v[0])}
+ minValue={10}
+ maxValue={60}
+ step={0.1}
+ formatTooltip="%"
+ />
+ </Field>
+ <Subfield name="Keep original size during zoom">
+ <Toggle
+ checked={
+ (project.camera.scaleDuringZoom ??
+ DEFAULT_CAMERA_SCALE_DURING_ZOOM) >= 1
+ }
+ onChange={(keep) =>
+ setProject(
+ "camera",
+ "scaleDuringZoom",
+ keep ? 1 : DEFAULT_CAMERA_SCALE_DURING_ZOOM,
+ )
+ }
+ />
- </Subfield>
- <Field name="Rounded Corners" icon={<IconCapCorners class="size-4" />}>
- <div class="flex flex-col gap-3">
- <Slider
- value={[project.camera.rounding ?? 0]}
- onChange={(v) => setProject("camera", "rounding", v[0])}
- minValue={0}
- maxValue={100}
- step={0.1}
- formatTooltip="%"
- />
- <CornerStyleSelect
- label="Corner Style"
- value={project.camera.roundingType}
- onChange={(value) => setProject("camera", "roundingType", value)}
- />
- </div>
- </Field>
- <Field name="Shadow" icon={<IconCapShadow class="size-4" />}>
- <div class="space-y-8">
- <Slider
- value={[project.camera.shadow ?? 0]}
- onChange={(v) => setProject("camera", "shadow", v[0])}
- minValue={0}
- maxValue={100}
- step={0.1}
- formatTooltip="%"
- />
- <ShadowSettings
- scrollRef={props.scrollRef}
- size={{
- value: [project.camera.advancedShadow?.size ?? 50],
- onChange: (v) => {
- setProject("camera", "advancedShadow", {
- ...(project.camera.advancedShadow ?? {
- size: 50,
- opacity: 18,
- blur: 50,
- }),
- size: v[0],
- });
- },
- }}
- opacity={{
- value: [project.camera.advancedShadow?.opacity ?? 18],
- onChange: (v) => {
- setProject("camera", "advancedShadow", {
- ...(project.camera.advancedShadow ?? {
- size: 50,
- opacity: 18,
- blur: 50,
- }),
- opacity: v[0],
- });
- },
- }}
- blur={{
- value: [project.camera.advancedShadow?.blur ?? 50],
- onChange: (v) => {
- setProject("camera", "advancedShadow", {
- ...(project.camera.advancedShadow ?? {
- size: 50,
- opacity: 18,
- blur: 50,
- }),
- blur: v[0],
- });
- },
- }}
- />
- </div>
- </Field>
++ </Subfield>
++ <Field
++ inline
++ name="Corners"
++ value={`${(project.camera.rounding ?? 0).toFixed(1)}%`}
++ >
++ <Slider
++ value={[project.camera.size]}
++ onChange={(v) => setProject("camera", "size", v[0])}
++ minValue={20}
++ maxValue={80}
+ step={0.1}
+ formatTooltip="%"
+ />
++ </Field>
++ <Field inline name="Corner Style">
+ <CornerStyleSelect
- label="Corner Style"
+ value={project.camera.roundingType}
+ onChange={(value) => setProject("camera", "roundingType", value)}
+ />
- </div>
- </Field>
- <Field name="Shadow" icon={<IconCapShadow class="size-4" />}>
- <div class="space-y-8">
++ </Field>
++ <Field
++ inline
++ name="Shadow"
++ value={`${(project.camera.shadow ?? 0).toFixed(1)}%`}
++ >
+ <Slider
- value={[project.camera.shadow ?? 0]}
- onChange={(v) => setProject("camera", "shadow", v[0])}
- minValue={0}
- maxValue={100}
++ value={[project.camera.zoomSize ?? 60]}
++ onChange={(v) => setProject("camera", "zoomSize", v[0])}
++ minValue={10}
++ maxValue={60}
+ step={0.1}
+ formatTooltip="%"
+ />
++ </Field>
++ <div class="flex flex-col">
+ <ShadowSettings
+ scrollRef={props.scrollRef}
+ size={{
+ value: [project.camera.advancedShadow?.size ?? 50],
+ onChange: (v) => {
+ setProject("camera", "advancedShadow", {
+ ...(project.camera.advancedShadow ?? {
+ size: 50,
+ opacity: 18,
+ blur: 50,
+ }),
+ size: v[0],
+ });
+ },
+ }}
+ opacity={{
+ value: [project.camera.advancedShadow?.opacity ?? 18],
+ onChange: (v) => {
+ setProject("camera", "advancedShadow", {
+ ...(project.camera.advancedShadow ?? {
+ size: 50,
+ opacity: 18,
+ blur: 50,
+ }),
+ opacity: v[0],
+ });
+ },
+ }}
+ blur={{
+ value: [project.camera.advancedShadow?.blur ?? 50],
+ onChange: (v) => {
+ setProject("camera", "advancedShadow", {
+ ...(project.camera.advancedShadow ?? {
+ size: 50,
+ opacity: 18,
+ blur: 50,
+ }),
+ blur: v[0],
+ });
+ },
+ }}
+ />
+ </div>
- </Field>
- <ColorCorrectionSection target="camera" scrollRef={props.scrollRef} />
- {/* <ComingSoonTooltip>
+ <Show when={!selectedStyle()}>
+ <ColorCorrectionSection target="camera" scrollRef={props.scrollRef} />
+ </Show>
+ {/* <ComingSoonTooltip>
<Field name="Shadow" icon={<IconCapShadow />}>
<Slider
disabled
@@@ -3524,19 -3434,19 +3499,11 @@@
}
function CornerStyleSelect(props: {
-- label?: string;
value: CornerRoundingType;
onChange: (value: CornerRoundingType) => void;
}) {
return (
-- <div class="flex flex-col gap-1.5">
-- <Show when={props.label}>
-- {(label) => (
-- <span class="text-[0.65rem] uppercase tracking-wide text-gray-11">
-- {label()}
-- </span>
-- )}
-- </Show>
++ <div class="w-32">
<KSelect<{ name: string; value: CornerRoundingType }>
options={CORNER_STYLE_OPTIONS}
optionValue="value"
@@@ -3557,18 -3467,18 +3524,18 @@@
</MenuItem>
)}
>
-- <KSelect.Trigger class="flex flex-row gap-2 items-center px-2 w-full h-8 rounded-lg transition-colors bg-gray-3 disabled:text-gray-11">
++ <KSelect.Trigger class="flex flex-row gap-1.5 items-center px-2 w-full h-[26px] rounded-[7px] transition-colors bg-ed-ctl hover:bg-ed-ctl-hover outline-hidden disabled:text-ed-text-3">
<KSelect.Value<{
name: string;
value: CornerRoundingType;
-- }> class="flex-1 text-sm text-left truncate text-(--gray-500) font-normal">
++ }> class="flex-1 text-[12px] text-left truncate text-ed-text-1 font-normal">
{(state) => <span>{state.selectedOption().name}</span>}
</KSelect.Value>
<KSelect.Icon<ValidComponent>
as={(iconProps) => (
<IconCapChevronDown
{...iconProps}
-- class="size-4 shrink-0 transform transition-transform data-expanded:rotate-180 text-(--gray-500)"
++ class="size-3.5 shrink-0 transform transition-transform data-expanded:rotate-180 text-ed-text-3"
/>
)}
/>
@@@ -3688,7 -3598,7 +3655,7 @@@ function TextStyleSelect<T extends stri
<KSelect.ItemLabel class="flex-1">
{selectItemProps.item.rawValue.label}
</KSelect.ItemLabel>
-- <KSelect.ItemIndicator class="ml-auto text-blue-9">
++ <KSelect.ItemIndicator class="ml-auto text-ed-accent">
<IconCapCircleCheck />
</KSelect.ItemIndicator>
</MenuItem>
@@@ -3699,7 -3609,7 +3666,7 @@@
{(state) => state.selectedOption()?.label ?? selected().label}
</KSelect.Value>
<KSelect.Icon>
-- <IconCapChevronDown class="size-4 shrink-0 transform transition-transform data-expanded:rotate-180 text-(--gray-500)" />
++ <IconCapChevronDown class="size-3.5 shrink-0 transform transition-transform data-expanded:rotate-180 text-ed-text-3" />
</KSelect.Icon>
</KSelect.Trigger>
<KSelect.Portal>
@@@ -3849,10 -3759,10 +3816,7 @@@ function TextSegmentConfig(props:
return (
<div class="space-y-4">
-- <Field
-- name={`Text ${props.segmentIndex + 1}`}
-- icon={<IconLucideType class="size-4" />}
-- >
++ <Section name={`Text ${props.segmentIndex + 1}`}>
<div class="flex items-center gap-3">
<textarea
class="flex-1 px-3 py-2 rounded-lg border border-gray-3 bg-gray-2 text-gray-12 resize-none min-h-[80px]"
@@@ -3864,7 -3774,7 +3828,7 @@@
}
/>
<div class="flex flex-col items-center gap-2">
-- <span class="text-xs text-gray-11">Enabled</span>
++ <span class="text-[11px] text-ed-text-3">Enabled</span>
<Toggle
checked={props.segment.enabled}
onChange={(value) =>
@@@ -3875,8 -3785,8 +3839,8 @@@
/>
</div>
</div>
-- </Field>
-- <Field name="Layout" icon={<IconLucideBoxSelect class="size-4" />}>
++ </Section>
++ <Field name="Layout">
<div class="flex flex-col gap-3">
<div class="grid grid-cols-2 gap-1 rounded-lg border border-gray-3 bg-gray-2 p-1">
<For each={TEXT_LAYOUT_OPTIONS}>
@@@ -3918,8 -3828,8 +3882,15 @@@
</p>
</Show>
<Show when={(props.segment.layout ?? "overlay") !== "overlay"}>
-- <div class="flex flex-col gap-1">
-- <span class="text-xs text-gray-11">Screen transition</span>
++ <Field
++ inline
++ name="Screen transition"
++ value={`${clampNumber(
++ props.segment.layoutTransition ?? 0.5,
++ 0.1,
++ 1.5,
++ ).toFixed(2)}s`}
++ >
<Slider
value={[
clampNumber(props.segment.layoutTransition ?? 0.5, 0.1, 1.5),
@@@ -3934,11 -3844,11 +3905,11 @@@
step={0.05}
formatTooltip="s"
/>
-- </div>
++ </Field>
</Show>
</div>
</Field>
-- <Field name="Templates" icon={<IconLucideSparkles class="size-4" />}>
++ <Field name="Templates">
<div class="grid grid-cols-2 gap-2">
<For each={TEXT_PRESETS}>
{(preset) => (
@@@ -3955,7 -3865,7 +3926,7 @@@
</For>
</div>
</Field>
-- <Field name="Font" icon={<IconLucideType class="size-4" />}>
++ <Field name="Font">
<div class="flex flex-col gap-2">
<FontPicker
value={props.segment.fontFamily ?? "sans-serif"}
@@@ -3996,8 -3906,8 +3967,17 @@@
<IconLucideItalic class="size-4" />
</button>
</div>
-- <div class="flex flex-col gap-1">
-- <span class="text-xs text-gray-11">Size</span>
++ <Field
++ inline
++ name="Size"
++ value={Math.round(
++ clampNumber(
++ props.segment.fontSize,
++ TEXT_FONT_SIZE_MIN,
++ TEXT_FONT_SIZE_MAX,
++ ),
++ )}
++ >
<Slider
value={[
clampNumber(
@@@ -4034,10 -3944,10 +4014,10 @@@
maxValue={TEXT_FONT_SIZE_MAX}
step={1}
/>
-- </div>
++ </Field>
</div>
</Field>
-- <Field name="Layout" icon={<IconLucideAlignCenter class="size-4" />}>
++ <Field name="Alignment">
<div class="flex flex-col gap-3">
<div class="grid grid-cols-3 gap-1 rounded-lg border border-gray-3 bg-gray-2 p-1">
<For each={TEXT_ALIGN_OPTIONS}>
@@@ -4061,8 -3971,8 +4041,13 @@@
)}
</For>
</div>
-- <div class="flex flex-col gap-1">
-- <span class="text-xs text-gray-11">Line height</span>
++ <Field
++ inline
++ name="Line height"
++ value={clampNumber(props.segment.lineHeight ?? 1.2, 0.8, 2).toFixed(
++ 2,
++ )}
++ >
<Slider
value={[clampNumber(props.segment.lineHeight ?? 1.2, 0.8, 2)]}
onChange={([value]) =>
@@@ -4074,9 -3984,9 +4059,16 @@@
maxValue={2}
step={0.05}
/>
-- </div>
-- <div class="flex flex-col gap-1">
-- <span class="text-xs text-gray-11">Letter spacing</span>
++ </Field>
++ <Field
++ inline
++ name="Letter spacing"
++ value={`${clampNumber(
++ props.segment.letterSpacing ?? 0,
++ -2,
++ 20,
++ ).toFixed(1)}px`}
++ >
<Slider
value={[clampNumber(props.segment.letterSpacing ?? 0, -2, 20)]}
onChange={([value]) =>
@@@ -4089,10 -3999,10 +4081,10 @@@
step={0.5}
formatTooltip="px"
/>
-- </div>
++ </Field>
</div>
</Field>
-- <Field name="Color" icon={<IconLucidePalette class="size-4" />}>
++ <Field name="Color">
<div class="flex flex-col gap-3">
<HexColorInput
value={props.segment.color}
@@@ -4103,8 -4013,8 +4095,7 @@@
})
}
/>
-- <div class="flex items-center justify-between gap-3">
-- <span class="text-xs text-gray-11">Background</span>
++ <Field inline name="Background">
<Toggle
checked={props.segment.backgroundColor != null}
onChange={(enabled) =>
@@@ -4113,7 -4023,7 +4104,7 @@@
})
}
/>
-- </div>
++ </Field>
<Show when={props.segment.backgroundColor != null}>
<HexColorInput
value={props.segment.backgroundColor ?? "#000000"}
@@@ -4125,8 -4035,8 +4116,11 @@@
}
/>
</Show>
-- <div class="flex flex-col gap-1">
-- <span class="text-xs text-gray-11">Opacity</span>
++ <Field
++ inline
++ name="Opacity"
++ value={`${Math.round(clampNumber(props.segment.opacity ?? 1, 0, 1) * 100)}%`}
++ >
<Slider
value={[clampNumber(props.segment.opacity ?? 1, 0, 1)]}
onChange={([value]) =>
@@@ -4138,9 -4048,9 +4132,12 @@@
maxValue={1}
step={0.01}
/>
-- </div>
-- <div class="flex flex-col gap-1">
-- <span class="text-xs text-gray-11">Shadow</span>
++ </Field>
++ <Field
++ inline
++ name="Shadow"
++ value={`${Math.round(clampNumber(props.segment.shadow ?? 0, 0, 1) * 100)}%`}
++ >
<Slider
value={[clampNumber(props.segment.shadow ?? 0, 0, 1)]}
onChange={([value]) =>
@@@ -4152,13 -4062,13 +4149,13 @@@
maxValue={1}
step={0.01}
/>
-- </div>
++ </Field>
</div>
</Field>
-- <Field name="Animation" icon={<IconLucideTimer class="size-4" />}>
++ <Field name="Animation">
<div class="flex flex-col gap-3">
<div class="flex flex-col gap-2">
-- <span class="text-xs text-gray-11">In</span>
++ <span class="text-[11px] text-ed-text-3">In</span>
<TextStyleSelect
options={TEXT_ANIMATION_OPTIONS}
value={props.segment.animationIn ?? "fade"}
@@@ -4184,7 -4094,7 +4181,7 @@@
</Show>
</div>
<div class="flex flex-col gap-2">
-- <span class="text-xs text-gray-11">Out</span>
++ <span class="text-[11px] text-ed-text-3">Out</span>
<TextStyleSelect
options={TEXT_ANIMATION_OPTIONS}
value={props.segment.animationOut ?? "fade"}
@@@ -4241,10 -4151,10 +4238,7 @@@ function AudioSegmentConfig(props:
return (
<div class="space-y-4">
-- <Field
-- name={`Audio ${props.segmentIndex + 1}`}
-- icon={<IconLucideMusic class="size-4" />}
-- >
++ <Section name={`Audio ${props.segmentIndex + 1}`}>
<div class="flex flex-col gap-3">
<button
type="button"
@@@ -4282,7 -4192,7 +4276,7 @@@
}
/>
<div class="flex flex-col gap-2 items-center">
-- <span class="text-xs text-gray-11">Enabled</span>
++ <span class="text-[11px] text-ed-text-3">Enabled</span>
<Toggle
checked={props.segment.enabled}
onChange={(value) =>
@@@ -4294,8 -4204,8 +4288,16 @@@
</div>
</div>
</div>
-- </Field>
-- <Field name="Volume" icon={<IconLucideVolume2 class="size-4" />}>
++ </Section>
++ <Field
++ inline
++ name="Volume"
++ value={`${clampNumber(
++ props.segment.volumeDb,
++ MIN_VOLUME_DB,
++ MAX_VOLUME_DB,
++ ).toFixed(1)} dB`}
++ >
<Slider
value={[
clampNumber(props.segment.volumeDb, MIN_VOLUME_DB, MAX_VOLUME_DB),
@@@ -4315,7 -4225,7 +4317,11 @@@
formatTooltip="dB"
/>
</Field>
-- <Field name="Fade In" icon={<IconLucideTimer class="size-4" />}>
++ <Field
++ inline
++ name="Fade In"
++ value={`${clampNumber(props.segment.fadeIn, 0, fadeMax()).toFixed(2)}s`}
++ >
<Slider
value={[clampNumber(props.segment.fadeIn, 0, fadeMax())]}
onChange={([value]) =>
@@@ -4329,7 -4239,7 +4335,11 @@@
formatTooltip="s"
/>
</Field>
-- <Field name="Fade Out" icon={<IconLucideTimer class="size-4" />}>
++ <Field
++ inline
++ name="Fade Out"
++ value={`${clampNumber(props.segment.fadeOut, 0, fadeMax()).toFixed(2)}s`}
++ >
<Slider
value={[clampNumber(props.segment.fadeOut, 0, fadeMax())]}
onChange={([value]) =>
@@@ -4367,10 -4277,10 +4377,7 @@@ function KeyboardSegmentConfig(props:
return (
<div class="space-y-4">
-- <Field
-- name={`Keyboard ${props.segmentIndex + 1}`}
-- icon={<IconLucideKeyboard class="size-4" />}
-- >
++ <Section name={`Keyboard ${props.segmentIndex + 1}`}>
<Input
type="text"
value={props.segment.displayText}
@@@ -4380,12 -4290,12 +4387,12 @@@
})
}
/>
-- </Field>
-- <Field name="Timing" icon={<IconLucideTimer class="size-4" />}>
-- <div class="rounded-xl border border-gray-3 bg-gray-2/70 p-3 space-y-3">
++ </Section>
++ <Field name="Timing">
++ <div class="rounded-xl bg-ed-card-2 p-3 space-y-3">
<div class="grid grid-cols-[1fr_auto_1fr] gap-2 items-start">
-- <div class="rounded-lg border border-gray-3 bg-gray-1/80 p-2.5 space-y-2">
-- <div class="flex items-center justify-between text-[10px] uppercase tracking-[0.08em] text-gray-10">
++ <div class="rounded-lg bg-ed-card p-2.5 space-y-2">
++ <div class="flex items-center justify-between text-[10px] uppercase tracking-[0.08em] text-ed-text-3">
<span>Start</span>
<span>{formatTime(props.segment.start)}</span>
</div>
@@@ -4401,9 -4311,9 +4408,9 @@@
}
/>
</div>
-- <div class="pt-10 text-xs font-medium text-gray-10">to</div>
-- <div class="rounded-lg border border-gray-3 bg-gray-1/80 p-2.5 space-y-2">
-- <div class="flex items-center justify-between text-[10px] uppercase tracking-[0.08em] text-gray-10">
++ <div class="pt-10 text-[11px] font-medium text-ed-text-3">to</div>
++ <div class="rounded-lg bg-ed-card p-2.5 space-y-2">
++ <div class="flex items-center justify-between text-[10px] uppercase tracking-[0.08em] text-ed-text-3">
<span>End</span>
<span>{formatTime(props.segment.end)}</span>
</div>
@@@ -4420,15 -4330,15 +4427,19 @@@
/>
</div>
</div>
-- <div class="flex items-center justify-between rounded-lg bg-gray-1/70 px-3 py-2 text-xs text-gray-11">
++ <div class="flex items-center justify-between rounded-lg bg-ed-card px-3 py-2 text-[11px] text-ed-text-2">
<span>Duration</span>
-- <span class="font-medium text-gray-12">
++ <span class="font-medium text-ed-text-1">
{Math.max(0, props.segment.end - props.segment.start).toFixed(2)}s
</span>
</div>
</div>
</Field>
-- <Field name="Fade Duration" icon={<IconLucideTimer class="size-4" />}>
++ <Field
++ inline
++ name="Fade Duration"
++ value={Math.round((props.segment.fadeDurationOverride ?? 0.15) * 100)}
++ >
<Slider
value={[(props.segment.fadeDurationOverride ?? 0.15) * 100]}
onChange={([value]) =>
@@@ -4475,10 -4385,10 +4486,7 @@@ function CaptionSegmentConfig(props:
return (
<div class="space-y-4">
-- <Field
-- name={`Caption ${props.segmentIndex + 1}`}
-- icon={<IconCapMessageBubble />}
-- >
++ <Section name={`Caption ${props.segmentIndex + 1}`}>
<textarea
class="flex-1 px-3 py-2 rounded-lg border border-gray-3 bg-gray-2 text-gray-12 resize-none min-h-[96px] w-full"
value={props.segment.text}
@@@ -4494,12 -4404,12 +4502,12 @@@
})
}
/>
-- </Field>
-- <Field name="Timing" icon={<IconLucideTimer class="size-4" />}>
-- <div class="rounded-xl border border-gray-3 bg-gray-2/70 p-3 space-y-3">
++ </Section>
++ <Field name="Timing">
++ <div class="rounded-xl bg-ed-card-2 p-3 space-y-3">
<div class="grid grid-cols-[1fr_auto_1fr] gap-2 items-start">
-- <div class="rounded-lg border border-gray-3 bg-gray-1/80 p-2.5 space-y-2">
-- <div class="flex items-center justify-between text-[10px] uppercase tracking-[0.08em] text-gray-10">
++ <div class="rounded-lg bg-ed-card p-2.5 space-y-2">
++ <div class="flex items-center justify-between text-[10px] uppercase tracking-[0.08em] text-ed-text-3">
<span>Start</span>
<span>{formatTime(props.segment.start)}</span>
</div>
@@@ -4520,9 -4430,9 +4528,9 @@@
}
/>
</div>
-- <div class="pt-10 text-xs font-medium text-gray-10">to</div>
-- <div class="rounded-lg border border-gray-3 bg-gray-1/80 p-2.5 space-y-2">
-- <div class="flex items-center justify-between text-[10px] uppercase tracking-[0.08em] text-gray-10">
++ <div class="pt-10 text-[11px] font-medium text-ed-text-3">to</div>
++ <div class="rounded-lg bg-ed-card p-2.5 space-y-2">
++ <div class="flex items-center justify-between text-[10px] uppercase tracking-[0.08em] text-ed-text-3">
<span>End</span>
<span>{formatTime(props.segment.end)}</span>
</div>
@@@ -4544,9 -4454,9 +4552,9 @@@
/>
</div>
</div>
-- <div class="flex items-center justify-between rounded-lg bg-gray-1/70 px-3 py-2 text-xs text-gray-11">
++ <div class="flex items-center justify-between rounded-lg bg-ed-card px-3 py-2 text-[11px] text-ed-text-2">
<span>Duration</span>
-- <span class="font-medium text-gray-12">
++ <span class="font-medium text-ed-text-1">
{Math.max(0, props.segment.end - props.segment.start).toFixed(2)}s
</span>
</div>
@@@ -4611,10 -4521,10 +4619,7 @@@ function MaskSegmentConfig(props:
return (
<div class="space-y-4">
-- <Field
-- name={`Mask ${props.segmentIndex + 1}`}
-- icon={<IconLucideBoxSelect class="size-4" />}
-- >
++ <Section name={`Mask ${props.segmentIndex + 1}`}>
<div class="flex items-center justify-between gap-4">
<RadioGroup
class="grid grid-cols-2 gap-2"
@@@ -4641,7 -4551,7 +4646,7 @@@
class="rounded-lg border border-gray-3 transition-colors data-checked:border-blue-8 data-checked:bg-blue-3/40"
>
<RadioGroup.ItemInput class="sr-only" />
-- <RadioGroup.ItemLabel class="flex items-center gap-2 p-2 text-sm text-gray-12">
++ <RadioGroup.ItemLabel class="flex items-center gap-2 p-2 text-[13px] text-ed-text-1">
<RadioGroup.ItemControl class="size-4 rounded-full border border-gray-7 data-checked:border-blue-9 data-checked:bg-blue-9" />
{option.label}
</RadioGroup.ItemLabel>
@@@ -4649,7 -4559,7 +4654,7 @@@
))}
</RadioGroup>
<div class="flex items-center gap-2">
-- <span class="text-xs text-gray-11">Enabled</span>
++ <span class="text-[11px] text-ed-text-3">Enabled</span>
<Toggle
checked={props.segment.enabled}
onChange={(value) =>
@@@ -4660,9 -4570,9 +4665,9 @@@
/>
</div>
</div>
-- </Field>
++ </Section>
<Show when={props.segment.maskType === "sensitive"}>
-- <Field name="Effect" icon={<IconLucideEyeOff class="size-4" />}>
++ <Field name="Effect">
<RadioGroup
class="grid grid-cols-2 gap-2"
value={maskEffect()}
@@@ -4677,7 -4587,7 +4682,7 @@@
class="rounded-lg border border-gray-3 transition-colors data-checked:border-blue-8 data-checked:bg-blue-3/40"
>
<RadioGroup.ItemInput class="sr-only" />
-- <RadioGroup.ItemLabel class="flex items-center gap-2 p-2 text-sm text-gray-12">
++ <RadioGroup.ItemLabel class="flex items-center gap-2 p-2 text-[13px] text-ed-text-1">
<RadioGroup.ItemControl class="size-4 rounded-full border border-gray-7 data-checked:border-blue-9 data-checked:bg-blue-9" />
{option.label}
</RadioGroup.ItemLabel>
@@@ -4688,14 -4598,14 +4693,9 @@@
</Show>
<Show when={props.segment.maskType === "sensitive"}>
<Field
++ inline
name={maskEffect() === "blur" ? "Blur" : "Pixel Size"}
-- icon={
-- maskEffect() === "blur" ? (
-- <IconLucideWind class="size-4" />
-- ) : (
-- <IconLucideGrid class="size-4" />
-- )
-- }
++ value={`${Math.round(maskEffectAmount())}px`}
>
<Slider
value={[maskEffectAmount()]}
@@@ -4708,7 -4618,7 +4708,11 @@@
</Field>
</Show>
<Show when={props.segment.maskType === "highlight"}>
-- <Field name="Outside Darkness" icon={<IconLucideMoon class="size-4" />}>
++ <Field
++ inline
++ name="Outside Darkness"
++ value={`${Math.round(props.segment.darkness * 100)}%`}
++ >
<Slider
value={[props.segment.darkness]}
onChange={([v]) =>
@@@ -4723,7 -4633,7 +4727,11 @@@
</Field>
</Show>
<Show when={props.segment.maskType === "highlight"}>
-- <Field name="Fade Duration" icon={<IconLucideTimer class="size-4" />}>
++ <Field
++ inline
++ name="Fade Duration"
++ value={`${(props.segment.fadeDuration ?? 0.15).toFixed(2)}s`}
++ >
<Slider
value={[props.segment.fadeDuration ?? 0.15]}
onChange={([v]) =>
@@@ -4826,7 -4736,7 +4834,7 @@@ function Camera3DTransitionInput(props
return (
<div class="flex flex-row justify-between items-center">
-- <span class="text-xs text-gray-11">{props.label}</span>
++ <span class="text-[11px] text-ed-text-3">{props.label}</span>
<div class="flex flex-row gap-1 items-center">
<NumberField.Root
value={text()}
@@@ -4877,7 -4787,7 +4885,6 @@@ const CAMERA3D_PREVIEW_TRANSITION = "70
function Camera3DSection(
props: ParentProps<{
name: string;
-- icon: JSX.Element;
summary?: string;
open: boolean;
onOpenChange: (open: boolean) => void;
@@@ -4885,16 -4795,16 +4892,15 @@@
) {
return (
<KCollapsible open={props.open} onOpenChange={props.onOpenChange}>
-- <KCollapsible.Trigger class="flex flex-row gap-1.5 items-center w-full text-sm font-medium group text-gray-12 outline-hidden">
-- {props.icon}
++ <KCollapsible.Trigger class="flex flex-row gap-1.5 items-center w-full min-h-[22px] text-[12px] font-medium group text-ed-text-2 outline-hidden">
{props.name}
-- <span class="flex flex-row gap-1.5 items-center ml-auto text-xs font-normal text-gray-10">
++ <span class="flex flex-row gap-1.5 items-center ml-auto text-[11px] font-normal text-ed-text-3">
{props.summary}
<IconCapChevronDown class="transition-transform duration-200 size-3.5 group-data-expanded:rotate-180" />
</span>
</KCollapsible.Trigger>
<KCollapsible.Content class="overflow-hidden opacity-0 transition-opacity animate-collapsible-up data-expanded:animate-collapsible-down data-expanded:opacity-100">
-- <div class="pt-4">{props.children}</div>
++ <div class="pt-2.5">{props.children}</div>
</KCollapsible.Content>
</KCollapsible>
);
@@@ -4907,6 -4817,6 +4913,7 @@@ function Camera3DPosePreview(props:
pose: Camera3DProperties;
height: number;
animate?: boolean;
++ illustrated?: boolean;
}) {
const style = () => cssPreviewTransform(props.pose, props.height);
@@@ -4922,14 -4832,14 +4929,28 @@@
}}
>
<div
-- class="absolute inset-0 rounded-[3px] border shadow-sm border-gray-6 bg-gray-1 dark:bg-gray-5"
++ class={cx(
++ "absolute inset-0 overflow-hidden rounded-[3px] border shadow-sm",
++ props.illustrated
++ ? "border-blue-8 bg-blue-9"
++ : "border-gray-6 bg-gray-1 dark:bg-gray-5",
++ )}
style={{
transform: style().transform,
transition: props.animate
? `transform ${CAMERA3D_PREVIEW_TRANSITION}`
: undefined,
}}
-- />
++ >
++ <Show when={props.illustrated}>
++ <div class="flex h-full flex-col gap-2 p-3">
++ <div class="h-1 w-1/2 rounded-full bg-white/90" />
++ <div class="h-1 w-full rounded-full bg-white/60" />
++ <div class="h-1 w-4/5 rounded-full bg-white/60" />
++ <div class="h-1 w-1/2 rounded-full bg-white/60" />
++ </div>
++ </Show>
++ </div>
</div>
);
}
@@@ -4942,6 -4852,6 +4963,7 @@@
function Camera3DSceneCard(props: {
scene: Camera3DScene;
shotCount?: number;
++ description?: string;
selected?: boolean;
onClick: () => void;
}) {
@@@ -4954,142 -4864,142 +4976,160 @@@
onClick={() => props.onClick()}
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
++ onFocus={() => setHovered(true)}
++ onBlur={() => setHovered(false)}
++ aria-pressed={props.selected}
class={cx(
-- "flex flex-col gap-1 p-1 rounded-lg border transition-colors outline-hidden",
++ "flex shrink-0 rounded-lg border transition-colors outline-hidden focus-visible:ring-2 focus-visible:ring-blue-9",
++ props.description
++ ? "flex-row items-center gap-3 p-2 text-left"
++ : "flex-col gap-1 p-1",
props.selected
? "border-blue-9 ring-1 ring-blue-9"
: "border-gray-4 hover:border-gray-7",
)}
>
-- <div class="relative">
++ <div class={cx("relative", props.description && "w-[86px] shrink-0")}>
<Camera3DPosePreview
animate
++ illustrated
pose={hovered() ? props.scene.shots[0].to : props.scene.shots[0].from}
height={CAMERA3D_SCENE_PREVIEW_HEIGHT}
/>
<span class="absolute top-1 right-1 rounded px-1 text-[9px] leading-[14px] bg-gray-1/80 dark:bg-gray-2/80 text-gray-11">
-- {shotCount()} {shotCount() === 1 ? "shot" : "shots"}
++ {shotCount() === 1 ? "One move" : `${shotCount()} shots`}
</span>
</div>
-- <span class="text-[10px] leading-tight text-center text-gray-11">
-- {props.scene.name}
-- </span>
++ <div
++ class={cx(
++ "flex flex-col gap-1",
++ props.description ? "min-w-0 flex-1" : "text-center",
++ )}
++ >
++ <span
++ class={
++ props.description
++ ? "text-xs font-medium text-gray-12"
++ : "text-[10px] leading-tight text-gray-11"
++ }
++ >
++ {props.scene.name}
++ </span>
++ <Show when={props.description}>
++ <p class="text-[11px] leading-snug text-gray-10">
++ {props.description}
++ </p>
++ </Show>
++ </div>
</button>
);
}
--/**
-- * The empty 3D track's setup flow: pick a look and how many cuts it makes,
-- * with the track drawing the result live underneath. Confirming lays the whole
-- * chain down in one step.
-- */
function Camera3DSetupPanel(props: {
-- setup: { sceneId: string; shots: number };
++ setup: Camera3DSetup;
onClose: () => void;
}) {
-- const { projectActions, setEditorState, totalDuration } = useEditorContext();
--
++ const { projectActions, setEditorState, camera3DScenePreview } =
++ useEditorContext();
++ const [sequencesOpen, setSequencesOpen] = createSignal(false);
const scene = () =>
-- CAMERA3D_SCENES.find((item) => item.id === props.setup.sceneId) ??
-- CAMERA3D_SCENES[0];
--
-- // A shot under the minimum is a glitch rather than a cut, so a short video
-- // simply offers fewer of them.
-- const maxShots = () =>
-- Math.max(
-- 1,
-- Math.min(
-- scene().shots.length,
-- Math.floor(totalDuration() / CAMERA3D_MIN_SHOT_DURATION),
-- ),
-- );
-- const shots = () => Math.min(props.setup.shots, maxShots());
--
-- const updateSetup = (changes: Partial<{ sceneId: string; shots: number }>) =>
++ findCamera3DScene(props.setup.sceneId) ?? CAMERA3D_STARTER_SCENES[0];
++ const preview = () => camera3DScenePreview(props.setup);
++ const range = () => {
++ const segments = preview();
++ if (!segments.length) return null;
++ return { start: segments[0].start, end: segments[segments.length - 1].end };
++ };
++ const updateSetup = (changes: Partial<Camera3DSetup>) =>
setEditorState("timeline", "camera3dSetup", (current) =>
current ? { ...current, ...changes } : current,
);
--
++ const cards = (scenes: Camera3DScene[]) => (
++ <div class="flex flex-col gap-2">
++ <For each={scenes}>
++ {(item) => (
++ <Camera3DSceneCard
++ scene={item}
++ description={CAMERA3D_SCENE_DESCRIPTIONS[item.id]}
++ selected={item.id === scene().id}
++ onClick={() => updateSetup({ sceneId: item.id })}
++ />
++ )}
++ </For>
++ </div>
++ );
return (
-- <div class="flex flex-col gap-4">
-- <div class="flex flex-row gap-2 items-center">
-- <EditorButton
-- onClick={() => props.onClose()}
-- leftIcon={<IconLucideX />}
++ <div class="flex h-full min-h-0 flex-col">
++ <div class="custom-scroll flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4">
++ <div class="flex items-center justify-between gap-2">
++ <span class="text-[13px] font-medium text-ed-text-1">
++ Add a 3D scene
++ </span>
++ <EditorButton
++ onClick={props.onClose}
++ tooltipText="Close"
++ leftIcon={<IconLucideX />}
++ />
++ </div>
++ <p class="text-xs text-gray-10">
++ Choose a camera move. Cap takes care of the animation.
++ </p>
++ {cards(CAMERA3D_STARTER_SCENES)}
++ <Camera3DSection
++ name="Multi-shot sequences"
++ summary="Optional"
++ open={sequencesOpen()}
++ onOpenChange={setSequencesOpen}
>
-- Close
-- </EditorButton>
-- <span class="text-sm text-gray-10">New 3D scene</span>
++ {cards(CAMERA3D_SCENES)}
++ </Camera3DSection>
</div>
--
-- <p class="text-xs text-gray-10">
-- Lay a chain of camera moves over the whole video
-- </p>
--
-- <Field name="Style" icon={<IconLucideRotate3d class="size-4" />}>
-- <div class="grid grid-cols-3 gap-2">
-- <For each={CAMERA3D_SCENES}>
-- {(item) => (
-- <Camera3DSceneCard
-- scene={item}
-- shotCount={shots()}
-- selected={item.id === scene().id}
-- onClick={() => updateSetup({ sceneId: item.id })}
-- />
-- )}
-- </For>
-- </div>
-- </Field>
--
-- <Field name="How many shots?">
-- <div class="flex flex-col gap-2">
-- <div class="flex flex-row gap-1 p-1 rounded-lg bg-gray-3">
-- <For each={scene().shots.map((_, index) => index + 1)}>
-- {(count) => {
-- const tooShort = () => count > maxShots();
-- return (
-- // The title lives on the wrapper: a disabled button never
-- // hovers, so it would never show its own tooltip.
-- <div
-- class="flex-1"
-- title={tooShort() ? "Video too short" : undefined}
-- >
-- <button
-- type="button"
-- disabled={tooShort()}
-- onClick={() => updateSetup({ shots: count })}
-- class={cx(
-- "py-1 w-full text-xs font-medium rounded-md transition-colors outline-hidden",
-- shots() === count
-- ? "bg-gray-1 dark:bg-gray-5 text-gray-12"
-- : "text-gray-11 hover:text-gray-12",
-- tooShort() && "opacity-40 cursor-not-allowed",
-- )}
-- >
-- {count}
-- </button>
-- </div>
-- );
-- }}
++ <div class="flex shrink-0 flex-col gap-3 border-t border-ed-line bg-ed-card p-4">
++ <Field inline name="Duration">
++ <div class="flex gap-0.5 p-0.5 w-40 rounded-lg bg-ed-ctl">
++ <For each={[3, 6, 10]}>
++ {(duration) => (
++ <button
++ type="button"
++ aria-pressed={props.setup.duration === duration}
++ onClick={() => updateSetup({ duration })}
++ class={cx(
++ "flex-1 h-[26px] rounded-md text-[11.5px] font-medium outline-hidden focus-visible:ring-1 focus-visible:ring-ed-accent",
++ props.setup.duration === duration
++ ? "bg-ed-card text-ed-text-1 shadow-[0_1px_2px_rgba(0,0,0,.12),0_0_0_.5px_rgba(0,0,0,.06)] dark:bg-white/11 dark:shadow-none"
++ : "text-ed-text-2 hover:text-ed-text-1",
++ )}
++ >
++ {duration}s
++ </button>
++ )}
</For>
</div>
-- <p class="text-xs text-gray-10">
-- Shots split the video into separate camera moves.
-- </p>
-- </div>
-- </Field>
--
-- <div class="flex flex-row gap-2 items-center">
++ </Field>
++ <Show
++ when={range()}
++ fallback={
++ <p class="text-[11px] text-ed-text-3">
++ Click an empty part of the 3D track to choose where to add your
++ scene.
++ </p>
++ }
++ >
++ {(placement) => (
++ <p class="text-xs text-gray-10">
++ {placement().start.toFixed(1)}s – {placement().end.toFixed(1)}s ·{" "}
++ {(placement().end - placement().start).toFixed(1)}s. Drag the
++ edges after adding to change the length.
++ </p>
++ )}
++ </Show>
<Button
variant="primary"
size="md"
-- disabled={totalDuration() <= 0}
-- onClick={() => projectActions.addCamera3DScene(scene().id, shots())}
++ disabled={!range()}
++ onClick={() => projectActions.addCamera3DScene()}
>
-- Add scene
-- </Button>
-- <Button variant="gray" size="md" onClick={() => props.onClose()}>
-- Cancel
++ Add {scene().name.toLowerCase()}
</Button>
</div>
</div>
@@@ -5305,88 -5215,88 +5345,7 @@@ function Camera3DSegmentConfig(props:
return (
<div class="space-y-4">
-- <Field name="Templates" icon={<IconLucideRotate3d class="size-4" />}>
-- <div class="flex flex-col gap-3">
-- {/* Scenes lead: one click lays a whole chained sequence over this
-- segment's range, where the rows below author a single shot. */}
-- <div class="grid grid-cols-3 gap-2">
-- <For each={CAMERA3D_SCENES}>
-- {(scene) => (
-- <Camera3DSceneCard
-- scene={scene}
-- onClick={() => applyScene(scene)}
-- />
-- )}
-- </For>
-- </div>
-- <div class="grid grid-cols-5 gap-1.5">
-- <For each={ANGLE_PRESETS}>
-- {(preset) => (
-- <button
-- type="button"
-- onClick={() => applyAnglePreset(preset)}
-- onMouseEnter={() => setHoveredTemplate(`angle-${preset.id}`)}
-- onMouseLeave={() =>
-- setHoveredTemplate((current) =>
-- current === `angle-${preset.id}` ? null : current,
-- )
-- }
-- class={cx(
-- "flex flex-col gap-1 p-1 rounded-lg border transition-colors outline-hidden",
-- activeAnglePresetId() === preset.id
-- ? "border-blue-9 ring-1 ring-blue-9"
-- : "border-gray-4 hover:border-gray-7",
-- )}
-- >
-- <Camera3DPosePreview
-- animate
-- pose={
-- hoveredTemplate() === `angle-${preset.id}`
-- ? anglePresetMotion(preset).to
-- : anglePresetPose(preset)
-- }
-- height={CAMERA3D_ANGLE_PREVIEW_HEIGHT}
-- />
-- <span class="text-[10px] leading-tight text-center text-gray-11">
-- {preset.name}
-- </span>
-- </button>
-- )}
-- </For>
-- </div>
-- <div class="grid grid-cols-4 gap-2">
-- <For each={MOTION_TEMPLATES}>
-- {(template) => (
-- <button
-- type="button"
-- onClick={() => applyTemplate(template)}
-- onMouseEnter={() => setHoveredTemplate(template.id)}
-- onMouseLeave={() =>
-- setHoveredTemplate((current) =>
-- current === template.id ? null : current,
-- )
-- }
-- class="flex flex-col gap-1 p-1 rounded-lg border transition-colors outline-hidden border-gray-4 hover:border-gray-7"
-- >
-- <Camera3DPosePreview
-- animate
-- pose={
-- hoveredTemplate() === template.id
-- ? template.to
-- : template.from
-- }
-- height={CAMERA3D_TEMPLATE_PREVIEW_HEIGHT}
-- />
-- <span class="text-[10px] leading-tight text-center text-gray-11">
-- {template.name}
-- </span>
-- </button>
-- )}
-- </For>
-- </div>
-- </div>
-- </Field>
-- <Field name="Motion" icon={<IconLucideMoveRight class="size-4" />}>
++ <Field name="Motion">
<div class="flex flex-col gap-2">
<div class="flex flex-row gap-2 items-center">
{poseCard("Start", false)}
@@@ -5412,7 -5322,7 +5371,7 @@@
when={!isStill()}
fallback={
<p class="text-[11px] text-gray-10">
-- Pick a template or edit the end pose to add motion
++ Open Customize camera to choose a move or adjust the end pose
</p>
}
>
@@@ -5428,12 -5338,12 +5387,94 @@@
</div>
</Field>
<Camera3DSection
-- name="Camera"
-- icon={<IconLucideVideo class="size-4" />}
++ name="Customize camera"
summary={editingEnd() ? "End pose" : "Start pose"}
open={cameraOpen()}
onOpenChange={setCameraOpen}
>
++ <Field name="Templates">
++ <div class="flex flex-col gap-3">
++ {/* Scenes lead: one click lays a whole chained sequence over this
++ segment's range, where the rows below author a single shot. */}
++ <div class="grid grid-cols-3 gap-2">
++ <For each={CAMERA3D_SCENES}>
++ {(scene) => (
++ <Camera3DSceneCard
++ scene={scene}
++ onClick={() => applyScene(scene)}
++ />
++ )}
++ </For>
++ </div>
++ <div class="grid grid-cols-5 gap-1.5">
++ <For each={ANGLE_PRESETS}>
++ {(preset) => (
++ <button
++ type="button"
++ onClick={() => applyAnglePreset(preset)}
++ onMouseEnter={() =>
++ setHoveredTemplate(`angle-${preset.id}`)
++ }
++ onMouseLeave={() =>
++ setHoveredTemplate((current) =>
++ current === `angle-${preset.id}` ? null : current,
++ )
++ }
++ class={cx(
++ "flex flex-col gap-1 p-1 rounded-lg border transition-colors outline-hidden",
++ activeAnglePresetId() === preset.id
++ ? "border-blue-9 ring-1 ring-blue-9"
++ : "border-gray-4 hover:border-gray-7",
++ )}
++ >
++ <Camera3DPosePreview
++ animate
++ pose={
++ hoveredTemplate() === `angle-${preset.id}`
++ ? anglePresetMotion(preset).to
++ : anglePresetPose(preset)
++ }
++ height={CAMERA3D_ANGLE_PREVIEW_HEIGHT}
++ />
++ <span class="text-[10px] leading-tight text-center text-gray-11">
++ {preset.name}
++ </span>
++ </button>
++ )}
++ </For>
++ </div>
++ <div class="grid grid-cols-4 gap-2">
++ <For each={MOTION_TEMPLATES}>
++ {(template) => (
++ <button
++ type="button"
++ onClick={() => applyTemplate(template)}
++ onMouseEnter={() => setHoveredTemplate(template.id)}
++ onMouseLeave={() =>
++ setHoveredTemplate((current) =>
++ current === template.id ? null : current,
++ )
++ }
++ class="flex flex-col gap-1 p-1 rounded-lg border transition-colors outline-hidden border-gray-4 hover:border-gray-7"
++ >
++ <Camera3DPosePreview
++ animate
++ pose={
++ hoveredTemplate() === template.id
++ ? template.to
++ : template.from
++ }
++ height={CAMERA3D_TEMPLATE_PREVIEW_HEIGHT}
++ />
++ <span class="text-[10px] leading-tight text-center text-gray-11">
++ {template.name}
++ </span>
++ </button>
++ )}
++ </For>
++ </div>
++ </div>
++ </Field>
<div class="flex flex-col gap-3">
<For each={CAMERA3D_SLIDERS}>
{(slider) => (
@@@ -5463,7 -5373,7 +5504,6 @@@
</Camera3DSection>
<Camera3DSection
name="Blur"
-- icon={<IconLucideWind class="size-4" />}
summary={blurSummary()}
open={blurOpen()}
onOpenChange={setBlurOpen}
@@@ -5493,18 -5403,18 +5533,18 @@@
</MenuItem>
)}
>
-- <KSelect.Trigger class="flex flex-row gap-2 items-center px-2 w-full h-8 rounded-lg transition-colors bg-gray-3 disabled:text-gray-11">
++ <KSelect.Trigger class="flex flex-row gap-1.5 items-center px-2 w-full h-[26px] rounded-[7px] transition-colors bg-ed-ctl hover:bg-ed-ctl-hover outline-hidden disabled:text-ed-text-3">
<KSelect.Value<{
value: Camera3DBlurMode;
label: string;
-- }> class="flex-1 text-sm text-left truncate text-(--gray-500) font-normal">
++ }> class="flex-1 text-[12px] text-left truncate text-ed-text-1 font-normal">
{(state) => <span>{state.selectedOption().label}</span>}
</KSelect.Value>
<KSelect.Icon<ValidComponent>
as={(iconProps) => (
<IconCapChevronDown
{...iconProps}
-- class="size-4 shrink-0 transform transition-transform data-expanded:rotate-180 text-(--gray-500)"
++ class="size-3.5 shrink-0 transform transition-transform data-expanded:rotate-180 text-ed-text-3"
/>
)}
/>
@@@ -5526,7 -5436,7 +5566,7 @@@
<Show
when={blur().mode !== "none"}
fallback={
-- <p class="text-xs text-gray-11">
++ <p class="text-[11px] text-ed-text-3">
Pick a mode to blur everything outside the focus area.
</p>
}
@@@ -5535,8 -5445,8 +5575,11 @@@
{(slider) => {
const limit = () => camera3dBlurLimit(slider.key, blur());
return (
-- <div class="flex flex-col gap-1">
-- <span class="text-xs text-gray-11">{slider.label}</span>
++ <Field
++ inline
++ name={slider.label}
++ value={`${blur()[slider.key].toFixed(1)}${slider.unit}`}
++ >
<Slider
value={[blur()[slider.key]]}
onChange={(v) => setBlurValue(slider.key, v[0])}
@@@ -5545,7 -5455,7 +5588,7 @@@
step={limit().step}
formatTooltip={slider.unit}
/>
-- </div>
++ </Field>
);
}}
</For>
@@@ -5563,7 -5473,7 +5606,6 @@@
</Camera3DSection>
<Camera3DSection
name="Advanced"
-- icon={<IconLucideTimer class="size-4" />}
open={advancedOpen()}
onOpenChange={setAdvancedOpen}
>
@@@ -5593,15 -5503,15 +5635,15 @@@
</MenuItem>
)}
>
-- <KSelect.Trigger class="flex flex-row gap-2 items-center px-2 w-full h-8 rounded-lg transition-colors bg-gray-3 disabled:text-gray-11">
-- <KSelect.Value<Camera3DMotionEasing> class="flex-1 text-sm text-left truncate text-(--gray-500) font-normal">
++ <KSelect.Trigger class="flex flex-row gap-1.5 items-center px-2 w-full h-[26px] rounded-[7px] transition-colors bg-ed-ctl hover:bg-ed-ctl-hover outline-hidden disabled:text-ed-text-3">
++ <KSelect.Value<Camera3DMotionEasing> class="flex-1 text-[12px] text-left truncate text-ed-text-1 font-normal">
{(state) => <span>{state.selectedOption().label}</span>}
</KSelect.Value>
<KSelect.Icon<ValidComponent>
as={(iconProps) => (
<IconCapChevronDown
{...iconProps}
-- class="size-4 shrink-0 transform transition-transform data-expanded:rotate-180 text-(--gray-500)"
++ class="size-3.5 shrink-0 transform transition-transform data-expanded:rotate-180 text-ed-text-3"
/>
)}
/>
@@@ -5809,8 -5719,8 +5851,9 @@@ function ZoomSegmentConfig(props:
return (
<>
<Field
++ inline
name={`Zoom ${props.segmentIndex + 1}`}
-- icon={<IconLucideSearch />}
++ value={`${props.segment.amount.toFixed(2)}x`}
>
<Slider
value={[props.segment.amount]}
@@@ -5829,7 -5739,7 +5872,7 @@@
formatTooltip="x"
/>
</Field>
-- <Field name="Zoom Mode" icon={<IconCapSettings />}>
++ <Field name="Zoom Mode">
<KTabs
class="space-y-6"
value={props.segment.mode === "auto" ? "auto" : "manual"}
@@@ -5843,27 -5753,27 +5886,27 @@@
);
}}
>
-- <KTabs.List class="flex flex-row items-center rounded-lg relative border">
++ <KTabs.List class="flex flex-row relative gap-0.5 items-center p-0.5 rounded-lg bg-ed-ctl">
<KTabs.Trigger
value="auto"
-- class="z-10 flex-1 py-2.5 text-gray-11 transition-colors duration-100 outline-hidden data-selected:text-gray-12 peer"
++ class="z-10 flex-1 h-[26px] rounded-md text-[11.5px] font-medium text-ed-text-2 transition-colors duration-100 outline-hidden data-selected:text-ed-text-1 peer"
disabled={!generalSettings.data?.custom_cursor_capture2}
>
Auto
</KTabs.Trigger>
<KTabs.Trigger
value="manual"
-- class="z-10 flex-1 py-2.5 text-gray-11 transition-colors duration-100 outline-hidden data-selected:text-gray-12 peer"
++ class="z-10 flex-1 h-[26px] rounded-md text-[11.5px] font-medium text-ed-text-2 transition-colors duration-100 outline-hidden data-selected:text-ed-text-1 peer"
>
Manual
</KTabs.Trigger>
-- <KTabs.Indicator class="absolute flex p-px inset-0 transition-transform peer-focus-visible:outline-solid outline-2 outline-blue-9 outline-offset-2 rounded-[0.6rem] overflow-hidden">
-- <div class="flex-1 bg-gray-3" />
++ <KTabs.Indicator class="flex overflow-hidden absolute inset-y-0.5 left-0 rounded-md transition-transform">
++ <div class="flex-1 bg-ed-card dark:bg-white/11 shadow-[0_1px_2px_rgba(0,0,0,.12),0_0_0_.5px_rgba(0,0,0,.06)] dark:shadow-none" />
</KTabs.Indicator>
</KTabs.List>
<div class="space-y-3">
<Show when={!generalSettings.data?.custom_cursor_capture2}>
-- <p class="text-xs text-gray-11">
++ <p class="text-[11px] text-ed-text-3">
Auto mode needs cursor capture. Enable "Custom cursor capture
(Studio)" in Settings → General.
</p>
@@@ -6183,21 -6093,21 +6226,16 @@@ function ZoomMultiSegmentConfig(props:
};
const modeButtonClass =
-- "flex-1 py-2.5 rounded-[0.6rem] text-gray-11 transition-colors duration-100 outline-hidden data-[selected='true']:bg-gray-3 data-[selected='true']:text-gray-12 not-data-[selected='true']:hover:text-gray-12 disabled:opacity-40 disabled:cursor-not-allowed";
++ "flex-1 h-[26px] rounded-md text-[11.5px] font-medium text-ed-text-2 transition-colors duration-100 outline-hidden data-[selected='true']:bg-ed-card data-[selected='true']:text-ed-text-1 data-[selected='true']:shadow-[0_1px_2px_rgba(0,0,0,.12),0_0_0_.5px_rgba(0,0,0,.06)] dark:data-[selected='true']:bg-white/11 dark:data-[selected='true']:shadow-none not-data-[selected='true']:hover:text-ed-text-1 disabled:opacity-40 disabled:cursor-not-allowed";
return (
<div class="space-y-4">
-- <div class="flex flex-col gap-6 p-4 rounded-lg border border-gray-200">
++ <div class="flex flex-col gap-3.5 p-4 rounded-xl bg-ed-card-2">
<Field
++ inline
name="Zoom Amount"
-- icon={<IconLucideSearch />}
-- value={
-- <Show when={sharedAmount() === null}>
-- <span class="text-[10px] px-1.5 py-0.5 bg-gray-3 rounded-full text-gray-11 font-medium">
-- Mixed
-- </span>
-- </Show>
-- }
++ badge={sharedAmount() === null ? "Mixed" : undefined}
++ value={`${(sharedAmount() ?? averageAmount()).toFixed(2)}x`}
>
<Slider
value={[sharedAmount() ?? averageAmount()]}
@@@ -6210,16 -6120,16 +6248,9 @@@
</Field>
<Field
name="Zoom Mode"
-- icon={<IconCapSettings />}
-- value={
-- <Show when={sharedMode() === "mixed"}>
-- <span class="text-[10px] px-1.5 py-0.5 bg-gray-3 rounded-full text-gray-11 font-medium">
-- Mixed
-- </span>
-- </Show>
-- }
++ badge={sharedMode() === "mixed" ? "Mixed" : undefined}
>
-- <div class="flex flex-row items-center p-px rounded-lg border">
++ <div class="flex flex-row gap-0.5 items-center p-0.5 rounded-lg bg-ed-ctl">
<button
type="button"
disabled={!generalSettings.data?.custom_cursor_capture2}
@@@ -6239,7 -6149,7 +6270,7 @@@
</button>
</div>
<Show when={!generalSettings.data?.custom_cursor_capture2}>
-- <p class="text-xs text-gray-11">
++ <p class="text-[11px] text-ed-text-3">
Auto mode needs cursor capture. Enable "Custom cursor capture
(Studio)" in Settings → General.
</p>
@@@ -6328,23 -6238,23 +6359,22 @@@ function SyncOffsetsConfig()
return (
<Show when={hasAnySource()}>
-- <div class="flex flex-col gap-6">
-- <div class="space-y-0.5">
-- <h3 class="font-medium text-gray-12">Sync</h3>
-- <p class="text-gray-11">
++ <div class="flex flex-col gap-3.5">
++ <Section name="Sync">
++ <p class="text-[11px] text-ed-text-3">
Fine-tune source offsets if audio or camera drifts out of sync with
the screen recording.
</p>
-- </div>
++ </Section>
<For each={editorInstance.recordings.segments}>
{(_, index) => (
-- <div class="flex flex-col gap-6">
++ <div class="flex flex-col gap-3.5">
<Show when={editorInstance.recordings.segments.length > 1}>
-- <span class="font-medium text-gray-12">Clip {index()}</span>
++ <SectionLabel name={`Clip ${index()}`} />
</Show>
<Show when={clipConfig(index())?.offsetsAutoCalculated === true}>
-- <p class="text-gray-11">
++ <p class="text-[11px] text-ed-text-3">
Cap calculated these offsets automatically to keep audio in
sync with the video. Adjust them if anything still sounds off.
</p>
@@@ -6453,7 -6363,7 +6483,7 @@@ function SourceOffsetField(props:
}
const SCENE_MODE_TRIGGER_CLASS =
-- "z-10 flex justify-center items-center gap-1.5 py-2.5 px-2 text-xs whitespace-nowrap text-gray-11 rounded-[10px] border border-transparent transition-colors duration-200 outline-hidden data-selected:border-gray-3 data-selected:bg-gray-3 data-selected:text-gray-12 not-data-selected:hover:border-gray-7 disabled:opacity-40 disabled:cursor-not-allowed";
++ "flex gap-1.5 justify-center items-center h-[30px] px-2 text-[11.5px] font-medium whitespace-nowrap text-ed-text-2 rounded-lg bg-ed-ctl transition-colors duration-200 outline-hidden data-selected:bg-ed-ctl-hover data-selected:text-ed-text-1 not-data-selected:hover:text-ed-text-1 disabled:opacity-40 disabled:cursor-not-allowed";
// 2D drag pad for a normalized focal point (mirrors the manual-zoom position
// picker): click/drag anywhere to set {x,y} in 0..1, pausing history so the
@@@ -6560,7 -6470,7 +6590,7 @@@ function SceneSegmentConfig(props:
Delete
</EditorButton>
</div>
-- <Field name="Camera Layout" icon={<IconLucideLayout />}>
++ <Field name="Camera Layout">
<KTabs
class="space-y-3"
value={props.segment.mode || "default"}
@@@ -6620,17 -6530,17 +6650,24 @@@
Floating
</KTabs.Trigger>
</KTabs.List>
-- <div class="p-2.5 rounded-md bg-gray-2 border border-gray-3">
-- <div class="text-xs text-center text-gray-11">{description()}</div>
++ <div class="p-2.5 rounded-lg bg-ed-card-2">
++ <div class="text-[11px] text-center text-ed-text-3">
++ {description()}
++ </div>
</div>
</KTabs>
</Field>
-- <Field name="Transition" icon={<IconLucideTimer class="size-4" />}>
-- <div class="flex flex-col gap-3">
-- <Subfield name="In">
++ <Field name="Transition">
++ <div class="flex flex-col">
++ <Field
++ inline
++ name="In"
++ value={`${(
++ props.segment.transitionIn ?? DEFAULT_SCENE_TRANSITION
++ ).toFixed(2)}s`}
++ >
<Slider
-- class="flex-1 ml-4"
value={[props.segment.transitionIn ?? DEFAULT_SCENE_TRANSITION]}
onChange={(v) =>
setProject(
@@@ -6646,10 -6556,10 +6683,15 @@@
step={0.05}
formatTooltip={(v) => `${v.toFixed(2)}s`}
/>
-- </Subfield>
-- <Subfield name="Out">
++ </Field>
++ <Field
++ inline
++ name="Out"
++ value={`${(
++ props.segment.transitionOut ?? DEFAULT_SCENE_TRANSITION
++ ).toFixed(2)}s`}
++ >
<Slider
-- class="flex-1 ml-4"
value={[props.segment.transitionOut ?? DEFAULT_SCENE_TRANSITION]}
onChange={(v) =>
setProject(
@@@ -6665,7 -6575,7 +6707,7 @@@
step={0.05}
formatTooltip={(v) => `${v.toFixed(2)}s`}
/>
-- </Subfield>
++ </Field>
</div>
</Field>
@@@ -6675,8 -6585,8 +6717,12 @@@
props.segment.mode === "floating"
}
>
-- <div class="w-full border-t border-dashed border-gray-5" />
-- <Field name="Screen Zoom" icon={<IconCapEnlarge class="size-4" />}>
++ <div class="w-full border-t border-ed-line" />
++ <Field
++ inline
++ name="Screen Zoom"
++ value={`${Math.round(split().screenZoom * 100)}%`}
++ >
<Slider
value={[split().screenZoom * 100]}
onChange={(v) => updateSplit({ screenZoom: v[0] / 100 })}
@@@ -6686,14 -6596,14 +6732,18 @@@
formatTooltip="%"
/>
</Field>
-- <Field name="Screen Position" icon={<IconLucideMove class="size-4" />}>
++ <Field name="Screen Position">
<PositionPad
value={() => split().screenPosition}
onChange={(pos) => updateSplit({ screenPosition: pos })}
/>
</Field>
-- <div class="w-full border-t border-dashed border-gray-5" />
-- <Field name="Camera Zoom" icon={<IconCapEnlarge class="size-4" />}>
++ <div class="w-full border-t border-ed-line" />
++ <Field
++ inline
++ name="Camera Zoom"
++ value={`${Math.round(split().cameraZoom * 100)}%`}
++ >
<Slider
value={[split().cameraZoom * 100]}
onChange={(v) => updateSplit({ cameraZoom: v[0] / 100 })}
@@@ -6703,7 -6613,7 +6753,7 @@@
formatTooltip="%"
/>
</Field>
-- <Field name="Camera Position" icon={<IconLucideMove class="size-4" />}>
++ <Field name="Camera Position">
<PositionPad
value={() => split().cameraPosition}
onChange={(pos) => updateSplit({ cameraPosition: pos })}
diff --cc apps/desktop/src/routes/editor/CursorStylePicker.tsx
index b033d2387,b033d2387..b1d09286d
--- a/apps/desktop/src/routes/editor/CursorStylePicker.tsx
+++ b/apps/desktop/src/routes/editor/CursorStylePicker.tsx
@@@ -5,13 -5,13 +5,12 @@@ import { createMemo, For, Show } from "
import { Toggle } from "~/components/Toggle";
import Tooltip from "~/components/Tooltip";
import type { CursorRippleConfig, CursorType } from "~/utils/tauri";
--import IconLucideMousePointerClick from "~icons/lucide/mouse-pointer-click";
import macArrow from "../../../../../crates/cursor-info/assets/mac/arrow.svg?raw";
import tahoeArrow from "../../../../../crates/cursor-info/assets/mac/tahoe/default.svg?raw";
import windowsArrow from "../../../../../crates/cursor-info/assets/windows/arrow.svg?raw";
import { RgbInput } from "./color-utils";
import { type TransformedMeta, useEditorContext } from "./context";
--import { Field, Slider } from "./ui";
++import { Field, Section, Slider } from "./ui";
export type CursorFamily = "macos" | "tahoe" | "windows";
type CursorStyle = CursorFamily | "circle";
@@@ -84,7 -84,7 +83,7 @@@ function CursorStyleCard(props: { style
props.style === "circle" ? "Circle" : CURSOR_FAMILIES[props.style].label;
const tile = () => (
-- <div class="flex h-[60px] w-full items-center justify-center rounded-[10px] border border-gray-3 bg-gray-2 transition-colors group-hover:border-gray-5 group-data-checked:border-blue-8 group-data-checked:bg-blue-3/40 group-data-checked:ring-1 group-data-checked:ring-blue-8 group-has-[input:focus-visible]:ring-2 group-has-[input:focus-visible]:ring-blue-8">
++ <div class="flex justify-center items-center w-full h-[60px] rounded-[10px] transition-shadow bg-ed-card-2 ring-1 ring-ed-line group-hover:ring-ed-line-strong group-data-checked:ring-2 group-data-checked:ring-ed-accent group-data-checked:ring-offset-2 group-data-checked:ring-offset-ed-card group-has-[input:focus-visible]:ring-2 group-has-[input:focus-visible]:ring-ed-accent">
<Show
when={props.style !== "circle" && props.style}
fallback={<CircleCursor />}
@@@ -103,7 -103,7 +102,7 @@@
{tile()}
</Tooltip>
</Show>
-- <span class="max-w-full truncate text-[11px] font-medium leading-none text-gray-11 transition-colors group-hover:text-gray-12 group-data-checked:text-gray-12">
++ <span class="max-w-full text-[11px] font-medium leading-none truncate transition-colors text-ed-text-2 group-hover:text-ed-text-1 group-data-checked:text-ed-text-1">
{label()}
</span>
</KRadioGroup.ItemLabel>
@@@ -123,7 -123,7 +122,7 @@@ export function CursorStylePicker()
});
return (
-- <Field name="Cursor Style" icon={<IconCapCursor />}>
++ <Section name="Cursor style">
<KRadioGroup
class="grid grid-cols-4 gap-2"
value={selected()}
@@@ -135,7 -135,7 +134,7 @@@
)}
</For>
</KRadioGroup>
-- </Field>
++ </Section>
);
}
@@@ -148,25 -148,25 +147,25 @@@ export function CursorRippleSection()
return (
<KCollapsible open={ripple().enabled}>
-- <Field
-- name="Click Ripple"
-- icon={<IconLucideMousePointerClick class="size-4" />}
-- value={
-- <Toggle
-- checked={ripple().enabled}
-- onChange={(value) => updateRipple({ enabled: value })}
-- />
-- }
-- />
-- <KCollapsible.Content class="overflow-hidden border-b opacity-0 transition-opacity border-gray-3 animate-collapsible-up data-expanded:animate-collapsible-down data-expanded:opacity-100">
-- <div class="flex flex-col gap-4 pt-4 pb-6">
++ <Field name="Click Ripple" inline>
++ <Toggle
++ checked={ripple().enabled}
++ onChange={(value) => updateRipple({ enabled: value })}
++ />
++ </Field>
++ <KCollapsible.Content class="overflow-hidden opacity-0 transition-opacity animate-collapsible-up data-expanded:animate-collapsible-down data-expanded:opacity-100">
++ <div class="flex flex-col gap-2 pt-1 pb-3.5">
<Field name="Color">
<RgbInput
value={ripple().color}
onChange={(color) => updateRipple({ color })}
/>
</Field>
-- <Field name="Strength">
++ <Field
++ name="Strength"
++ inline
++ value={`${Math.round(ripple().strength * 100)}%`}
++ >
<Slider
value={[Math.round(ripple().strength * 100)]}
onChange={(v) => updateRipple({ strength: v[0] / 100 })}
@@@ -176,7 -176,7 +175,11 @@@
formatTooltip={(v) => `${Math.round(v)}%`}
/>
</Field>
-- <Field name="Size">
++ <Field
++ name="Size"
++ inline
++ value={`${Math.round(ripple().size * 100)}%`}
++ >
<Slider
value={[Math.round(ripple().size * 100)]}
onChange={(v) => updateRipple({ size: v[0] / 100 })}
@@@ -186,7 -186,7 +189,11 @@@
formatTooltip={(v) => `${Math.round(v)}%`}
/>
</Field>
-- <Field name="Duration">
++ <Field
++ name="Duration"
++ inline
++ value={`${ripple().duration.toFixed(2)}s`}
++ >
<Slider
value={[ripple().duration]}
onChange={(v) => updateRipple({ duration: v[0] })}
@@@ -197,6 -197,6 +204,7 @@@
/>
</Field>
</div>
++ <div class="w-full border-t border-ed-line" />
</KCollapsible.Content>
</KCollapsible>
);
diff --cc apps/desktop/src/routes/editor/Editor.tsx
index 6898f8589,23a88edbe..9ae5a3c9f
--- a/apps/desktop/src/routes/editor/Editor.tsx
+++ b/apps/desktop/src/routes/editor/Editor.tsx
@@@ -17,7 -17,7 +17,6 @@@ import
createResource,
createSignal,
ErrorBoundary,
-- For,
lazy,
Match,
on,
@@@ -76,13 -76,12 +75,17 @@@ const TranscriptPanel = lazy(() =
import("./TranscriptPage").then((m) => ({ default: m.TranscriptPanel })),
);
--const DEFAULT_TIMELINE_HEIGHT = 260;
--const MIN_PLAYER_CONTENT_HEIGHT = 320;
++// Preview stage minimum plus the 44px player toolbar and 48px transport bar.
++const MIN_PLAYER_HEIGHT = 320;
const MIN_TIMELINE_HEIGHT = 240;
-const RESIZE_HANDLE_HEIGHT = 16;
-const MIN_PLAYER_HEIGHT = MIN_PLAYER_CONTENT_HEIGHT + RESIZE_HANDLE_HEIGHT;
-const TIMELINE_RESIZE_GRIP_MARKS = [0, 1, 2] as const;
+const MIN_COMPACT_TIMELINE_HEIGHT = 144;
- const RESIZE_HANDLE_HEIGHT = 16;
- const MIN_PLAYER_HEIGHT = MIN_PLAYER_CONTENT_HEIGHT + RESIZE_HANDLE_HEIGHT;
- const TIMELINE_RESIZE_GRIP_MARKS = [0, 1, 2] as const;
++// The timeline card's own vertical padding (pt-2.5 + pb-3); the Timeline
++// reports the height its ruler and rows need inside that box.
++const TIMELINE_CARD_PADDING_Y = 22;
++const DEFAULT_TIMELINE_CONTENT_HEIGHT = 124;
++// Vertical gutter between the player row and the timeline card, plus the
++// gutter below the timeline card; both live inside the measured layout box.
++const LAYOUT_GUTTERS = 16;
const scheduleIdleWork = (callback: () => void) => {
const win = window as Window & {
@@@ -524,54 -501,30 +527,66 @@@ function Inner(props:
const [layoutRef, setLayoutRef] = createSignal<HTMLDivElement>();
const layoutBounds = createElementBounds(layoutRef);
-- const [storedTimelineHeight, setStoredTimelineHeight] = makePersisted(
-- createSignal(DEFAULT_TIMELINE_HEIGHT),
-- { name: "editorTimelineHeight" },
++ const [userTimelineHeight, setUserTimelineHeight] = makePersisted(
++ createSignal<number | null>(null),
++ { name: "editorTimelineHeightOverride" },
);
const [isResizingTimeline, setIsResizingTimeline] = createSignal(false);
++ const [timelineContentHeight, setTimelineContentHeight] = createSignal(
++ DEFAULT_TIMELINE_CONTENT_HEIGHT,
++ );
const [timelineViewportOverflow, setTimelineViewportOverflow] = createSignal<{
overflow: number;
visibleTrackCount: number;
} | null>(null);
++ const huggedTimelineHeight = () =>
++ timelineContentHeight() + TIMELINE_CARD_PADDING_Y;
++
+ const layoutLimits = createMemo(() => {
+ const fullHeight = MIN_PLAYER_HEIGHT + MIN_TIMELINE_HEIGHT;
- const available = Math.max(layoutBounds.height ?? fullHeight, 0);
++ const available = Math.max(
++ (layoutBounds.height ?? fullHeight + LAYOUT_GUTTERS) - LAYOUT_GUTTERS,
++ 0,
++ );
+ const minPlayerHeight =
+ MIN_PLAYER_HEIGHT * Math.min(1, available / fullHeight);
+ const maxTimelineHeight = Math.floor(
+ Math.max(0, available - minPlayerHeight),
+ );
+
+ return {
+ minPlayerHeight,
+ maxTimelineHeight,
+ minTimelineHeight: Math.min(
+ maxTimelineHeight,
+ MIN_TIMELINE_HEIGHT,
++ huggedTimelineHeight(),
+ Math.max(MIN_COMPACT_TIMELINE_HEIGHT, available - MIN_PLAYER_HEIGHT),
+ ),
+ compactness: Math.min(
+ 1,
+ Math.max(
+ 0,
+ (fullHeight - available) /
+ (MIN_TIMELINE_HEIGHT - MIN_COMPACT_TIMELINE_HEIGHT),
+ ),
+ ),
+ };
+ });
+
const clampTimelineHeight = (value: number) => {
- const available = layoutBounds.height ?? 0;
- const maxHeight =
- available > 0
- ? Math.max(MIN_TIMELINE_HEIGHT, available - MIN_PLAYER_HEIGHT)
- : Number.POSITIVE_INFINITY;
- const upperBound = Number.isFinite(maxHeight)
- ? maxHeight
- : Math.max(value, MIN_TIMELINE_HEIGHT);
- return Math.min(Math.max(value, MIN_TIMELINE_HEIGHT), upperBound);
+ const limits = layoutLimits();
+ return Math.min(
+ Math.max(value, limits.minTimelineHeight),
+ limits.maxTimelineHeight,
+ );
};
const timelineHeight = createMemo(() =>
-- Math.round(clampTimelineHeight(storedTimelineHeight())),
++ Math.round(
++ clampTimelineHeight(userTimelineHeight() ?? huggedTimelineHeight()),
++ ),
);
const handleTimelineResizeStart = (event: MouseEvent) => {
@@@ -583,7 -536,7 +598,7 @@@
const handleMove = (moveEvent: MouseEvent) => {
const delta = moveEvent.clientY - startY;
-- setStoredTimelineHeight(clampTimelineHeight(startHeight - delta));
++ setUserTimelineHeight(clampTimelineHeight(startHeight - delta));
};
const handleUp = () => {
@@@ -599,18 -552,20 +614,19 @@@
createEffect(
on(timelineViewportOverflow, (next, prev) => {
if (
++ userTimelineHeight() !== null &&
next &&
prev &&
next.visibleTrackCount > prev.visibleTrackCount &&
next.overflow > 0
) {
- setStoredTimelineHeight((height) =>
- clampTimelineHeight(height + next.overflow),
- );
+ const height = timelineHeight();
+ const expandedHeight = clampTimelineHeight(height + next.overflow);
+ if (expandedHeight > height) {
- setStoredTimelineHeight((preferredHeight) =>
- Math.max(preferredHeight, expandedHeight),
++ setUserTimelineHeight((preferredHeight) =>
++ Math.max(preferredHeight ?? 0, expandedHeight),
+ );
+ }
}
return next;
@@@ -816,7 -771,7 +832,7 @@@
>
<div
ref={setLayoutRef}
-- class="flex overflow-hidden flex-col flex-1 min-h-0"
++ class="flex overflow-hidden flex-col flex-1 gap-2 pb-2 min-h-0"
>
<div
ref={setSplitContainerRef}
@@@ -826,7 -781,7 +842,7 @@@
}}
>
<div
-- class="flex flex-col rounded-xl border bg-gray-1 dark:bg-gray-2 border-gray-3 overflow-hidden"
++ class="flex overflow-hidden flex-col rounded-xl bg-ed-card shadow-ed-card"
style={{
flex: isTranscriptMode()
? `0 0 ${splitRatio() * 100}%`
@@@ -834,33 -789,33 +850,7 @@@
"min-width": "0",
}}
>
- <PlayerContent />
- <div
- role="separator"
- aria-orientation="horizontal"
- class="flex-none shrink-0 border-t border-gray-4 dark:border-gray-5 bg-gray-2/95 dark:bg-gray-3/55 transition-colors hover:bg-gray-3/70 dark:hover:bg-gray-4/55"
- style={{ height: `${RESIZE_HANDLE_HEIGHT}px` }}
- >
- <div
- class="flex flex-col gap-0.5 justify-center items-center h-full w-full cursor-row-resize select-none group"
- classList={{
- "bg-gray-3/55 dark:bg-gray-4/50": isResizingTimeline(),
- }}
- onMouseDown={handleTimelineResizeStart}
- aria-label="Resize timeline height"
- >
- <For each={TIMELINE_RESIZE_GRIP_MARKS}>
- {() => (
- <div
- class="h-0.5 w-20 max-w-[85%] rounded-full bg-gray-6 dark:bg-gray-7 shadow-[0_1px_0_rgb(0_0_0_/0.06)] transition-colors group-hover:bg-gray-9 dark:group-hover:bg-gray-11"
- classList={{
- "bg-gray-9 dark:bg-gray-11": isResizingTimeline(),
- }}
- />
- )}
- </For>
- </div>
- </div>
+ <PlayerContent compactness={layoutLimits().compactness} />
- <div
- role="separator"
- aria-orientation="horizontal"
- class="flex-none shrink-0 border-t border-gray-4 dark:border-gray-5 bg-gray-2/95 dark:bg-gray-3/55 transition-colors hover:bg-gray-3/70 dark:hover:bg-gray-4/55"
- style={{ height: `${RESIZE_HANDLE_HEIGHT}px` }}
- >
- <div
- class="flex flex-col gap-0.5 justify-center items-center h-full w-full cursor-row-resize select-none group"
- classList={{
- "bg-gray-3/55 dark:bg-gray-4/50": isResizingTimeline(),
- }}
- onMouseDown={handleTimelineResizeStart}
- aria-label="Resize timeline height"
- >
- <For each={TIMELINE_RESIZE_GRIP_MARKS}>
- {() => (
- <div
- class="h-0.5 w-20 max-w-[85%] rounded-full bg-gray-6 dark:bg-gray-7 shadow-[0_1px_0_rgb(0_0_0_/0.06)] transition-colors group-hover:bg-gray-9 dark:group-hover:bg-gray-11"
- classList={{
- "bg-gray-9 dark:bg-gray-11": isResizingTimeline(),
- }}
- />
- )}
- </For>
- </div>
- </div>
</div>
<Show when={!isTranscriptMode()}>
<div class="ml-2 flex min-h-0 w-104 min-w-104 flex-none overflow-hidden">
@@@ -894,14 -849,14 +884,14 @@@
aria-orientation="vertical"
>
<div
-- class="w-1 h-10 rounded-full bg-gray-6 dark:bg-gray-7 transition-colors group-hover:bg-gray-9 dark:group-hover:bg-gray-11"
++ class="w-1 h-10 rounded-full transition-colors bg-ed-line-strong group-hover:bg-ed-text-3"
classList={{
-- "bg-gray-9 dark:bg-gray-11": isResizingSplit(),
++ "bg-ed-text-3": isResizingSplit(),
}}
/>
</div>
<div
-- class="flex flex-col min-h-0 overflow-hidden rounded-xl border bg-gray-1 dark:bg-gray-2 border-gray-3 animate-in fade-in duration-150"
++ class="flex overflow-hidden flex-col min-h-0 rounded-xl duration-150 bg-ed-card shadow-ed-card animate-in fade-in"
style={{
flex: isResizingSplit()
? `0 0 calc(${(1 - splitRatio()) * 100}% - 12px)`
@@@ -916,14 -871,14 +906,31 @@@
</Show>
</div>
<div
-- class="flex-none min-h-0 px-2 overflow-hidden relative"
++ class="relative flex-none px-2 min-h-0"
style={{ height: `${timelineHeight()}px` }}
>
-- <div class="h-full">
-- <Timeline
-- onViewportOverflowChange={setTimelineViewportOverflow}
++ <div
++ role="separator"
++ aria-orientation="horizontal"
++ aria-label="Resize timeline height"
++ class="group absolute left-2 right-2 h-[14px] -top-[11px] z-20 cursor-row-resize select-none"
++ onMouseDown={handleTimelineResizeStart}
++ >
++ <div
++ class="absolute left-1/2 top-[5px] w-9 h-1 rounded-full transition-colors -translate-x-1/2 bg-ed-line-strong group-hover:bg-ed-text-3"
++ classList={{
++ "bg-ed-text-3": isResizingTimeline(),
++ }}
/>
</div>
++ <div class="overflow-hidden relative px-3 pt-2.5 pb-3 h-full rounded-xl bg-ed-card shadow-ed-card">
++ <div class="h-full">
++ <Timeline
++ onViewportOverflowChange={setTimelineViewportOverflow}
++ onContentHeightChange={setTimelineContentHeight}
++ />
++ </div>
++ </div>
</div>
</div>
<Dialogs />
@@@ -1362,7 -1282,7 +1369,7 @@@ function Dialogs()
format={false}
>
<NumberField.Input
-- class="rounded-lg bg-gray-2 hover:ring-1 py-[18px] hover:ring-gray-5 h-8 font-normal placeholder:text-black-transparent-40 text-xs caret-gray-500 transition-shadow duration-200 focus:ring-offset-1 focus:bg-gray-3 focus:ring-offset-gray-100 focus:ring-1 focus:ring-gray-10 px-2 w-full text-[0.875rem] outline-hidden text-gray-12"
++ class="rounded-[7px] bg-ed-ctl border-0 py-[18px] h-8 font-normal placeholder:text-ed-text-3 text-xs caret-ed-accent transition-shadow duration-200 hover:bg-ed-ctl-hover focus:bg-ed-ctl-hover focus:ring-1 focus:ring-ed-accent px-2 w-full text-[13px] outline-hidden text-ed-text-1"
onKeyDown={composeEventHandlers<HTMLInputElement>([
(e) => e.stopPropagation(),
])}
diff --cc apps/desktop/src/routes/editor/FrameButton.tsx
index ceb3d7afc,c680c2869..a88339d94
--- a/apps/desktop/src/routes/editor/FrameButton.tsx
+++ b/apps/desktop/src/routes/editor/FrameButton.tsx
@@@ -61,12 -60,12 +61,12 @@@ const FRAME_STYLES: Array<
];
const THEME_TAB_TRIGGER_CLASS =
-- "z-10 flex-1 h-full text-xs text-gray-11 transition-colors duration-100 outline-hidden data-selected:text-gray-12 peer";
++ "z-10 flex-1 h-full text-xs text-ed-text-2 transition-colors duration-100 outline-hidden data-selected:text-ed-text-1 peer";
function SettingRow(props: { name: string; children: JSX.Element }) {
return (
<div class="flex gap-3 justify-between items-center">
-- <span class="text-xs font-medium text-gray-11">{props.name}</span>
++ <span class="text-xs font-medium text-ed-text-2">{props.name}</span>
{props.children}
</div>
);
@@@ -84,112 -83,98 +84,112 @@@ function FrameSettings()
return (
<>
-- <div class="flex flex-col gap-0.5 px-4 pt-3.5 pb-3 border-b shrink-0 border-gray-3">
-- <span class="text-[0.8125rem] font-semibold text-gray-12">Frame</span>
-- <span class="text-[0.6875rem] leading-snug text-gray-10">
++ <div class="flex flex-col gap-0.5 px-4 pt-3.5 pb-3 border-b shrink-0 border-ed-line">
++ <span class="text-[13px] font-semibold text-ed-text-1">Frame</span>
++ <span class="text-[0.6875rem] leading-snug text-ed-text-3">
Wrap your recording in a window or device frame.
</span>
</div>
- <div class="flex flex-col gap-0.5 p-1.5">
- <For each={FRAME_STYLES}>
- {(option) => {
- const selected = () => style() === option.value;
- return (
- <button
- type="button"
- onClick={() => updateFrame({ style: option.value })}
- class="flex items-center gap-3 rounded-xl p-2 text-left outline-hidden transition-colors duration-150 hover:bg-gray-3 focus-visible:bg-gray-3"
- >
- <span
- class={cx(
- "flex justify-center items-center rounded-[0.625rem] size-8 shrink-0 transition-colors duration-150",
- selected()
- ? "bg-blue-9 text-white"
- : "bg-gray-3 text-gray-11",
- )}
+ <Show when={selectedStyle()}>
+ <div class="px-4 pb-3">
+ <StyleGroupToggle group="background" />
+ </div>
+ </Show>
+ <Show
+ when={!selectedStyle() || selectedStyle()?.overrides.background != null}
+ >
+ <div class="flex flex-col gap-0.5 p-1.5">
+ <For each={FRAME_STYLES}>
+ {(option) => {
+ const selected = () => style() === option.value;
+ return (
+ <button
+ type="button"
+ onClick={() => updateFrame({ style: option.value })}
- class="flex items-center gap-3 rounded-xl p-2 text-left outline-hidden transition-colors duration-150 hover:bg-gray-3 focus-visible:bg-gray-3"
++ class="flex items-center gap-3 rounded-xl p-2 text-left outline-hidden transition-colors duration-150 hover:bg-ed-ctl-hover focus-visible:bg-ed-ctl-hover"
>
- <Dynamic component={option.icon} class="size-4" />
- </span>
- <span class="flex flex-col flex-1 min-w-0">
- <span class="text-[0.8125rem] font-medium leading-tight text-gray-12">
- {option.label}
+ <span
+ class={cx(
+ "flex justify-center items-center rounded-[0.625rem] size-8 shrink-0 transition-colors duration-150",
+ selected()
- ? "bg-blue-9 text-white"
- : "bg-gray-3 text-gray-11",
++ ? "bg-ed-accent text-white"
++ : "bg-ed-ctl text-ed-text-2",
+ )}
+ >
+ <Dynamic component={option.icon} class="size-4" />
</span>
- <span class="text-[0.6875rem] leading-snug text-gray-10">
- {option.description}
+ <span class="flex flex-col flex-1 min-w-0">
- <span class="text-[0.8125rem] font-medium leading-tight text-gray-12">
++ <span class="text-[13px] font-medium leading-tight text-ed-text-1">
+ {option.label}
+ </span>
- <span class="text-[0.6875rem] leading-snug text-gray-10">
++ <span class="text-[0.6875rem] leading-snug text-ed-text-3">
+ {option.description}
+ </span>
</span>
- </span>
- <Show when={selected()}>
- <IconCapCircleCheck class="size-4 shrink-0 text-blue-9" />
- </Show>
- </button>
- );
- }}
- </For>
- </div>
- <Show when={style() !== "none" && project.background.frame}>
- {(frame) => (
- <div class="flex flex-col gap-3 p-3 border-t border-gray-3">
- <SettingRow name="Theme">
- <KTabs
- class="w-40"
- value={frame().theme}
- onChange={(v) =>
- updateFrame({ theme: v as FrameConfiguration["theme"] })
- }
- >
- <KTabs.List class="flex relative flex-row items-center h-8 rounded-lg border border-gray-3">
- <KTabs.Trigger value="light" class={THEME_TAB_TRIGGER_CLASS}>
- Light
- </KTabs.Trigger>
- <KTabs.Trigger value="dark" class={THEME_TAB_TRIGGER_CLASS}>
- Dark
- </KTabs.Trigger>
- <KTabs.Indicator class="overflow-hidden absolute inset-0 rounded-lg transition-transform flex p-px peer-focus-visible:outline-solid outline-2 outline-blue-9 outline-offset-2">
- <div class="flex-1 bg-gray-3" />
- </KTabs.Indicator>
- </KTabs.List>
- </KTabs>
- </SettingRow>
- <Show when={frame().style === "browser"}>
- <SettingRow name="URL">
- <div class="w-40">
- <Input
- value={frame().url}
- placeholder="cap.so"
- onInput={(e) => updateFrame({ url: e.currentTarget.value })}
- />
- </div>
- </SettingRow>
- </Show>
- <Show when={frame().style === "macOS"}>
- <SettingRow name="Title">
- <div class="w-40">
- <Input
- value={frame().title}
- placeholder="Window title"
- onInput={(e) =>
- updateFrame({ title: e.currentTarget.value })
- }
- />
- </div>
+ <Show when={selected()}>
- <IconCapCircleCheck class="size-4 shrink-0 text-blue-9" />
++ <IconCapCircleCheck class="size-4 shrink-0 text-ed-accent" />
+ </Show>
+ </button>
+ );
+ }}
+ </For>
+ </div>
+ <Show when={style() !== "none" && project.background.frame}>
+ {(frame) => (
- <div class="flex flex-col gap-3 p-3 border-t border-gray-3">
++ <div class="flex flex-col gap-3 p-3 border-t border-ed-line">
+ <SettingRow name="Theme">
+ <KTabs
+ class="w-40"
+ value={frame().theme}
+ onChange={(v) =>
+ updateFrame({ theme: v as FrameConfiguration["theme"] })
+ }
+ >
- <KTabs.List class="flex relative flex-row items-center h-8 rounded-lg border border-gray-3">
++ <KTabs.List class="flex relative flex-row gap-0.5 items-center p-0.5 h-8 rounded-lg bg-ed-ctl">
+ <KTabs.Trigger
+ value="light"
+ class={THEME_TAB_TRIGGER_CLASS}
+ >
+ Light
+ </KTabs.Trigger>
+ <KTabs.Trigger value="dark" class={THEME_TAB_TRIGGER_CLASS}>
+ Dark
+ </KTabs.Trigger>
- <KTabs.Indicator class="overflow-hidden absolute inset-0 rounded-lg transition-transform flex p-px peer-focus-visible:outline-solid outline-2 outline-blue-9 outline-offset-2">
- <div class="flex-1 bg-gray-3" />
++ <KTabs.Indicator class="overflow-hidden absolute inset-0 rounded-lg transition-transform flex p-0.5 peer-focus-visible:outline-solid outline-2 outline-ed-accent outline-offset-2">
++ <div class="flex-1 rounded-md bg-ed-card shadow-[0_1px_2px_rgba(0,0,0,0.12),0_0_0_0.5px_rgba(0,0,0,0.06)] dark:bg-white/12 dark:shadow-none" />
+ </KTabs.Indicator>
+ </KTabs.List>
+ </KTabs>
</SettingRow>
- </Show>
- </div>
- )}
+ <Show when={frame().style === "browser"}>
+ <SettingRow name="URL">
+ <div class="w-40">
+ <Input
+ value={frame().url}
+ placeholder="cap.so"
+ onInput={(e) =>
+ updateFrame({ url: e.currentTarget.value })
+ }
+ />
+ </div>
+ </SettingRow>
+ </Show>
+ <Show when={frame().style === "macOS"}>
+ <SettingRow name="Title">
+ <div class="w-40">
+ <Input
+ value={frame().title}
+ placeholder="Window title"
+ onInput={(e) =>
+ updateFrame({ title: e.currentTarget.value })
+ }
+ />
+ </div>
+ </SettingRow>
+ </Show>
+ </div>
+ )}
+ </Show>
</Show>
</>
);
@@@ -224,24 -190,24 +224,26 @@@ function ScopedFrameButton()
const hasFrame = () => activeStyle().value !== "none";
return (
-- <KPopover placement="bottom-start" gutter={8} fitViewport>
++ <KPopover placement="bottom-start" gutter={8} flip fitViewport>
<EditorButton<typeof KPopover.Trigger>
as={KPopover.Trigger}
++ variant="text"
tooltipText="Add a frame"
leftIcon={
<Dynamic
component={hasFrame() ? activeStyle().icon : IconLucideAppWindowMac}
-- class="w-5 text-gray-12"
/>
}
rightIcon={<IconCapChevronDown />}
>
-- {hasFrame() ? activeStyle().label : "Frame"}
++ <span class="max-[1200px]:hidden">
++ {hasFrame() ? activeStyle().label : "Frame"}
++ </span>
</EditorButton>
<KPopover.Portal>
<KPopover.Content
class={cx(
-- "z-60 flex w-[min(19rem,calc(100vw-1.5rem))] flex-col overflow-hidden rounded-2xl border border-gray-3 bg-gray-1 shadow-[0_24px_48px_-20px_rgba(0,0,0,0.55)] outline-hidden",
++ "z-60 flex w-[min(19rem,calc(100vw-1.5rem))] flex-col overflow-hidden rounded-2xl bg-ed-card shadow-ed-pop outline-hidden",
"origin-[var(--kb-popover-content-transform-origin)] data-expanded:animate-in data-expanded:fade-in data-expanded:zoom-in-95 data-closed:animate-out data-closed:fade-out data-closed:zoom-out-95",
)}
>
diff --cc apps/desktop/src/routes/editor/GradientEditor.tsx
index a2aba5995,a2aba5995..0570944ba
--- a/apps/desktop/src/routes/editor/GradientEditor.tsx
+++ b/apps/desktop/src/routes/editor/GradientEditor.tsx
@@@ -4,7 -4,7 +4,7 @@@ import { BrandColorsDropdown } from "./
import { hexToRgb, RgbInput } from "./color-utils";
import { useEditorContext } from "./context";
import type { RGBColor } from "./projectConfig";
--import { Slider, Subfield } from "./ui";
++import { EditorButton, Field, Section, Slider } from "./ui";
type GradientSourceFields = {
type: "gradient";
@@@ -93,8 -93,8 +93,8 @@@ export function GradientEditor(props:
return (
<Show when={source()}>
{(src) => (
-- <div class="flex flex-col gap-3">
-- <div class="relative overflow-hidden rounded-xl h-28 border border-gray-5">
++ <div class="flex flex-col gap-3.5">
++ <div class="relative overflow-hidden rounded-xl h-28 border border-ed-line">
<div
class="absolute inset-0"
style={{
@@@ -130,7 -130,7 +130,7 @@@
<div class="flex gap-3 items-end">
<div class="flex-1 min-w-0">
-- <span class="text-[11px] text-gray-10 mb-1 block">From</span>
++ <span class="text-[11px] text-ed-text-3 mb-1 block">From</span>
<div class="flex flex-col gap-2">
<RgbInput
value={src().from}
@@@ -145,7 -145,7 +145,7 @@@
</div>
</div>
<div class="flex-1 min-w-0">
-- <span class="text-[11px] text-gray-10 mb-1 block">To</span>
++ <span class="text-[11px] text-ed-text-3 mb-1 block">To</span>
<div class="flex flex-col gap-2">
<RgbInput
value={src().to}
@@@ -161,12 -161,12 +161,11 @@@
</div>
</div>
-- <div class="w-full border-t border-dashed border-gray-5 my-1" />
++ <div class="w-full border-t border-ed-line" />
-- <Subfield name="Angle" class="gap-4 items-center">
-- <div class="flex flex-1 gap-3 items-center">
++ <div class="flex flex-col">
++ <Field inline name="Angle" value={`${Math.round(angle())}°`}>
<Slider
-- class="flex-1"
value={[angle()]}
onChange={(v) => {
updateGradient({ angle: v[0] });
@@@ -176,16 -176,16 +175,13 @@@
step={1}
formatTooltip={(value) => `${Math.round(value)}°`}
/>
-- <span class="w-12 text-xs text-right text-gray-11 tabular-nums">
-- {Math.round(angle())}°
-- </span>
-- </div>
-- </Subfield>
--
-- <div class="w-full border-t border-dashed border-gray-5 my-1" />
++ </Field>
-- <Subfield name="Noise">
-- <div class="w-[120px]">
++ <Field
++ inline
++ name="Noise"
++ value={`${noiseIntensity().toFixed(1)}%`}
++ >
<Slider
value={[noiseIntensity()]}
onChange={(v) => {
@@@ -198,12 -198,12 +194,14 @@@
step={1}
formatTooltip="%"
/>
-- </div>
-- </Subfield>
++ </Field>
-- <Show when={noiseIntensity() > 0}>
-- <Subfield name="Grain Scale">
-- <div class="w-[120px]">
++ <Show when={noiseIntensity() > 0}>
++ <Field
++ inline
++ name="Grain Scale"
++ value={`${noiseScale().toFixed(1)}%`}
++ >
<Slider
value={[noiseScale()]}
onChange={(v) => {
@@@ -216,71 -216,71 +214,79 @@@
step={1}
formatTooltip="%"
/>
-- </div>
-- </Subfield>
-- </Show>
++ </Field>
++ </Show>
++ </div>
-- <div class="w-full border-t border-dashed border-gray-5 my-1" />
++ <div class="w-full border-t border-ed-line" />
-- <div class="flex flex-wrap gap-2">
-- <button
-- type="button"
-- class="flex items-center justify-center rounded-lg transition-all duration-200 size-8 hover:opacity-80 hover:scale-105 border border-dashed border-gray-8 bg-gray-2 text-gray-10"
-- onClick={() => {
-- updateGradient({
-- from: randomColor(),
-- to: randomColor(),
-- });
-- }}
-- title="Randomize"
-- >
-- <svg
-- xmlns="http://www.w3.org/2000/svg"
-- width="14"
-- height="14"
-- viewBox="0 0 24 24"
-- fill="none"
-- stroke="currentColor"
-- stroke-width="2"
-- stroke-linecap="round"
-- stroke-linejoin="round"
++ <Section
++ name="Presets"
++ action={
++ <EditorButton
++ size="sm"
++ title="Randomize"
++ leftIcon={
++ <svg
++ xmlns="http://www.w3.org/2000/svg"
++ width="14"
++ height="14"
++ viewBox="0 0 24 24"
++ fill="none"
++ stroke="currentColor"
++ stroke-width="2"
++ stroke-linecap="round"
++ stroke-linejoin="round"
++ >
++ <path d="M2 18h1.4c1.3 0 2.5-.6 3.3-1.7l6.1-8.6c.7-1.1 2-1.7 3.3-1.7H22" />
++ <path d="m18 2 4 4-4 4" />
++ <path d="M2 6h1.9c1.5 0 2.9.9 3.6 2.2" />
++ <path d="M22 18h-5.9c-1.3 0-2.6-.7-3.3-1.8l-.5-.8" />
++ <path d="m18 14 4 4-4 4" />
++ </svg>
++ }
++ onClick={() => {
++ updateGradient({
++ from: randomColor(),
++ to: randomColor(),
++ });
++ }}
>
-- <path d="M2 18h1.4c1.3 0 2.5-.6 3.3-1.7l6.1-8.6c.7-1.1 2-1.7 3.3-1.7H22" />
-- <path d="m18 2 4 4-4 4" />
-- <path d="M2 6h1.9c1.5 0 2.9.9 3.6 2.2" />
-- <path d="M22 18h-5.9c-1.3 0-2.6-.7-3.3-1.8l-.5-.8" />
-- <path d="m18 14 4 4-4 4" />
-- </svg>
-- </button>
-- <For each={GRADIENT_PRESETS}>
-- {(gradient) => (
-- <button
-- type="button"
-- class="rounded-lg transition-all duration-200 size-8 hover:opacity-80 hover:scale-105 ring-offset-2 ring-offset-gray-200"
-- classList={{
-- "ring-2 ring-gray-500":
-- src().from[0] === gradient.from[0] &&
-- src().from[1] === gradient.from[1] &&
-- src().from[2] === gradient.from[2] &&
-- src().to[0] === gradient.to[0] &&
-- src().to[1] === gradient.to[1] &&
-- src().to[2] === gradient.to[2],
-- }}
-- style={{
-- background: `linear-gradient(${angle()}deg, rgb(${gradient.from.join(
-- ",",
-- )}), rgb(${gradient.to.join(",")}))`,
-- }}
-- onClick={() => {
-- updateGradient({
-- from: gradient.from as RGBColor,
-- to: gradient.to as RGBColor,
-- });
-- }}
-- />
-- )}
-- </For>
-- </div>
++ Randomize
++ </EditorButton>
++ }
++ >
++ <div class="flex flex-wrap gap-2">
++ <For each={GRADIENT_PRESETS}>
++ {(gradient) => (
++ <button
++ type="button"
++ class="rounded-lg transition-all duration-200 size-8 hover:opacity-80 hover:scale-105 ring-offset-2 ring-offset-ed-card"
++ classList={{
++ "ring-2 ring-ed-accent":
++ src().from[0] === gradient.from[0] &&
++ src().from[1] === gradient.from[1] &&
++ src().from[2] === gradient.from[2] &&
++ src().to[0] === gradient.to[0] &&
++ src().to[1] === gradient.to[1] &&
++ src().to[2] === gradient.to[2],
++ }}
++ style={{
++ background: `linear-gradient(${angle()}deg, rgb(${gradient.from.join(
++ ",",
++ )}), rgb(${gradient.to.join(",")}))`,
++ }}
++ onClick={() => {
++ updateGradient({
++ from: gradient.from as RGBColor,
++ to: gradient.to as RGBColor,
++ });
++ }}
++ />
++ )}
++ </For>
++ </div>
++ </Section>
</div>
)}
</Show>
diff --cc apps/desktop/src/routes/editor/Header.tsx
index c10c6b537,36b3c7224..94b519d12
--- a/apps/desktop/src/routes/editor/Header.tsx
+++ b/apps/desktop/src/routes/editor/Header.tsx
@@@ -1,4 -1,4 +1,3 @@@
--import { Button } from "@cap/ui-solid";
import { ask } from "@tauri-apps/plugin-dialog";
import { revealItemInDir } from "@tauri-apps/plugin-opener";
import { type as ostype } from "@tauri-apps/plugin-os";
@@@ -92,66 -92,63 +91,66 @@@ export function Header(props: { registe
return (
<div
data-tauri-drag-region
- class="flex relative shrink-0 flex-row items-center w-full h-14 max-[900px]:grid max-[900px]:grid-cols-[minmax(0,1fr)_auto] max-[900px]:grid-rows-[36px_36px] max-[900px]:h-[72px]"
- class="flex relative flex-row items-center w-full h-14"
++ class="flex relative shrink-0 flex-row items-center w-full h-13 pr-3 max-[900px]:grid max-[900px]:grid-cols-1 max-[900px]:grid-rows-[36px_36px] max-[900px]:h-[72px] max-[900px]:pr-2"
>
<div
data-tauri-drag-region
- class="flex flex-row flex-1 min-w-0 gap-2 items-center px-4 h-full max-[1200px]:gap-1 max-[1200px]:px-2"
- class={cx("flex flex-row flex-1 gap-2 items-center px-4 h-full")}
++ class={cx(
++ "flex flex-row flex-1 min-w-0 items-center h-full",
++ ostype() === "windows" && "max-[900px]:pr-[146px]",
++ )}
>
- {ostype() === "macos" && <div class="h-full w-16 shrink-0" />}
- {ostype() === "linux" && <CaptionControlsMacOS class="mr-1 shrink-0" />}
- {ostype() === "macos" && <div class="h-full w-16" />}
- {ostype() === "linux" && <CaptionControlsMacOS class="mr-1" />}
-- <EditorButton
-- onClick={async () => {
-- clearTimelineSelection();
--
-- if (!(await ask("Are you sure you want to delete this recording?")))
-- return;
--
-- await commands.editorDeleteProject();
-- }}
-- tooltipText="Delete recording"
-- leftIcon={<IconCapTrash class="w-5" />}
-- />
-- <EditorButton
-- onClick={() => {
-- clearTimelineSelection();
--
-- console.log({ path: `${editorInstance.path}/` });
-- revealItemInDir(`${editorInstance.path}/`);
-- }}
-- tooltipText="Open recording bundle"
-- leftIcon={<IconLucideFolder class="w-5" />}
-- />
++ {ostype() === "macos" && (
++ <div data-tauri-drag-region class="h-full w-[92px] shrink-0" />
++ )}
++ {ostype() === "linux" && (
++ <CaptionControlsMacOS class="mr-1 ml-3 shrink-0" />
++ )}
++ {ostype() === "windows" && <div class="w-3 shrink-0" />}
- <div class="flex min-w-0 flex-row items-center">
- <div class="flex flex-row items-center">
++ <div class="flex gap-1.5 items-center min-w-0">
<NameEditor
name={meta().prettyName}
registerTitleSave={props.registerTitleSave}
readOnly={titleReadOnly()}
setReadOnly={setTitleReadOnly}
/>
- <span class="shrink-0 text-sm text-gray-11">.cap</span>
- <span class="text-sm text-gray-11">.cap</span>
++ <span class="shrink-0 text-[13px] text-ed-text-3">.cap</span>
</div>
-- <div data-tauri-drag-region class="flex-1 h-full" />
-- </div>
-- <div
-- data-tauri-drag-region
- class={cx(
- "flex shrink-0 flex-row items-center justify-center gap-2 px-4 border-x border-black-transparent-10 max-[1200px]:gap-1 max-[1200px]:px-2",
- ostype() === "windows" && "max-[900px]:pr-[146px]",
- )}
- class="flex flex-row items-center justify-center gap-2 px-4 border-x border-black-transparent-10"
-- >
-- <PresetsDropdown />
-- <OrganizationDropdown />
++ <div class="flex gap-0.5 items-center ml-1.5 shrink-0">
++ <EditorButton
++ onClick={() => {
++ clearTimelineSelection();
++
++ console.log({ path: `${editorInstance.path}/` });
++ revealItemInDir(`${editorInstance.path}/`);
++ }}
++ tooltipText="Open recording bundle"
++ leftIcon={<IconLucideFolder />}
++ />
++ <EditorButton
++ onClick={async () => {
++ clearTimelineSelection();
++
++ if (
++ !(await ask("Are you sure you want to delete this recording?"))
++ )
++ return;
++
++ await commands.editorDeleteProject();
++ }}
++ tooltipText="Delete recording"
++ leftIcon={<IconCapTrash />}
++ />
++ </div>
++
++ <div data-tauri-drag-region class="flex-1 h-full min-w-2" />
</div>
<div
data-tauri-drag-region
-- class={cx(
- "flex-1 min-w-max h-full flex flex-row items-center gap-2 pl-2 max-[1200px]:flex-none max-[1200px]:gap-1 max-[900px]:col-span-2 max-[900px]:justify-end",
- "flex-1 h-full flex flex-row items-center gap-2 pl-2",
-- ostype() !== "windows" && "pr-2",
-- )}
++ class="flex shrink-0 flex-row items-center gap-1 max-[900px]:justify-end"
>
<EditorButton
onClick={() => {
@@@ -163,7 -160,7 +162,7 @@@
!projectHistory.canUndo() && !editorState.timeline.selection
}
tooltipText="Undo"
-- leftIcon={<IconCapUndo class="w-5" />}
++ leftIcon={<IconCapUndo />}
/>
<EditorButton
onClick={() => {
@@@ -175,17 -172,15 +174,16 @@@
!projectHistory.canRedo() && !editorState.timeline.selection
}
tooltipText="Redo"
-- leftIcon={<IconCapRedo class="w-5" />}
++ leftIcon={<IconCapRedo />}
/>
-- <div data-tauri-drag-region class="flex-1 h-full" />
-- <Show when={customDomain.data}>
-- <ShareButton />
-- </Show>
-- <Button
-- variant={isClipsOpen() ? "white" : "gray"}
- class="flex shrink-0 gap-1.5 justify-center h-[40px] max-[900px]:h-8"
- class="flex gap-1.5 justify-center h-[40px]"
++ <div class="mx-1.5 w-px h-4 shrink-0 bg-ed-line-strong" />
++ <OrganizationDropdown />
++ <PresetsDropdown />
++ <EditorButton
+ title="Clips"
+ aria-label="Clips"
++ class={cx(isClipsOpen() && "bg-ed-ctl-hover text-ed-text-1")}
++ leftIcon={<IconCapClapperboard />}
onClick={() => {
clearTimelineSelection();
if (isClipsOpen()) {
@@@ -195,15 -190,13 +193,18 @@@
}
}}
>
-- <IconCapClapperboard class="size-4" />
- Clips
- </Button>
+ <span class="max-[1200px]:hidden">Clips</span>
- </Button>
++ </EditorButton>
<Show when={hasTranscript()}>
-- <Button
-- variant={isTranscriptOpen() ? "white" : "gray"}
- class="flex shrink-0 gap-1.5 justify-center h-[40px] max-[900px]:h-8"
- class="flex gap-1.5 justify-center h-[40px]"
++ <EditorButton
+ title={isTranscriptOpen() ? "Back to editor" : "Captions"}
+ aria-label={isTranscriptOpen() ? "Back to editor" : "Captions"}
++ class={cx(isTranscriptOpen() && "bg-ed-ctl-hover text-ed-text-1")}
++ leftIcon={
++ <Show when={isTranscriptOpen()} fallback={<IconCapCaptions />}>
++ <IconLucideArrowLeft />
++ </Show>
++ }
onClick={() => {
clearTimelineSelection();
if (isTranscriptOpen()) {
@@@ -213,26 -206,24 +214,22 @@@
}
}}
>
-- <Show
-- when={isTranscriptOpen()}
-- fallback={<IconCapCaptions class="size-4" />}
-- >
-- <IconLucideArrowLeft class="size-4" />
-- </Show>
- {isTranscriptOpen() ? "Back" : "Captions"}
- </Button>
+ <span class="max-[1200px]:hidden">
+ {isTranscriptOpen() ? "Back" : "Captions"}
+ </span>
- </Button>
++ </EditorButton>
++ </Show>
++ <Show when={customDomain.data}>
++ <ShareButton />
</Show>
<button
type="button"
class={cx(
- "flex shrink-0 gap-1.5 justify-center items-center px-4 w-[100px] h-[40px] max-[900px]:h-8 text-[0.8125rem] font-medium text-white rounded-xl outline-hidden",
- "flex gap-1.5 justify-center items-center px-4 w-full h-[40px] max-w-[100px] text-[0.8125rem] font-medium text-white rounded-xl outline-hidden",
-- "bg-linear-to-b from-[#3b82f6] to-[#2563eb]",
-- "shadow-[0_4px_14px_-6px_rgba(37,99,235,0.5),inset_0_1px_0_0_rgba(255,255,255,0.22)]",
-- "transition-[box-shadow,filter] duration-200 ease-out",
-- "hover:brightness-[1.08] hover:shadow-[0_8px_22px_-8px_rgba(37,99,235,0.6),inset_0_1px_0_0_rgba(255,255,255,0.28)]",
-- "active:brightness-95",
++ "flex shrink-0 gap-[7px] justify-center items-center pl-3 pr-3.5 ml-1.5 h-[30px] text-[13px] font-medium text-white rounded-lg outline-hidden",
++ "bg-linear-to-b from-ed-accent-2 to-ed-accent",
++ "shadow-[inset_0_1px_0_rgba(255,255,255,0.22),0_1px_2px_rgba(0,60,160,0.25)]",
++ "transition-[filter] duration-150 ease-out",
++ "hover:brightness-[1.06] active:brightness-[0.96]",
)}
onClick={() => {
clearTimelineSelection();
@@@ -338,12 -327,12 +335,12 @@@ function NameEditor(props:
);
return (
- <Tooltip disabled={!truncated()} content={props.name}>
- <div class="flex relative flex-row items-center text-sm font-normal font-inherit tracking-inherit text-gray-12">
+ <Tooltip content={props.name} childClass="min-w-0">
- <div class="flex min-w-0 relative flex-row items-center text-sm font-normal font-inherit tracking-inherit text-gray-12">
++ <div class="flex relative flex-row items-center min-w-0 text-[13px] font-medium tracking-[-0.01em] text-ed-text-1">
<input
ref={prettyNameRef}
class={cx(
-- "absolute inset-0 px-px m-0 opacity-0 overflow-hidden focus:opacity-100 bg-transparent border-b border-transparent focus:border-gray-7 focus:outline-hidden peer whitespace-pre select-text",
++ "absolute inset-0 px-px m-0 opacity-0 overflow-hidden focus:opacity-100 bg-transparent border-b border-transparent focus:border-ed-line-strong focus:outline-hidden peer whitespace-pre select-text",
truncated() && "truncate",
(prettyName().length < 5 || prettyName().length > 100) &&
"focus:border-red-500",
diff --cc apps/desktop/src/routes/editor/KeyboardTab.tsx
index 5b5af46fe,d9162485f..59593329c
--- a/apps/desktop/src/routes/editor/KeyboardTab.tsx
+++ b/apps/desktop/src/routes/editor/KeyboardTab.tsx
@@@ -25,11 -30,11 +30,16 @@@ import
MenuItem,
MenuItemList,
PopperContent,
++ Section,
++ SectionLabel,
Slider,
Subfield,
topSlideAnimateClasses,
} from "./ui";
++const selectTriggerClass =
++ "flex flex-row gap-1.5 items-center px-2 h-7 max-w-full rounded-[7px] text-[13px] transition-colors outline-hidden bg-ed-ctl text-ed-text-1 hover:bg-ed-ctl-hover focus-visible:ring-1 focus-visible:ring-ed-accent";
++
export function KeyboardTab(props: {
brandColorSwatches: OrganizationBrandColorSwatch[];
}) {
@@@ -126,119 -162,119 +167,124 @@@
};
return (
-- <Field
-- name="Show keyboard"
-- value={
-- <Toggle checked={getSetting("enabled")} onChange={setKeyboardVisible} />
-- }
-- badge="Beta"
-- >
-- <div class="flex flex-col gap-4">
-- <div
-- class={cx(
-- "space-y-4",
-- !getSetting("enabled") && "opacity-50 pointer-events-none",
-- )}
-- >
-- <Field name="Font Settings" icon={<IconLucideKeyboard />}>
-- <div class="space-y-3">
-- <div class="flex flex-col gap-2">
-- <span class="text-gray-11 text-sm">Font Family</span>
-- <KSelect<string>
-- options={FONT_OPTIONS.map((f) => f.value)}
-- value={getSetting("font")}
-- onChange={(value) => {
-- if (value === null) return;
-- updateSetting("font", value);
-- }}
-- itemComponent={(props) => (
-- <MenuItem<typeof KSelect.Item>
-- as={KSelect.Item}
-- item={props.item}
-- >
-- <KSelect.ItemLabel class="flex-1">
-- {
-- FONT_OPTIONS.find(
-- (f) => f.value === props.item.rawValue,
-- )?.label
-- }
-- </KSelect.ItemLabel>
-- </MenuItem>
-- )}
-- >
-- <KSelect.Trigger class="w-full flex items-center justify-between rounded-lg px-3 py-2 bg-gray-2 border border-gray-3 text-gray-12 hover:border-gray-4 hover:bg-gray-3 focus:border-blue-9 focus:ring-1 focus:ring-blue-9 transition-colors">
-- <KSelect.Value<string>>
-- {(state) =>
++ <div class="flex flex-col gap-3.5">
++ <div class="flex flex-row gap-2 items-center min-h-[22px]">
++ <SectionLabel name="Show keyboard" />
++ <span class="px-1.5 py-0.5 text-[10px] font-medium rounded-full bg-ed-ctl text-ed-text-2">
++ Beta
++ </span>
++ <div class="ml-auto">
++ <Toggle
++ checked={getSetting("enabled")}
++ onChange={setKeyboardVisible}
++ />
++ </div>
++ </div>
++ <div
++ class={cx(
++ "flex flex-col gap-3.5",
++ !getSetting("enabled") && "opacity-50 pointer-events-none",
++ )}
++ >
++ <Section name="Font settings">
++ <div class="flex flex-col gap-2">
++ <Field name="Font Family" inline>
++ <KSelect<string>
++ options={FONT_OPTIONS.map((f) => f.value)}
++ value={getSetting("font")}
++ onChange={(value) => {
++ if (value === null) return;
++ updateSetting("font", value);
++ }}
++ itemComponent={(props) => (
++ <MenuItem<typeof KSelect.Item>
++ as={KSelect.Item}
++ item={props.item}
++ >
++ <KSelect.ItemLabel class="flex-1">
++ {
FONT_OPTIONS.find(
-- (f) => f.value === state.selectedOption(),
++ (f) => f.value === props.item.rawValue,
)?.label
}
-- </KSelect.Value>
-- <KSelect.Icon>
-- <IconCapChevronDown />
-- </KSelect.Icon>
-- </KSelect.Trigger>
-- <KSelect.Portal>
-- <PopperContent<typeof KSelect.Content>
-- as={KSelect.Content}
-- class={topSlideAnimateClasses}
-- >
-- <MenuItemList<typeof KSelect.Listbox>
-- class="max-h-48 overflow-y-auto"
-- as={KSelect.Listbox}
-- />
-- </PopperContent>
-- </KSelect.Portal>
-- </KSelect>
-- </div>
--
-- <div class="flex flex-col gap-2">
-- <span class="text-gray-11 text-sm">Size</span>
-- <Slider
-- value={[getSetting("size")]}
-- onChange={(v) => updateSetting("size", v[0])}
-- minValue={12}
-- maxValue={100}
-- step={1}
-- />
-- </div>
--
-- <div class="flex flex-col gap-2">
-- <span class="text-gray-11 text-sm">Text Color</span>
-- <HexColorInput
-- value={getSetting("color")}
-- brandColorSwatches={props.brandColorSwatches}
-- onChange={(value) => updateSetting("color", value)}
-- />
-- </div>
-- </div>
-- </Field>
++ </KSelect.ItemLabel>
++ </MenuItem>
++ )}
++ >
++ <KSelect.Trigger class={selectTriggerClass}>
++ <KSelect.Value<string> class="truncate">
++ {(state) =>
++ FONT_OPTIONS.find(
++ (f) => f.value === state.selectedOption(),
++ )?.label
++ }
++ </KSelect.Value>
++ <KSelect.Icon>
++ <IconCapChevronDown class="shrink-0 size-3.5 text-ed-text-3" />
++ </KSelect.Icon>
++ </KSelect.Trigger>
++ <KSelect.Portal>
++ <PopperContent<typeof KSelect.Content>
++ as={KSelect.Content}
++ class={topSlideAnimateClasses}
++ >
++ <MenuItemList<typeof KSelect.Listbox>
++ class="overflow-y-auto max-h-48"
++ as={KSelect.Listbox}
++ />
++ </PopperContent>
++ </KSelect.Portal>
++ </KSelect>
++ </Field>
-- <Field name="Background Settings" icon={<IconLucideKeyboard />}>
-- <div class="space-y-3">
-- <div class="flex flex-col gap-2">
-- <span class="text-gray-11 text-sm">Background Color</span>
-- <HexColorInput
-- value={getSetting("backgroundColor")}
-- brandColorSwatches={props.brandColorSwatches}
-- onChange={(value) => updateSetting("backgroundColor", value)}
-- />
-- </div>
--
-- <div class="flex flex-col gap-2">
-- <span class="text-gray-11 text-sm">Background Opacity</span>
-- <Slider
-- value={[getSetting("backgroundOpacity")]}
-- onChange={(v) => updateSetting("backgroundOpacity", v[0])}
-- minValue={0}
-- maxValue={100}
-- step={1}
-- />
-- </div>
-- </div>
-- </Field>
++ <Field name="Size" inline>
++ <Slider
++ value={[getSetting("size")]}
++ onChange={(v) => updateSetting("size", v[0])}
++ minValue={12}
++ maxValue={100}
++ step={1}
++ />
++ </Field>
++
++ <Field name="Text Color">
++ <HexColorInput
++ value={getSetting("color")}
++ brandColorSwatches={props.brandColorSwatches}
++ onChange={(value) => updateSetting("color", value)}
++ />
++ </Field>
++ </div>
++ </Section>
++
++ <div class="w-full border-t border-ed-line" />
+
- <Field name="Position" icon={<IconLucideKeyboard />}>
++ <Section name="Background settings">
++ <div class="flex flex-col gap-2">
++ <Field name="Background Color">
++ <HexColorInput
++ value={getSetting("backgroundColor")}
++ brandColorSwatches={props.brandColorSwatches}
++ onChange={(value) => updateSetting("backgroundColor", value)}
++ />
++ </Field>
++
++ <Field name="Background Opacity" inline>
++ <Slider
++ value={[getSetting("backgroundOpacity")]}
++ onChange={(v) => updateSetting("backgroundOpacity", v[0])}
++ minValue={0}
++ maxValue={100}
++ step={1}
++ />
++ </Field>
++ </div>
++ </Section>
++
++ <div class="w-full border-t border-ed-line" />
+
- <Field name="Position" icon={<IconLucideKeyboard />}>
++ <div class="flex flex-col gap-2">
++ <Field name="Position" inline>
<KSelect<string>
options={KEYBOARD_POSITION_OPTIONS.map((p) => p.value)}
value={getSetting("position")}
@@@ -261,8 -297,8 +307,8 @@@
</MenuItem>
)}
>
-- <KSelect.Trigger class="w-full flex items-center justify-between rounded-lg px-3 py-2 bg-gray-2 border border-gray-3 text-gray-12 hover:border-gray-4 hover:bg-gray-3 focus:border-blue-9 focus:ring-1 focus:ring-blue-9 transition-colors">
-- <KSelect.Value<string>>
++ <KSelect.Trigger class={selectTriggerClass}>
++ <KSelect.Value<string> class="truncate">
{(state) => (
<span>
{
@@@ -274,7 -310,7 +320,7 @@@
)}
</KSelect.Value>
<KSelect.Icon>
-- <IconCapChevronDown />
++ <IconCapChevronDown class="shrink-0 size-3.5 text-ed-text-3" />
</KSelect.Icon>
</KSelect.Trigger>
<KSelect.Portal>
@@@ -288,7 -324,7 +334,7 @@@
</KSelect>
</Field>
-- <Field name="Font Weight" icon={<IconLucideKeyboard />}>
++ <Field name="Font Weight" inline>
<KSelect
options={TEXT_WEIGHT_OPTIONS}
optionValue="value"
@@@ -309,13 -345,13 +355,13 @@@
<KSelect.ItemLabel class="flex-1">
{selectItemProps.item.rawValue.label}
</KSelect.ItemLabel>
-- <KSelect.ItemIndicator class="ml-auto text-blue-9">
++ <KSelect.ItemIndicator class="ml-auto text-ed-accent">
<IconCapCircleCheck />
</KSelect.ItemIndicator>
</MenuItem>
)}
>
-- <KSelect.Trigger class="flex w-full items-center justify-between rounded-md border border-gray-3 bg-gray-2 px-3 py-2 text-sm text-gray-12 transition-colors hover:border-gray-4 hover:bg-gray-3 focus:border-blue-9 focus:outline-hidden focus:ring-1 focus:ring-blue-9">
++ <KSelect.Trigger class={selectTriggerClass}>
<KSelect.Value<{
label: string;
value: number;
@@@ -326,7 -362,7 +372,7 @@@
}
</KSelect.Value>
<KSelect.Icon>
-- <IconCapChevronDown class="size-4 shrink-0 transform transition-transform data-expanded:rotate-180 text-(--gray-500)" />
++ <IconCapChevronDown class="shrink-0 size-3.5 transition-transform transform text-ed-text-3 data-expanded:rotate-180" />
</KSelect.Icon>
</KSelect.Trigger>
<KSelect.Portal>
@@@ -342,112 -378,112 +388,103 @@@
</KSelect.Portal>
</KSelect>
</Field>
++ </div>
-- <Field name="Animation" icon={<IconLucideKeyboard />}>
-- <div class="space-y-3">
-- <div class="flex flex-col gap-2">
-- <span class="text-gray-11 text-sm">Fade Duration</span>
-- <Slider
-- value={[getSetting("fadeDuration") * 100]}
-- onChange={(v) => updateSetting("fadeDuration", v[0] / 100)}
-- minValue={0}
-- maxValue={50}
-- step={1}
-- />
-- <span class="text-xs text-gray-11 text-right">
-- {(getSetting("fadeDuration") * 1000).toFixed(0)}ms
-- </span>
-- </div>
--
-- <div class="flex flex-col gap-2">
-- <span class="text-gray-11 text-sm">Linger Duration</span>
-- <Slider
-- value={[getSetting("lingerDuration") * 100]}
-- onChange={(v) => updateSetting("lingerDuration", v[0] / 100)}
-- minValue={0}
-- maxValue={300}
-- step={5}
-- />
-- <span class="text-xs text-gray-11 text-right">
-- {(getSetting("lingerDuration") * 1000).toFixed(0)}ms
-- </span>
-- </div>
--
-- <div class="flex flex-col gap-2">
-- <span class="text-gray-11 text-sm">Grouping Threshold</span>
-- <Slider
-- value={[getSetting("groupingThresholdMs")]}
-- onChange={(v) => updateSetting("groupingThresholdMs", v[0])}
-- minValue={50}
-- maxValue={1000}
-- step={10}
-- />
-- <span class="text-xs text-gray-11 text-right">
-- {getSetting("groupingThresholdMs").toFixed(0)}ms
-- </span>
-- </div>
-- </div>
-- </Field>
++ <div class="w-full border-t border-ed-line" />
-- <Field name="Behavior" icon={<IconLucideKeyboard />}>
-- <div class="space-y-3">
-- <div class="flex flex-col gap-2">
-- <div class="flex items-center justify-between">
-- <span class="text-gray-11 text-sm">Show Modifier Keys</span>
-- <Toggle
-- checked={getSetting("showModifiers")}
-- onChange={(checked) =>
-- updateSetting("showModifiers", checked)
-- }
-- />
-- </div>
-- </div>
--
-- <div class="flex flex-col gap-2">
-- <div class="flex items-center justify-between">
-- <span class="text-gray-11 text-sm">Show Special Keys</span>
-- <Toggle
-- checked={getSetting("showSpecialKeys")}
-- onChange={(checked) =>
-- updateSetting("showSpecialKeys", checked)
-- }
-- />
-- </div>
-- </div>
--
-- <div class="flex flex-col gap-2">
-- <div class="flex items-center justify-between">
-- <span class="text-gray-11 text-sm">Uppercase</span>
-- <Toggle
-- checked={getSetting("uppercase")}
-- onChange={(checked) => updateSetting("uppercase", checked)}
-- />
-- </div>
-- </div>
-- </div>
-- </Field>
++ <Section name="Animation">
++ <div class="flex flex-col gap-2">
++ <Field
++ name="Fade Duration"
++ inline
++ value={`${(getSetting("fadeDuration") * 1000).toFixed(0)}ms`}
++ >
++ <Slider
++ value={[getSetting("fadeDuration") * 100]}
++ onChange={(v) => updateSetting("fadeDuration", v[0] / 100)}
++ minValue={0}
++ maxValue={50}
++ step={1}
++ />
++ </Field>
++
++ <Field
++ name="Linger Duration"
++ inline
++ value={`${(getSetting("lingerDuration") * 1000).toFixed(0)}ms`}
++ >
++ <Slider
++ value={[getSetting("lingerDuration") * 100]}
++ onChange={(v) => updateSetting("lingerDuration", v[0] / 100)}
++ minValue={0}
++ maxValue={300}
++ step={5}
++ />
++ </Field>
-- <div class="pt-2">
-- <Button
-- onClick={generateSegments}
-- disabled={isGenerating()}
-- class="w-full"
++ <Field
++ name="Grouping Threshold"
++ inline
++ value={`${getSetting("groupingThresholdMs").toFixed(0)}ms`}
>
-- {isGenerating()
-- ? "Generating..."
-- : hasKeyboardSegments()
-- ? "Regenerate Keyboard Segments"
-- : "Generate Keyboard Segments"}
-- </Button>
++ <Slider
++ value={[getSetting("groupingThresholdMs")]}
++ onChange={(v) => updateSetting("groupingThresholdMs", v[0])}
++ minValue={50}
++ maxValue={1000}
++ step={10}
++ />
++ </Field>
</div>
++ </Section>
-- <Show when={selectedSegment()}>
-- {(seg) => (
-- <Field
-- name="Selected Segment Override"
-- icon={<IconLucideKeyboard />}
-- >
-- <div class="space-y-3">
++ <div class="w-full border-t border-ed-line" />
++
++ <Section name="Behavior">
++ <div class="flex flex-col gap-2">
++ <Field name="Show Modifier Keys" inline>
++ <Toggle
++ checked={getSetting("showModifiers")}
++ onChange={(checked) => updateSetting("showModifiers", checked)}
++ />
++ </Field>
++
++ <Field name="Show Special Keys" inline>
++ <Toggle
++ checked={getSetting("showSpecialKeys")}
++ onChange={(checked) =>
++ updateSetting("showSpecialKeys", checked)
++ }
++ />
++ </Field>
++
++ <Field name="Uppercase" inline>
++ <Toggle
++ checked={getSetting("uppercase")}
++ onChange={(checked) => updateSetting("uppercase", checked)}
++ />
++ </Field>
++ </div>
++ </Section>
++
++ <Button
++ onClick={generateSegments}
++ disabled={isGenerating()}
++ class="w-full"
++ >
++ {isGenerating()
++ ? "Generating..."
++ : hasKeyboardSegments()
++ ? "Regenerate Keyboard Segments"
++ : "Generate Keyboard Segments"}
++ </Button>
++
++ <Show when={selectedSegment()}>
++ {(seg) => (
++ <>
++ <div class="w-full border-t border-ed-line" />
++ <Section name="Selected segment override">
++ <div class="flex flex-col gap-1">
<Subfield name="Start Time">
<Input
type="number"
@@@ -499,6 -535,6 +536,7 @@@
</Subfield>
<Subfield name="Fade Duration Override">
<Slider
++ class="flex-1"
value={[
(seg().fadeDurationOverride ??
getSetting("fadeDuration")) * 100,
@@@ -534,21 -570,21 +572,21 @@@
/>
</Subfield>
</div>
-- </Field>
-- )}
-- </Show>
--
-- <Show when={!hasKeyboardSegments()}>
-- <div class="text-center text-sm text-gray-11 py-4">
-- <p>No keyboard segments yet.</p>
-- <p class="text-xs mt-1 text-gray-10">
-- Click "Generate Keyboard Segments" to create segments from
-- recorded keyboard presses.
-- </p>
-- </div>
-- </Show>
-- </div>
++ </Section>
++ </>
++ )}
++ </Show>
++
++ <Show when={!hasKeyboardSegments()}>
++ <div class="py-2 text-center text-ed-text-2">
++ <p class="text-[13px]">No keyboard segments yet.</p>
++ <p class="mt-1 text-[11px] text-ed-text-3">
++ Click "Generate Keyboard Segments" to create segments from
++ recorded keyboard presses.
++ </p>
++ </div>
++ </Show>
</div>
-- </Field>
++ </div>
);
}
diff --cc apps/desktop/src/routes/editor/MaskOverlay.tsx
index df515aca9,df515aca9..82fda05ef
--- a/apps/desktop/src/routes/editor/MaskOverlay.tsx
+++ b/apps/desktop/src/routes/editor/MaskOverlay.tsx
@@@ -7,6 -7,6 +7,7 @@@ import { useCanvasSnapTargets } from ".
import { useEditorContext } from "./context";
import { evaluateMask, type MaskSegment } from "./masks";
import { SNAP_PX, snapMovingRect } from "./snapping";
++import { getOverlayZIndex } from "./timelineTracks";
type MaskOverlayProps = {
size: { width: number; height: number };
@@@ -24,7 -24,7 +25,14 @@@ export function MaskOverlay(props: Mask
const time = currentAbsoluteTime();
return segments
.map((segment, index) => ({ segment, index }))
-- .filter(({ segment }) => time >= segment.start && time < segment.end);
++ .filter(
++ ({ segment }) =>
++ segment.enabled && time >= segment.start && time < segment.end,
++ )
++ .sort(
++ (a, b) =>
++ (a.segment.track ?? 0) - (b.segment.track ?? 0) || a.index - b.index,
++ );
});
const selectedMaskIndex = createMemo(() => {
@@@ -120,24 -120,24 +128,8 @@@
);
};
-- const handleBackgroundClick = (e: MouseEvent) => {
-- if (e.target === e.currentTarget && selectedMaskIndex() !== null) {
-- e.preventDefault();
-- e.stopPropagation();
-- setEditorState("timeline", "selection", null);
-- }
-- };
--
-- const hasMaskSelection = () => selectedMaskIndex() !== null;
--
return (
<div class="absolute inset-0 pointer-events-none">
-- <Show when={hasMaskSelection()}>
-- <div
-- class="absolute inset-0 pointer-events-auto"
-- onMouseDown={handleBackgroundClick}
-- />
-- </Show>
<Show when={shouldRenderHoveredMask() ? hoveredMask() : null}>
{(hovered) => {
const rect = () =>
@@@ -146,6 -146,6 +138,11 @@@
<div
class="absolute z-20 pointer-events-none rounded-md border-2 border-gray-11/65 shadow-[0_0_0_1px_rgba(255,255,255,0.03)]"
style={{
++ "z-index": getOverlayZIndex(
++ project,
++ "mask",
++ hovered().segment.track ?? 0,
++ ),
left: `${rect().left}px`,
top: `${rect().top}px`,
width: `${rect().width}px`,
@@@ -177,6 -177,6 +174,11 @@@
overlayClass(),
)}
style={{
++ "z-index": getOverlayZIndex(
++ project,
++ "mask",
++ segment.track ?? 0,
++ ),
left: `${rect().left}px`,
top: `${rect().top}px`,
width: `${rect().width}px`,
@@@ -189,6 -189,6 +191,7 @@@
<MaskOverlayContent
size={props.size}
maskIndex={index}
++ zIndex={getOverlayZIndex(project, "mask", segment.track ?? 0)}
maskState={maskState}
updateSegment={updateSegment}
projectHistory={projectHistory}
@@@ -204,6 -204,6 +207,7 @@@
function MaskOverlayContent(props: {
size: { width: number; height: number };
maskIndex: number;
++ zIndex: number;
maskState: () => ReturnType<typeof evaluateMask>;
updateSegment: (fn: (segment: MaskSegment) => void) => void;
projectHistory: ReturnType<typeof useEditorContext>["projectHistory"];
@@@ -328,6 -328,6 +332,7 @@@
<div
class="absolute pointer-events-auto group z-10"
style={{
++ "z-index": props.zIndex,
left: `${rect().left}px`,
top: `${rect().top}px`,
width: `${rect().width}px`,
diff --cc apps/desktop/src/routes/editor/OrganizationDropdown.tsx
index 23fe73063,d01a121d0..264b6f8d4
--- a/apps/desktop/src/routes/editor/OrganizationDropdown.tsx
+++ b/apps/desktop/src/routes/editor/OrganizationDropdown.tsx
@@@ -65,7 -65,7 +65,7 @@@ function OrganizationAvatar(props:
return (
<span
class={cx(
-- "flex shrink-0 items-center justify-center overflow-hidden rounded-lg bg-gray-3 text-[11px] font-medium text-gray-12",
++ "flex shrink-0 items-center justify-center overflow-hidden rounded-lg bg-ed-ctl text-[11px] font-medium text-ed-text-1",
props.class ?? "size-6",
)}
>
@@@ -420,10 -416,10 +420,10 @@@ export function OrganizationDropdown()
<div class="p-3">
<div class="flex flex-col gap-3">
<div class="flex flex-col gap-1">
-- <span class="text-sm font-medium text-gray-12">
++ <span class="text-sm font-medium text-ed-text-1">
{fallbackTitle()}
</span>
-- <span class="text-xs leading-5 text-gray-11">
++ <span class="text-xs leading-5 text-ed-text-2">
{fallbackDescription()}
</span>
</div>
@@@ -462,7 -458,7 +462,7 @@@
<For
each={organizationSelection.organizations()}
fallback={
-- <div class="py-1 text-center text-sm text-gray-11">
++ <div class="py-1 text-center text-sm text-ed-text-3">
No organizations
</div>
}
@@@ -479,7 -475,7 +479,7 @@@
<Show
when={selectedOrganization()?.id === organization.id}
>
-- <IconLucideCheck class="size-4 text-blue-500" />
++ <IconLucideCheck class="size-4 text-ed-accent" />
</Show>
</DropdownItem>
)}
@@@ -488,7 -484,7 +488,7 @@@
<Show when={selectedOrganization()?.canEditBrand}>
<MenuItemList<typeof KDropdownMenu.Group>
as={KDropdownMenu.Group}
-- class="border-t"
++ class="border-t border-ed-line"
>
<DropdownItem
onSelect={() =>
diff --cc apps/desktop/src/routes/editor/Player.tsx
index 9dcb2486f,1da2c7e40..931184654
--- a/apps/desktop/src/routes/editor/Player.tsx
+++ b/apps/desktop/src/routes/editor/Player.tsx
@@@ -1,11 -1,12 +1,18 @@@
--import { Select as KSelect } from "@kobalte/core/select";
import { ToggleButton as KToggleButton } from "@kobalte/core/toggle-button";
import { createElementBounds } from "@solid-primitives/bounds";
import { debounce } from "@solid-primitives/scheduled";
import { Menu } from "@tauri-apps/api/menu";
import { type as ostype } from "@tauri-apps/plugin-os";
import { cx } from "cva";
--import { createEffect, createSignal, onMount, Show } from "solid-js";
-
++import {
++ createEffect,
++ createSignal,
++ For,
++ on,
++ onMount,
++ Show,
++ untrack,
++} from "solid-js";
import Tooltip from "~/components/Tooltip";
import { captionsStore } from "~/store/captions";
import { commands } from "~/utils/tauri";
@@@ -24,14 -29,14 +31,7 @@@ import { MaskOverlay } from "./MaskOver
import { PerformanceOverlay } from "./PerformanceOverlay";
import { SplitScreenOverlay } from "./SplitScreenOverlay";
import { TextOverlay } from "./TextOverlay";
--import {
-- EditorButton,
-- MenuItem,
-- MenuItemList,
-- PopperContent,
-- Slider,
-- topLeftAnimateClasses,
--} from "./ui";
++import { EditorButton, Slider } from "./ui";
import { useEditorShortcuts } from "./useEditorShortcuts";
import { formatTime } from "./utils";
@@@ -296,100 -287,89 +296,76 @@@ export function PlayerContent(props: {
return (
<div class="flex flex-col flex-1 min-h-0">
- <div class="flex items-center justify-between gap-3 p-3">
- <div class="flex items-center gap-3">
- <AspectRatioSelect />
+ <div
- class="flex flex-none overflow-x-auto items-center justify-between gap-3 px-3"
- style={{ "padding-block": `${12 - 4 * (props.compactness ?? 0)}px` }}
++ class="flex overflow-x-auto relative z-10 flex-none flex-row gap-3 items-center px-3"
++ style={{ height: `${44 - 4 * (props.compactness ?? 0)}px` }}
+ >
- <div class="flex items-center gap-3">
++ <div class="flex flex-1 gap-0.5 items-center min-w-fit">
+ <Show when={!selectedStyle()}>
+ <AspectRatioSelect />
+ </Show>
<EditorButton
++ variant="text"
tooltipText="Crop Video"
onClick={cropDialogHandler}
-- leftIcon={<IconCapCrop class="w-5 text-gray-12" />}
++ leftIcon={<IconCapCrop />}
>
-- Crop
++ <span class="max-[1200px]:hidden">Crop</span>
</EditorButton>
<FrameButton />
</div>
-- <div class="flex items-center gap-2">
-- <span class="text-xs font-medium text-gray-11">Preview quality</span>
-- <KSelect<{ label: string; value: EditorPreviewQuality }>
-- options={previewOptions}
-- optionValue="value"
-- optionTextValue="label"
-- value={previewOptions.find(
-- (option) => option.value === previewQuality(),
-- )}
-- onChange={(next) => {
-- if (next) handlePreviewQualityChange(next.value);
-- }}
-- disallowEmptySelection
-- itemComponent={(props) => (
-- <MenuItem<typeof KSelect.Item>
-- as={KSelect.Item}
-- item={props.item}
-- >
-- <KSelect.ItemLabel class="flex-1">
-- {props.item.rawValue.label}
-- </KSelect.ItemLabel>
-- <KSelect.ItemIndicator class="ml-auto text-blue-9">
-- <IconCapCircleCheck />
-- </KSelect.ItemIndicator>
-- </MenuItem>
-- )}
++ <div class="flex flex-row flex-none gap-2 items-center">
++ <span class="text-xs text-ed-text-2">Preview</span>
++ <div
++ role="group"
++ aria-label="Preview quality"
++ class="inline-flex gap-0.5 p-0.5 rounded-lg shrink-0 bg-ed-ctl"
>
-- <KSelect.Trigger class="flex items-center gap-2 h-9 px-3 rounded-lg border border-gray-3 bg-gray-2 dark:bg-gray-3 text-sm text-gray-12">
-- <KSelect.Value<{
-- label: string;
-- value: EditorPreviewQuality;
-- }> class="flex-1 text-left truncate">
-- {(state) =>
-- state.selectedOption()?.label ?? "Select preview quality"
-- }
-- </KSelect.Value>
-- <KSelect.Icon>
-- <IconCapChevronDown class="size-4 text-gray-11" />
-- </KSelect.Icon>
-- </KSelect.Trigger>
-- <KSelect.Portal>
-- <PopperContent<typeof KSelect.Content>
-- as={KSelect.Content}
-- class={cx(topLeftAnimateClasses, "w-44")}
-- >
-- <MenuItemList<typeof KSelect.Listbox>
-- as={KSelect.Listbox}
-- class="max-h-40"
-- />
-- </PopperContent>
-- </KSelect.Portal>
-- </KSelect>
++ <For each={previewOptions}>
++ {(option) => {
++ const selected = () => previewQuality() === option.value;
++ return (
++ <button
++ type="button"
++ title={`${option.label} preview quality`}
++ aria-label={`${option.label} preview quality`}
++ aria-pressed={selected()}
++ onClick={() => handlePreviewQualityChange(option.value)}
++ class={cx(
++ "flex items-center px-2.5 h-6 text-xs font-medium rounded-md transition-colors duration-100",
++ selected()
++ ? "bg-ed-card text-ed-text-1 shadow-[0_1px_2px_rgba(0,0,0,0.12),0_0_0_0.5px_rgba(0,0,0,0.06)] dark:bg-white/12 dark:shadow-none"
++ : "text-ed-text-2 hover:text-ed-text-1",
++ )}
++ >
++ {option.label}
++ </button>
++ );
++ }}
++ </For>
++ </div>
</div>
</div>
<PreviewCanvas />
- <div class="relative flex overflow-hidden z-10 flex-row gap-3 justify-between items-center p-5">
- <div class="flex-1">
+ <div
- class="relative flex flex-none overflow-x-auto z-10 flex-row gap-3 justify-between items-center px-5"
- style={{
- "padding-top": `${20 - 12 * (props.compactness ?? 0)}px`,
- "padding-bottom": `${20 - 4 * (props.compactness ?? 0)}px`,
- }}
++ class="flex overflow-x-auto relative z-10 flex-none flex-row gap-3 items-center px-3.5"
++ style={{ height: `${48 - 4 * (props.compactness ?? 0)}px` }}
+ >
- <div class="flex-1">
++ <div class="flex flex-1 items-center min-w-fit whitespace-nowrap">
<Time
-- class="text-gray-12"
++ class="font-medium text-ed-text-1"
seconds={Math.max(
editorState.previewTime ?? editorState.playbackTime,
0,
)}
/>
-- <span class="text-gray-11 text-[0.875rem] tabular-nums"> / </span>
++ <span class="text-[13px] tabular-nums text-ed-text-3"> / </span>
<Time seconds={totalDuration()} />
</div>
-- <div class="flex flex-row items-center justify-center text-gray-11 gap-8 text-[0.875rem]">
++ <div class="flex flex-row flex-none gap-3.5 items-center">
<button
type="button"
-- class="transition-opacity hover:opacity-70 will-change-[opacity]"
++ class="text-ed-text-2 transition-opacity hover:opacity-70 will-change-[opacity]"
onClick={async () => {
await commands.stopPlayback();
setEditorState("playing", false);
@@@ -397,35 -377,35 +373,34 @@@
editorState.timeline.transform.setPosition(0);
}}
>
-- <IconCapPrev class="text-gray-12 size-3" />
++ <IconCapPrev class="size-3.5" />
</button>
<Tooltip kbd={["Space"]} content="Play/Pause video">
<button
type="button"
onClick={handlePlayPauseClick}
-- class="flex justify-center items-center rounded-full border border-gray-300 transition-colors bg-gray-3 hover:bg-gray-4 hover:text-black size-9"
++ class="flex justify-center items-center rounded-full transition-opacity size-8 bg-ed-text-1 text-ed-card hover:opacity-90"
>
{!editorState.playing || isAtEnd() ? (
-- <IconCapPlay class="text-gray-12 size-3" />
++ <IconCapPlay class="size-3" />
) : (
-- <IconCapPause class="text-gray-12 size-3" />
++ <IconCapPause class="size-3" />
)}
</button>
</Tooltip>
<button
type="button"
-- class="transition-opacity hover:opacity-70 will-change-[opacity]"
++ class="text-ed-text-2 transition-opacity hover:opacity-70 will-change-[opacity]"
onClick={async () => {
await commands.stopPlayback();
setEditorState("playing", false);
setEditorState("playbackTime", totalDuration());
}}
>
-- <IconCapNext class="text-gray-12 size-3" />
++ <IconCapNext class="size-3.5" />
</button>
</div>
-- <div class="flex flex-row flex-1 gap-4 justify-end items-center">
-- <div class="flex-1" />
++ <div class="flex flex-row flex-1 gap-0.5 justify-end items-center min-w-fit">
<EditorButton<typeof KToggleButton>
tooltipText="Toggle Split"
kbd={["S"]}
@@@ -435,68 -415,68 +410,60 @@@
}
as={KToggleButton}
variant="danger"
-- leftIcon={
-- <IconCapScissors
-- class={cx(
-- editorState.timeline.interactMode === "split"
-- ? "text-white"
-- : "text-gray-12",
-- )}
-- />
-- }
++ leftIcon={<IconCapScissors />}
/>
-- <div class="w-px h-8 rounded-full bg-gray-4" />
-- <Tooltip kbd={["meta", "-"]} content="Zoom out">
-- <IconCapZoomOut
++ <div class="mx-1.5 w-px h-4 shrink-0 bg-ed-line-strong" />
++ <div class="flex flex-row gap-0.5 items-center" title={zoomHint()}>
++ <EditorButton
++ tooltipText="Zoom out"
++ kbd={["meta", "-"]}
onClick={() => {
editorState.timeline.transform.updateZoom(
editorState.timeline.transform.zoom * 1.1,
editorState.playbackTime,
);
}}
-- class="text-gray-12 size-5 will-change-[opacity] transition-opacity hover:opacity-70"
++ leftIcon={<IconCapZoomOut />}
/>
-- </Tooltip>
-- <Tooltip kbd={["meta", "+"]} content="Zoom in">
-- <IconCapZoomIn
++ <Slider
++ class="w-18 shrink-0"
++ thumbClass="size-3! -top-[4.5px]!"
++ minValue={0}
++ maxValue={1}
++ step={0.001}
++ value={[
++ Math.min(
++ Math.max(
++ 1 - editorState.timeline.transform.zoom / zoomOutLimit(),
++ 0,
++ ),
++ 1,
++ ),
++ ]}
++ onChange={([v]) => {
++ editorState.timeline.transform.updateZoom(
++ (1 - v) * zoomOutLimit(),
++ editorState.playbackTime,
++ );
++ }}
++ formatTooltip={() =>
++ `${editorState.timeline.transform.zoom.toFixed(
++ 0,
++ )} seconds visible`
++ }
++ />
++ <EditorButton
++ tooltipText="Zoom in"
++ kbd={["meta", "+"]}
onClick={() => {
editorState.timeline.transform.updateZoom(
editorState.timeline.transform.zoom / 1.1,
editorState.playbackTime,
);
}}
-- class="text-gray-12 size-5 will-change-[opacity] transition-opacity hover:opacity-70"
++ leftIcon={<IconCapZoomIn />}
/>
-- </Tooltip>
-- <Slider
-- class="w-24"
-- minValue={0}
-- maxValue={1}
-- step={0.001}
-- value={[
-- Math.min(
-- Math.max(
-- 1 - editorState.timeline.transform.zoom / zoomOutLimit(),
-- 0,
-- ),
-- 1,
-- ),
-- ]}
-- onChange={([v]) => {
-- editorState.timeline.transform.updateZoom(
-- (1 - v) * zoomOutLimit(),
-- editorState.playbackTime,
-- );
-- }}
-- formatTooltip={() =>
-- `${editorState.timeline.transform.zoom.toFixed(
-- 0,
-- )} seconds visible`
-- }
-- />
-- </div>
-- <div class="absolute right-2 bottom-1 text-[11px] leading-none text-right text-gray-9 pointer-events-none whitespace-nowrap">
-- {zoomHint()}
++ </div>
</div>
</div>
</div>
@@@ -554,15 -534,15 +521,24 @@@ function PreviewCanvas()
100,
);
-- createEffect(() => {
-- const width = containerBounds.width ?? 0;
-- const height = containerBounds.height ?? 0;
-- if (debouncedBounds().width === 0 && debouncedBounds().height === 0) {
-- setDebouncedBounds({ width, height });
-- } else {
-- updateDebouncedBounds(width, height);
-- }
-- });
++ // Only react to real container-size changes. Reading debouncedBounds()
++ // reactively here would resubscribe the effect to its own debounced write:
++ // the trailing setter rewrites debouncedBounds with a fresh object every
++ // 100ms, which would re-run this effect and re-arm the timer forever,
++ // spinning the whole preview graph at ~10Hz while the editor sits idle.
++ createEffect(
++ on(
++ () => [containerBounds.width ?? 0, containerBounds.height ?? 0] as const,
++ ([width, height]) => {
++ const current = untrack(debouncedBounds);
++ if (current.width === 0 && current.height === 0) {
++ setDebouncedBounds({ width, height });
++ } else {
++ updateDebouncedBounds(width, height);
++ }
++ },
++ ),
++ );
createEffect(() => {
const canvas = canvasRef();
@@@ -583,7 -563,7 +559,7 @@@
console.warn("[Player] Canvas initialized successfully");
});
-- const padding = 4;
++ const padding = 16;
const frameWidth = () => latestFrame()?.width ?? 1920;
const frameHeight = () => latestFrame()?.height ?? 1080;
@@@ -625,7 -605,7 +601,7 @@@
return (
<div
ref={setCanvasContainerRef}
- class="relative flex-1 min-h-0 justify-center items-center"
- class="relative flex-1 justify-center items-center"
++ class="relative flex-1 justify-center items-center min-h-0 bg-ed-card"
style={{ contain: "layout style" }}
onContextMenu={handleContextMenu}
>
@@@ -643,6 -623,6 +619,7 @@@
}}
>
<canvas
++ class="rounded-md shadow-[0_12px_32px_-8px_rgba(0,0,0,0.35),0_0_0_0.5px_rgba(0,0,0,0.12)]"
style={{
width: `${size().width}px`,
height: `${size().height}px`,
@@@ -655,10 -635,9 +632,12 @@@
/>
<Show when={hasFrame()}>
<CanvasElementsOverlay size={size()} />
-- <MaskOverlay size={size()} />
++ <div class="absolute inset-0 isolate pointer-events-none">
++ <MaskOverlay size={size()} />
++ <ImageOverlay size={size()} />
++ <TextOverlay size={size()} />
++ </div>
<CaptionOverlay size={size()} />
- <ImageOverlay size={size()} />
-- <TextOverlay size={size()} />
<SplitScreenOverlay size={size()} />
<SnapGuidesOverlay size={size()} />
<PerformanceOverlay size={size()} />
@@@ -671,7 -650,7 +650,7 @@@
function Time(props: { seconds: number; fps?: number; class?: string }) {
return (
-- <span class={cx("text-gray-11 text-sm tabular-nums", props.class)}>
++ <span class={cx("text-[13px] tabular-nums text-ed-text-3", props.class)}>
{formatTime(props.seconds, props.fps ?? FPS)}
</span>
);
diff --cc apps/desktop/src/routes/editor/PresetsDropdown.tsx
index 38ee9b6f2,6d9b6896d..bd0f7d053
--- a/apps/desktop/src/routes/editor/PresetsDropdown.tsx
+++ b/apps/desktop/src/routes/editor/PresetsDropdown.tsx
@@@ -3,6 -3,6 +3,7 @@@ import { cx } from "cva"
import { For, Show, Suspense } from "solid-js";
import { reconcile } from "solid-js/store";
import toast from "solid-toast";
++import { commands } from "~/utils/tauri";
import { normalizeProject, useEditorContext } from "./context";
import {
DropdownItem,
@@@ -17,6 -17,6 +18,20 @@@
export function PresetsDropdown() {
const { setDialog, presets, setProject, project } = useEditorContext();
++ async function applyDefaultPreset() {
++ const stock = await commands.getDefaultProjectConfig();
++ setProject(
++ reconcile(
++ normalizeProject({
++ ...stock,
++ timeline: project.timeline ?? null,
++ overlayOrder: project.overlayOrder ?? [],
++ clips: project.clips,
++ }),
++ ),
++ );
++ }
++
return (
<KDropdownMenu gutter={8} placement="bottom">
<EditorButton<typeof KDropdownMenu.Trigger>
@@@ -38,11 -36,11 +53,48 @@@
as={KDropdownMenu.Group}
class="overflow-y-auto flex-1 scrollbar-none"
>
++ <KDropdownMenu.Sub gutter={16}>
++ <MenuItem<typeof KDropdownMenu.SubTrigger>
++ as={KDropdownMenu.SubTrigger}
++ class="h-10"
++ onClick={() => {
++ applyDefaultPreset();
++ }}
++ >
++ <span class="mr-auto">Default</span>
++ <Show when={(presets.query.data?.default ?? null) === null}>
++ <span class="px-2 py-1 text-[11px] rounded-full bg-ed-ctl text-ed-text-2">
++ Default
++ </span>
++ </Show>
++ <IconCapSettings class="text-ed-text-3 group-hover:text-[currentColor] shrink-0" />
++ </MenuItem>
++ <KDropdownMenu.Portal>
++ <MenuItemList<typeof KDropdownMenu.SubContent>
++ as={KDropdownMenu.SubContent}
++ class={cx(
++ "w-52 animate-in fade-in slide-in-from-left-1",
++ dropdownContainerClasses,
++ )}
++ >
++ <DropdownItem
++ onSelect={() => {
++ applyDefaultPreset();
++ }}
++ >
++ Apply
++ </DropdownItem>
++ <DropdownItem onSelect={() => presets.setDefault(null)}>
++ Set as default
++ </DropdownItem>
++ </MenuItemList>
++ </KDropdownMenu.Portal>
++ </KDropdownMenu.Sub>
<For
each={presets.query.data?.presets ?? []}
fallback={
-- <div class="py-1 w-full text-sm text-center text-gray-11">
-- No Presets
++ <div class="py-1 w-full text-sm text-center text-ed-text-3">
++ No saved presets
</div>
}
>
@@@ -51,6 -49,6 +103,7 @@@
const normalizedConfig = normalizeProject({
...preset.config,
timeline: project.timeline ?? null,
++ overlayOrder: project.overlayOrder ?? [],
clips: project.clips,
});
setProject(reconcile(normalizedConfig));
@@@ -67,11 -65,11 +120,11 @@@
>
<span class="mr-auto">{preset.name}</span>
<Show when={presets.query.data?.default === i()}>
-- <span class="px-2 py-1 text-[11px] rounded-full bg-gray-2 text-gray-11">
++ <span class="px-2 py-1 text-[11px] rounded-full bg-ed-ctl text-ed-text-2">
Default
</span>
</Show>
-- <IconCapSettings class="text-gray-11 group-hover:text-[currentColor] shrink-0" />
++ <IconCapSettings class="text-ed-text-3 group-hover:text-[currentColor] shrink-0" />
</MenuItem>
<KDropdownMenu.Portal>
<MenuItemList<typeof KDropdownMenu.SubContent>
@@@ -134,7 -132,7 +187,7 @@@
</MenuItemList>
<MenuItemList<typeof KDropdownMenu.Group>
as={KDropdownMenu.Group}
-- class="border-t shrink-0"
++ class="border-t border-ed-line shrink-0"
>
<DropdownItem
onSelect={() => setDialog({ type: "createPreset", open: true })}
diff --cc apps/desktop/src/routes/editor/ShadowSettings.tsx
index cdef3c41e,cdef3c41e..cfdeea3d7
--- a/apps/desktop/src/routes/editor/ShadowSettings.tsx
+++ b/apps/desktop/src/routes/editor/ShadowSettings.tsx
@@@ -39,20 -39,20 +39,20 @@@ const ShadowSettings = (props: Props) =
<button
type="button"
onClick={handleToggle}
-- class="flex gap-1 items-center w-full font-medium text-left transition duration-200 text-gray-12 hover:text-gray-10"
++ class="flex gap-1 items-center w-full text-left transition-colors duration-200 outline-hidden text-ed-text-2 hover:text-ed-text-1"
>
-- <span class="text-sm">Advanced shadow settings</span>
++ <span class="text-[12px] font-medium">Advanced shadow settings</span>
<IconCapChevronDown
class={cx(
-- "size-5",
-- isOpen() ? "transition-transform rotate-180" : "",
++ "size-3.5 text-ed-text-3 transition-transform duration-200",
++ isOpen() && "rotate-180",
)}
/>
</button>
<KCollapsible open={isOpen()}>
<KCollapsible.Content class="overflow-hidden opacity-0 transition-opacity animate-collapsible-up data-expanded:animate-collapsible-down data-expanded:opacity-100">
-- <div class="mt-4 space-y-6 font-medium">
-- <Field name="Size">
++ <div class="flex flex-col mt-2">
++ <Field inline name="Size" value={props.size.value[0]?.toFixed(1)}>
<Slider
value={props.size.value}
onChange={props.size.onChange}
@@@ -61,7 -61,7 +61,11 @@@
step={0.1}
/>
</Field>
-- <Field name="Opacity">
++ <Field
++ inline
++ name="Opacity"
++ value={props.opacity.value[0]?.toFixed(1)}
++ >
<Slider
value={props.opacity.value}
onChange={props.opacity.onChange}
@@@ -70,7 -70,7 +74,7 @@@
step={0.1}
/>
</Field>
-- <Field name="Blur">
++ <Field inline name="Blur" value={props.blur.value[0]?.toFixed(1)}>
<Slider
value={props.blur.value}
onChange={props.blur.onChange}
diff --cc apps/desktop/src/routes/editor/ShareButton.tsx
index b094e41d8,a53fc08a6..8a1207c0c
--- a/apps/desktop/src/routes/editor/ShareButton.tsx
+++ b/apps/desktop/src/routes/editor/ShareButton.tsx
@@@ -1,4 -1,4 +1,3 @@@
--import { Button } from "@cap/ui-solid";
import { Select as KSelect } from "@kobalte/core/select";
import { createMutation } from "@tanstack/solid-query";
import { Channel } from "@tauri-apps/api/core";
@@@ -15,6 -14,6 +14,7 @@@ import { RESOLUTION_OPTIONS } from "./H
import {
Dialog,
DialogContent,
++ EditorButton,
MenuItem,
MenuItemList,
PopperContent,
@@@ -212,33 -197,33 +212,29 @@@ function ShareButton()
};
return (
- <div class="flex gap-3 items-center max-[1200px]:gap-1">
- <div class="flex gap-3 items-center">
-- <Tooltip
-- content={
++ <div class="flex gap-1 items-center">
++ <EditorButton
++ disabled={upload.isPending}
++ tooltipText={
upload.isPending ? "Reuploading video" : "Reupload video"
}
-- >
-- <Button
-- disabled={upload.isPending}
-- onClick={() => {
-- if (editorState.timeline.selection) {
-- setEditorState("timeline", "selection", null);
-- return;
-- }
-- upload.mutate();
-- }}
-- variant="dark"
- class="flex justify-center items-center size-[41px] max-[900px]:size-8 px-0! py-0! space-x-1"
- class="flex justify-center items-center size-[41px] px-0! py-0! space-x-1"
-- >
-- {upload.isPending ? (
-- <IconLucideLoaderCircle class="animate-spin size-4" />
++ onClick={() => {
++ if (editorState.timeline.selection) {
++ setEditorState("timeline", "selection", null);
++ return;
++ }
++ upload.mutate();
++ }}
++ leftIcon={
++ upload.isPending ? (
++ <IconLucideLoaderCircle class="animate-spin" />
) : (
-- <IconLucideRotateCcw class="size-4" />
-- )}
-- </Button>
-- </Tooltip>
++ <IconLucideRotateCcw />
++ )
++ }
++ />
<Tooltip content="Open link">
- <div class="rounded-xl px-3 py-2 flex flex-row items-center gap-1.5 bg-gray-3 hover:bg-gray-4 transition-colors duration-100 max-[900px]:py-1">
- <div class="rounded-xl px-3 py-2 flex flex-row items-center gap-1.5 bg-gray-3 hover:bg-gray-4 transition-colors duration-100">
++ <div class="flex flex-row gap-1.5 items-center px-2.5 h-7 rounded-[7px] transition-colors duration-100 bg-ed-ctl hover:bg-ed-ctl-hover">
<a
href={
linkToDisplay() === customLink
@@@ -247,14 -232,9 +243,14 @@@
}
target="_blank"
rel="noreferrer"
- class="w-full truncate max-w-[200px]"
+ title={linkToDisplay() ?? "Open link"}
+ aria-label="Open recording link"
+ class="w-full truncate max-w-[200px] max-[1400px]:w-4 max-[1400px]:shrink-0"
>
- <span class="text-xs text-gray-12 max-[1400px]:hidden">
- <span class="text-xs text-gray-12">{linkToDisplay()}</span>
++ <span class="text-xs text-ed-text-2 max-[1400px]:hidden">
+ {linkToDisplay()}
+ </span>
- <IconLucideExternalLink class="hidden size-4 text-gray-12 max-[1400px]:block" />
++ <IconLucideExternalLink class="hidden size-4 text-ed-text-2 max-[1400px]:block" />
</a>
{/** Dropdown */}
<Show
@@@ -284,7 -264,7 +280,7 @@@
placement="bottom-end"
gutter={4}
>
-- <KSelect.Trigger class="flex justify-center items-center transition-colors duration-200 rounded-lg size-[22px] text-gray-12 bg-gray-6 hover:bg-gray-7 group focus:outline-hidden focus-visible:outline-hidden">
++ <KSelect.Trigger class="flex justify-center items-center transition-colors duration-200 rounded-md size-5 text-ed-text-2 bg-ed-ctl-hover hover:bg-ed-ctl-active group focus:outline-hidden focus-visible:outline-hidden">
<KSelect.Icon>
<IconCapChevronDown class="size-4 transition-transform duration-200 group-data-expanded:rotate-180" />
</KSelect.Icon>
@@@ -306,7 -286,7 +302,7 @@@
{/** Copy button */}
<Tooltip content="Copy link">
<div
-- class="flex justify-center items-center transition-colors duration-200 rounded-lg size-[22px] text-gray-12 bg-gray-6 hover:bg-gray-7"
++ class="flex justify-center items-center transition-colors duration-200 rounded-md size-5 text-ed-text-2 bg-ed-ctl-hover hover:bg-ed-ctl-active"
onClick={copyLink}
>
{!copyPressed() ? (
diff --cc apps/desktop/src/routes/editor/TextInput.tsx
index 84d6a18a7,84d6a18a7..18a1a154e
--- a/apps/desktop/src/routes/editor/TextInput.tsx
+++ b/apps/desktop/src/routes/editor/TextInput.tsx
@@@ -1,3 -1,3 +1,4 @@@
++import { cx } from "cva";
import type { ComponentProps } from "solid-js";
import { composeEventHandlers } from "~/utils/composeEventHandlers";
@@@ -5,6 -5,6 +6,10 @@@ export function TextInput(props: Compon
return (
<input
{...props}
++ class={cx(
++ "rounded-[7px] border-0 bg-ed-ctl text-ed-text-1 caret-ed-accent outline-hidden transition-colors duration-150 placeholder:text-ed-text-3 hover:bg-ed-ctl-hover focus:bg-ed-ctl-hover focus:ring-1 focus:ring-ed-accent",
++ props.class,
++ )}
onKeyDown={composeEventHandlers<HTMLInputElement, KeyboardEvent>([
props.onKeyDown,
(e) => {
diff --cc apps/desktop/src/routes/editor/TextOverlay.tsx
index 253104368,253104368..2ca0d6fff
--- a/apps/desktop/src/routes/editor/TextOverlay.tsx
+++ b/apps/desktop/src/routes/editor/TextOverlay.tsx
@@@ -26,6 -26,6 +26,7 @@@ import
type TextAlign,
type TextSegment,
} from "./text";
++import { getOverlayZIndex } from "./timelineTracks";
// Figma-style text manipulation on the canvas: the selection box always hugs
// the rendered glyphs (a hidden measure div mirrors the renderer's font
@@@ -58,7 -58,7 +59,14 @@@ export function TextOverlay(props: Text
const time = currentAbsoluteTime();
return segments
.map((segment, index) => ({ segment, index }))
-- .filter(({ segment }) => time >= segment.start && time < segment.end);
++ .filter(
++ ({ segment }) =>
++ segment.enabled && time >= segment.start && time < segment.end,
++ )
++ .sort(
++ (a, b) =>
++ (a.segment.track ?? 0) - (b.segment.track ?? 0) || a.index - b.index,
++ );
});
const selectedTextIndex = createMemo(() => {
@@@ -164,16 -164,16 +172,6 @@@
});
};
-- const handleBackgroundClick = (e: MouseEvent) => {
-- if (e.target === e.currentTarget && selectedTextIndex() !== null) {
-- e.preventDefault();
-- e.stopPropagation();
-- setEditorState("timeline", "selection", null);
-- }
-- };
--
-- const hasTextSelection = () => selectedTextIndex() !== null;
--
// A pending inline-edit request (set when the Add-track picker creates a
// text segment) only survives while that segment stays selected; the
// segment's overlay consumes it on mount.
@@@ -231,17 -231,17 +229,14 @@@
});
return (
-- <div
-- class="absolute inset-0"
-- classList={{ "pointer-events-none": !hasTextSelection() }}
-- onMouseDown={handleBackgroundClick}
-- >
++ <div class="absolute inset-0 pointer-events-none">
<For each={visibleTextSegments()}>
{({ segment, index }) => (
<TextSegmentOverlay
size={props.size}
segment={segment}
index={index}
++ zIndex={getOverlayZIndex(project, "text", segment.track ?? 0)}
isSelected={selectedTextIndex() === index}
onSelect={() => handleSelectSegment(index)}
updateSegment={(fn) => updateSegmentByIndex(index, fn)}
@@@ -309,6 -309,6 +304,7 @@@ function TextSegmentOverlay(props:
size: { width: number; height: number };
segment: TauriTextSegment;
index: number;
++ zIndex: number;
isSelected: boolean;
onSelect: () => void;
updateSegment: (fn: (segment: TextSegment) => void) => void;
@@@ -770,6 -770,6 +766,7 @@@
"cursor-text": editing(),
}}
style={{
++ "z-index": props.zIndex,
left: `${rect().left}px`,
top: `${rect().top}px`,
width: `${rect().width}px`,
diff --cc apps/desktop/src/routes/editor/Timeline/AudioTrack.tsx
index 455164e10,455164e10..c39e04187
--- a/apps/desktop/src/routes/editor/Timeline/AudioTrack.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/AudioTrack.tsx
@@@ -85,31 -85,31 +85,31 @@@ function FadeCornerTriangle(props: { ed
<div
class={cx(
"overflow-hidden size-[11px]",
-- props.edge === "in" ? "rounded-tl-xl" : "rounded-tr-xl",
++ props.edge === "in" ? "rounded-tl-lg" : "rounded-tr-lg",
)}
>
<svg class="block size-full" viewBox="0 0 11 11" aria-hidden="true">
{props.edge === "in" ? (
<>
-- <polygon points="0,0 11,0 0,11" fill="rgba(255,255,255,0.9)" />
++ <polygon class="cap-fade-corner" points="0,0 11,0 0,11" />
<line
++ class="cap-fade-corner-line"
x1="11"
y1="0"
x2="0"
y2="11"
-- stroke="rgba(0,0,0,0.18)"
stroke-width="0.75"
/>
</>
) : (
<>
-- <polygon points="11,0 0,0 11,11" fill="rgba(255,255,255,0.9)" />
++ <polygon class="cap-fade-corner" points="11,0 0,0 11,11" />
<line
++ class="cap-fade-corner-line"
x1="0"
y1="0"
x2="11"
y2="11"
-- stroke="rgba(0,0,0,0.18)"
stroke-width="0.75"
/>
</>
@@@ -143,16 -143,16 +143,16 @@@ function FadeControl(props:
aria-hidden="true"
>
<rect
++ class="cap-fade-shade"
x={geometry().shadeX}
y="0"
width={geometry().shadeWidth}
height="100"
-- fill="rgba(0,0,0,0.34)"
/>
<path
++ class="cap-fade-curve"
d={fadeEnvelopeCurve(props.edge, geometry().span)}
fill="none"
-- stroke="rgba(255,255,255,0.94)"
stroke-width="1.5"
vector-effect="non-scaling-stroke"
/>
@@@ -172,7 -172,7 +172,7 @@@
onMouseDown={props.onMouseDown}
onDblClick={props.onDblClick}
>
-- <div class="absolute top-0 left-1/2 -translate-x-1/2 border border-black/20 bg-white shadow-sm pointer-events-none size-2.5" />
++ <div class="absolute top-0 left-1/2 -translate-x-1/2 bg-ed-card ring-1 ring-ed-line-strong shadow-sm pointer-events-none size-2.5" />
</div>
</Show>
@@@ -400,29 -400,29 +400,20 @@@ export function AudioTrack(props:
fallback={
<button
type="button"
-- class={cx(
-- "group/empty flex gap-2 justify-center items-center w-full text-sm rounded-xl border transition-all duration-200 pointer-events-auto",
++ class="cap-empty-lane pointer-events-auto"
++ data-active={
editorState.timeline.audioPicker === props.laneIndex
-- ? "border-emerald-7 bg-emerald-9/10 text-emerald-11"
-- : "border-dashed border-gray-4/60 bg-gray-3/15 text-(--text-tertiary) hover:border-emerald-7/60 hover:bg-emerald-9/5 hover:text-gray-12",
-- )}
++ ? ""
++ : undefined
++ }
onMouseDown={(e) => e.stopPropagation()}
onClick={(e) => {
e.stopPropagation();
props.onRequestAdd(props.laneIndex);
}}
>
-- <span
-- class={cx(
-- "flex justify-center items-center rounded-full transition-colors size-6",
-- editorState.timeline.audioPicker === props.laneIndex
-- ? "bg-emerald-9 text-emerald-1"
-- : "bg-gray-4/40 text-gray-11 group-hover/empty:bg-emerald-9 group-hover/empty:text-emerald-1",
-- )}
-- >
-- <IconLucidePlus class="size-3.5" />
-- </span>
-- <span class="font-medium">Add audio</span>
++ <span>Add background music or import your own audio</span>
++ <span class="cap-empty-lane-action">· Add audio</span>
</button>
}
>
@@@ -451,12 -451,12 +442,9 @@@
data-index={index}
forceVisible={isDragging()}
segColor="var(--track-audio)"
-- class={cx(
-- "border transition-colors duration-200 group",
-- isSelected() ? "border-emerald-11" : "border-transparent",
-- !segment.enabled && "opacity-50",
-- )}
-- innerClass="ring-emerald-8"
++ class="group"
++ selected={isSelected()}
++ muted={!segment.enabled}
title={segment.name || "Audio"}
segment={segment}
onMouseDown={(e) => {
@@@ -506,7 -506,7 +494,7 @@@
)}
/>
<SegmentContent
-- class="relative z-0 flex justify-center items-center cursor-grab px-3 overflow-hidden"
++ class="relative z-0 flex items-center cursor-grab overflow-hidden"
onMouseDown={createMouseDownDrag(
() => index,
() => ({ original: { ...segment } }),
@@@ -532,16 -532,16 +520,18 @@@
<SegmentLabel
compactAt={24}
full={() => (
-- <div class="flex z-10 gap-1.5 items-center max-w-full text-xs text-white/95 drop-shadow-sm">
-- <IconLucideMusic class="size-3 shrink-0 opacity-90" />
-- <span class="max-w-full font-medium truncate">
++ <div class="cap-seg-labels z-10 max-w-full">
++ <span class="cap-seg-label max-w-full truncate">
{segment.name || "Audio"}
</span>
++ <span class="cap-seg-sublabel">
++ {`${Math.round(segment.end - segment.start)}s`}
++ </span>
</div>
)}
compact={() => (
-- <div class="flex z-10 items-center max-w-full text-xs text-white/95 drop-shadow-sm">
-- <span class="max-w-full font-medium truncate">
++ <div class="cap-seg-labels z-10 max-w-full">
++ <span class="cap-seg-label max-w-full truncate">
{segment.name || "Audio"}
</span>
</div>
diff --cc apps/desktop/src/routes/editor/Timeline/CaptionsTrack.tsx
index e5e5f130d,e5e5f130d..d344925bb
--- a/apps/desktop/src/routes/editor/Timeline/CaptionsTrack.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/CaptionsTrack.tsx
@@@ -1,5 -1,5 +1,4 @@@
import { createEventListenerMap } from "@solid-primitives/event-listener";
--import { cx } from "cva";
import { createMemo, createRoot, For } from "solid-js";
import { useEditorContext } from "../context";
@@@ -144,10 -144,10 +143,11 @@@ export function CaptionsTrack(props:
<For
each={captionSegments()}
fallback={
-- <div class="text-center text-sm text-(--text-tertiary) flex flex-col gap-2 justify-center items-center inset-0 w-full bg-gray-3/20 dark:bg-gray-3/10 rounded-xl">
-- <div>No captions</div>
++ <div class="cap-empty-lane">
++ <span>No captions</span>
<button
-- class="h-8 px-3 rounded-lg border border-green-7/50 bg-green-6/15 text-green-11 text-xs font-medium transition-colors hover:bg-green-6/25 disabled:opacity-50 disabled:cursor-not-allowed"
++ type="button"
++ class="cap-empty-lane-action outline-hidden"
disabled={props.isGenerating}
onMouseDown={(e) => e.stopPropagation()}
onClick={(e) => {
@@@ -155,7 -155,7 +155,7 @@@
void props.onGenerate();
}}
>
-- {props.isGenerating ? "Generating..." : "Generate captions"}
++ · {props.isGenerating ? "Generating..." : "Generate captions"}
</button>
</div>
}
@@@ -173,8 -173,8 +173,8 @@@
// Truncation degrades gracefully, so the same row serves both the
// full and compact tiers; it just clips against a smaller box.
const captionLabel = () => (
-- <div class="flex gap-1 justify-center items-center text-[10px] text-gray-1 dark:text-gray-12">
-- <span class="truncate max-w-full opacity-80">
++ <div class="cap-seg-labels">
++ <span class="cap-seg-label truncate max-w-full">
{segment.text || "Caption"}
</span>
</div>
@@@ -185,11 -185,11 +185,8 @@@
data-caption-segment
data-index={i()}
segColor="var(--track-caption)"
-- class={cx(
-- "border duration-200 transition-colors group",
-- isSelected() ? "border-green-7" : "border-transparent",
-- )}
-- innerClass="ring-green-6"
++ class="group"
++ selected={isSelected()}
title={segment.text || "Caption"}
segment={{
start: segment.start,
@@@ -239,7 -239,7 +236,7 @@@
)}
/>
<SegmentContent
-- class="flex justify-center items-center cursor-grab px-2 overflow-hidden"
++ class="flex items-center cursor-grab overflow-hidden"
onMouseDown={createMouseDownDrag(
i,
() => {
diff --cc apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx
index 0d02e9301,0d02e9301..29ce29541
--- a/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx
@@@ -290,16 -290,16 +290,15 @@@ function WaveformCanvas(props:
ctx.restore();
};
-- drawWaveform(
-- props.micWaveform,
-- "rgba(255,255,255,0.4)",
-- project.audio.micVolumeDb,
-- );
++ const trackColor = getComputedStyle(canvas).color;
++ ctx.globalAlpha = 0.55;
++ drawWaveform(props.micWaveform, trackColor, project.audio.micVolumeDb);
drawWaveform(
props.systemWaveform,
-- "rgba(255,150,0,0.5)",
++ trackColor,
project.audio.systemVolumeDb,
);
++ ctx.globalAlpha = 1;
};
createEffect(() => {
@@@ -343,8 -343,8 +342,8 @@@
ref={(el) => {
canvas = el;
}}
-- class="absolute top-0 h-full pointer-events-none"
-- style={{ left: "0px" }}
++ class="absolute bottom-0 h-[18px] pointer-events-none"
++ style={{ left: "0px", color: "var(--track-clip)" }}
height={CANVAS_HEIGHT}
/>
);
@@@ -371,7 -371,7 +370,7 @@@ function ClipSpeedControl(props:
>
<Popover.Trigger
class={cx(
-- "pointer-events-auto flex items-center gap-0.5 rounded-full bg-black/30 px-1.5 py-0.5 text-[10px] font-medium text-white transition-colors hover:bg-black/50",
++ "pointer-events-auto flex items-center gap-0.5 rounded-full bg-ed-ctl-active px-1.5 py-0.5 text-[10px] font-medium text-ed-text-2 transition-colors hover:bg-ed-ctl-hover hover:text-ed-text-1",
props.triggerClass,
)}
aria-label={`Clip speed: ${props.timescale}x`}
@@@ -383,7 -383,7 +382,7 @@@
<Popover.Portal>
<Popover.Content
onMouseDown={(event) => event.stopPropagation()}
-- class="z-50 flex w-max flex-col gap-1.5 rounded-xl border border-gray-3 bg-gray-1 p-2 text-gray-12 shadow-xl outline-hidden animate-in fade-in slide-in-from-bottom-2"
++ class="z-50 flex w-max flex-col gap-1.5 rounded-xl bg-ed-card p-2 text-ed-text-1 shadow-ed-pop outline-hidden animate-in fade-in slide-in-from-bottom-2"
>
<div class="flex items-center gap-1 rounded-lg bg-gray-2 p-1">
{[0.25, 0.5, 1, 1.5, 2, 4, 8].map((mult) => (
@@@ -818,11 -818,11 +817,8 @@@ export function ClipTrack
</Show>
<SegmentRoot
segColor="var(--track-clip)"
-- class={cx(
-- "border transition-colors duration-200 group",
-- isSelected() ? "border-gray-12" : "border-transparent",
-- )}
-- innerClass="ring-blue-9"
++ class="group"
++ selected={isSelected()}
title={clipTitle()}
segment={relativeSegment()}
onMouseMove={(e) => {
@@@ -969,28 -969,28 +965,34 @@@
return (
<div
class={cx(
-- "absolute inset-y-0 z-[3] flex items-center justify-center gap-1 overflow-hidden bg-black/45 backdrop-saturate-50 border-x transition-colors",
-- causeSelected() ? "border-blue-9" : "border-white/25",
++ "absolute inset-y-0 z-[3] flex items-center justify-center gap-1 overflow-hidden bg-ed-card/75 backdrop-saturate-50 border-x transition-colors",
++ causeSelected()
++ ? "border-ed-accent"
++ : "border-ed-line-strong",
)}
style={{
left: `${(hold[0] - relativeSegment().start) / secsPerPixel()}px`,
width: `${holdWidth()}px`,
"background-image":
-- "repeating-linear-gradient(-45deg, rgba(255,255,255,0.07) 0px, rgba(255,255,255,0.07) 4px, transparent 4px, transparent 8px)",
++ "repeating-linear-gradient(-45deg, rgba(127,127,127,0.12) 0px, rgba(127,127,127,0.12) 4px, transparent 4px, transparent 8px)",
}}
title="Video paused while the fullscreen text is shown"
>
<IconLucidePause
class={cx(
"size-3 shrink-0",
-- causeSelected() ? "text-blue-9" : "text-white/70",
++ causeSelected()
++ ? "text-ed-accent"
++ : "text-ed-text-3",
)}
/>
<Show when={holdWidth() >= 64}>
<span
class={cx(
"text-[10px] font-medium whitespace-nowrap",
-- causeSelected() ? "text-blue-9" : "text-white/70",
++ causeSelected()
++ ? "text-ed-accent"
++ : "text-ed-text-3",
)}
>
Paused
@@@ -1005,7 -1005,7 +1007,7 @@@
<button
type="button"
data-transition
-- class="absolute inset-y-0 left-0 z-[4] grid w-4 -translate-x-1/2 place-items-center bg-blue-9/40 text-xs text-white opacity-0 transition-opacity hover:bg-blue-9/60 group-hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-2 focus-visible:outline-blue-9"
++ class="absolute inset-y-0 left-0 z-[4] grid w-4 -translate-x-1/2 place-items-center bg-ed-accent/40 text-xs text-white opacity-0 transition-opacity hover:bg-ed-accent/60 group-hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-2 focus-visible:outline-ed-accent"
aria-label={`Add transition before clip ${i() + 1}`}
onClick={(event) => {
event.stopPropagation();
@@@ -1043,11 -1043,11 +1045,11 @@@
<Popover.Trigger
data-transition
class={cx(
-- "absolute inset-y-0 left-0 z-[5] overflow-hidden border-x border-blue-7/80 bg-blue-9/25 text-white transition-colors hover:bg-blue-9/40",
++ "absolute inset-y-0 left-0 z-[5] overflow-hidden border-x border-ed-accent/60 bg-ed-accent/20 transition-colors hover:bg-ed-accent/35",
editorState.timeline.selection?.type ===
"transition" &&
editorState.timeline.selection.index === i() &&
-- "bg-blue-9/50 ring-1 ring-inset ring-blue-10",
++ "bg-ed-accent/45 ring-1 ring-inset ring-ed-accent",
)}
style={{
width: `${transition().duration / secsPerPixel()}px`,
@@@ -1062,7 -1062,7 +1064,7 @@@
<Popover.Portal>
<Popover.Content
onMouseDown={(event) => event.stopPropagation()}
-- class="z-50 flex w-64 flex-col gap-3 rounded-xl border border-gray-3 bg-gray-1 p-3 text-gray-12 shadow-xl outline-hidden"
++ class="z-50 flex w-64 flex-col gap-3 rounded-xl bg-ed-card p-3 text-ed-text-1 shadow-ed-pop outline-hidden"
>
<div class="flex items-center justify-between">
<span class="text-sm font-medium">
@@@ -1134,7 -1134,7 +1136,6 @@@
<SegmentHandle
position="start"
data-clip-handle
-- class="opacity-0 group-hover:opacity-100"
onMouseDown={(downEvent) => {
if (split()) return;
const seg = segment();
@@@ -1231,7 -1231,7 +1232,7 @@@
});
}}
/>
-- <SegmentContent class="relative justify-center items-center">
++ <SegmentContent class="relative items-center">
{(() => {
const seg = segment();
@@@ -1254,19 -1254,19 +1255,20 @@@
return (
<SegmentLabel
full={() => (
-- <div class="flex flex-col gap-1 justify-center items-center text-xs whitespace-nowrap text-gray-12">
-- <span class="text-white/70">{clipName()}</span>
-- <div class="flex gap-1 items-center text-md dark:text-gray-12 text-gray-1">
-- <IconLucideClock class="size-3.5" />{" "}
++ <div class="cap-seg-labels">
++ <span class="cap-seg-label truncate">
++ {clipName()}
++ </span>
++ <span class="cap-seg-sublabel">
{formatTime(seg.end - seg.start)}
-- {speedControl()}
-- </div>
++ </span>
++ {speedControl("shrink-0")}
</div>
)}
compact={() => (
-- <div class="flex gap-1 items-center text-[10px] whitespace-nowrap dark:text-gray-12 text-gray-1">
++ <div class="cap-seg-labels">
{speedControl("shrink-0")}
-- <span class="truncate">
++ <span class="cap-seg-sublabel truncate">
{formatTime(seg.end - seg.start)}
</span>
</div>
@@@ -1283,7 -1283,7 +1285,6 @@@
<SegmentHandle
position="end"
data-clip-handle
-- class="opacity-0 group-hover:opacity-100"
onMouseDown={(downEvent) => {
const seg = segment();
const end = seg.end;
@@@ -1467,7 -1467,7 +1468,7 @@@ function Markings(props:
style={{
transform: `translateX(${translateX()}px)`,
}}
-- class="absolute z-10 w-px h-12 bg-linear-to-b from-transparent to-transparent via-white-transparent-40 dark:via-black-transparent-60"
++ class="absolute inset-y-0 z-10 w-px bg-linear-to-b from-transparent to-transparent via-ed-line-strong"
/>
);
}}
diff --cc apps/desktop/src/routes/editor/Timeline/KeyboardTrack.tsx
index 33f9ab02c,33f9ab02c..7a27cfd7b
--- a/apps/desktop/src/routes/editor/Timeline/KeyboardTrack.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/KeyboardTrack.tsx
@@@ -1,5 -1,5 +1,4 @@@
import { createEventListenerMap } from "@solid-primitives/event-listener";
--import { cx } from "cva";
import { createMemo, createRoot, For } from "solid-js";
import { useEditorContext } from "../context";
@@@ -144,11 -144,11 +143,11 @@@ export function KeyboardTrack(props:
<For
each={keyboardSegments()}
fallback={
-- <div class="text-center text-sm text-(--text-tertiary) flex flex-col justify-center items-center inset-0 w-full bg-gray-3/20 dark:bg-gray-3/10 rounded-xl pointer-events-none">
-- <div>No keyboard events</div>
-- <div class="text-[10px] text-(--text-tertiary)/40 mt-0.5">
-- Record keyboard presses or generate from recording
-- </div>
++ <div class="cap-empty-lane pointer-events-none">
++ <span>No keyboard events</span>
++ <span class="cap-empty-lane-action">
++ · Record keyboard presses or generate from recording
++ </span>
</div>
}
>
@@@ -165,8 -165,8 +164,8 @@@
// Truncation degrades gracefully, so the same row serves both the
// full and compact tiers; it just clips against a smaller box.
const keysLabel = () => (
-- <div class="flex gap-1 justify-center items-center font-mono text-[10px] text-gray-1 dark:text-gray-12">
-- <span class="truncate max-w-full opacity-80">
++ <div class="cap-seg-labels font-mono">
++ <span class="cap-seg-label truncate max-w-full">
{segment.displayText || "⌨"}
</span>
</div>
@@@ -177,11 -177,11 +176,8 @@@
data-keyboard-segment
data-index={i()}
segColor="var(--track-keyboard)"
-- class={cx(
-- "border duration-200 transition-colors group",
-- isSelected() ? "border-sky-7" : "border-transparent",
-- )}
-- innerClass="ring-sky-6"
++ class="group"
++ selected={isSelected()}
title={segment.displayText || "Keyboard"}
segment={{
start: segment.start,
@@@ -231,7 -231,7 +227,7 @@@
)}
/>
<SegmentContent
-- class="flex justify-center items-center cursor-grab px-2 overflow-hidden"
++ class="flex items-center cursor-grab overflow-hidden"
onMouseDown={createMouseDownDrag(
i,
() => {
@@@ -261,11 -261,11 +257,7 @@@
compactAt={24}
full={keysLabel}
compact={keysLabel}
-- glyph={() => (
-- <span class="font-mono text-[10px] text-gray-1 opacity-80 dark:text-gray-12">
-- ⌨
-- </span>
-- )}
++ glyph={() => <span class="cap-seg-label font-mono">⌨</span>}
/>
</SegmentContent>
<SegmentHandle
diff --cc apps/desktop/src/routes/editor/Timeline/MaskTrack.tsx
index 668ece38c,668ece38c..573b88119
--- a/apps/desktop/src/routes/editor/Timeline/MaskTrack.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/MaskTrack.tsx
@@@ -1,5 -1,5 +1,4 @@@
import { createEventListenerMap } from "@solid-primitives/event-listener";
--import { cx } from "cva";
import { createMemo, createRoot, createSignal, For, Show } from "solid-js";
import { produce } from "solid-js/store";
@@@ -328,13 -328,13 +327,11 @@@ export function MaskTrack(props:
fallback={
<Show
when={!newSegmentDetails()}
-- fallback={<div class="w-full rounded-xl bg-transparent" />}
++ fallback={<div class="w-full rounded-lg bg-transparent" />}
>
-- <div class="text-center text-sm text-(--text-tertiary) flex flex-col justify-center items-center inset-0 w-full bg-gray-3/20 dark:bg-gray-3/10 hover:bg-gray-3/30 dark:hover:bg-gray-3/20 transition-colors rounded-xl pointer-events-none">
-- <div>Click to add a mask</div>
-- <div class="text-[10px] text-(--text-tertiary)/40 mt-0.5">
-- (Combine sensitive blur or highlight masks)
-- </div>
++ <div class="cap-empty-lane pointer-events-none">
++ <span>Combine sensitive blur or highlight masks</span>
++ <span class="cap-empty-lane-action">· Add mask</span>
</div>
</Show>
}
@@@ -356,13 -356,13 +353,8 @@@
data-mask-segment
data-index={index}
segColor="var(--track-mask)"
-- class={cx(
-- "duration-200 transition-colors group",
-- isSelected()
-- ? "border border-gray-12"
-- : "border border-transparent",
-- )}
-- innerClass="ring-red-5"
++ class="group"
++ selected={isSelected()}
title={`Mask · ${contentLabel()}`}
segment={segment}
onMouseEnter={(e) => {
@@@ -441,7 -441,7 +433,7 @@@
)}
/>
<SegmentContent
-- class="flex justify-center items-center cursor-grab px-3"
++ class="flex items-center cursor-grab"
onMouseDown={createMouseDownDrag(
() => index,
() => {
@@@ -480,16 -480,16 +472,16 @@@
>
<SegmentLabel
full={() => (
-- <div class="flex flex-col gap-0.5 justify-center items-center text-xs whitespace-nowrap text-gray-1 dark:text-gray-12">
-- <span class="opacity-70">Mask</span>
-- <div class="flex gap-1 items-center text-md">
-- <span>{contentLabel()}</span>
-- </div>
++ <div class="cap-seg-labels">
++ <span class="cap-seg-label">Mask</span>
++ <span class="cap-seg-sublabel">{contentLabel()}</span>
</div>
)}
compact={() => (
-- <div class="flex gap-1 items-center text-xs whitespace-nowrap text-gray-1 dark:text-gray-12">
-- <span class="truncate">{contentLabel()}</span>
++ <div class="cap-seg-labels">
++ <span class="cap-seg-label truncate">
++ {contentLabel()}
++ </span>
</div>
)}
/>
@@@ -530,15 -530,15 +522,13 @@@
<Show when={!draggingSegment() && newSegmentDetails()}>
{(details) => (
<SegmentRoot
-- class="pointer-events-none z-10 border border-transparent"
-- innerClass="ring-red-300"
++ class="pointer-events-none z-10"
++ ghost
segColor="var(--track-mask)"
segment={details()}
>
-- <SegmentContent>
-- <p class="w-full text-center text-gray-1 dark:text-gray-12 text-md">
-- +
-- </p>
++ <SegmentContent class="justify-center">
++ <p class="cap-seg-label">+</p>
</SegmentContent>
</SegmentRoot>
)}
diff --cc apps/desktop/src/routes/editor/Timeline/Minimap.tsx
index 408e9a3dc,408e9a3dc..11f18b6c7
--- a/apps/desktop/src/routes/editor/Timeline/Minimap.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/Minimap.tsx
@@@ -99,7 -99,7 +99,7 @@@ export function Minimap()
<div
ref={setBarRef}
class={cx(
-- "relative w-full h-full overflow-hidden rounded-full border border-gray-4 bg-gray-3/80 transition-opacity duration-200",
++ "relative w-full h-full overflow-hidden rounded-[2px] bg-ed-ctl-active transition-opacity duration-200",
zoomedIn() ? "opacity-100" : "pointer-events-none opacity-0",
)}
onMouseDown={handleBarMouseDown}
@@@ -111,13 -111,13 +111,16 @@@
<For each={clipBoundaries()}>
{(offset) => (
<div
-- class="absolute inset-y-0 w-px bg-gray-6/50"
-- style={{ left: `${(offset / total()) * 100}%` }}
++ class="absolute inset-y-0 w-px opacity-50"
++ style={{
++ left: `${(offset / total()) * 100}%`,
++ background: "var(--track-clip)",
++ }}
/>
)}
</For>
<div
-- class="absolute inset-y-0 rounded-full border border-gray-7/80 bg-gray-6/70 transition-colors duration-150 cursor-grab hover:bg-gray-7/70 active:cursor-grabbing"
++ class="absolute inset-y-0 rounded-[2px] bg-ed-text-3/50 transition-colors duration-150 cursor-grab hover:bg-ed-text-3/75 active:cursor-grabbing"
style={{ left: `${chipLeft()}px`, width: `${chipWidth()}px` }}
onMouseDown={(e) => beginDrag(e, "move")}
>
diff --cc apps/desktop/src/routes/editor/Timeline/SceneTrack.tsx
index 22e996585,22e996585..84a08ac56
--- a/apps/desktop/src/routes/editor/Timeline/SceneTrack.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/SceneTrack.tsx
@@@ -2,7 -2,7 +2,6 @@@ import
createEventListener,
createEventListenerMap,
} from "@solid-primitives/event-listener";
--import { cx } from "cva";
import {
batch,
createEffect,
@@@ -215,11 -215,11 +214,9 @@@ export function SceneTrack(props:
<For
each={project.timeline?.sceneSegments}
fallback={
-- <div class="text-center text-sm text-(--text-tertiary) flex flex-col justify-center items-center inset-0 w-full bg-gray-3/20 dark:bg-gray-3/10 hover:bg-gray-3/30 dark:hover:bg-gray-3/20 transition-colors rounded-xl pointer-events-none">
-- <div>Click to add scene segment</div>
-- <div class="text-[10px] text-(--text-tertiary)/40 mt-0.5">
-- (Make the camera full screen, or hide it)
-- </div>
++ <div class="cap-empty-lane pointer-events-none">
++ <span>Switch layouts between your screen and camera</span>
++ <span class="cap-empty-lane-action">· Add scene</span>
</div>
}
>
@@@ -416,11 -416,11 +413,8 @@@
return (
<SegmentRoot
segColor="var(--track-scene)"
-- class={cx(
-- "border transition-colors duration-200 group",
-- isSelected() ? "border-gray-12" : "border-transparent",
-- )}
-- innerClass="ring-blue-5"
++ class="group"
++ selected={isSelected()}
title={`Scene · ${getSceneLabel(segment.mode)}`}
segment={segment}
onMouseEnter={() => {
@@@ -502,7 -502,7 +496,7 @@@
)}
/>
<SegmentContent
-- class="flex justify-center items-center cursor-grab"
++ class="flex items-center cursor-grab"
onMouseDown={createMouseDownDrag(
() => {
const original = { ...segment };
@@@ -542,24 -542,24 +536,22 @@@
>
<SegmentLabel
full={() => (
-- <div class="flex flex-col gap-1 justify-center items-center text-xs whitespace-nowrap text-gray-1 dark:text-gray-12 animate-in fade-in">
-- <span class="opacity-70">Scene</span>
-- <div class="flex gap-1 items-center text-md">
-- {getSceneIcon(segment.mode)}
-- <span class="text-xs">
-- {getSceneLabel(segment.mode)}
-- </span>
-- </div>
++ <div class="cap-seg-labels animate-in fade-in">
++ <span class="cap-seg-label">Scene</span>
++ <span class="cap-seg-sublabel truncate">
++ {getSceneLabel(segment.mode)}
++ </span>
</div>
)}
compact={() => (
-- <div class="flex gap-1 items-center text-md whitespace-nowrap text-gray-1 dark:text-gray-12">
-- {getSceneIcon(segment.mode)}
-- <span class="text-xs">{getSceneLabel(segment.mode)}</span>
++ <div class="cap-seg-labels">
++ <span class="cap-seg-label truncate">
++ {getSceneLabel(segment.mode)}
++ </span>
</div>
)}
glyph={() => (
-- <div class="flex justify-center items-center text-gray-1 dark:text-gray-12">
++ <div class="cap-seg-label flex justify-center items-center">
{getSceneIcon(segment.mode)}
</div>
)}
@@@ -633,17 -633,17 +625,15 @@@
{(time) => (
<SegmentRoot
class="pointer-events-none"
-- innerClass="ring-blue-300"
++ ghost
segColor="var(--track-scene)"
segment={{
start: time(),
end: time() + maxAvailableDuration(),
}}
>
-- <SegmentContent class="group">
-- <p class="w-full text-center text-gray-1 dark:text-gray-12 text-md text-primary">
-- +
-- </p>
++ <SegmentContent class="group justify-center">
++ <p class="cap-seg-label">+</p>
</SegmentContent>
</SegmentRoot>
)}
diff --cc apps/desktop/src/routes/editor/Timeline/TextTrack.tsx
index 57ec6af42,57ec6af42..d693335a3
--- a/apps/desktop/src/routes/editor/Timeline/TextTrack.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/TextTrack.tsx
@@@ -1,5 -1,5 +1,4 @@@
import { createEventListenerMap } from "@solid-primitives/event-listener";
--import { cx } from "cva";
import { createMemo, createRoot, createSignal, For, Show } from "solid-js";
import { produce } from "solid-js/store";
@@@ -304,13 -304,13 +303,11 @@@ export function TextTrack(props:
fallback={
<Show
when={!newSegmentDetails()}
-- fallback={<div class="w-full rounded-xl bg-transparent" />}
++ fallback={<div class="w-full rounded-lg bg-transparent" />}
>
-- <div class="text-center text-sm text-(--text-tertiary) flex flex-col justify-center items-center inset-0 w-full bg-gray-3/20 dark:bg-gray-3/10 hover:bg-gray-3/30 dark:hover:bg-gray-3/20 transition-colors rounded-xl pointer-events-none">
-- <div>Click to add text</div>
-- <div class="text-[10px] text-(--text-tertiary)/40 mt-0.5">
-- (Set a label over your video)
-- </div>
++ <div class="cap-empty-lane pointer-events-none">
++ <span>Set a label over your video</span>
++ <span class="cap-empty-lane-action">· Add text</span>
</div>
</Show>
}
@@@ -325,15 -325,15 +322,15 @@@
const segmentWidth = () => segment.end - segment.start;
const textContentRow = () => (
-- <div class="flex gap-1.5 justify-center items-center max-w-full text-md">
++ <div class="cap-seg-labels max-w-full">
<span
-- class="size-2 shrink-0 rounded-full border border-white/40"
++ class="size-2 shrink-0 rounded-full ring-1 ring-ed-line-strong"
style={{
"background-color": segment.color ?? "#ffffff",
}}
/>
<span
-- class="truncate max-w-full"
++ class="cap-seg-label truncate max-w-full"
style={{
"font-family": cssFontFamily(
segment.fontFamily ?? "sans-serif",
@@@ -359,12 -359,12 +356,9 @@@
data-text-segment
data-index={index}
segColor="var(--track-text)"
-- class={cx(
-- "border duration-200 transition-colors group",
-- isSelected() ? "border-blue-7" : "border-transparent",
-- !segment.enabled && "opacity-60",
-- )}
-- innerClass="ring-blue-6"
++ class="group"
++ selected={isSelected()}
++ muted={!segment.enabled}
title={textTitle()}
segment={segment}
onMouseDown={(e) => {
@@@ -419,7 -419,7 +413,7 @@@
)}
/>
<SegmentContent
-- class="flex justify-center items-center cursor-grab px-3 overflow-hidden"
++ class="flex items-center cursor-grab overflow-hidden"
onMouseDown={createMouseDownDrag(
() => index,
() => {
@@@ -458,8 -458,8 +452,8 @@@
>
<SegmentLabel
full={() => (
-- <div class="flex flex-col gap-0.5 justify-center items-center text-xs text-gray-1 dark:text-gray-12">
-- <span class="flex gap-1 items-center opacity-70">
++ <div class="cap-seg-labels">
++ <span class="cap-seg-label flex gap-1 items-center">
Text
<Show when={segment.layout === "fullscreen"}>
<IconLucidePause class="size-2.5" />
@@@ -468,16 -468,16 +462,10 @@@
{textContentRow()}
</div>
)}
-- compact={() => (
-- <div class="flex justify-center items-center text-xs text-gray-1 dark:text-gray-12">
-- {textContentRow()}
-- </div>
-- )}
++ compact={() => textContentRow()}
glyph={
segment.layout === "fullscreen"
-- ? () => (
-- <IconLucidePause class="size-2.5 text-gray-1 opacity-70 dark:text-gray-12" />
-- )
++ ? () => <IconLucidePause class="size-2.5 cap-seg-label" />
: undefined
}
/>
@@@ -518,15 -518,15 +506,13 @@@
<Show when={!draggingSegment() && newSegmentDetails()}>
{(details) => (
<SegmentRoot
-- class="pointer-events-none z-10 border border-transparent"
-- innerClass="ring-blue-300"
++ class="pointer-events-none z-10"
++ ghost
segColor="var(--track-text)"
segment={details()}
>
-- <SegmentContent>
-- <p class="w-full text-center text-gray-1 dark:text-gray-12 text-md">
-- +
-- </p>
++ <SegmentContent class="justify-center">
++ <p class="cap-seg-label">+</p>
</SegmentContent>
</SegmentRoot>
)}
diff --cc apps/desktop/src/routes/editor/Timeline/ThreeDTrack.tsx
index 8fa01ff53,8fa01ff53..1f4a3f7f9
--- a/apps/desktop/src/routes/editor/Timeline/ThreeDTrack.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/ThreeDTrack.tsx
@@@ -1,19 -1,19 +1,10 @@@
import { createEventListenerMap } from "@solid-primitives/event-listener";
--import { cx } from "cva";
--import { Array, Option } from "effect";
--import {
-- batch,
-- createMemo,
-- createRoot,
-- createSignal,
-- Index,
-- Show,
--} from "solid-js";
++import { createMemo, createRoot, Index, Show } from "solid-js";
import { produce } from "solid-js/store";
import { useEditorContext } from "../context";
import {
-- CAMERA3D_SCENES,
-- defaultCamera3DSegment,
++ camera3DSceneRange,
++ findCamera3DScene,
fitCamera3DMotionToSegment,
hasCamera3DMotion,
} from "../three-d";
@@@ -36,16 -36,16 +27,6 @@@ export type ThreeDSegmentDragState
| { type: "moving" };
const MIN_THREE_D_SEGMENT_PIXEL_WIDTH = 40;
--const MIN_NEW_SEGMENT_PIXEL_WIDTH = 80;
--const MIN_NEW_SEGMENT_SECS_WIDTH = 1;
--
--/** What the setup flow opens on: the full showcase sequence. */
--const CAMERA3D_SETUP_SEED = { sceneId: "showcase", shots: 3 };
--
--/**
-- * One shot of the scene the setup flow is offering, drawn where it would land.
-- * Non-interactive: the whole placeholder area belongs to the open flow.
-- */
function Camera3DSetupGhost(props: {
segment: { start: number; end: number };
label: string;
@@@ -55,7 -55,7 +36,7 @@@
return (
<div
-- class="flex absolute inset-y-0 justify-center items-center rounded-xl border border-dashed pointer-events-none"
++ class="flex absolute inset-y-0 justify-center items-center rounded-lg border border-dashed pointer-events-none"
style={{
transform: `translateX(${translateX()}px)`,
width: `${width()}px`,
@@@ -63,7 -63,7 +44,12 @@@
background: "color-mix(in srgb, var(--track-3d) 14%, transparent)",
}}
>
-- <span class="px-2 text-xs truncate text-gray-12">{props.label}</span>
++ <span
++ class="px-2 truncate cap-seg-label"
++ style={{ "--seg-color": "var(--track-3d)" }}
++ >
++ {props.label}
++ </span>
</div>
);
}
@@@ -86,114 -86,114 +72,38 @@@ export function ThreeDTrack(props:
const { duration, secsPerPixel } = useTimelineContext();
const setPreviewTime = useSetPreviewTime();
-- const [creatingSegmentViaDrag, setCreatingSegmentViaDrag] =
-- createSignal(false);
--
const hasCamera3DSegments = () =>
(project.timeline?.camera3dSegments?.length ?? 0) > 0;
--
const setup = () => editorState.timeline.camera3dSetup;
--
-- const setupSegments = createMemo(() => {
++ const setupRange = createMemo(() => {
const current = setup();
-- if (!current) return [];
-- return camera3DScenePreview(current.sceneId, current.shots);
++ if (!current) return null;
++ const segments = camera3DScenePreview(current);
++ if (!segments.length) return null;
++ return { start: segments[0].start, end: segments[segments.length - 1].end };
});
--
-- const setupShotLabel = (index: number) => {
-- const current = setup();
-- const scene = current
-- ? CAMERA3D_SCENES.find((s) => s.id === current.sceneId)
-- : undefined;
-- return scene?.shots[index]?.name ?? `Shot ${index + 1}`;
-- };
--
-- const startSetup = () =>
-- batch(() => {
-- setEditorState("timeline", "selection", null);
-- setEditorState("timeline", "audioPicker", null);
-- setEditorState("timeline", "audioReplace", null);
-- setEditorState("timeline", "camera3dSetup", { ...CAMERA3D_SETUP_SEED });
-- });
++ const startSetup = (time = editorState.playbackTime) =>
++ projectActions.startCamera3DSetup(time);
const selectedCamera3DIndices = createMemo(() => {
const selection = editorState.timeline.selection;
if (!selection || selection.type !== "3d") return null;
return new Set(selection.indices);
});
-- const newSegmentMinDuration = () =>
-- Math.max(
-- MIN_NEW_SEGMENT_PIXEL_WIDTH * secsPerPixel(),
-- MIN_NEW_SEGMENT_SECS_WIDTH,
-- );
--
-- // Returns a start and end time for a new segment that can be inserted at the
-- // current previewTime, if conditions permit
const newSegmentDetails = () => {
if (
-- creatingSegmentViaDrag() ||
++ setup() ||
++ !hasCamera3DSegments() ||
editorState.timeline.hoveredTrack !== "3d" ||
editorState.previewTime === null
)
-- return;
--
-- // An empty track belongs to the setup flow, whether it is open or still
-- // only offering itself, so nothing is drag-created over it.
-- if (!hasCamera3DSegments() || setup()) return;
--
-- const { previewTime } = editorState;
--
-- const nextSegment = Array.findFirstWithIndex(
-- project.timeline?.camera3dSegments ?? [],
-- (s) => previewTime <= s.start,
-- );
--
-- const prevSegment = Array.findLastIndex(
++ return null;
++ return camera3DSceneRange(
project.timeline?.camera3dSegments ?? [],
-- (s) => previewTime >= s.start,
-- ).pipe(
-- Option.flatMap((index) =>
-- Option.fromNullable(project.timeline?.camera3dSegments?.[index]).pipe(
-- Option.map((segment) => [segment, index] as const),
-- ),
-- ),
++ editorState.previewTime,
++ 6,
++ totalDuration(),
);
--
-- if (
-- Option.isSome(prevSegment) &&
-- previewTime > prevSegment.value[0].start &&
-- previewTime < prevSegment.value[0].end
-- )
-- return;
--
-- const minDuration = newSegmentMinDuration();
--
-- if (Option.isSome(nextSegment)) {
-- if (Option.isSome(prevSegment)) {
-- const availableTime =
-- nextSegment.value[0].start - prevSegment.value[0].end;
--
-- if (availableTime < minDuration) return;
-- }
--
-- if (nextSegment.value[0].start - previewTime < 1)
-- return {
-- index: nextSegment.value[1],
-- start: nextSegment.value[0].start - minDuration,
-- end: nextSegment.value[0].start,
-- max: nextSegment.value[0].start,
-- };
-- }
--
-- return {
-- index: nextSegment.pipe(Option.map(([_, i]) => i)),
-- start: previewTime,
-- end: previewTime + minDuration,
-- max: nextSegment.pipe(
-- Option.map(([s]) => s.start),
-- Option.getOrElse(() => totalDuration()),
-- ),
-- };
};
return (
@@@ -201,287 -201,287 +111,149 @@@
onMouseEnter={() => setEditorState("timeline", "hoveredTrack", "3d")}
onMouseLeave={() => setEditorState("timeline", "hoveredTrack", null)}
onMouseDown={(e) => {
-- if (e.button !== 0) return;
--
-- const baseSegment = newSegmentDetails();
-- if (!baseSegment) return;
--
-- createRoot((dispose) => {
-- let segmentCreated = false;
-- let createdSegmentIndex = -1;
-- const initialMouseX = e.clientX;
-- const initialEndTime = baseSegment.end;
--
-- const minDuration = newSegmentMinDuration;
--
-- const createSegment = (endTime: number) => {
-- if (segmentCreated) return;
--
-- batch(() => {
-- setProject("timeline", "camera3dSegments", (v) => v ?? []);
-- setProject(
-- "timeline",
-- "camera3dSegments",
-- produce((camera3dSegments) => {
-- camera3dSegments ??= [];
--
-- let index = 0;
--
-- for (let i = 0; i < camera3dSegments.length; i++) {
-- if (camera3dSegments[i].start < baseSegment.start) {
-- index = i + 1;
-- }
-- }
--
-- const minEndTime = baseSegment.start + minDuration();
--
-- camera3dSegments.splice(
-- index,
-- 0,
-- defaultCamera3DSegment(
-- baseSegment.start,
-- Math.max(minEndTime, endTime),
-- ),
-- );
--
-- createdSegmentIndex = index;
-- }),
-- );
-- setEditorState("timeline", "selection", {
-- type: "3d",
-- indices: [createdSegmentIndex],
-- });
-- });
-- segmentCreated = true;
-- };
--
-- const updateSegment = (endTime: number) => {
-- if (!segmentCreated || createdSegmentIndex === -1) return;
--
-- const minEndTime = baseSegment.start + minDuration();
--
++ if (e.button !== 0 || editorState.timeline.interactMode !== "seek")
++ return;
++ e.stopPropagation();
++ const time = editorState.previewTime ?? editorState.playbackTime;
++ if (setup()) {
++ setEditorState("timeline", "camera3dSetup", "start", time);
++ } else startSetup(time);
++ }}
++ >
++ <Show when={!hasCamera3DSegments() && !setup()}>
++ <button
++ type="button"
++ class="cap-empty-lane pointer-events-auto outline-hidden"
++ onMouseDown={(e) => e.stopPropagation()}
++ onClick={(e) => {
++ e.stopPropagation();
++ startSetup();
++ }}
++ >
++ <span>Tilt the scene in 3D perspective</span>
++ <span class="cap-empty-lane-action">· Add 3D scene</span>
++ </button>
++ </Show>
++ <Index each={project.timeline?.camera3dSegments}>
++ {(segment, i) => {
++ const { setTrackState } = useTrackContext();
++
++ const camera3dSegments = () =>
++ project.timeline?.camera3dSegments ?? [];
++
++ const motionLabel = () =>
++ hasCamera3DMotion(segment()) ? "Motion" : "Still";
++
++ // Double-clicking a handle expands the segment as far as it can go
++ // in that direction (up to the neighbouring segment / timeline edge).
++ const fillStart = () => {
++ const segs = camera3dSegments();
++ let minValue = 0;
++ for (let j = segs.length - 1; j >= 0; j--) {
++ const s = segs[j];
++ if (s && s.end <= segment().start) {
++ minValue = s.end;
++ break;
++ }
++ }
setProject(
"timeline",
"camera3dSegments",
-- createdSegmentIndex,
-- "end",
-- Math.max(minEndTime, endTime),
++ produce((s) => {
++ const target = s[i];
++ if (!target) return;
++ target.start = minValue;
++ fitCamera3DMotionToSegment(target);
++ s.sort((a, b) => a.start - b.start);
++ }),
);
++ setPreviewTime(minValue);
};
-- const handleMouseMove = (moveEvent: MouseEvent) => {
-- const deltaX = moveEvent.clientX - initialMouseX;
-- const deltaTime =
-- deltaX * secsPerPixel() - (baseSegment.end - baseSegment.start);
-- const newEndTime = initialEndTime + deltaTime;
--
-- const minEndTime = baseSegment.start + minDuration();
-- const maxEndTime = baseSegment.max;
--
-- const clampedEndTime = Math.min(
-- Math.max(minEndTime, newEndTime),
-- maxEndTime,
-- );
--
-- if (!segmentCreated) {
-- setCreatingSegmentViaDrag(true);
-- createSegment(clampedEndTime);
-- } else {
-- if (deltaTime < 0) return;
-- updateSegment(clampedEndTime);
-- }
-- };
--
-- const handleMouseUp = () => {
-- setCreatingSegmentViaDrag(false);
-- dispose();
--
-- if (!segmentCreated) {
-- createSegment(initialEndTime);
++ const fillEnd = () => {
++ const segs = camera3dSegments();
++ let maxValue = totalDuration();
++ for (let j = 0; j < segs.length; j++) {
++ const s = segs[j];
++ if (s && s.start > segment().end) {
++ maxValue = s.start;
++ break;
++ }
}
++ setProject(
++ "timeline",
++ "camera3dSegments",
++ produce((s) => {
++ const target = s[i];
++ if (!target) return;
++ target.end = maxValue;
++ fitCamera3DMotionToSegment(target);
++ s.sort((a, b) => a.start - b.start);
++ }),
++ );
++ setPreviewTime(maxValue);
};
-- createEventListenerMap(window, {
-- mousemove: handleMouseMove,
-- mouseup: handleMouseUp,
-- });
-- });
-- }}
-- >
-- <Show
-- when={hasCamera3DSegments()}
-- fallback={
-- <Show
-- when={setup()}
-- fallback={
-- // An empty 3D track is the one place a whole scene can land
-- // without overwriting anything, so it is offered here.
-- <button
-- type="button"
-- style={{
-- "--accent": "var(--track-3d)",
-- "--accent-soft":
-- "color-mix(in srgb, var(--track-3d) 12%, transparent)",
-- }}
-- class="group/empty flex gap-2 justify-center items-center w-full text-sm rounded-xl border transition-all duration-200 pointer-events-auto border-dashed border-gray-4/60 bg-gray-3/15 text-(--text-tertiary) hover:border-[var(--accent)] hover:bg-[var(--accent-soft)] hover:text-gray-12"
-- onMouseDown={(e) => e.stopPropagation()}
-- onClick={(e) => {
-- e.stopPropagation();
-- startSetup();
-- }}
-- >
-- <span class="flex justify-center items-center rounded-full transition-colors size-6 bg-gray-4/40 text-gray-11 group-hover/empty:bg-[var(--accent)] group-hover/empty:text-white">
-- <IconLucidePlus class="size-3.5" />
-- </span>
-- <span class="font-medium">Add 3D scene</span>
-- </button>
-- }
-- >
-- {/* The open flow owns the whole track: the shots it would lay
-- down are drawn where they will land, and a click anywhere
-- over them leaves the flow alone rather than closing it. */}
-- <div
-- class="absolute inset-0 pointer-events-auto"
-- onMouseDown={(e) => e.stopPropagation()}
-- >
-- <Index each={setupSegments()}>
-- {(ghost, index) => (
-- <Camera3DSetupGhost
-- segment={ghost()}
-- label={setupShotLabel(index)}
-- />
-- )}
-- </Index>
-- </div>
-- </Show>
-- }
-- >
-- <Index each={project.timeline?.camera3dSegments}>
-- {(segment, i) => {
-- const { setTrackState } = useTrackContext();
--
-- const camera3dSegments = () =>
-- project.timeline?.camera3dSegments ?? [];
--
-- const motionLabel = () =>
-- hasCamera3DMotion(segment()) ? "Motion" : "Still";
--
-- // Double-clicking a handle expands the segment as far as it can go
-- // in that direction (up to the neighbouring segment / timeline edge).
-- const fillStart = () => {
-- const segs = camera3dSegments();
-- let minValue = 0;
-- for (let j = segs.length - 1; j >= 0; j--) {
-- const s = segs[j];
-- if (s && s.end <= segment().start) {
-- minValue = s.end;
-- break;
-- }
-- }
-- setProject(
-- "timeline",
-- "camera3dSegments",
-- produce((s) => {
-- const target = s[i];
-- if (!target) return;
-- target.start = minValue;
-- fitCamera3DMotionToSegment(target);
-- s.sort((a, b) => a.start - b.start);
-- }),
-- );
-- setPreviewTime(minValue);
-- };
--
-- const fillEnd = () => {
-- const segs = camera3dSegments();
-- let maxValue = totalDuration();
-- for (let j = 0; j < segs.length; j++) {
-- const s = segs[j];
-- if (s && s.start > segment().end) {
-- maxValue = s.start;
-- break;
-- }
-- }
-- setProject(
-- "timeline",
-- "camera3dSegments",
-- produce((s) => {
-- const target = s[i];
-- if (!target) return;
-- target.end = maxValue;
-- fitCamera3DMotionToSegment(target);
-- s.sort((a, b) => a.start - b.start);
-- }),
-- );
-- setPreviewTime(maxValue);
-- };
++ function createMouseDownDrag<T>(
++ setup: () => T,
++ _update: (e: MouseEvent, v: T, initialMouseX: number) => void,
++ ) {
++ return (downEvent: MouseEvent) => {
++ if (editorState.timeline.interactMode !== "seek") return;
-- function createMouseDownDrag<T>(
-- setup: () => T,
-- _update: (e: MouseEvent, v: T, initialMouseX: number) => void,
-- ) {
-- return (downEvent: MouseEvent) => {
-- if (editorState.timeline.interactMode !== "seek") return;
++ downEvent.stopPropagation();
-- downEvent.stopPropagation();
++ const initial = setup();
-- const initial = setup();
++ let moved = false;
++ let initialMouseX: null | number = null;
-- let moved = false;
-- let initialMouseX: null | number = null;
++ setTrackState("draggingSegment", true);
-- setTrackState("draggingSegment", true);
++ const resumeHistory = projectHistory.pause();
-- const resumeHistory = projectHistory.pause();
++ props.onDragStateChanged({ type: "movePending" });
-- props.onDragStateChanged({ type: "movePending" });
++ function finish(e: MouseEvent) {
++ resumeHistory();
++ if (!moved) {
++ e.stopPropagation();
-- function finish(e: MouseEvent) {
-- resumeHistory();
-- if (!moved) {
-- e.stopPropagation();
--
-- const currentSelection = editorState.timeline.selection;
-- const segmentIndex = i;
-- const isMultiSelect = e.ctrlKey || e.metaKey;
-- const isRangeSelect = e.shiftKey;
--
-- if (isRangeSelect && currentSelection?.type === "3d") {
-- const existingIndices = currentSelection.indices;
-- const lastIndex =
-- existingIndices[existingIndices.length - 1];
-- const start = Math.min(lastIndex, segmentIndex);
-- const end = Math.max(lastIndex, segmentIndex);
-- const rangeIndices: number[] = [];
-- for (let idx = start; idx <= end; idx++) {
-- rangeIndices.push(idx);
-- }
++ const currentSelection = editorState.timeline.selection;
++ const segmentIndex = i;
++ const isMultiSelect = e.ctrlKey || e.metaKey;
++ const isRangeSelect = e.shiftKey;
++
++ if (isRangeSelect && currentSelection?.type === "3d") {
++ const existingIndices = currentSelection.indices;
++ const lastIndex =
++ existingIndices[existingIndices.length - 1];
++ const start = Math.min(lastIndex, segmentIndex);
++ const end = Math.max(lastIndex, segmentIndex);
++ const rangeIndices: number[] = [];
++ for (let idx = start; idx <= end; idx++) {
++ rangeIndices.push(idx);
++ }
-- setEditorState("timeline", "selection", {
-- type: "3d",
-- indices: rangeIndices,
-- });
-- } else if (isMultiSelect) {
-- if (currentSelection?.type === "3d") {
-- const baseIndices = currentSelection.indices;
-- const exists = baseIndices.includes(segmentIndex);
-- const newIndices = exists
-- ? baseIndices.filter((idx) => idx !== segmentIndex)
-- : [...baseIndices, segmentIndex];
--
-- if (newIndices.length > 0) {
-- setEditorState("timeline", "selection", {
-- type: "3d",
-- indices: newIndices,
-- });
-- } else {
-- setEditorState("timeline", "selection", null);
-- }
-- } else {
++ setEditorState("timeline", "selection", {
++ type: "3d",
++ indices: rangeIndices,
++ });
++ } else if (isMultiSelect) {
++ if (currentSelection?.type === "3d") {
++ const baseIndices = currentSelection.indices;
++ const exists = baseIndices.includes(segmentIndex);
++ const newIndices = exists
++ ? baseIndices.filter((idx) => idx !== segmentIndex)
++ : [...baseIndices, segmentIndex];
++
++ if (newIndices.length > 0) {
setEditorState("timeline", "selection", {
type: "3d",
-- indices: [segmentIndex],
++ indices: newIndices,
});
++ } else {
++ setEditorState("timeline", "selection", null);
}
} else {
setEditorState("timeline", "selection", {
@@@ -489,260 -489,260 +261,267 @@@
indices: [segmentIndex],
});
}
-- props.handleUpdatePlayhead(e);
++ } else {
++ setEditorState("timeline", "selection", {
++ type: "3d",
++ indices: [segmentIndex],
++ });
}
-- props.onDragStateChanged({ type: "idle" });
-- setTrackState("draggingSegment", false);
++ props.handleUpdatePlayhead(e);
}
++ props.onDragStateChanged({ type: "idle" });
++ setTrackState("draggingSegment", false);
++ }
-- function update(event: MouseEvent) {
-- if (Math.abs(event.clientX - downEvent.clientX) > 2) {
-- if (!moved) {
-- moved = true;
-- initialMouseX = event.clientX;
-- props.onDragStateChanged({
-- type: "moving",
-- });
-- }
++ function update(event: MouseEvent) {
++ if (Math.abs(event.clientX - downEvent.clientX) > 2) {
++ if (!moved) {
++ moved = true;
++ initialMouseX = event.clientX;
++ props.onDragStateChanged({
++ type: "moving",
++ });
}
++ }
-- if (initialMouseX === null) return;
++ if (initialMouseX === null) return;
-- _update(event, initial, initialMouseX);
-- }
++ _update(event, initial, initialMouseX);
++ }
-- createRoot((dispose) => {
-- createEventListenerMap(window, {
-- mousemove: (e) => {
-- update(e);
-- },
-- mouseup: (e) => {
-- update(e);
-- finish(e);
-- dispose();
-- },
-- });
++ createRoot((dispose) => {
++ createEventListenerMap(window, {
++ mousemove: (e) => {
++ update(e);
++ },
++ mouseup: (e) => {
++ update(e);
++ finish(e);
++ dispose();
++ },
});
-- };
-- }
++ });
++ };
++ }
-- const isSelected = createMemo(() => {
-- const indices = selectedCamera3DIndices();
-- if (!indices) return false;
-- return indices.has(i);
-- });
--
-- return (
-- <SegmentRoot
-- segColor="var(--track-3d)"
-- class={cx(
-- "border duration-200 transition-colors group",
-- isSelected() ? "border-gray-12" : "border-transparent",
-- )}
-- innerClass="ring-red-5"
-- title={`3D Perspective · ${motionLabel()}`}
-- segment={segment()}
-- onMouseDown={(e) => {
-- e.stopPropagation();
++ const isSelected = createMemo(() => {
++ const indices = selectedCamera3DIndices();
++ if (!indices) return false;
++ return indices.has(i);
++ });
-- if (editorState.timeline.interactMode === "split") {
-- const rect = e.currentTarget.getBoundingClientRect();
-- const fraction = (e.clientX - rect.left) / rect.width;
++ return (
++ <SegmentRoot
++ segColor="var(--track-3d)"
++ class="group"
++ selected={isSelected()}
++ title={`3D Perspective · ${motionLabel()}`}
++ segment={segment()}
++ onMouseDown={(e) => {
++ e.stopPropagation();
-- const splitTime =
-- fraction * (segment().end - segment().start);
++ if (editorState.timeline.interactMode === "split") {
++ const rect = e.currentTarget.getBoundingClientRect();
++ const fraction = (e.clientX - rect.left) / rect.width;
-- projectActions.splitCamera3DSegment(i, splitTime);
-- }
++ const splitTime =
++ fraction * (segment().end - segment().start);
++
++ projectActions.splitCamera3DSegment(i, splitTime);
++ }
++ }}
++ >
++ <SegmentHandle
++ position="start"
++ onDblClick={(e) => {
++ e.stopPropagation();
++ fillStart();
}}
-- >
-- <SegmentHandle
-- position="start"
-- onDblClick={(e) => {
-- e.stopPropagation();
-- fillStart();
-- }}
-- onMouseDown={createMouseDownDrag(
-- () => {
-- const start = segment().start;
-- const minDuration = Math.max(
-- 1,
-- secsPerPixel() * MIN_THREE_D_SEGMENT_PIXEL_WIDTH,
-- );
--
-- let minValue = 0;
--
-- const maxValue = segment().end - minDuration;
--
-- for (let j = camera3dSegments().length - 1; j >= 0; j--) {
-- const other = camera3dSegments()[j];
-- if (!other) continue;
-- if (other.end <= start) {
-- minValue = other.end;
-- break;
-- }
++ onMouseDown={createMouseDownDrag(
++ () => {
++ const start = segment().start;
++ const minDuration = Math.max(
++ 1,
++ secsPerPixel() * MIN_THREE_D_SEGMENT_PIXEL_WIDTH,
++ );
++
++ let minValue = 0;
++
++ const maxValue = segment().end - minDuration;
++
++ for (let j = camera3dSegments().length - 1; j >= 0; j--) {
++ const other = camera3dSegments()[j];
++ if (!other) continue;
++ if (other.end <= start) {
++ minValue = other.end;
++ break;
}
++ }
-- return { start, minValue, maxValue };
-- },
-- (e, value, initialMouseX) => {
-- const newStart =
-- value.start +
-- (e.clientX - initialMouseX) * secsPerPixel();
-- const nextStart = Math.min(
-- value.maxValue,
-- Math.max(value.minValue, newStart),
-- );
--
-- setProject(
-- "timeline",
-- "camera3dSegments",
-- produce((s) => {
-- const target = s[i];
-- if (!target) return;
-- target.start = nextStart;
-- fitCamera3DMotionToSegment(target);
-- s.sort((a, b) => a.start - b.start);
-- }),
-- );
-- setPreviewTime(nextStart);
-- },
-- )}
-- />
-- <SegmentContent
-- class="flex justify-center items-center cursor-grab"
-- onMouseDown={createMouseDownDrag(
-- () => {
-- const original = { ...segment() };
--
-- const prevSegment = camera3dSegments()[i - 1];
-- const nextSegment = camera3dSegments()[i + 1];
--
-- const minStart = prevSegment?.end ?? 0;
-- const maxEnd = nextSegment?.start ?? duration();
--
-- return {
-- original,
-- minStart,
-- maxEnd,
-- };
-- },
-- (e, value, initialMouseX) => {
-- const rawDelta =
-- (e.clientX - initialMouseX) * secsPerPixel();
--
-- const newStart = value.original.start + rawDelta;
-- const newEnd = value.original.end + rawDelta;
--
-- let delta = rawDelta;
--
-- if (newStart < value.minStart)
-- delta = value.minStart - value.original.start;
-- else if (newEnd > value.maxEnd)
-- delta = value.maxEnd - value.original.end;
--
-- setProject("timeline", "camera3dSegments", i, {
-- start: value.original.start + delta,
-- end: value.original.end + delta,
-- });
-- },
-- )}
-- >
-- {(() => {
-- const visibleBox = useSegmentVisibleBox();
--
-- return (
-- <SegmentLabel
-- full={() => (
-- <div class="flex flex-col gap-1 justify-center items-center text-xs whitespace-nowrap text-gray-1 dark:text-gray-12 animate-in fade-in">
-- <span class="opacity-70">
-- {visibleBox().width >= 140
-- ? "3D Perspective"
-- : "3D"}
-- </span>
-- <div class="flex gap-1 items-center text-md">
-- <IconLucideRotate3d class="size-3.5" />
-- <span>{motionLabel()}</span>
-- {/* Presentation only: the arrow says the shot
-- moves from its start pose to its end pose. */}
-- <Show when={hasCamera3DMotion(segment())}>
-- <IconLucideChevronRight class="size-3 opacity-70" />
-- </Show>
-- </div>
-- </div>
-- )}
-- compact={() => (
-- <div class="flex gap-1 items-center text-xs whitespace-nowrap text-gray-1 dark:text-gray-12">
-- <IconLucideRotate3d class="size-3" />
-- <span>3D</span>
-- </div>
-- )}
-- glyph={() => (
-- <div class="flex justify-center items-center">
-- <IconLucideRotate3d class="size-3.5 text-gray-1 dark:text-gray-12" />
-- </div>
-- )}
-- />
++ return { start, minValue, maxValue };
++ },
++ (e, value, initialMouseX) => {
++ const newStart =
++ value.start +
++ (e.clientX - initialMouseX) * secsPerPixel();
++ const nextStart = Math.min(
++ value.maxValue,
++ Math.max(value.minValue, newStart),
);
-- })()}
-- </SegmentContent>
-- <SegmentHandle
-- position="end"
-- onDblClick={(e) => {
-- e.stopPropagation();
-- fillEnd();
-- }}
-- onMouseDown={createMouseDownDrag(
-- () => {
-- const end = segment().end;
-- const minDuration = Math.max(
-- 1,
-- secsPerPixel() * MIN_THREE_D_SEGMENT_PIXEL_WIDTH,
-- );
--
-- const minValue = segment().start + minDuration;
--
-- let maxValue = duration();
--
-- for (let j = 0; j < camera3dSegments().length; j++) {
-- const other = camera3dSegments()[j];
-- if (!other) continue;
-- if (other.start > end) {
-- maxValue = other.start;
-- break;
-- }
++
++ setProject(
++ "timeline",
++ "camera3dSegments",
++ produce((s) => {
++ const target = s[i];
++ if (!target) return;
++ target.start = nextStart;
++ fitCamera3DMotionToSegment(target);
++ s.sort((a, b) => a.start - b.start);
++ }),
++ );
++ setPreviewTime(nextStart);
++ },
++ )}
++ />
++ <SegmentContent
++ class="flex items-center cursor-grab"
++ onMouseDown={createMouseDownDrag(
++ () => {
++ const original = { ...segment() };
++
++ const prevSegment = camera3dSegments()[i - 1];
++ const nextSegment = camera3dSegments()[i + 1];
++
++ const minStart = prevSegment?.end ?? 0;
++ const maxEnd = nextSegment?.start ?? duration();
++
++ return {
++ original,
++ minStart,
++ maxEnd,
++ };
++ },
++ (e, value, initialMouseX) => {
++ const rawDelta =
++ (e.clientX - initialMouseX) * secsPerPixel();
++
++ const newStart = value.original.start + rawDelta;
++ const newEnd = value.original.end + rawDelta;
++
++ let delta = rawDelta;
++
++ if (newStart < value.minStart)
++ delta = value.minStart - value.original.start;
++ else if (newEnd > value.maxEnd)
++ delta = value.maxEnd - value.original.end;
++
++ setProject("timeline", "camera3dSegments", i, {
++ start: value.original.start + delta,
++ end: value.original.end + delta,
++ });
++ },
++ )}
++ >
++ {(() => {
++ const visibleBox = useSegmentVisibleBox();
++
++ return (
++ <SegmentLabel
++ full={() => (
++ <div class="cap-seg-labels animate-in fade-in">
++ <span class="cap-seg-label">
++ {visibleBox().width >= 140
++ ? "3D Perspective"
++ : "3D"}
++ </span>
++ <span class="cap-seg-sublabel flex gap-1 items-center">
++ {motionLabel()}
++ {/* Presentation only: the arrow says the shot
++ moves from its start pose to its end pose. */}
++ <Show when={hasCamera3DMotion(segment())}>
++ <IconLucideChevronRight class="size-3" />
++ </Show>
++ </span>
++ </div>
++ )}
++ compact={() => (
++ <div class="cap-seg-labels">
++ <span class="cap-seg-label">3D</span>
++ </div>
++ )}
++ glyph={() => (
++ <div class="cap-seg-label flex justify-center items-center">
++ <IconLucideRotate3d class="size-3.5" />
++ </div>
++ )}
++ />
++ );
++ })()}
++ </SegmentContent>
++ <SegmentHandle
++ position="end"
++ onDblClick={(e) => {
++ e.stopPropagation();
++ fillEnd();
++ }}
++ onMouseDown={createMouseDownDrag(
++ () => {
++ const end = segment().end;
++ const minDuration = Math.max(
++ 1,
++ secsPerPixel() * MIN_THREE_D_SEGMENT_PIXEL_WIDTH,
++ );
++
++ const minValue = segment().start + minDuration;
++
++ let maxValue = duration();
++
++ for (let j = 0; j < camera3dSegments().length; j++) {
++ const other = camera3dSegments()[j];
++ if (!other) continue;
++ if (other.start > end) {
++ maxValue = other.start;
++ break;
}
++ }
-- return { end, minValue, maxValue };
-- },
-- (e, value, initialMouseX) => {
-- const newEnd =
-- value.end +
-- (e.clientX - initialMouseX) * secsPerPixel();
-- const nextEnd = Math.min(
-- value.maxValue,
-- Math.max(value.minValue, newEnd),
-- );
--
-- setProject(
-- "timeline",
-- "camera3dSegments",
-- produce((s) => {
-- const target = s[i];
-- if (!target) return;
-- target.end = nextEnd;
-- fitCamera3DMotionToSegment(target);
-- s.sort((a, b) => a.start - b.start);
-- }),
-- );
-- setPreviewTime(nextEnd);
-- },
-- )}
-- />
-- </SegmentRoot>
-- );
-- }}
-- </Index>
++ return { end, minValue, maxValue };
++ },
++ (e, value, initialMouseX) => {
++ const newEnd =
++ value.end + (e.clientX - initialMouseX) * secsPerPixel();
++ const nextEnd = Math.min(
++ value.maxValue,
++ Math.max(value.minValue, newEnd),
++ );
++
++ setProject(
++ "timeline",
++ "camera3dSegments",
++ produce((s) => {
++ const target = s[i];
++ if (!target) return;
++ target.end = nextEnd;
++ fitCamera3DMotionToSegment(target);
++ s.sort((a, b) => a.start - b.start);
++ }),
++ );
++ setPreviewTime(nextEnd);
++ },
++ )}
++ />
++ </SegmentRoot>
++ );
++ }}
++ </Index>
++ <Show when={setupRange()}>
++ {(range) => (
++ <Camera3DSetupGhost
++ segment={range()}
++ label={`${findCamera3DScene(setup()?.sceneId ?? "")?.name ?? "3D scene"} · ${(range().end - range().start).toFixed(1)}s`}
++ />
++ )}
</Show>
<Show
when={
@@@ -752,14 -752,14 +531,12 @@@
{(details) => (
<SegmentRoot
class="pointer-events-none z-0"
-- innerClass="ring-red-300"
++ ghost
segColor="var(--track-3d)"
segment={details()}
>
-- <SegmentContent class="group">
-- <p class="w-full text-center text-gray-1 dark:text-gray-12 text-md text-primary">
-- +
-- </p>
++ <SegmentContent class="group justify-center">
++ <p class="cap-seg-label">+ Add 3D scene</p>
</SegmentContent>
</SegmentRoot>
)}
diff --cc apps/desktop/src/routes/editor/Timeline/Track.tsx
index ebc13fc6e,ebc13fc6e..31086687b
--- a/apps/desktop/src/routes/editor/Timeline/Track.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/Track.tsx
@@@ -24,7 -24,7 +24,7 @@@ export const CAP_TRACK_FILL_CLASS = "ca
export function TrackRoot(props: ComponentProps<"div">) {
const [ref, setRef] = createSignal<HTMLDivElement>();
-- const height = "var(--track-height, 3.25rem)";
++ const height = "var(--track-height, 44px)";
const style =
typeof props.style === "string"
? `${props.style};height:${height}`
@@@ -67,20 -67,20 +67,24 @@@ export function useSegmentWidth(segment
export function SegmentRoot(
props: ComponentProps<"div"> & {
-- innerClass: string;
segColor?: string;
segment: { start: number; end: number };
forceVisible?: boolean;
++ selected?: boolean;
++ muted?: boolean;
++ ghost?: boolean;
onMouseDown?: (
e: MouseEvent & { currentTarget: HTMLDivElement; target: Element },
) => void;
},
) {
const [local, rest] = splitProps(props, [
-- "innerClass",
"segColor",
"segment",
"forceVisible",
++ "selected",
++ "muted",
++ "ghost",
"onMouseDown",
"class",
"style",
@@@ -103,7 -103,7 +107,7 @@@
<div
{...rest}
class={cx(
-- "absolute overflow-visible border rounded-xl inset-y-0",
++ "absolute overflow-visible inset-y-0",
editorState.timeline.interactMode === "split" &&
"timeline-scissors-cursor",
local.class,
@@@ -120,9 -120,9 +124,11 @@@
<div
class={cx(
CAP_TRACK_FILL_CLASS,
-- "relative h-full flex flex-row rounded-xl overflow-hidden group",
-- local.innerClass,
++ "relative h-full flex flex-row overflow-hidden group",
)}
++ data-selected={local.selected ? "" : undefined}
++ data-muted={local.muted ? "" : undefined}
++ data-ghost={local.ghost ? "" : undefined}
style={
local.segColor
? ({ "--seg-color": local.segColor } as Record<string, string>)
@@@ -139,6 -139,6 +145,8 @@@
export const SEGMENT_LABEL_FULL_PX = 100;
export const SEGMENT_LABEL_COMPACT_PX = 48;
++const SEGMENT_LABEL_INSET_PX = 13;
++const SEGMENT_LABEL_TAIL_PX = 10;
// Pixel box of the segment's intersection with the viewport, in
// segment-local coordinates, with a clamped center for label anchoring.
@@@ -147,6 -147,6 +155,7 @@@
export function useSegmentVisibleBox(): Accessor<{
width: number;
centerX: number;
++ startX: number;
}> {
const { width, segment } = useSegmentContext();
const { secsPerPixel } = useTrackContext();
@@@ -176,7 -176,7 +185,7 @@@
segmentWidth - margin,
);
-- return { width: visibleWidth, centerX };
++ return { width: visibleWidth, centerX, startX: visibleStart };
});
}
@@@ -195,16 -195,16 +204,43 @@@ export function SegmentLabel(props:
const fullAt = () => props.fullAt ?? SEGMENT_LABEL_FULL_PX;
const compactAt = () => props.compactAt ?? SEGMENT_LABEL_COMPACT_PX;
++ // Segments read left-to-right, so the label hugs the leading edge of the
++ // visible slice rather than the segment's true centre (which is often
++ // scrolled out of view on a long clip). The glyph tier is too narrow for
++ // the content padding, so it stays centred.
++ const leftAligned = () => {
++ const visibleWidth = visibleBox().width;
++ return (
++ visibleWidth >= fullAt() ||
++ (visibleWidth >= compactAt() && !!props.compact)
++ );
++ };
++
return (
<div
class="absolute pointer-events-none"
-- style={{
-- left: `${visibleBox().centerX}px`,
-- top: "50%",
-- transform: "translate(-50%, -50%)",
-- "max-width": `${Math.max(0, visibleBox().width - 8)}px`,
-- overflow: "hidden",
-- }}
++ style={
++ leftAligned()
++ ? {
++ left: `${visibleBox().startX + SEGMENT_LABEL_INSET_PX}px`,
++ top: "50%",
++ transform: "translateY(-50%)",
++ "max-width": `${Math.max(
++ 0,
++ visibleBox().width -
++ SEGMENT_LABEL_INSET_PX -
++ SEGMENT_LABEL_TAIL_PX,
++ )}px`,
++ overflow: "hidden",
++ }
++ : {
++ left: `${visibleBox().centerX}px`,
++ top: "50%",
++ transform: "translate(-50%, -50%)",
++ "max-width": `${Math.max(0, visibleBox().width - 8)}px`,
++ overflow: "hidden",
++ }
++ }
>
<Switch>
<Match when={visibleBox().width >= fullAt()}>{props.full()}</Match>
@@@ -225,8 -225,8 +261,8 @@@ export function SegmentContent(props: C
<div
{...props}
class={cx(
-- "relative w-full h-full flex flex-row items-center py-1",
-- ctx.width() < 100 ? "px-0" : "px-2",
++ "relative w-full h-full flex flex-row items-center",
++ ctx.width() < 100 ? "px-0" : "pl-[13px] pr-[10px]",
props.class,
)}
/>
@@@ -243,16 -243,16 +279,16 @@@ export function SegmentHandle
<div
{...props}
class={cx(
-- "absolute inset-y-0 z-10 flex w-5 cursor-col-resize items-center justify-center transition-opacity",
++ "absolute inset-y-0 z-10 flex w-5 cursor-col-resize items-center transition-opacity",
props.position === "start"
-- ? "left-0 -translate-x-1/2"
-- : "right-0 translate-x-1/2",
-- compact() ? "opacity-55" : "opacity-35 group-hover:opacity-100",
++ ? "left-0 -translate-x-1/2 justify-end pr-[2px]"
++ : "right-0 translate-x-1/2 justify-start pl-[2px]",
++ compact() ? "opacity-55" : "opacity-0 group-hover:opacity-90",
props.class,
)}
data-compact={compact()}
>
-- <div class="w-[3px] h-8 bg-solid-white rounded-full" />
++ <div class="cap-seg-handle" />
</div>
);
}
diff --cc apps/desktop/src/routes/editor/Timeline/TrackManager.tsx
index 2de962efa,08971c4f2..30084783f
--- a/apps/desktop/src/routes/editor/Timeline/TrackManager.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/TrackManager.tsx
@@@ -1,8 -1,8 +1,8 @@@
import { Popover } from "@kobalte/core/popover";
import { cx } from "cva";
import { createSignal, For, type JSX, Show } from "solid-js";
++import IconLucideGripVertical from "~icons/lucide/grip-vertical";
import type { TimelineTrackType } from "../context";
--import { CAP_TRACK_FILL_CLASS } from "./Track";
type TrackManagerOption = {
type: TimelineTrackType;
@@@ -93,40 -85,40 +93,33 @@@ function TrackOptionRow(props:
if (!available()) return;
props.onSelect();
}}
-- style={{
-- "--accent": accent(),
-- "--accent-soft": `color-mix(in srgb, ${accent()} 18%, transparent)`,
-- }}
++ style={{ "--seg-color": accent() }}
class={cx(
-- "group/row flex items-center gap-3 rounded-xl p-2 text-left outline-hidden transition-colors duration-150",
++ "group/row flex items-center gap-2.5 rounded-lg p-2 text-left outline-hidden transition-colors duration-150",
available()
-- ? "cursor-default hover:bg-gray-3 focus-visible:bg-gray-3"
++ ? "cursor-default hover:bg-ed-ctl focus-visible:bg-ed-ctl"
: "cursor-not-allowed opacity-55",
)}
>
<span
-- class="flex justify-center items-center rounded-[0.625rem] size-9 shrink-0 text-white transition-shadow duration-150"
-- style={{
-- background: available() ? accent() : "var(--gray-3)",
-- color: available() ? "white" : "var(--gray-10)",
-- }}
++ class={cx(
++ "flex justify-center items-center rounded-md size-[22px] shrink-0",
++ available() ? "cap-track-tile" : "bg-ed-ctl text-ed-text-3",
++ )}
>
{props.option.icon()}
</span>
-- <span class="flex flex-col flex-1 min-w-0">
-- <span class="flex gap-1.5 items-center text-[0.8125rem] font-medium leading-tight text-gray-12">
++ <span class="flex flex-col flex-1 gap-0.5 min-w-0">
++ <span class="flex gap-1.5 items-center text-[13px] font-medium leading-none text-ed-text-1">
<span class="truncate">{props.option.label}</span>
<Show when={!isToggle() && (props.option.count ?? 0) > 0}>
-- <span
-- class="rounded-full min-w-4 px-1.5 py-px text-center text-[0.625rem] font-semibold leading-none text-white tabular-nums"
-- style={{ background: accent() }}
-- >
++ <span class="cap-track-tile rounded-full min-w-4 px-1.5 py-px text-center text-[10px] font-semibold leading-none tabular-nums">
{props.option.count}
</span>
</Show>
</span>
-- <span class="text-[0.6875rem] leading-snug text-gray-10 line-clamp-2">
++ <span class="text-[12px] leading-snug text-ed-text-2 line-clamp-2">
{description()}
</span>
</span>
@@@ -136,20 -128,20 +129,17 @@@
fallback={
<span
class={cx(
-- "flex justify-center items-center rounded-full border size-6 shrink-0 transition-colors duration-150",
++ "flex justify-center items-center rounded-md size-5 shrink-0 transition-colors duration-150",
available()
-- ? "border-gray-5 text-gray-10 group-hover/row:border-[var(--accent)] group-hover/row:bg-[var(--accent-soft)] group-hover/row:text-[var(--accent)]"
-- : "border-gray-4 text-gray-9",
++ ? "text-ed-text-3 group-hover/row:bg-ed-ctl-hover group-hover/row:text-ed-text-1"
++ : "text-ed-text-3",
)}
>
<IconLucidePlus class="size-3.5" />
</span>
}
>
-- <span
-- class="flex justify-center items-center text-white rounded-full size-6 shrink-0"
-- style={{ background: accent() }}
-- >
++ <span class="flex justify-center items-center rounded-md size-5 shrink-0 text-ed-accent group-hover/row:bg-ed-ctl-hover">
<IconLucideCheck class="size-3.5 group-hover/row:hidden" />
<IconLucideX class="hidden size-3.5 group-hover/row:block" />
</span>
@@@ -181,18 -173,18 +171,14 @@@ export function TrackManager(props:
>
<Popover.Trigger
class={cx(
-- "group flex relative z-30 gap-1 items-center justify-center px-2 h-8 w-full min-w-0 text-[0.6875rem] font-medium text-white rounded-lg outline-hidden",
-- "bg-linear-to-b from-[#3b82f6] to-[#2563eb]",
-- "shadow-[0_2px_8px_-4px_rgba(37,99,235,0.55),inset_0_1px_0_0_rgba(255,255,255,0.2)]",
-- "transition-[box-shadow,filter] duration-200 ease-out",
-- "hover:brightness-[1.06]",
-- "active:brightness-95",
++ "flex relative z-30 shrink-0 gap-[5px] items-center pl-1.5 pr-2 h-6 rounded-md outline-hidden",
++ "bg-ed-ctl text-[12px] font-medium text-ed-text-2",
++ "transition-colors duration-150 hover:bg-ed-ctl-hover hover:text-ed-text-1",
)}
onMouseDown={(e) => e.stopPropagation()}
>
-- <IconLucidePlus class="size-3.5 shrink-0" />
-- <span class="truncate">Add track</span>
-- <IconCapChevronDown class="size-2.5 shrink-0 text-white/70 transition-transform duration-200 group-data-expanded:rotate-180" />
++ <IconLucidePlus class="size-3 shrink-0" />
++ <span class="whitespace-nowrap">Add track</span>
</Popover.Trigger>
<Popover.Portal>
<Popover.Content
@@@ -202,15 -194,15 +188,15 @@@
// trigger on close would steal it back.
onCloseAutoFocus={(e) => e.preventDefault()}
class={cx(
-- "z-50 flex w-[min(21rem,calc(100vw-1.5rem))] flex-col overflow-hidden rounded-2xl border border-gray-3 bg-gray-1 shadow-[0_24px_48px_-20px_rgba(0,0,0,0.55)] outline-hidden",
++ "z-50 flex w-[min(21rem,calc(100vw-1.5rem))] flex-col overflow-hidden rounded-xl bg-ed-card shadow-ed-pop outline-hidden",
"origin-[var(--kb-popover-content-transform-origin)] data-expanded:animate-in data-expanded:fade-in data-expanded:zoom-in-95 data-closed:animate-out data-closed:fade-out data-closed:zoom-out-95",
)}
>
-- <div class="flex flex-col gap-0.5 px-4 pt-3.5 pb-3 border-b shrink-0 border-gray-3">
-- <span class="text-[0.8125rem] font-semibold text-gray-12">
++ <div class="flex flex-col gap-1 px-3.5 pt-3 pb-2.5 border-b shrink-0 border-ed-line">
++ <span class="text-[13px] font-semibold leading-none tracking-[-0.01em] text-ed-text-1">
Add a track
</span>
-- <span class="text-[0.6875rem] leading-snug text-gray-10">
++ <span class="text-[12px] leading-snug text-ed-text-2">
Layer captions, audio, zooms and more onto your timeline.
</span>
</div>
@@@ -231,8 -223,8 +217,8 @@@
)}
</For>
</div>
-- <div class="p-1.5 border-t shrink-0 border-gray-3">
-- <Popover.CloseButton class="flex gap-1.5 justify-center items-center px-3 w-full h-9 text-[0.8125rem] font-medium rounded-lg border transition-colors duration-150 outline-hidden border-gray-4/70 bg-gray-2 text-gray-12 hover:bg-gray-3 hover:border-gray-5">
++ <div class="p-1.5 border-t shrink-0 border-ed-line">
++ <Popover.CloseButton class="flex gap-1.5 justify-center items-center px-3 w-full h-8 text-[13px] font-medium rounded-lg transition-colors duration-150 outline-hidden bg-ed-ctl text-ed-text-2 hover:bg-ed-ctl-hover hover:text-ed-text-1">
<IconLucideX class="size-3.5" />
Close
</Popover.CloseButton>
@@@ -245,44 -237,44 +231,23 @@@
export function TrackIcon(props: {
icon: JSX.Element;
-- label?: string;
++ showGrip?: boolean;
type?: TimelineTrackType;
class?: string;
}) {
-- if (!props.type) {
-- return (
-- <div
-- class={cx(
-- "relative z-10 w-full h-13 flex flex-col items-center justify-center gap-0.5 rounded-xl border shadow-[0_4px_16px_-12px_rgba(0,0,0,0.8)]",
-- "border-gray-4/70 bg-gray-2/60 text-gray-12 dark:border-gray-4/60 dark:bg-gray-3/40",
-- props.class,
-- )}
-- onMouseDown={(e) => e.stopPropagation()}
-- >
-- {props.icon}
-- <Show when={props.label}>
-- <span class="text-[0.625rem] leading-none font-medium">
-- {props.label}
-- </span>
-- </Show>
-- </div>
-- );
-- }
--
return (
<div
class={cx(
-- CAP_TRACK_FILL_CLASS,
-- "relative z-10 w-full h-13 flex flex-col items-center justify-center gap-0.5 rounded-xl shadow-[0_4px_16px_-12px_rgba(0,0,0,0.8)] text-white",
++ "pointer-events-none relative z-10 flex size-[22px] shrink-0 items-center justify-center rounded-md",
++ props.type ? "cap-track-tile" : "bg-ed-ctl text-ed-text-2",
props.class,
)}
-- style={{ "--seg-color": trackColor(props.type) }}
-- onMouseDown={(e) => e.stopPropagation()}
++ style={props.type ? { "--seg-color": trackColor(props.type) } : undefined}
>
-- {props.icon}
-- <Show when={props.label}>
-- <span class="text-[0.625rem] leading-none font-medium">
-- {props.label}
++ <Show when={props.showGrip} fallback={props.icon}>
++ <span class="group-hover/icon:hidden">{props.icon}</span>
++ <span class="hidden group-hover/icon:block">
++ <IconLucideGripVertical class="size-3" />
</span>
</Show>
</div>
diff --cc apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx
index 3f9c347c5,3f9c347c5..fb60837b9
--- a/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/ZoomTrack.tsx
@@@ -1,7 -1,7 +1,5 @@@
--import { Button } from "@cap/ui-solid";
import { createEventListenerMap } from "@solid-primitives/event-listener";
import { Menu } from "@tauri-apps/api/menu";
--import { cx } from "cva";
import { Array, Option } from "effect";
import {
batch,
@@@ -297,39 -297,39 +295,38 @@@ export function ZoomTrack(props:
<Show
when={hasZoomSegments()}
fallback={
-- <div class="relative z-1 isolate text-center text-sm text-(--text-tertiary) flex flex-col gap-2 justify-center items-center inset-0 w-full bg-gray-3/20 dark:bg-gray-3/10 hover:bg-gray-3/30 dark:hover:bg-gray-3/20 transition-colors rounded-xl pointer-events-auto px-2 py-1">
++ <div class="cap-empty-lane relative z-1 isolate pointer-events-auto">
<Show
when={
hasRecordedCursorData() && !sessionDismissedGenerateZoomPrompt()
}
++ fallback={<span>Drag across this lane to add a zoom</span>}
>
<div
-- class="relative z-10 flex items-center gap-1"
++ class="relative z-10 flex items-center gap-1.5"
onMouseEnter={() => setIsHoveringGenerateZoomButton(true)}
onMouseLeave={() => setIsHoveringGenerateZoomButton(false)}
onMouseDown={(e) => e.stopPropagation()}
>
-- <Button
-- variant="gray"
-- size="md"
-- class="shadow-md border-gray-7 dark:border-gray-8 font-medium"
++ <span>Generate zoom segments automatically</span>
++ <button
++ type="button"
++ class="cap-empty-lane-action outline-hidden"
disabled={isGeneratingAutoZoom()}
onClick={() => {
void handleGenerateZoomSegments();
}}
>
-- {isGeneratingAutoZoom()
-- ? "Generating..."
-- : "Click to generate zoom segments"}
-- </Button>
++ · {isGeneratingAutoZoom() ? "Generating..." : "Generate"}
++ </button>
<button
type="button"
-- class="flex shrink-0 justify-center items-center rounded-full outline-hidden text-gray-11 hover:text-gray-12 hover:bg-gray-5 focus-visible:ring-2 focus-visible:ring-gray-8 size-8 transition-colors"
++ class="flex shrink-0 justify-center items-center rounded-md outline-hidden text-ed-text-3 hover:text-ed-text-1 hover:bg-ed-ctl-hover size-5 transition-colors"
disabled={isGeneratingAutoZoom()}
aria-label="Dismiss for this session"
onClick={() => setSessionDismissedGenerateZoomPrompt(true)}
>
-- <IconLucideX class="size-4" />
++ <IconLucideX class="size-3" />
</button>
</div>
</Show>
@@@ -521,11 -521,11 +518,8 @@@
return (
<SegmentRoot
segColor="var(--track-zoom)"
-- class={cx(
-- "border duration-200 transition-colors group",
-- isSelected() ? "border-gray-12" : "border-transparent",
-- )}
-- innerClass="ring-red-5"
++ class="group"
++ selected={isSelected()}
title={`${zoomModeLabel()} · ${zoomPercentage()}`}
segment={segment()}
onMouseDown={(e) => {
@@@ -652,7 -652,7 +646,7 @@@
)}
/>
<SegmentContent
-- class="flex justify-center items-center cursor-grab"
++ class="flex items-center cursor-grab"
onMouseDown={createMouseDownDrag(
() => {
const original = { ...segment() };
@@@ -696,27 -696,27 +690,28 @@@
return (
<SegmentLabel
full={() => (
-- <div class="flex flex-col gap-1 justify-center items-center text-xs whitespace-nowrap text-gray-1 dark:text-gray-12 animate-in fade-in">
-- <span class="opacity-70">
++ <div class="cap-seg-labels animate-in fade-in">
++ <span class="cap-seg-label truncate">
{visibleBox().width >= 140
? zoomModeLabel()
: "Zoom"}
</span>
-- <div class="flex gap-1 items-center text-md">
-- <IconLucideSearch class="size-3.5" />
++ <span class="cap-seg-sublabel">
{zoomPercentage()}
-- </div>
++ </span>
</div>
)}
compact={() => (
-- <div class="flex gap-1 items-center text-xs whitespace-nowrap text-gray-1 dark:text-gray-12">
-- <IconLucideSearch class="size-3" />
-- <span>{zoomPercentage()}</span>
++ <div class="cap-seg-labels">
++ <span class="cap-seg-label">Zoom</span>
++ <span class="cap-seg-sublabel">
++ {zoomPercentage()}
++ </span>
</div>
)}
glyph={() => (
<div class="flex justify-center items-center">
-- <IconLucideSearch class="size-3.5 text-gray-1 dark:text-gray-12" />
++ <IconLucideSearch class="size-3.5 cap-seg-label" />
</div>
)}
/>
@@@ -789,14 -789,14 +784,12 @@@
{(details) => (
<SegmentRoot
class="pointer-events-none z-0"
-- innerClass="ring-red-300"
++ ghost
segColor="var(--track-zoom)"
segment={details()}
>
-- <SegmentContent class="group">
-- <p class="w-full text-center text-gray-1 dark:text-gray-12 text-md text-primary">
-- +
-- </p>
++ <SegmentContent class="group justify-center">
++ <p class="cap-seg-label">+</p>
</SegmentContent>
</SegmentRoot>
)}
diff --cc apps/desktop/src/routes/editor/Timeline/index.tsx
index 431746859,240c52021..34ee58fea
--- a/apps/desktop/src/routes/editor/Timeline/index.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/index.tsx
@@@ -16,9 -16,9 +16,11 @@@ import
For,
Index,
type JSX,
++ Match,
onCleanup,
onMount,
Show,
++ Switch,
} from "solid-js";
import { produce } from "solid-js/store";
import toast from "solid-toast";
@@@ -39,15 -35,15 +41,25 @@@ import
getSelectedTranscriptionSettings,
transcribeEditorCaptions,
} from "../captions";
++import { clipDuration, clipTimelineOffsets } from "../clip-transitions";
import { FPS, type TimelineTrackType, useEditorContext } from "../context";
import { defaultMaskSegment, type MaskSegment } from "../masks";
import { autoTextColorAt, defaultTextSegment, type TextSegment } from "../text";
++import { effectiveToOutput, holdWindows } from "../timeline-holds";
import {
++ getOverlayTrackRows,
getSegmentTrack,
getTrackRowsWithCount,
getUsedTrackCount,
++ isOverlayTrackKind,
++ moveOverlayTrack,
++ moveTrackLane,
++ type OverlayTrack,
placeSegmentAtTime,
++ removeOverlayTrack,
++ sameOverlayTrack,
sortTrackSegments,
++ trackInsertionIndex,
} from "../timelineTracks";
import { formatTime } from "../utils";
import { type AudioSegmentDragState, AudioTrack } from "./AudioTrack";
@@@ -63,26 -59,24 +75,34 @@@ import { type ThreeDSegmentDragState, T
import { TrackIcon, TrackManager } from "./TrackManager";
import { type ZoomSegmentDragState, ZoomTrack } from "./ZoomTrack";
--const TIMELINE_PADDING = 16;
--const TRACK_GUTTER_GAP = 8;
--const TRACK_GUTTER = 112;
--const TRACK_ICON_WIDTH = TRACK_GUTTER - TRACK_GUTTER_GAP;
--const TIMELINE_HEADER_HEIGHT = 32;
--const PLAYHEAD_TOP_OFFSET = 24;
++// The timeline renders inside the editor's timeline card, which supplies the
++// 10px 12px 12px padding; these constants describe the geometry inside it.
++// 104 is the narrowest gutter that fits the "Add track" pill without
++// truncating its label on the widest system UI font (Segoe UI on Windows).
++const TRACK_GUTTER = 104;
++const TRACK_ICON_WIDTH = TRACK_GUTTER;
++const TRACK_GUTTER_INSET = 4;
++const TIMELINE_HEADER_HEIGHT = 26;
++const TIMELINE_HEADER_GAP = 4;
++const PLAYHEAD_TOP_OFFSET = TIMELINE_HEADER_HEIGHT - 12;
++const TRACK_ROW_HEIGHT = 44;
++const TRACK_ROW_GAP = 6;
++const TRACK_HEIGHT = `${TRACK_ROW_HEIGHT}px`;
const START_SNAP_PX = 10;
++const RULER_SCRUB_OVERHANG_PX = 4;
const trackIcons: Record<TimelineTrackType, () => JSX.Element> = {
- style: () => <IconLucidePalette class="size-4" />,
- image: () => <IconCapImage class="size-4" />,
-- clip: () => <IconLucideClapperboard class="size-4" />,
-- caption: () => <IconCapCaptions class="size-4" />,
-- keyboard: () => <IconLucideKeyboard class="size-4" />,
-- text: () => <IconLucideType class="size-4" />,
-- mask: () => <IconLucideBoxSelect class="size-4" />,
-- zoom: () => <IconLucideSearch class="size-4" />,
-- scene: () => <IconLucideVideo class="size-4" />,
-- audio: () => <IconLucideMusic class="size-4" />,
-- "3d": () => <IconLucideRotate3d class="size-4" />,
++ style: () => <IconLucidePalette class="size-3" />,
++ image: () => <IconCapImage class="size-3" />,
++ clip: () => <IconLucideClapperboard class="size-3" />,
++ caption: () => <IconCapCaptions class="size-3" />,
++ keyboard: () => <IconLucideKeyboard class="size-3" />,
++ text: () => <IconLucideType class="size-3" />,
++ mask: () => <IconLucideBoxSelect class="size-3" />,
++ zoom: () => <IconLucideSearch class="size-3" />,
++ scene: () => <IconLucideVideo class="size-3" />,
++ audio: () => <IconLucideMusic class="size-3" />,
++ "3d": () => <IconLucideRotate3d class="size-3" />,
};
type TrackDefinition = {
@@@ -169,6 -161,6 +189,7 @@@ export function Timeline(props:
overflow: number;
visibleTrackCount: number;
}) => void;
++ onContentHeightChange?: (height: number) => void;
}) {
const {
project,
@@@ -254,52 -236,38 +275,48 @@@
})),
);
const sceneTrackVisible = () => trackState().scene && sceneAvailable();
- const textTrackRows = createMemo(() =>
+ const styleTrackRows = createMemo(() =>
getTrackRowsWithCount(
- project.timeline?.textSegments ?? [],
- trackState().text,
- ),
+ project.timeline?.styleSegments ?? [],
+ trackState().style,
- ),
++ ).reverse(),
);
- const imageTrackRows = createMemo(() =>
- getTrackRowsWithCount(
- project.timeline?.imageSegments ?? [],
- trackState().image,
- ),
- );
- const textTrackRows = createMemo(() =>
- getTrackRowsWithCount(
- project.timeline?.textSegments ?? [],
- trackState().text,
- ),
- );
-- const maskTrackRows = createMemo(() =>
-- getTrackRowsWithCount(
-- project.timeline?.maskSegments ?? [],
-- trackState().mask,
++ const overlayTrackRows = createMemo<OverlayTrack[]>((previous) =>
++ getOverlayTrackRows(project, trackState()).map(
++ (row) => previous?.find((item) => sameOverlayTrack(item, row)) ?? row,
),
);
const audioTrackRows = createMemo(() =>
getTrackRowsWithCount(
project.timeline?.audioSegments ?? [],
trackState().audio,
-- ),
++ ).reverse(),
);
const visibleTrackCount = createMemo(
() =>
2 +
+ styleTrackRows().length +
- imageTrackRows().length +
++ overlayTrackRows().length +
(captionTrackVisible() ? 1 : 0) +
(keyboardTrackVisible() ? 1 : 0) +
-- textTrackRows().length +
-- maskTrackRows().length +
audioTrackRows().length +
(threeDTrackVisible() ? 1 : 0) +
(sceneTrackVisible() ? 1 : 0),
);
-- const trackHeight = createMemo(() =>
-- visibleTrackCount() > 2 ? "3rem" : "3.25rem",
-- );
++
++ const contentHeight = createMemo(() => {
++ const rows = Math.max(visibleTrackCount(), 1);
++ return (
++ TIMELINE_HEADER_HEIGHT +
++ TIMELINE_HEADER_GAP +
++ rows * TRACK_ROW_HEIGHT +
++ (rows - 1) * TRACK_ROW_GAP
++ );
++ });
++
++ createEffect(() => {
++ props.onContentHeightChange?.(contentHeight());
++ });
createEffect(() => {
const visibleTracks = visibleTrackCount();
@@@ -366,6 -334,6 +383,10 @@@
}
if (type === "3d") {
++ if (next && !project.timeline?.camera3dSegments?.length) {
++ projectActions.startCamera3DSetup();
++ return;
++ }
batch(() => {
setEditorState("timeline", "tracks", "3d", next);
if (!next && editorState.timeline.selection?.type === "3d") {
@@@ -550,40 -495,9 +571,46 @@@
}
function handleDeleteTrackLane(
- type: "text" | "mask" | "audio",
+ type: "text" | "mask" | "audio" | "style" | "image",
laneIndex: number,
) {
+ if (type === "style" || type === "image") {
+ const resumeHistory = projectHistory.pause();
+ const segments =
+ (type === "style"
+ ? project.timeline?.styleSegments
+ : project.timeline?.imageSegments) ?? [];
+ projectActions.deleteOverlaySegments(
+ type,
+ segments.flatMap((segment, index) =>
+ segment.track === laneIndex ? [index] : [],
+ ),
+ );
+ setProject(
+ produce((project) => {
+ const remaining =
+ type === "style"
+ ? project.timeline?.styleSegments
+ : project.timeline?.imageSegments;
+ for (const segment of remaining ?? [])
+ if (segment.track > laneIndex) segment.track -= 1;
++ if (type === "image")
++ project.overlayOrder = removeOverlayTrack(
++ project.overlayOrder,
++ type,
++ laneIndex,
++ );
+ }),
+ );
+ setEditorState(
+ "timeline",
+ "tracks",
+ type,
+ Math.max(0, trackState()[type] - 1),
+ );
+ resumeHistory();
+ return;
+ }
const resumeHistory = projectHistory.pause();
const currentTrackCount = trackState()[type];
const nextTextSegments =
@@@ -632,6 -546,6 +659,12 @@@
} else if (nextAudioSegments) {
timeline.audioSegments = nextAudioSegments;
}
++ if (isOverlayTrackKind(type))
++ project.overlayOrder = removeOverlayTrack(
++ project.overlayOrder,
++ type,
++ laneIndex,
++ );
}),
);
setEditorState("timeline", "tracks", type, nextTrackCount);
@@@ -905,12 -807,12 +938,8 @@@
const rect = container.getBoundingClientRect();
return {
-- left: rect.left + TIMELINE_PADDING + TRACK_GUTTER,
-- width: Math.max(
-- timelineBounds.width ??
-- rect.width - TIMELINE_PADDING * 2 - TRACK_GUTTER,
-- 0,
-- ),
++ left: rect.left + TRACK_GUTTER,
++ width: Math.max(timelineBounds.width ?? rect.width - TRACK_GUTTER, 0),
};
}
@@@ -1205,50 -1094,50 +1234,6 @@@
const split = () => editorState.timeline.interactMode === "split";
-- const maskImage = () => {
-- const pos = transform().position;
-- const zoom = transform().zoom;
-- const total = totalDuration();
-- const secPerPx = secsPerPixel();
--
-- const FADE_WIDTH = 32;
-- const FADE_RAMP_PX = 50;
-- const LEFT_OFFSET = TRACK_GUTTER;
-- const RIGHT_PADDING = 0;
--
-- // Calculate alpha for left fade (0 = fully faded, 1 = no fade)
-- // When pos is 0, we are at start -> no fade needed -> strength 0
-- // When pos increases, we want fade to appear -> strength 1
-- const scrollLeftPx = pos / secPerPx;
-- const leftFadeStrength = Math.min(1, scrollLeftPx / FADE_RAMP_PX);
--
-- // Calculate alpha for right fade
-- // When at end, right scroll is 0 -> no fade -> strength 0
-- const scrollRightPx = (total - (pos + zoom)) / secPerPx;
-- const rightFadeStrength = Math.min(1, scrollRightPx / FADE_RAMP_PX);
--
-- const leftStartColor = `rgba(0, 0, 0, ${1 - leftFadeStrength})`;
-- const rightEndColor = `rgba(0, 0, 0, ${1 - rightFadeStrength})`;
--
-- // Left stops:
-- // 0px to LEFT_OFFSET: Always black (icons area)
-- // LEFT_OFFSET: Starts fading. If strength is 0 (start), it's black. If strength is 1, it's transparent.
-- // LEFT_OFFSET + FADE_WIDTH: Always black (content fully visible)
-- const leftStops = `black 0px, black ${LEFT_OFFSET}px, ${leftStartColor} ${LEFT_OFFSET}px, black ${
-- LEFT_OFFSET + FADE_WIDTH
-- }px`;
--
-- // Right stops:
-- // calc(100% - (RIGHT_PADDING + FADE_WIDTH)): Always black (content fully visible)
-- // calc(100% - RIGHT_PADDING): Ends fading. If strength is 0 (end), it's black. If strength is 1, it's transparent.
-- // 100%: Transparent
-- const rightStops = `black calc(100% - ${
-- RIGHT_PADDING + FADE_WIDTH
-- }px), ${rightEndColor} calc(100% - ${RIGHT_PADDING}px), transparent 100%`;
--
-- return `linear-gradient(to right, ${leftStops}, ${rightStops})`;
-- };
--
return (
<TimelineContextProvider
duration={duration()}
@@@ -1257,12 -1146,12 +1242,8 @@@
>
<div
ref={setTimelineContainerRef}
-- class="pt-8 relative overflow-hidden flex flex-col gap-2 h-full"
-- style={{
-- "padding-left": `${TIMELINE_PADDING}px`,
-- "padding-right": `${TIMELINE_PADDING}px`,
-- "--track-height": trackHeight(),
-- }}
++ class="relative overflow-hidden flex flex-col gap-1 h-full"
++ style={{ "--track-height": TRACK_HEIGHT }}
onMouseDown={(e) => {
createRoot((dispose) => {
createEventListener(e.currentTarget, "mouseup", () => {
@@@ -1317,27 -1206,27 +1298,22 @@@
}
}}
>
-- <div
-- class="absolute z-30"
-- style={{
-- top: "2px",
-- left: `${TIMELINE_PADDING + TRACK_GUTTER}px`,
-- right: `${TIMELINE_PADDING}px`,
-- height: "12px",
-- }}
-- >
++ <div class="absolute bottom-0 right-0 z-30 h-1 w-[78px]">
<Minimap />
</div>
<div
-- class="relative z-20"
++ class="relative z-20 shrink-0"
style={{ height: `${TIMELINE_HEADER_HEIGHT}px` }}
>
<div class="absolute inset-0 flex items-end">
<TimelineMarkings />
</div>
<div
-- class="absolute bottom-0 left-0 z-30"
-- style={{ width: `${TRACK_ICON_WIDTH}px` }}
++ class="absolute inset-y-0 left-0 z-30 flex items-center"
++ style={{
++ width: `${TRACK_ICON_WIDTH}px`,
++ "padding-left": `${TRACK_GUTTER_INSET}px`,
++ }}
>
<TrackManager
options={trackOptions()}
@@@ -1345,12 -1234,12 +1321,12 @@@
onAdd={handleAddTrack}
/>
</div>
-- {/* Scrub surface for the ruler. It reaches START_SNAP_PX left of
-- the timeline origin so the snap-to-zero zone always places the
-- playhead instead of hitting the "Add track" trigger beneath. */}
++ {/* Scrub surface for the ruler. It overhangs the timeline origin so
++ the snap-to-zero zone places the playhead instead of hitting the
++ "Add track" trigger beneath, without swallowing that trigger. */}
<div
class="absolute inset-y-0 right-0 z-40"
-- style={{ left: `${TRACK_GUTTER - START_SNAP_PX}px` }}
++ style={{ left: `${TRACK_GUTTER - RULER_SCRUB_OVERHANG_PX}px` }}
onMouseDown={beginRulerScrub}
/>
</div>
@@@ -1365,12 -1254,12 +1341,9 @@@
>
{(preview) => (
<div
-- class={cx(
-- "flex absolute bottom-0 z-20 justify-center items-center w-px pointer-events-none bg-linear-to-b to-120%",
-- split() ? "from-red-300" : "from-gray-400",
-- )}
++ class="absolute bottom-0 z-20 w-px pointer-events-none bg-ed-text-3/50"
style={{
-- left: `${TIMELINE_PADDING + TRACK_GUTTER}px`,
++ left: `${TRACK_GUTTER}px`,
top: `${PLAYHEAD_TOP_OFFSET}px`,
transform: `translateX(${
((preview().time ?? 0) - transform().position) /
@@@ -1378,22 -1267,22 +1351,17 @@@
}px)`,
}}
>
-- <div
-- class={cx(
-- "absolute left-1/2 top-0 size-3 -translate-x-1/2 -translate-y-2 rounded-full",
-- split() ? "bg-red-300" : "bg-gray-10",
-- )}
-- />
++ <div class="absolute top-0 left-1/2 size-2.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-ed-text-3/50" />
</div>
)}
</Show>
<div
class={cx(
-- "absolute bottom-0 rounded-full z-20 w-px pointer-events-none bg-linear-to-b to-120% from-[rgb(226,64,64)]",
++ "absolute bottom-0 z-20 w-px pointer-events-none bg-ed-playhead",
split() && "opacity-50",
)}
style={{
-- left: `${TIMELINE_PADDING + TRACK_GUTTER}px`,
++ left: `${TRACK_GUTTER}px`,
top: `${PLAYHEAD_TOP_OFFSET}px`,
transform: `translateX(${Math.min(
(editorState.playbackTime - transform().position) /
@@@ -1402,17 -1291,17 +1370,17 @@@
)}px)`,
}}
>
-- <div class="size-3 bg-[rgb(226,64,64)] rounded-full -mt-2 -ml-[calc(0.37rem-0.5px)]" />
++ <div class="size-3 rounded-full bg-ed-playhead ring-2 ring-ed-card -mt-1.5 -ml-[5.5px]" />
</div>
<Show when={split() ? editorState.timeline.splitPreview : null}>
{(preview) => (
<div
class={cx(
"absolute bottom-0 z-20 w-px pointer-events-none",
-- preview().snapped ? "bg-blue-9" : "bg-gray-10/70",
++ preview().snapped ? "bg-ed-accent" : "bg-ed-text-3/70",
)}
style={{
-- left: `${TIMELINE_PADDING + TRACK_GUTTER}px`,
++ left: `${TRACK_GUTTER}px`,
top: `${PLAYHEAD_TOP_OFFSET}px`,
transform: `translateX(${
(preview().time - transform().position) / secsPerPixel()
@@@ -1420,20 -1309,20 +1388,15 @@@
}}
>
<Show when={preview().snapped}>
-- <div class="absolute top-0 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rotate-45 rounded-[1px] bg-blue-9" />
++ <div class="absolute top-0 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rotate-45 rounded-[1px] bg-ed-accent" />
</Show>
</div>
)}
</Show>
-- <div
-- class="relative flex-1 min-h-0"
-- style={{
-- "mask-image": maskImage(),
-- "-webkit-mask-image": maskImage(),
-- }}
-- >
++ <div class="overflow-hidden relative flex-1 min-h-0">
<div
ref={setTimelineScrollRef}
++ data-track-scroll
class="absolute inset-0 overflow-y-auto overflow-x-hidden pr-1"
onWheel={(e) => {
if (!e.ctrlKey && Math.abs(e.deltaY) > Math.abs(e.deltaX)) {
@@@ -1441,7 -1330,7 +1404,7 @@@
}
}}
>
-- <div class="flex flex-col gap-2 min-h-full">
++ <div class="flex flex-col gap-1.5 min-h-full">
<TrackRow icon={trackIcons.clip} label="Video" type="clip">
<ClipTrack
ref={setTimelineRef}
@@@ -1480,87 -1369,45 +1443,69 @@@
/>
</TrackRow>
</Show>
- <For each={textTrackRows()}>
+ <For each={styleTrackRows()}>
{(laneIndex) => (
<TrackRow
- icon={trackIcons.text}
- label="Text"
- type="text"
- onDelete={() => handleDeleteTrackLane("text", laneIndex)}
- onContextMenu={(e) =>
- handleOpenTrackMenu(e, "text", laneIndex)
+ icon={trackIcons.style}
+ label={`Style ${laneIndex + 1}`}
+ type="style"
++ laneIndex={laneIndex}
+ onDelete={() => handleDeleteTrackLane("style", laneIndex)}
+ onContextMenu={(event) =>
+ handleOpenTrackMenu(event, "style", laneIndex)
}
>
- <TextTrack
+ <StyleTrack
laneIndex={laneIndex}
- onDragStateChanged={(v) => {
- textSegmentDragState = v;
+ onDragStateChanged={(value) => {
+ styleSegmentDragState = value;
}}
handleUpdatePlayhead={handleUpdatePlayhead}
/>
</TrackRow>
)}
</For>
- <For each={imageTrackRows()}>
- <For each={maskTrackRows()}>
-- {(laneIndex) => (
++ <For each={overlayTrackRows()}>
++ {(row) => (
<TrackRow
- icon={trackIcons.image}
- label={`Image ${laneIndex + 1}`}
- type="image"
- onDelete={() => handleDeleteTrackLane("image", laneIndex)}
- icon={trackIcons.mask}
- label="Mask"
- type="mask"
- onDelete={() => handleDeleteTrackLane("mask", laneIndex)}
- onContextMenu={(e) =>
- handleOpenTrackMenu(e, "mask", laneIndex)
++ icon={trackIcons[row.kind]}
++ label={`${row.kind[0].toUpperCase()}${row.kind.slice(1)} ${row.track + 1}`}
++ type={row.kind}
++ laneIndex={row.track}
++ onDelete={() => handleDeleteTrackLane(row.kind, row.track)}
+ onContextMenu={(event) =>
- handleOpenTrackMenu(event, "image", laneIndex)
++ handleOpenTrackMenu(event, row.kind, row.track)
}
>
- <ImageTrack
- laneIndex={laneIndex}
- onDragStateChanged={(value) => {
- imageSegmentDragState = value;
- }}
- handleUpdatePlayhead={handleUpdatePlayhead}
- />
- </TrackRow>
- )}
- </For>
- <For each={textTrackRows()}>
- {(laneIndex) => (
- <TrackRow
- icon={trackIcons.text}
- label="Text"
- type="text"
- onDelete={() => handleDeleteTrackLane("text", laneIndex)}
- onContextMenu={(e) =>
- handleOpenTrackMenu(e, "text", laneIndex)
- }
- >
- <TextTrack
- laneIndex={laneIndex}
- onDragStateChanged={(v) => {
- textSegmentDragState = v;
- }}
- handleUpdatePlayhead={handleUpdatePlayhead}
- />
- </TrackRow>
- )}
- </For>
- <For each={maskTrackRows()}>
- {(laneIndex) => (
- <TrackRow
- icon={trackIcons.mask}
- label="Mask"
- type="mask"
- onDelete={() => handleDeleteTrackLane("mask", laneIndex)}
- onContextMenu={(e) =>
- handleOpenTrackMenu(e, "mask", laneIndex)
- }
- >
-- <MaskTrack
-- laneIndex={laneIndex}
-- onDragStateChanged={(v) => {
-- maskSegmentDragState = v;
-- }}
-- handleUpdatePlayhead={handleUpdatePlayhead}
-- />
++ <Switch>
++ <Match when={row.kind === "image"}>
++ <ImageTrack
++ laneIndex={row.track}
++ onDragStateChanged={(value) => {
++ imageSegmentDragState = value;
++ }}
++ handleUpdatePlayhead={handleUpdatePlayhead}
++ />
++ </Match>
++ <Match when={row.kind === "text"}>
++ <TextTrack
++ laneIndex={row.track}
++ onDragStateChanged={(value) => {
++ textSegmentDragState = value;
++ }}
++ handleUpdatePlayhead={handleUpdatePlayhead}
++ />
++ </Match>
++ <Match when={row.kind === "mask"}>
++ <MaskTrack
++ laneIndex={row.track}
++ onDragStateChanged={(value) => {
++ maskSegmentDragState = value;
++ }}
++ handleUpdatePlayhead={handleUpdatePlayhead}
++ />
++ </Match>
++ </Switch>
</TrackRow>
)}
</For>
@@@ -1568,8 -1415,8 +1513,9 @@@
{(laneIndex) => (
<TrackRow
icon={trackIcons.audio}
-- label="Audio"
++ label={`Audio ${laneIndex + 1}`}
type="audio"
++ laneIndex={laneIndex}
onDelete={() => handleDeleteTrackLane("audio", laneIndex)}
onContextMenu={(e) =>
handleOpenTrackMenu(e, "audio", laneIndex)
@@@ -1659,30 -1506,30 +1605,399 @@@ function TrackRow(props:
icon: () => JSX.Element;
label?: string;
type: TimelineTrackType;
++ laneIndex?: number;
children: JSX.Element;
onDelete?: () => void;
deleteLabel?: string;
deleteTitle?: string;
onContextMenu?: (e: MouseEvent) => void;
}) {
++ const { project, setProject, editorState, setEditorState } =
++ useEditorContext();
++ const [dragging, setDragging] = createSignal(false);
++ let suppressClick = false;
++ let finishDrag: (() => void) | undefined;
++ onCleanup(() => finishDrag?.());
++ const overlayRows = () =>
++ getOverlayTrackRows(project, editorState.timeline.tracks);
++ const moveToSlot = (slot: number) => {
++ const from = props.laneIndex;
++ if (from === undefined) return;
++ if (isOverlayTrackKind(props.type)) {
++ const order = overlayRows();
++ const source = { kind: props.type, track: from };
++ if (order.findIndex((item) => sameOverlayTrack(item, source)) === slot)
++ return;
++ setProject("overlayOrder", moveOverlayTrack(order, source, slot));
++ return;
++ }
++ const to = laneCount() - 1 - slot;
++ if (from === to) return;
++ setProject(
++ "timeline",
++ produce((timeline) => {
++ if (!timeline) return;
++ if (props.type === "style")
++ moveTrackLane(timeline.styleSegments, from, to);
++ else if (props.type === "audio")
++ moveTrackLane(timeline.audioSegments ?? [], from, to);
++ }),
++ );
++ };
++ const trackSegments = (): Array<{
++ start: number;
++ end: number;
++ track?: number;
++ }> => {
++ const timeline = project.timeline;
++ switch (props.type) {
++ case "style":
++ return timeline?.styleSegments ?? [];
++ case "image":
++ return timeline?.imageSegments ?? [];
++ case "text":
++ return timeline?.textSegments ?? [];
++ case "mask":
++ return timeline?.maskSegments ?? [];
++ case "audio":
++ return timeline?.audioSegments ?? [];
++ case "caption":
++ return timeline?.captionSegments ?? [];
++ case "keyboard":
++ return timeline?.keyboardSegments ?? [];
++ case "zoom":
++ return timeline?.zoomSegments ?? [];
++ case "3d":
++ return timeline?.camera3dSegments ?? [];
++ case "scene":
++ return timeline?.sceneSegments ?? [];
++ case "clip": {
++ const segments = timeline?.segments ?? [];
++ const offsets = clipTimelineOffsets(
++ segments,
++ timeline?.transitions ?? [],
++ );
++ const holds = holdWindows(timeline?.textSegments);
++ return segments.map((segment, index) => ({
++ start: effectiveToOutput(holds, offsets[index]),
++ end: effectiveToOutput(holds, offsets[index] + clipDuration(segment)),
++ }));
++ }
++ }
++ };
++ const laneCount = () => {
++ const count = editorState.timeline.tracks[props.type];
++ return Math.max(
++ typeof count === "number" ? count : 0,
++ getUsedTrackCount(trackSegments()),
++ );
++ };
++ const active = () => {
++ const selection = editorState.timeline.selection;
++ if (
++ !selection ||
++ selection.type !== props.type ||
++ !("indices" in selection)
++ )
++ return false;
++ if (props.laneIndex === undefined) return true;
++ const segments = trackSegments();
++ return selection.indices.some((index) => {
++ const segment = segments[index];
++ return (
++ segment !== undefined && getSegmentTrack(segment) === props.laneIndex
++ );
++ });
++ };
++ const selectTrack = () => {
++ const segments = trackSegments();
++ const items = segments
++ .map((segment, index) => ({ segment, index }))
++ .filter(
++ ({ segment }) =>
++ props.laneIndex === undefined ||
++ getSegmentTrack(segment) === props.laneIndex,
++ );
++ const time = editorState.playbackTime;
++ const activeItems = props.type === "clip" ? [...items].reverse() : items;
++ const item =
++ activeItems.find(
++ ({ segment }) => time >= segment.start && time < segment.end,
++ ) ?? items[0];
++ batch(() => {
++ setEditorState("timeline", "audioPicker", null);
++ setEditorState("timeline", "audioReplace", null);
++ setEditorState("timeline", "camera3dSetup", null);
++ setEditorState(
++ "timeline",
++ "selection",
++ item ? { type: props.type, indices: [item.index] } : null,
++ );
++ if (item) {
++ setEditorState("previewTime", null);
++ setEditorState(
++ "playbackTime",
++ Math.max(
++ item.segment.start,
++ Math.min(time, item.segment.end - 0.001),
++ ),
++ );
++ }
++ });
++ };
++
++ const canReorder = () =>
++ props.laneIndex !== undefined &&
++ (isOverlayTrackKind(props.type) ? overlayRows().length : laneCount()) > 1;
++ const reorderWithKeyboard = (event: KeyboardEvent) => {
++ if (
++ !canReorder() ||
++ !event.altKey ||
++ !["ArrowUp", "ArrowDown"].includes(event.key)
++ )
++ return;
++ event.preventDefault();
++ event.stopPropagation();
++ const kind = props.type;
++ const visual = isOverlayTrackKind(kind);
++ const count = visual ? overlayRows().length : laneCount();
++ const from = visual
++ ? overlayRows().findIndex(
++ (item) => item.kind === kind && item.track === props.laneIndex,
++ )
++ : count - 1 - (props.laneIndex ?? 0);
++ const to = Math.max(
++ 0,
++ Math.min(count - 1, from + (event.key === "ArrowUp" ? -1 : 1)),
++ );
++ const rows = (event.currentTarget as HTMLElement).closest(
++ "[data-track-lane]",
++ )?.parentElement;
++ moveToSlot(to);
++ if (!visual)
++ rows
++ ?.querySelector<HTMLButtonElement>(
++ `[data-track-type="${kind}"][data-track-lane="${count - 1 - to}"] [data-track-reorder]`,
++ )
++ ?.focus();
++ };
++ const startReorder = (event: MouseEvent) => {
++ if (event.button !== 0) return;
++ event.preventDefault();
++ event.stopPropagation();
++ (event.currentTarget as HTMLElement).focus({ preventScroll: true });
++ if (!canReorder()) return;
++ finishDrag?.();
++ suppressClick = false;
++ const header = event.currentTarget as HTMLElement;
++ const row = header.closest<HTMLElement>("[data-track-lane]");
++ const scroll = row?.closest<HTMLElement>("[data-track-scroll]");
++ if (!row || !scroll) return;
++ const visual = isOverlayTrackKind(props.type);
++ const allRows = Array.from(
++ row.parentElement?.querySelectorAll<HTMLElement>("[data-track-lane]") ??
++ [],
++ ).filter((item) =>
++ visual
++ ? isOverlayTrackKind(item.dataset.trackType ?? "")
++ : item.dataset.trackType === props.type,
++ );
++ const rows = allRows.filter((item) => item !== row);
++ let target: number | null = null;
++ let pointer = { x: event.clientX, y: event.clientY };
++ let ghost: HTMLElement | undefined;
++ let indicator: HTMLElement | undefined;
++ let frame = 0;
++ let lastFrame = 0;
++ const previousCursor = document.body.style.cursor;
++ const updateTarget = () => {
++ if (!ghost || !indicator) return;
++ ghost.style.transform = `translate(${pointer.x + 14}px, ${pointer.y - 22}px)`;
++ const bounds = scroll.getBoundingClientRect();
++ const hoveredRow = document
++ .elementFromPoint(pointer.x, pointer.y)
++ ?.closest<HTMLElement>("[data-track-type]");
++ if (
++ (hoveredRow && !allRows.includes(hoveredRow)) ||
++ allRows.some((item) => !item.isConnected) ||
++ pointer.x < bounds.left ||
++ pointer.x > bounds.right ||
++ pointer.y < bounds.top ||
++ pointer.y > bounds.bottom
++ ) {
++ target = null;
++ indicator.style.display = "none";
++ return;
++ }
++ const rects = rows.map((item) => item.getBoundingClientRect());
++ target = trackInsertionIndex(
++ rects.map((rect) => rect.top + rect.height / 2),
++ pointer.y,
++ );
++ const after = rects[target];
++ const before = rects[target - 1];
++ const top = after
++ ? before
++ ? (before.bottom + after.top) / 2
++ : after.top - 4
++ : before.bottom + 4;
++ indicator.style.display = "block";
++ indicator.style.left = `${bounds.left}px`;
++ indicator.style.top = `${Math.max(bounds.top + 1, Math.min(bounds.bottom - 3, top - 1))}px`;
++ indicator.style.width = `${bounds.width - 4}px`;
++ indicator.textContent = visual
++ ? target === 0
++ ? "Front"
++ : target === rows.length
++ ? "Back"
++ : "Place here"
++ : "Place here";
++ };
++ const tick = (now: number) => {
++ const bounds = scroll.getBoundingClientRect();
++ const elapsed = Math.min(32, lastFrame ? now - lastFrame : 16);
++ lastFrame = now;
++ if (
++ pointer.x >= bounds.left &&
++ pointer.x <= bounds.right &&
++ pointer.y >= bounds.top - 24 &&
++ pointer.y <= bounds.bottom + 24
++ ) {
++ const edge = Math.min(40, bounds.height / 3);
++ const velocity =
++ pointer.y < bounds.top + edge
++ ? -Math.min(1, (bounds.top + edge - pointer.y) / edge)
++ : pointer.y > bounds.bottom - edge
++ ? Math.min(1, (pointer.y - bounds.bottom + edge) / edge)
++ : 0;
++ scroll.scrollTop += velocity * elapsed * 0.55;
++ }
++ updateTarget();
++ frame = requestAnimationFrame(tick);
++ };
++ const move = (next: MouseEvent) => {
++ pointer = { x: next.clientX, y: next.clientY };
++ if (
++ !dragging() &&
++ Math.hypot(pointer.x - event.clientX, pointer.y - event.clientY) < 4
++ )
++ return;
++ next.preventDefault();
++ next.stopPropagation();
++ if (!dragging()) {
++ setDragging(true);
++ suppressClick = true;
++ document.body.style.cursor = "grabbing";
++ ghost = header.cloneNode(true) as HTMLElement;
++ ghost.removeAttribute("data-track-reorder");
++ ghost.setAttribute("aria-hidden", "true");
++ ghost.style.cssText = `position:fixed;left:0;top:0;width:${header.offsetWidth}px;pointer-events:none;z-index:2147483647;opacity:.95;filter:drop-shadow(0 8px 16px #0006);`;
++ indicator = document.createElement("div");
++ indicator.style.cssText =
++ "position:fixed;height:2px;background:var(--blue-9);color:var(--blue-9);font-size:10px;font-weight:600;line-height:22px;pointer-events:none;z-index:2147483646;text-align:right;";
++ document.body.append(ghost, indicator);
++ frame = requestAnimationFrame(tick);
++ }
++ updateTarget();
++ };
++ const finish = (commit: boolean) => {
++ window.removeEventListener("mousemove", move, true);
++ window.removeEventListener("mouseup", drop, true);
++ window.removeEventListener("blur", cancel);
++ window.removeEventListener("keydown", keydown, true);
++ cancelAnimationFrame(frame);
++ ghost?.remove();
++ indicator?.remove();
++ document.body.style.cursor = previousCursor;
++ const shouldCommit =
++ commit &&
++ dragging() &&
++ target !== null &&
++ allRows.every((item) => item.isConnected);
++ setDragging(false);
++ finishDrag = undefined;
++ if (shouldCommit && target !== null) moveToSlot(target);
++ };
++ const drop = (next: MouseEvent) => {
++ move(next);
++ finish(true);
++ };
++ const cancel = () => finish(false);
++ const keydown = (next: KeyboardEvent) => {
++ if (next.key === "Escape") {
++ next.preventDefault();
++ next.stopImmediatePropagation();
++ cancel();
++ }
++ };
++ finishDrag = cancel;
++ window.addEventListener("mousemove", move, true);
++ window.addEventListener("mouseup", drop, true);
++ window.addEventListener("blur", cancel);
++ window.addEventListener("keydown", keydown, true);
++ };
++
return (
-- <div class="flex items-stretch gap-2" onContextMenu={props.onContextMenu}>
++ <div
++ class={cx(
++ "group/row relative flex items-stretch rounded-lg transition-[background-color,opacity] duration-150",
++ active() ? "bg-ed-ctl-hover" : "bg-ed-ctl hover:bg-ed-ctl-hover",
++ )}
++ classList={{ "opacity-35": dragging() }}
++ data-track-type={props.type}
++ data-track-lane={props.laneIndex}
++ onContextMenu={props.onContextMenu}
++ >
<div
class="group/icon relative shrink-0"
style={{ width: `${TRACK_ICON_WIDTH}px` }}
>
-- <TrackIcon icon={props.icon()} label={props.label} type={props.type} />
++ <button
++ type="button"
++ class="relative flex h-full w-full items-center gap-1.5 rounded-md pl-1 text-left focus-visible:outline-2 focus-visible:outline-ed-accent"
++ classList={{ "cursor-grab active:cursor-grabbing": canReorder() }}
++ data-track-reorder={canReorder() ? "" : undefined}
++ title={
++ canReorder()
++ ? "Drag this header to reorder. Higher visual layers appear in front. Alt + Up or Down also moves the track."
++ : undefined
++ }
++ onMouseDown={startReorder}
++ onKeyDown={reorderWithKeyboard}
++ aria-label={`Select ${props.label ?? props.type} track`}
++ onClick={(event) => {
++ event.stopPropagation();
++ if (suppressClick) {
++ suppressClick = false;
++ return;
++ }
++ selectTrack();
++ }}
++ >
++ <TrackIcon
++ icon={props.icon()}
++ showGrip={canReorder()}
++ type={props.type}
++ />
++ <Show when={props.label}>
++ <span
++ class={cx(
++ "min-w-0 flex-1 truncate text-[11px] font-medium leading-none transition-[padding,color] duration-150",
++ active()
++ ? "text-ed-text-1"
++ : "text-ed-text-2 group-hover/row:text-ed-text-1",
++ )}
++ classList={{ "group-hover/icon:pr-5": !!props.onDelete }}
++ >
++ {props.label}
++ </span>
++ </Show>
++ </button>
<Show when={props.onDelete}>
<button
type="button"
-- class={cx(
-- "absolute inset-x-0 top-0 z-20 flex h-13 flex-col items-center justify-center gap-0.5 rounded-xl text-white",
-- "bg-linear-to-b from-red-500 to-red-600",
-- "shadow-[0_2px_8px_-4px_rgba(220,38,38,0.55),inset_0_1px_0_0_rgba(255,255,255,0.2)]",
-- "pointer-events-none opacity-0 transition-opacity duration-150",
-- "group-hover/icon:pointer-events-auto group-hover/icon:opacity-100",
-- "hover:brightness-[1.06] active:brightness-95",
-- )}
++ class="absolute right-0 top-1/2 z-30 flex size-5 -translate-y-1/2 items-center justify-center rounded-md text-ed-text-3 opacity-0 transition-opacity hover:bg-ed-ctl-active hover:text-red-9 group-hover/icon:opacity-100 focus-visible:opacity-100"
++ aria-label={props.deleteTitle ?? "Delete track"}
onClick={(e) => {
e.stopPropagation();
props.onDelete?.();
@@@ -1690,14 -1537,14 +2005,11 @@@
onMouseDown={(e) => e.stopPropagation()}
title={props.deleteTitle ?? "Delete track"}
>
-- <IconCapTrash class="size-4" />
-- <span class="text-[0.625rem] leading-none font-medium">
-- {props.deleteLabel ?? "Delete"}
-- </span>
++ <IconCapTrash class="size-3.5" />
</button>
</Show>
</div>
-- <div class="flex-1 relative overflow-hidden min-w-0">
++ <div class="flex-1 relative overflow-hidden min-w-0 rounded-r-lg">
{props.children}
</div>
</div>
@@@ -1719,29 -1566,29 +2031,32 @@@ function TimelineMarkings()
return (
<div
-- class="relative flex-1 h-4 text-xs text-gray-9"
++ class="relative flex-1 h-full overflow-hidden"
style={{ "margin-left": `${TRACK_GUTTER}px` }}
>
<Index each={Array.from({ length: markingCount() })}>
{(_, index) => {
const second = () => getMarkingTime(index);
const isVisible = () => second() >= 0;
-- const showLabel = () => second() % 1 === 0;
++ const isMajor = () => second() % 1 === 0;
const translateX = () =>
-- (second() - transform().position) / secsPerPixel() - 1;
++ (second() - transform().position) / secsPerPixel();
return (
<div
-- class="absolute left-0 bottom-1 w-1 h-1 text-center bg-current rounded-full"
++ class={cx(
++ "absolute left-0 bottom-0 w-px bg-ed-line-strong",
++ isMajor() ? "h-2" : "h-[5px]",
++ )}
style={{
transform: `translateX(${translateX()}px)`,
visibility: isVisible() ? "visible" : "hidden",
}}
>
-- <Show when={showLabel()}>
++ <Show when={isMajor()}>
<div
class={cx(
-- "absolute -top-4.5",
++ "absolute bottom-2.5 left-0 text-[11px] leading-none tabular-nums whitespace-nowrap text-ed-text-3",
// Left-anchor the origin label so it doesn't overhang
// into the track icon gutter and get covered
second() !== 0 && "-translate-x-1/2",
diff --cc apps/desktop/src/routes/editor/Timeline/style-track.tsx
index f8c51b3a1,000000000..69b2c690b
mode 100644,000000..100644
--- a/apps/desktop/src/routes/editor/Timeline/style-track.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/style-track.tsx
@@@ -1,232 -1,0 +1,262 @@@
+import { For, onCleanup, Show } from "solid-js";
+import { useEditorContext } from "../context";
+import { editOverlayInterval } from "../style";
+import { useTimelineContext } from "./context";
+import {
+ SegmentContent,
+ SegmentHandle,
+ SegmentLabel,
+ SegmentRoot,
+ TrackRoot,
+} from "./Track";
+
+export type OverlayDragState = { type: "idle" | "movePending" | "moving" };
+export type OverlayTrackProps = {
+ laneIndex: number;
+ onDragStateChanged(value: OverlayDragState): void;
+ handleUpdatePlayhead(event: MouseEvent): void;
+};
+
+export function StyleTrack(props: OverlayTrackProps) {
+ return <OverlayTrack {...props} type="style" />;
+}
+
+export function OverlayTrack(
+ props: OverlayTrackProps & { type: "style" | "image" },
+) {
+ const {
+ project,
+ setProject,
+ editorState,
+ setEditorState,
+ projectActions,
+ projectHistory,
+ totalDuration,
+ } = useEditorContext();
+ const { secsPerPixel, timelineBounds } = useTimelineContext();
+ const allSegments = () =>
+ (props.type === "style"
+ ? project.timeline?.styleSegments
+ : project.timeline?.imageSegments) ?? [];
+ const segments = () =>
+ allSegments()
+ .map((segment, index) => ({ segment, index }))
+ .filter(({ segment }) => segment.track === props.laneIndex);
+ const selected = (index: number) =>
+ editorState.timeline.selection?.type === props.type &&
+ editorState.timeline.selection.indices.includes(index);
+ let endDrag: (() => void) | undefined;
+ onCleanup(() => endDrag?.());
+
+ const timeAt = (event: MouseEvent) =>
+ Math.max(
+ 0,
+ Math.min(
+ totalDuration(),
+ editorState.timeline.transform.position +
+ (event.clientX - (timelineBounds.left ?? 0)) * secsPerPixel(),
+ ),
+ );
+ const add = (time: number) => {
+ if (props.type === "style")
+ projectActions.addStyleSegment(props.laneIndex, time);
+ else void projectActions.importImageSegment(props.laneIndex, time);
+ };
+ function select(index: number, event: MouseEvent) {
+ const previous = editorState.timeline.selection;
+ let indices = [index];
+ if (previous?.type === props.type) {
+ if (event.metaKey || event.ctrlKey)
+ indices = previous.indices.includes(index)
+ ? previous.indices.filter((value) => value !== index)
+ : [...previous.indices, index];
+ else if (event.shiftKey) {
+ const anchor = previous.indices[previous.indices.length - 1] ?? index;
+ indices = segments()
+ .filter(
+ (item) =>
+ item.index >= Math.min(anchor, index) &&
+ item.index <= Math.max(anchor, index),
+ )
+ .map((item) => item.index);
+ }
+ }
+ setEditorState(
+ "timeline",
+ "selection",
+ indices.length ? { type: props.type, indices } : null,
+ );
+ const segment = allSegments()[index];
+ if (segment) {
+ setEditorState("previewTime", null);
+ setEditorState(
+ "playbackTime",
+ Math.min(
+ Math.max(editorState.playbackTime, segment.start),
+ segment.end - 0.001,
+ ),
+ );
+ }
+ }
+ function drag(
+ event: MouseEvent,
+ index: number,
+ edge: "start" | "move" | "end",
+ ) {
+ event.stopPropagation();
+ if (event.button !== 0) return;
+ if (editorState.timeline.interactMode === "split") {
+ projectActions.splitOverlaySegment(props.type, index, timeAt(event));
+ return;
+ }
+ event.preventDefault();
+ select(index, event);
+ if (event.metaKey || event.ctrlKey || event.shiftKey) return;
+ endDrag?.();
+ const segment = allSegments()[index];
+ if (!segment) return;
+ const initial = { start: segment.start, end: segment.end };
++ const initialPlaybackTime = editorState.playbackTime;
+ const lane = segments();
+ const position = lane.findIndex((item) => item.index === index);
+ const previousEnd = lane[position - 1]?.segment.end ?? 0;
+ const nextStart = lane[position + 1]?.segment.start ?? totalDuration();
+ const resume = projectHistory.pause();
+ let moved = false;
+ props.onDragStateChanged({ type: "movePending" });
+ const move = (next: MouseEvent) => {
+ if (allSegments()[index] !== segment) return;
+ if (!moved && Math.abs(next.clientX - event.clientX) < 2) return;
+ moved = true;
+ props.onDragStateChanged({ type: "moving" });
+ const interval = editOverlayInterval(
+ initial,
+ (next.clientX - event.clientX) * secsPerPixel(),
+ edge,
+ previousEnd,
+ nextStart,
+ );
+ if (props.type === "style")
+ setProject("timeline", "styleSegments", index, interval);
+ else setProject("timeline", "imageSegments", index, interval);
+ setEditorState("previewTime", null);
+ setEditorState(
+ "playbackTime",
+ edge === "end" ? interval.end - 0.001 : interval.start,
+ );
+ };
- const finish = (next?: MouseEvent) => {
++ const finish = (next?: MouseEvent, cancelled = false) => {
+ if (!endDrag) return;
+ if (next) move(next);
+ window.removeEventListener("mousemove", move);
+ window.removeEventListener("mouseup", finish);
+ window.removeEventListener("blur", cancel);
++ window.removeEventListener("keydown", keydown, true);
+ endDrag = undefined;
++ if (cancelled && moved && allSegments()[index] === segment) {
++ if (props.type === "style")
++ setProject("timeline", "styleSegments", index, initial);
++ else setProject("timeline", "imageSegments", index, initial);
++ setEditorState("playbackTime", initialPlaybackTime);
++ }
+ resume();
+ props.onDragStateChanged({ type: "idle" });
+ };
- const cancel = () => finish();
++ const cancel = () => finish(undefined, true);
++ const keydown = (next: KeyboardEvent) => {
++ if (next.key !== "Escape") return;
++ next.preventDefault();
++ next.stopImmediatePropagation();
++ cancel();
++ };
+ endDrag = cancel;
+ window.addEventListener("mousemove", move);
+ window.addEventListener("mouseup", finish);
+ window.addEventListener("blur", cancel);
++ window.addEventListener("keydown", keydown, true);
+ }
+
+ return (
+ <TrackRoot
+ onDblClick={(event) => {
+ if (!(event.target as HTMLElement).closest("[data-overlay-segment]")) {
+ event.stopPropagation();
+ add(timeAt(event));
+ }
+ }}
+ >
+ <Show when={segments().length === 0}>
+ <button
+ type="button"
+ disabled={props.type === "image" && editorState.importingImage}
- class="sticky left-3 self-center mx-3 rounded-md border border-gray-5 bg-gray-2 px-3 py-1 text-xs text-gray-12 hover:bg-gray-3 disabled:opacity-50"
++ class="cap-empty-lane pointer-events-auto"
+ onMouseDown={(event) => event.stopPropagation()}
+ onClick={(event) => {
+ event.stopPropagation();
+ add(editorState.playbackTime);
+ }}
+ >
- {props.type === "image"
- ? editorState.importingImage
- ? "Importing image…"
- : "+ Add image"
- : "+ Add style"}
++ <Show
++ when={props.type === "image"}
++ fallback={
++ <>
++ <span>
++ Change background, camera and cursor for part of your video
++ </span>
++ <span class="cap-empty-lane-action">· Add style</span>
++ </>
++ }
++ >
++ <span>Place images and logos on your video</span>
++ <span class="cap-empty-lane-action">
++ {editorState.importingImage
++ ? "· Importing image…"
++ : "· Add image"}
++ </span>
++ </Show>
+ </button>
+ </Show>
+ <For each={segments()}>
+ {({ segment, index }) => (
+ <SegmentRoot
+ segment={segment}
+ data-overlay-segment
+ data-index={index}
+ segColor={`var(--track-${props.type})`}
- innerClass="ring-blue-6"
- class={`border ${selected(index) ? "border-blue-7" : "border-transparent"} ${segment.enabled ? "" : "opacity-50"}`}
++ class="group"
++ selected={selected(index)}
++ muted={!segment.enabled}
+ title={`${segment.name} · ${(segment.end - segment.start).toFixed(2)}s`}
+ >
+ <SegmentHandle
+ position="start"
+ onMouseDown={(event) => drag(event, index, "start")}
+ />
+ <SegmentContent
- class="cursor-grab overflow-hidden px-3"
++ class="cursor-grab overflow-hidden"
+ onMouseDown={(event) => drag(event, index, "move")}
+ >
+ <SegmentLabel
+ full={() => (
- <span class="truncate text-xs text-white">
- {segment.name}
- </span>
++ <div class="cap-seg-labels">
++ <span class="cap-seg-label truncate">{segment.name}</span>
++ <span class="cap-seg-sublabel">
++ {`${(segment.end - segment.start).toFixed(1)}s`}
++ </span>
++ </div>
+ )}
+ compact={() => (
- <span class="truncate text-[10px] text-white">
- {segment.name}
- </span>
++ <span class="cap-seg-label truncate">{segment.name}</span>
+ )}
+ />
+ </SegmentContent>
+ <SegmentHandle
+ position="end"
+ onMouseDown={(event) => drag(event, index, "end")}
+ />
+ </SegmentRoot>
+ )}
+ </For>
+ </TrackRoot>
+ );
+}
diff --cc apps/desktop/src/routes/editor/Timeline/styles.css
index 43dc511ad,43dc511ad..fbdd93c11
--- a/apps/desktop/src/routes/editor/Timeline/styles.css
+++ b/apps/desktop/src/routes/editor/Timeline/styles.css
@@@ -21,6 -21,6 +21,154 @@@
}
.cap-track-fill {
-- background: var(--seg-color);
-- border: 1px solid color-mix(in srgb, var(--seg-color) 58%, black);
++ --seg-color: var(--ed-text-3);
++ --ed-seg-tint-selected: calc(var(--ed-seg-tint) + 10%);
++ --ed-seg-line-hover: calc(var(--ed-seg-line) + 10%);
++ border-radius: 8px;
++ background-color: color-mix(
++ in srgb,
++ var(--seg-color) var(--ed-seg-tint),
++ var(--ed-card)
++ );
++ box-shadow: inset 0 0 0 1px
++ color-mix(in srgb, var(--seg-color) var(--ed-seg-line), transparent);
++ transition:
++ background-color 0.15s ease,
++ box-shadow 0.15s ease;
++}
++
++.cap-track-fill::before {
++ content: "";
++ position: absolute;
++ top: 0;
++ bottom: 0;
++ left: 0;
++ width: 3px;
++ background-color: var(--seg-color);
++ pointer-events: none;
++ z-index: 1;
++}
++
++.cap-track-fill:hover {
++ box-shadow: inset 0 0 0 1px
++ color-mix(in srgb, var(--seg-color) var(--ed-seg-line-hover), transparent);
++}
++
++.cap-track-fill[data-selected] {
++ background-color: color-mix(
++ in srgb,
++ var(--seg-color) var(--ed-seg-tint-selected),
++ var(--ed-card)
++ );
++ box-shadow: inset 0 0 0 1.5px var(--ed-accent);
++}
++
++.cap-track-fill[data-muted] {
++ background-color: color-mix(
++ in srgb,
++ var(--seg-color) calc(var(--ed-seg-tint) / 2),
++ var(--ed-card)
++ );
++}
++
++.cap-track-fill[data-ghost] {
++ opacity: 0.55;
++}
++
++.cap-seg-labels {
++ display: flex;
++ align-items: center;
++ gap: 8px;
++ min-width: 0;
++}
++
++.cap-seg-label {
++ font-size: 12px;
++ font-weight: 500;
++ line-height: 1.2;
++ white-space: nowrap;
++ color: color-mix(
++ in srgb,
++ var(--seg-color) var(--ed-seg-label-mix),
++ var(--ed-seg-label-base)
++ );
++}
++
++.cap-seg-sublabel {
++ font-size: 11px;
++ line-height: 1.2;
++ white-space: nowrap;
++ font-variant-numeric: tabular-nums;
++ color: color-mix(in srgb, var(--seg-color) 45%, var(--ed-text-3));
++}
++
++.cap-track-fill[data-muted] .cap-seg-label,
++.cap-track-fill[data-muted] .cap-seg-sublabel {
++ color: var(--ed-text-3);
++}
++
++.cap-seg-handle {
++ width: 3px;
++ height: 16px;
++ border-radius: 2px;
++ background-color: color-mix(
++ in srgb,
++ var(--seg-color) 70%,
++ var(--ed-seg-label-base)
++ );
++}
++
++.cap-fade-shade {
++ fill: color-mix(in srgb, var(--ed-seg-label-base) 22%, transparent);
++}
++
++.cap-fade-curve,
++.cap-fade-corner {
++ stroke: color-mix(in srgb, var(--seg-color) 70%, var(--ed-seg-label-base));
++ fill: color-mix(in srgb, var(--seg-color) 70%, var(--ed-seg-label-base));
++}
++
++.cap-fade-curve {
++ fill: none;
++}
++
++.cap-fade-corner-line {
++ stroke: color-mix(in srgb, var(--ed-card) 65%, transparent);
++}
++
++.cap-track-tile {
++ background-color: color-mix(in srgb, var(--seg-color) 16%, transparent);
++ color: color-mix(in srgb, var(--seg-color) 62%, var(--ed-seg-label-base));
++}
++
++.cap-empty-lane {
++ display: flex;
++ width: 100%;
++ height: 100%;
++ align-items: center;
++ justify-content: center;
++ gap: 6px;
++ font-size: 12px;
++ line-height: 1.2;
++ color: var(--ed-text-3);
++ text-align: center;
++ transition: color 0.15s ease;
++}
++
++button.cap-empty-lane:hover:not(:disabled),
++.cap-empty-lane[data-active] {
++ color: var(--ed-text-2);
++}
++
++.cap-empty-lane-action {
++ font-weight: 500;
++ color: var(--ed-text-2);
++}
++
++button.cap-empty-lane-action:hover:not(:disabled) {
++ color: var(--ed-text-1);
++}
++
++.cap-empty-lane-action:disabled {
++ opacity: 0.6;
}
diff --cc apps/desktop/src/routes/editor/TranscriptPage.tsx
index d2d976e52,37536cf51..acc73e952
--- a/apps/desktop/src/routes/editor/TranscriptPage.tsx
+++ b/apps/desktop/src/routes/editor/TranscriptPage.tsx
@@@ -1,6 -1,6 +1,5 @@@
import { createEventListener } from "@solid-primitives/event-listener";
import { makePersisted } from "@solid-primitives/storage";
--import { save } from "@tauri-apps/plugin-dialog";
import { writeTextFile } from "@tauri-apps/plugin-fs";
import { cx } from "cva";
import {
@@@ -245,15 -243,15 +244,10 @@@ export function TranscriptPanel()
setExportingFormat(format);
try {
-- const path = await save({
-- defaultPath: captionExportDefaultPath(meta().prettyName, format),
-- filters: [
-- {
-- name: format === "srt" ? "SubRip Subtitle" : "WebVTT",
-- extensions: [format],
-- },
-- ],
-- });
++ const path = await commands.saveFileDialog(
++ captionExportDefaultPath(meta().prettyName, format),
++ format,
++ );
if (!path) return;
await writeTextFile(path, formatCaptionCues(cues, format));
@@@ -513,9 -510,9 +507,9 @@@
});
return (
-- <div class="flex flex-col min-h-0 h-full">
-- <div class="px-3 py-2 border-b border-gray-3 flex items-center justify-between shrink-0">
-- <span class="text-xs font-medium text-gray-12">Captions</span>
++ <div class="flex overflow-hidden flex-col min-h-0 h-full rounded-xl">
++ <div class="px-3 py-2 border-b border-ed-line flex items-center justify-between shrink-0">
++ <span class="text-xs font-medium text-ed-text-1">Captions</span>
<div class="flex items-center gap-1">
<button
type="button"
diff --cc apps/desktop/src/routes/editor/context.ts
index 3f4374edc,5ec4ab3c0..1509c89cd
--- a/apps/desktop/src/routes/editor/context.ts
+++ b/apps/desktop/src/routes/editor/context.ts
@@@ -78,31 -75,28 +78,39 @@@ import
transitionsAfterClipSplit,
} from "./clip-transitions";
import { normalizeColorCorrection } from "./colorCorrection";
+import { defaultImageSegment, type ImageSegment, pickImage } from "./images";
+ import {
+ generateForStableKeyboardTimeline,
+ keyboardTimelineSignature,
+ mapKeyboardTrackTimes,
+ rippleKeyboardTrack,
+ splitKeyboardSegment,
+ } from "./keyboard-timing";
import type { MaskSegment } from "./masks";
+import { createProjectConfigSave } from "./project-config-save";
import type { SnapGuide } from "./snapping";
+import {
+ defaultStyleSegment,
+ resolveStyle,
+ type StyleGroup,
+ type StyleSegment,
+ splitOverlaySegment,
+} from "./style";
import type { TextSegment } from "./text";
import {
applySceneToRange,
CAMERA3D_SCENES,
type Camera3DSegment,
++ type Camera3DSetup,
++ camera3DSceneRange,
defaultCamera3DTracks,
evaluatePose,
++ findCamera3DScene,
getEndPose,
getMotionEasing,
getStartPose,
normalizeCamera3DSegments,
scaleKeyframeTimes,
-- sceneWithShotCount,
setMotion,
} from "./three-d";
import {
@@@ -283,12 -273,6 +293,12 @@@ export function normalizeProject
const timeline = config.timeline
? {
...config.timeline,
+ styleSegments: normalizeTrackSegments(
+ config.timeline.styleSegments ?? [],
+ ),
- imageSegments: normalizeTrackSegments(
- config.timeline.imageSegments ?? [],
- ),
++ imageSegments: (config.overlayOrder?.length
++ ? sortTrackSegments
++ : normalizeTrackSegments)(config.timeline.imageSegments ?? []),
transitions:
(
config.timeline as TimelineConfiguration & {
@@@ -298,14 -282,14 +308,18 @@@
sceneSegments: config.timeline.sceneSegments ?? [],
captionSegments: config.timeline.captionSegments ?? [],
keyboardSegments: config.timeline.keyboardSegments ?? [],
-- maskSegments: normalizeTrackSegments(
++ maskSegments: (config.overlayOrder?.length
++ ? sortTrackSegments
++ : normalizeTrackSegments)(
(
config.timeline as TimelineConfiguration & {
maskSegments?: MaskSegment[];
}
).maskSegments ?? [],
),
-- textSegments: normalizeTrackSegments(
++ textSegments: (config.overlayOrder?.length
++ ? sortTrackSegments
++ : normalizeTrackSegments)(
(
config.timeline as TimelineConfiguration & {
textSegments?: TextSegment[];
@@@ -398,296 -494,139 +412,296 @@@ export const [EditorContextProvider, us
setProject(
produce((project) => {
const timeline = project.timeline;
- if (!timeline) return;
- const normalized = normalizeClipTransitions(
- timeline.segments,
- timeline.transitions ?? [],
+ if (!timeline || segmentIndex <= 0) return;
+ const segment = timeline.segments[segmentIndex];
+ const previous = timeline.segments[segmentIndex - 1];
+ if (!segment || !previous) return;
+ const transitions = timeline.transitions ?? [];
+
+ const oldDuration =
+ getClipTransition(timeline.segments, transitions, segmentIndex)
+ ?.duration ?? 0;
+ const duration = transition
+ ? clampTransitionDuration(transition.duration, previous, segment)
+ : 0;
- const boundary =
++ const boundary = effectiveToOutput(
++ holdWindows(timeline.textSegments),
+ clipTimelineOffsets(timeline.segments, transitions)[
+ segmentIndex
- ] + oldDuration;
++ ] + oldDuration,
+ );
- if (
- normalized.length === timeline.transitions.length &&
- normalized.every((transition, index) => {
- const current = timeline.transitions[index];
- return (
- current?.segmentIndex === transition.segmentIndex &&
- current.type === transition.type &&
- current.duration === transition.duration
- );
- })
- )
- return;
- timeline.transitions = normalized;
- }),
- );
- },
- deleteClipTransition: (segmentIndex: number) => {
- setClipTransition(segmentIndex, null);
- setEditorState("timeline", "selection", null);
- },
- splitClipSegment: (time: number, requestedSegmentIndex?: number) => {
- let didSplit = false;
- setProject(
- produce((project) => {
- const timeline = project.timeline;
- if (!timeline) return;
- const segments = timeline.segments;
- // The click position is in held-output time; clip offsets
- // live in the gapless recording-flow domain.
- time -= heldTimeBefore(holdWindows(timeline.textSegments), time);
- const offsets = clipTimelineOffsets(
- segments,
- timeline.transitions ?? [],
+ const shift = oldDuration - duration;
+
+ timeline.transitions = transitions.filter(
+ (value) => value.segmentIndex !== segmentIndex,
);
- let currentSegmentIndex = requestedSegmentIndex ?? -1;
- if (currentSegmentIndex < 0) {
- for (let index = 0; index < segments.length; index++) {
- const duration =
- (segments[index].end - segments[index].start) /
- segments[index].timescale;
- if (
- time >= offsets[index] &&
- time <= offsets[index] + duration
- ) {
- currentSegmentIndex = index;
- }
- }
+ if (transition && duration > 0) {
+ timeline.transitions.push({
+ ...transition,
+ segmentIndex,
+ duration,
+ });
+ timeline.transitions.sort(
+ (a, b) => a.segmentIndex - b.segmentIndex,
+ );
}
- if (currentSegmentIndex === -1) return;
- const segment = segments[currentSegmentIndex];
- const localTime = time - offsets[currentSegmentIndex];
- const duration = (segment.end - segment.start) / segment.timescale;
- if (localTime <= 0 || localTime >= duration) return;
- const incomingDuration =
- getClipTransition(
- segments,
- timeline.transitions ?? [],
- currentSegmentIndex,
- )?.duration ?? 0;
- const outgoingDuration =
- getClipTransition(
- segments,
- timeline.transitions ?? [],
- currentSegmentIndex + 1,
- )?.duration ?? 0;
- if (
- localTime < incomingDuration * 2 ||
- duration - localTime < outgoingDuration * 2
- )
- return;
- const splitPositionInRecording = localTime * segment.timescale;
-
- segments.splice(currentSegmentIndex + 1, 0, {
- ...segment,
- start: segment.start + splitPositionInRecording,
- end: segment.end,
- });
- segments[currentSegmentIndex].end =
- segment.start + splitPositionInRecording;
- timeline.transitions = transitionsAfterClipSplit(
- timeline.transitions ?? [],
- currentSegmentIndex,
+ if (shift === 0) return;
+ const camera3dSegments = timeline.camera3dSegments ?? [];
+ const previousCamera3dDurations = camera3dSegments.map(
+ (segment) => segment.end - segment.start,
+ );
+ const tracks = [
+ timeline.styleSegments,
+ timeline.imageSegments,
+ timeline.zoomSegments,
+ timeline.sceneSegments ?? [],
+ timeline.maskSegments,
+ timeline.textSegments,
+ timeline.captionSegments ?? [],
- timeline.keyboardSegments ?? [],
+ timeline.audioSegments ?? [],
+ camera3dSegments,
+ ];
+ for (const track of tracks) {
+ rippleTimelineTrack(track, boundary, shift);
+ }
++ rippleKeyboardTrack(
++ timeline.keyboardSegments ?? [],
++ boundary,
++ shift,
+ );
- didSplit = true;
+ for (let index = 0; index < camera3dSegments.length; index++) {
+ const camera3dSegment = camera3dSegments[index];
+ const previousDuration = previousCamera3dDurations[index];
+ // Keyframe times are relative to the segment start, so a
+ // segment the ripple resized (the straddling case) has to
+ // have them rescaled onto its new length.
+ const nextDuration = camera3dSegment.end - camera3dSegment.start;
+ if (previousDuration <= 0 || nextDuration === previousDuration)
+ continue;
+ scaleKeyframeTimes(
+ camera3dSegment.tracks,
+ nextDuration / previousDuration,
+ );
+ }
}),
);
- if (didSplit) setEditorState("timeline", "selection", null);
- },
- deleteClipSegment: (segmentIndex: number) => {
- if (!project.timeline) return;
- if (project.timeline.segments.length < 2) return;
+ };
+
+ // Output-time boundaries of every clip that fall strictly inside a range.
+ // A 3D scene lines its cuts up with these so the camera changes shot on
+ // the same frame the footage does.
+ const camera3DClipCuts = (start: number, end: number) => {
+ const timeline = project.timeline;
+ if (!timeline) return [];
+ const offsets = clipTimelineOffsets(
+ timeline.segments,
+ timeline.transitions ?? [],
+ );
+ const cuts: number[] = [];
+ for (let index = 0; index < timeline.segments.length; index++) {
+ const boundaries = [
+ offsets[index],
+ offsets[index] + clipDuration(timeline.segments[index]),
+ ];
+ for (const boundary of boundaries)
+ if (boundary > start && boundary < end) cuts.push(boundary);
+ }
+ return cuts;
+ };
+
- /**
- * The chain a scene would lay over the whole timeline. The setup flow's
- * ghost placeholder and the action that commits it read this same
- * function, so the track previews exactly what lands.
- */
- const camera3DScenePreview = (sceneId: string, shots: number) => {
- const scene = CAMERA3D_SCENES.find((s) => s.id === sceneId);
- if (!scene) return [];
-
- const end = totalDuration();
++ const camera3DScenePreview = (setup: Camera3DSetup) => {
++ const scene = findCamera3DScene(setup.sceneId);
++ const range = camera3DSceneRange(
++ project.timeline?.camera3dSegments ?? [],
++ setup.start,
++ setup.duration,
++ totalDuration(),
++ );
++ if (!scene || !range) return [];
+ return applySceneToRange(
- sceneWithShotCount(scene, shots),
- 0,
- end,
- camera3DClipCuts(0, end),
++ scene,
++ range.start,
++ range.end,
++ camera3DClipCuts(range.start, range.end),
+ );
+ };
+ const overlayPlacement = (
+ type: "style" | "image",
+ lane: number,
+ time: number,
+ ) => {
+ const segments =
+ (type === "style"
+ ? project.timeline?.styleSegments
+ : project.timeline?.imageSegments) ?? [];
+ const length = Math.min(3, totalDuration());
+ if (length <= 0) return null;
+ const requested = placeSegmentAtTime(
+ segments.filter((segment) => segment.track === lane),
+ time,
+ length,
+ totalDuration(),
+ );
+ if (requested) return { ...requested, lane };
+ const placement = placeSegmentAtTime([], time, length, totalDuration());
+ return placement
+ ? {
+ ...placement,
+ lane: Math.max(
+ getUsedTrackCount<{
+ start: number;
+ end: number;
+ track?: number;
+ }>(segments),
+ lane + 1,
+ ),
+ }
+ : null;
+ };
+ const selectAddedOverlay = (
+ type: "style" | "image",
+ lane: number,
+ start: number,
+ ) => {
+ const segments =
+ (type === "style"
+ ? project.timeline?.styleSegments
+ : project.timeline?.imageSegments) ?? [];
+ const index = segments.findIndex(
+ (segment) => segment.track === lane && segment.start === start,
+ );
batch(() => {
+ setEditorState(
+ "timeline",
+ "tracks",
+ type,
+ Math.max(editorState.timeline.tracks[type], lane + 1),
+ );
+ setEditorState("timeline", "selection", { type, indices: [index] });
+ if (type === "style") enterStyleScope(index);
+ setEditorState("playbackTime", start);
+ setEditorState("previewTime", null);
+ });
+ };
+ const projectActions = {
+ setClipTransition,
+ normalizeClipTransitions: () => {
setProject(
produce((project) => {
const timeline = project.timeline;
if (!timeline) return;
- deleteClipAndRippleAllTracks(timeline, segmentIndex);
+ const normalized = normalizeClipTransitions(
+ timeline.segments,
+ timeline.transitions ?? [],
+ );
+ if (
+ normalized.length === timeline.transitions.length &&
+ normalized.every((transition, index) => {
+ const current = timeline.transitions[index];
+ return (
+ current?.segmentIndex === transition.segmentIndex &&
+ current.type === transition.type &&
+ current.duration === transition.duration
+ );
+ })
+ )
+ return;
+ timeline.transitions = normalized;
}),
);
+ },
+ deleteClipTransition: (segmentIndex: number) => {
+ setClipTransition(segmentIndex, null);
setEditorState("timeline", "selection", null);
- });
- },
- splitZoomSegment: (index: number, time: number) => {
- setProject(
- "timeline",
- "zoomSegments",
- produce((segments) => {
- const segment = segments[index];
- if (!segment) return;
+ },
+ splitClipSegment: (time: number, requestedSegmentIndex?: number) => {
+ let didSplit = false;
+ setProject(
+ produce((project) => {
+ const timeline = project.timeline;
+ if (!timeline) return;
+ const segments = timeline.segments;
+ // The click position is in held-output time; clip offsets
+ // live in the gapless recording-flow domain.
+ time -= heldTimeBefore(holdWindows(timeline.textSegments), time);
+ const offsets = clipTimelineOffsets(
+ segments,
+ timeline.transitions ?? [],
+ );
+ let currentSegmentIndex = requestedSegmentIndex ?? -1;
+ if (currentSegmentIndex < 0) {
+ for (let index = 0; index < segments.length; index++) {
+ const duration =
+ (segments[index].end - segments[index].start) /
+ segments[index].timescale;
+ if (
+ time >= offsets[index] &&
+ time <= offsets[index] + duration
+ ) {
+ currentSegmentIndex = index;
+ }
+ }
+ }
- const newLengths = [segment.end - segment.start - time, time];
+ if (currentSegmentIndex === -1) return;
+ const segment = segments[currentSegmentIndex];
+ const localTime = time - offsets[currentSegmentIndex];
+ const duration =
+ (segment.end - segment.start) / segment.timescale;
+ if (localTime <= 0 || localTime >= duration) return;
+ const incomingDuration =
+ getClipTransition(
+ segments,
+ timeline.transitions ?? [],
+ currentSegmentIndex,
+ )?.duration ?? 0;
+ const outgoingDuration =
+ getClipTransition(
+ segments,
+ timeline.transitions ?? [],
+ currentSegmentIndex + 1,
+ )?.duration ?? 0;
+ if (
+ localTime < incomingDuration * 2 ||
+ duration - localTime < outgoingDuration * 2
+ )
+ return;
+ const splitPositionInRecording = localTime * segment.timescale;
- if (newLengths.some((l) => l < 1)) return;
+ segments.splice(currentSegmentIndex + 1, 0, {
+ ...segment,
+ start: segment.start + splitPositionInRecording,
+ end: segment.end,
+ });
+ segments[currentSegmentIndex].end =
+ segment.start + splitPositionInRecording;
+ timeline.transitions = transitionsAfterClipSplit(
+ timeline.transitions ?? [],
+ currentSegmentIndex,
+ );
+ didSplit = true;
+ }),
+ );
+ if (didSplit) setEditorState("timeline", "selection", null);
+ },
+ deleteClipSegment: (segmentIndex: number) => {
+ if (!project.timeline) return;
- const segment = project.timeline.segments[segmentIndex];
- if (!segment || project.timeline.segments.length < 2) return;
++ if (project.timeline.segments.length < 2) return;
- segments.splice(index + 1, 0, {
- ...segment,
- start: segment.start + time,
- end: segment.end,
- });
- segments[index].end = segment.start + time;
- sortTrackSegments(segments);
- }),
- );
- },
- deleteZoomSegments: (segmentIndices: number[]) => {
- batch(() => {
+ batch(() => {
+ setProject(
+ produce((project) => {
+ const timeline = project.timeline;
+ if (!timeline) return;
- timeline.segments.splice(segmentIndex, 1);
- timeline.transitions = transitionsAfterClipDelete(
- timeline.transitions ?? [],
- segmentIndex,
- );
++ deleteClipAndRippleAllTracks(timeline, segmentIndex);
+ }),
+ );
+ setEditorState("timeline", "selection", null);
+ });
+ },
+ splitZoomSegment: (index: number, time: number) => {
setProject(
"timeline",
"zoomSegments",
@@@ -732,186 -689,68 +746,194 @@@
"timeline",
"camera3dSegments",
produce((segments) => {
- if (!segments) return;
- const sorted = [...new Set(segmentIndices)]
- .filter(
- (i) => Number.isInteger(i) && i >= 0 && i < segments.length,
- )
- .sort((a, b) => b - a);
- if (sorted.length === 0) return;
- for (const i of sorted) segments.splice(i, 1);
+ const segment = segments?.[index];
+ if (!segment) return;
+
+ const duration = segment.end - segment.start;
+ const remaining = duration - time;
+ if (time < 1 || remaining < 1) return;
+
+ // A split must not change what plays: both halves meet on the pose
+ // the segment held at the cut, so the left half moves start -> mid
+ // and the right half picks up mid -> end. Blur is segment-level, so
+ // it is simply carried onto both halves.
+ const startPose = getStartPose(segment);
+ const midPose = evaluatePose(segment, time);
+ const endPose = getEndPose(segment);
+ const easing = getMotionEasing(segment);
+
+ const right: Camera3DSegment = {
+ ...segment,
+ start: segment.start + time,
+ end: segment.end,
+ properties: { ...segment.properties },
+ blur: { ...segment.blur },
+ tracks: defaultCamera3DTracks(),
+ };
+ setMotion(right, midPose, endPose, easing);
+ segments.splice(index + 1, 0, right);
+
+ const left = segments[index];
+ left.end = segment.start + time;
+ left.tracks = defaultCamera3DTracks();
+ setMotion(left, startPose, midPose, easing);
+ sortTrackSegments(segments);
}),
);
- setEditorState("timeline", "selection", null);
- });
- },
- applyCamera3DScene: (segmentIndex: number, sceneId: string) => {
- const scene = CAMERA3D_SCENES.find((s) => s.id === sceneId);
- const segment = project.timeline?.camera3dSegments?.[segmentIndex];
- if (!scene || !segment) return;
-
- const { start, end } = segment;
- const generated = applySceneToRange(
- scene,
- start,
- end,
- camera3DClipCuts(start, end),
- );
- if (generated.length === 0) return;
+ },
+ deleteCamera3DSegments: (segmentIndices: number[]) => {
+ batch(() => {
+ setProject(
+ "timeline",
+ "camera3dSegments",
+ produce((segments) => {
+ if (!segments) return;
+ const sorted = [...new Set(segmentIndices)]
+ .filter(
+ (i) => Number.isInteger(i) && i >= 0 && i < segments.length,
+ )
+ .sort((a, b) => b - a);
+ if (sorted.length === 0) return;
+ for (const i of sorted) segments.splice(i, 1);
+ }),
+ );
+ setEditorState("timeline", "selection", null);
+ });
+ },
+ applyCamera3DScene: (segmentIndex: number, sceneId: string) => {
+ const scene = CAMERA3D_SCENES.find((s) => s.id === sceneId);
+ const segment = project.timeline?.camera3dSegments?.[segmentIndex];
+ if (!scene || !segment) return;
+
+ const { start, end } = segment;
+ const generated = applySceneToRange(
+ scene,
+ start,
+ end,
+ camera3DClipCuts(start, end),
+ );
+ if (generated.length === 0) return;
- batch(() => {
+ batch(() => {
+ setProject(
+ "timeline",
+ "camera3dSegments",
+ produce((segments) => {
+ if (!segments) return;
+ segments.splice(segmentIndex, 1, ...generated);
+ sortTrackSegments(segments);
+ }),
+ );
+ setEditorState("timeline", "selection", {
+ type: "3d",
+ indices: generated.map((_, offset) => segmentIndex + offset),
+ });
+ setEditorState("playbackTime", start);
+ setEditorState("previewTime", null);
+ });
+ },
- addCamera3DScene: (sceneId: string, shots: number) => {
- // Only ever an empty-track offer: the scene owns the whole timeline,
- // so it must not land on top of shots someone has already authored.
- if (!project.timeline) return;
- if ((project.timeline.camera3dSegments?.length ?? 0) > 0) return;
-
- const generated = camera3DScenePreview(sceneId, shots);
++ startCamera3DSetup: (start = editorState.playbackTime) => {
++ batch(() => {
++ setEditorState("timeline", "selection", null);
++ setEditorState("timeline", "audioPicker", null);
++ setEditorState("timeline", "audioReplace", null);
++ setEditorState("timeline", "camera3dSetup", {
++ sceneId: "glide-across",
++ start,
++ duration: 6,
++ });
++ setEditorState("timeline", "tracks", "3d", true);
++ });
++ },
++ addCamera3DScene: () => {
++ const setup = editorState.timeline.camera3dSetup;
++ if (!project.timeline || !setup) return;
++ const generated = camera3DScenePreview(setup);
+ if (generated.length === 0) return;
-
++ const start = generated[0].start;
++ const index = (project.timeline.camera3dSegments ?? []).filter(
++ (segment) => segment.start < start,
++ ).length;
+ batch(() => {
- setProject("timeline", "camera3dSegments", (v) => v ?? []);
- setProject(
- "timeline",
- "camera3dSegments",
- produce((segments) => {
- if (!segments) return;
- segments.push(...generated);
- sortTrackSegments(segments);
- }),
++ setProject("timeline", "camera3dSegments", (segments) =>
++ [...(segments ?? []), ...generated].sort(
++ (a, b) => a.start - b.start,
++ ),
+ );
+ setEditorState("timeline", "camera3dSetup", null);
+ setEditorState("timeline", "tracks", "3d", true);
+ setEditorState("timeline", "selection", {
+ type: "3d",
- indices: [0],
++ indices: [index],
+ });
- setEditorState("playbackTime", 0);
++ setEditorState("playbackTime", start);
+ setEditorState("previewTime", null);
+ });
+ },
+ splitOverlaySegment: (
+ type: "style" | "image",
+ index: number,
+ time: number,
+ ) => {
+ const key = type === "style" ? "styleSegments" : "imageSegments";
setProject(
- "timeline",
- "camera3dSegments",
- produce((segments) => {
- if (!segments) return;
- segments.splice(segmentIndex, 1, ...generated);
- sortTrackSegments(segments);
+ produce((value) => {
+ const timeline = value.timeline;
+ if (!timeline || !timeline[key][index]) return;
+ if (type === "style") {
+ const parts = splitOverlaySegment(
+ structuredClone(unwrap(timeline.styleSegments[index])),
+ time,
+ );
+ if (parts) timeline.styleSegments.splice(index, 1, ...parts);
+ } else {
+ const parts = splitOverlaySegment(
+ structuredClone(unwrap(timeline.imageSegments[index])),
+ time,
+ );
+ if (parts) timeline.imageSegments.splice(index, 1, ...parts);
+ }
}),
);
- setEditorState("timeline", "selection", {
- type: "3d",
- indices: generated.map((_, offset) => segmentIndex + offset),
+ setEditorState("timeline", "selection", { type, indices: [index] });
+ if (type === "style") enterStyleScope(index);
+ },
+ deleteOverlaySegments: (type: "style" | "image", indices: number[]) => {
+ const remove = new Set(indices);
+ batch(() => {
+ setProject(
+ produce((value) => {
+ if (!value.timeline) return;
+ if (type === "style")
+ value.timeline.styleSegments =
+ value.timeline.styleSegments.filter(
+ (_, index) => !remove.has(index),
+ );
+ else
+ value.timeline.imageSegments =
+ value.timeline.imageSegments.filter(
+ (_, index) => !remove.has(index),
+ );
+ }),
+ );
+ if (type === "style") setEditorState("styleEditIndex", null);
+ setEditorState("timeline", "selection", null);
});
- setEditorState("playbackTime", start);
- setEditorState("previewTime", null);
- });
- },
- addCamera3DScene: (sceneId: string, shots: number) => {
- // Only ever an empty-track offer: the scene owns the whole timeline,
- // so it must not land on top of shots someone has already authored.
- if (!project.timeline) return;
- if ((project.timeline.camera3dSegments?.length ?? 0) > 0) return;
-
- const generated = camera3DScenePreview(sceneId, shots);
- if (generated.length === 0) return;
-
- batch(() => {
- setProject("timeline", "camera3dSegments", (v) => v ?? []);
+ },
+ addStyleSegment: (lane: number, time = editorState.playbackTime) => {
+ const placement = overlayPlacement("style", lane, time);
+ if (!placement || !project.timeline) return;
setProject(
"timeline",
- "camera3dSegments",
+ "styleSegments",
produce((segments) => {
- if (!segments) return;
- segments.push(...generated);
+ segments.push(
+ defaultStyleSegment(
+ placement.start,
+ placement.end,
+ placement.lane,
+ ),
+ );
sortTrackSegments(segments);
}),
);
@@@ -995,84 -789,90 +1017,82 @@@
"timeline",
"maskSegments",
produce((segments) => {
- if (!segments) return;
- const sorted = [...new Set(segmentIndices)]
- .filter(
- (i) => Number.isInteger(i) && i >= 0 && i < segments.length,
- )
- .sort((a, b) => b - a);
- for (const i of sorted) segments.splice(i, 1);
- normalizeTrackSegments(segments);
+ const segment = segments?.[index];
+ if (!segment) return;
+
+ const duration = segment.end - segment.start;
+ const remaining = duration - time;
+ if (time < 1 || remaining < 1) return;
+
+ segments.splice(index + 1, 0, {
+ ...segment,
+ start: segment.start + time,
+ end: segment.end,
+ });
+ segments[index].end = segment.start + time;
+ sortTrackSegments(segments);
}),
);
- setEditorState("timeline", "selection", null);
- });
- },
- splitTextSegment: (index: number, time: number) => {
- setProject(
- "timeline",
- "textSegments",
- produce((segments) => {
- const segment = segments?.[index];
- if (!segment) return;
-
- const duration = segment.end - segment.start;
- const remaining = duration - time;
- if (time < 1 || remaining < 1) return;
-
- segments.splice(index + 1, 0, {
- ...segment,
- start: segment.start + time,
- end: segment.end,
- });
- segments[index].end = segment.start + time;
- sortTrackSegments(segments);
- }),
- );
- },
- deleteTextSegments: (segmentIndices: number[]) => {
- batch(() => {
+ },
+ deleteMaskSegments: (segmentIndices: number[]) => {
+ batch(() => {
+ setProject(
+ "timeline",
+ "maskSegments",
+ produce((segments) => {
+ if (!segments) return;
+ const sorted = [...new Set(segmentIndices)]
+ .filter(
+ (i) => Number.isInteger(i) && i >= 0 && i < segments.length,
+ )
+ .sort((a, b) => b - a);
+ for (const i of sorted) segments.splice(i, 1);
- normalizeTrackSegments(segments);
+ }),
+ );
+ setEditorState("timeline", "selection", null);
+ });
+ },
+ splitTextSegment: (index: number, time: number) => {
setProject(
"timeline",
"textSegments",
produce((segments) => {
- if (!segments) return;
- const sorted = [...new Set(segmentIndices)]
- .filter(
- (i) => Number.isInteger(i) && i >= 0 && i < segments.length,
- )
- .sort((a, b) => b - a);
- for (const i of sorted) segments.splice(i, 1);
- normalizeTrackSegments(segments);
+ const segment = segments?.[index];
+ if (!segment) return;
+
+ const duration = segment.end - segment.start;
+ const remaining = duration - time;
+ if (time < 1 || remaining < 1) return;
+
+ segments.splice(index + 1, 0, {
+ ...segment,
+ start: segment.start + time,
+ end: segment.end,
+ });
+ segments[index].end = segment.start + time;
+ sortTrackSegments(segments);
}),
);
- setEditorState("timeline", "selection", null);
- });
- },
- splitAudioSegment: (index: number, time: number) => {
- setProject(
- "timeline",
- "audioSegments",
- produce((segments) => {
- const segment = segments?.[index];
- if (!segment) return;
-
- const duration = segment.end - segment.start;
- const remaining = duration - time;
- if (time < MIN_AUDIO_SEGMENT_DURATION) return;
- if (remaining < MIN_AUDIO_SEGMENT_DURATION) return;
-
- segments.splice(index + 1, 0, {
- ...segment,
- start: segment.start + time,
- end: segment.end,
- trimStart: segment.trimStart + time,
- // Fades belong to the outer edges of the original clip; the
- // new boundary created by the split should be a hard cut.
- fadeIn: 0,
- });
- segments[index].end = segment.start + time;
- segments[index].fadeOut = 0;
- sortTrackSegments(segments);
- }),
- );
- },
- deleteAudioSegments: (segmentIndices: number[]) => {
- batch(() => {
+ },
+ deleteTextSegments: (segmentIndices: number[]) => {
+ batch(() => {
+ setProject(
+ "timeline",
+ "textSegments",
+ produce((segments) => {
+ if (!segments) return;
+ const sorted = [...new Set(segmentIndices)]
+ .filter(
+ (i) => Number.isInteger(i) && i >= 0 && i < segments.length,
+ )
+ .sort((a, b) => b - a);
+ for (const i of sorted) segments.splice(i, 1);
- normalizeTrackSegments(segments);
+ }),
+ );
+ setEditorState("timeline", "selection", null);
+ });
+ },
+ splitAudioSegment: (index: number, time: number) => {
setProject(
"timeline",
"audioSegments",
@@@ -1219,42 -1001,42 +1239,40 @@@
"timeline",
"keyboardSegments",
produce((segments) => {
- if (!segments) return;
- const sorted = [...new Set(segmentIndices)]
- .filter(
- (i) => Number.isInteger(i) && i >= 0 && i < segments.length,
- )
- .sort((a, b) => b - a);
- for (const i of sorted) segments.splice(i, 1);
+ const segment = segments?.[index];
+ if (!segment) return;
+
+ const duration = segment.end - segment.start;
+ const remaining = duration - time;
+ if (time < 0.3 || remaining < 0.3) return;
-
- segments.splice(index + 1, 0, {
- ...segment,
- id: `kb-split-${Date.now()}-${Math.random().toString(36).slice(2)}`,
- start: segment.start + time,
- end: segment.end,
- });
- segments[index].end = segment.start + time;
++ const parts = splitKeyboardSegment(
++ structuredClone(unwrap(segment)),
++ segment.start + time,
++ `kb-split-${Date.now()}-${Math.random().toString(36).slice(2)}`,
++ );
++ if (parts) segments.splice(index, 1, ...parts);
}),
);
- setEditorState("timeline", "selection", null);
- });
- },
- splitCaptionSegment: (index: number, time: number) => {
- setProject(
- "timeline",
- "captionSegments",
- produce((segments) => {
- const segment = segments?.[index];
- if (!segment) return;
-
- const duration = segment.end - segment.start;
- const remaining = duration - time;
- if (time < 0.5 || remaining < 0.5) return;
-
- segments.splice(index + 1, 0, {
- ...segment,
- id: `cap-split-${Date.now()}-${Math.random().toString(36).slice(2)}`,
- start: segment.start + time,
- end: segment.end,
- });
- segments[index].end = segment.start + time;
- }),
- );
- },
- deleteCaptionSegments: (segmentIndices: number[]) => {
- batch(() => {
+ },
+ deleteKeyboardSegments: (segmentIndices: number[]) => {
+ batch(() => {
+ setProject(
+ "timeline",
+ "keyboardSegments",
+ produce((segments) => {
+ if (!segments) return;
+ const sorted = [...new Set(segmentIndices)]
+ .filter(
+ (i) => Number.isInteger(i) && i >= 0 && i < segments.length,
+ )
+ .sort((a, b) => b - a);
+ for (const i of sorted) segments.splice(i, 1);
+ }),
+ );
+ setEditorState("timeline", "selection", null);
+ });
+ },
+ splitCaptionSegment: (index: number, time: number) => {
setProject(
"timeline",
"captionSegments",
@@@ -1298,800 -1079,685 +1316,835 @@@
setProject(
"timeline",
"sceneSegments",
- produce((s) => {
- if (!s) return;
- s.splice(segmentIndex, 1);
+ produce((segments) => {
+ const segment = segments?.[index];
+ if (!segment) return;
+
+ const newLengths = [segment.end - segment.start - time, time];
+
+ if (newLengths.some((l) => l < 1)) return;
+
+ segments.splice(index + 1, 0, {
+ ...segment,
+ start: segment.start + time,
+ end: segment.end,
+ });
+ segments[index].end = segment.start + time;
}),
);
- setEditorState("timeline", "selection", null);
- });
- },
- setClipSegmentTimescale: (index: number, timescale: number) => {
- setProject(
- produce((project) => {
- const timeline = project.timeline;
- if (!timeline) return;
+ },
+ deleteSceneSegment: (segmentIndex: number) => {
+ batch(() => {
+ setProject(
+ "timeline",
+ "sceneSegments",
+ produce((s) => {
+ if (!s) return;
+ s.splice(segmentIndex, 1);
+ }),
+ );
+ setEditorState("timeline", "selection", null);
+ });
+ },
+ setClipSegmentTimescale: (index: number, timescale: number) => {
+ setProject(
+ produce((project) => {
+ const timeline = project.timeline;
+ if (!timeline) return;
- const segment = timeline.segments[index];
- if (!segment) return;
+ const segment = timeline.segments[index];
+ if (!segment) return;
- const oldDuration = clipTimelineDuration(
- timeline.segments,
- timeline.transitions ?? [],
- );
- const oldOffsets = clipTimelineOffsets(
- timeline.segments,
- timeline.transitions ?? [],
- );
- const oldHolds = holdWindows(timeline.textSegments);
- const incomingDuration =
- getClipTransition(
+ const oldDuration = clipTimelineDuration(
timeline.segments,
timeline.transitions ?? [],
- index,
- )?.duration ?? 0;
- segment.timescale = timescale;
- timeline.transitions = normalizeClipTransitions(
- timeline.segments,
- timeline.transitions ?? [],
- );
- const newDuration = clipTimelineDuration(
- timeline.segments,
- timeline.transitions,
- );
- const newOffsets = clipTimelineOffsets(
- timeline.segments,
- timeline.transitions,
- );
- const absoluteStart = oldOffsets[index] + incomingDuration;
- const oldNextBoundary = oldOffsets[index + 1] ?? oldDuration;
- const newNextBoundary = newOffsets[index + 1] ?? newDuration;
-
- const diff = (value: number) =>
- timelineShiftAfterClipDurationChange(
- value,
- oldOffsets[index],
- newOffsets[index],
- absoluteStart,
- oldNextBoundary,
- newNextBoundary,
);
- const mapOutputTime = (value: number) => {
- const held = heldTimeBefore(oldHolds, value);
- return value + diff(value - held);
- };
-
- for (const zoomSegment of timeline.zoomSegments) {
- zoomSegment.start = mapOutputTime(zoomSegment.start);
- zoomSegment.end = mapOutputTime(zoomSegment.end);
- }
-
- for (const sceneSegment of timeline.sceneSegments ?? []) {
- sceneSegment.start = mapOutputTime(sceneSegment.start);
- sceneSegment.end = mapOutputTime(sceneSegment.end);
- }
+ const oldOffsets = clipTimelineOffsets(
+ timeline.segments,
+ timeline.transitions ?? [],
+ );
++ const oldHolds = holdWindows(timeline.textSegments);
+ const incomingDuration =
+ getClipTransition(
+ timeline.segments,
+ timeline.transitions ?? [],
+ index,
+ )?.duration ?? 0;
+ segment.timescale = timescale;
+ timeline.transitions = normalizeClipTransitions(
+ timeline.segments,
+ timeline.transitions ?? [],
+ );
+ const newDuration = clipTimelineDuration(
+ timeline.segments,
+ timeline.transitions,
+ );
+ const newOffsets = clipTimelineOffsets(
+ timeline.segments,
+ timeline.transitions,
+ );
+ const absoluteStart = oldOffsets[index] + incomingDuration;
+ const oldNextBoundary = oldOffsets[index + 1] ?? oldDuration;
+ const newNextBoundary = newOffsets[index + 1] ?? newDuration;
+
+ const diff = (value: number) =>
+ timelineShiftAfterClipDurationChange(
+ value,
+ oldOffsets[index],
+ newOffsets[index],
+ absoluteStart,
+ oldNextBoundary,
+ newNextBoundary,
+ );
++ const mapOutputTime = (value: number) => {
++ const held = heldTimeBefore(oldHolds, value);
++ return value + diff(value - held);
++ };
+
+ for (const overlay of [
+ ...timeline.styleSegments,
+ ...timeline.imageSegments,
+ ]) {
- overlay.start += diff(overlay.start);
- overlay.end += diff(overlay.end);
++ overlay.start = mapOutputTime(overlay.start);
++ overlay.end = mapOutputTime(overlay.end);
+ }
+ for (const zoomSegment of timeline.zoomSegments) {
- zoomSegment.start += diff(zoomSegment.start);
- zoomSegment.end += diff(zoomSegment.end);
++ zoomSegment.start = mapOutputTime(zoomSegment.start);
++ zoomSegment.end = mapOutputTime(zoomSegment.end);
+ }
- for (const maskSegment of timeline.maskSegments) {
- maskSegment.start = mapOutputTime(maskSegment.start);
- maskSegment.end = mapOutputTime(maskSegment.end);
- }
+ for (const sceneSegment of timeline.sceneSegments ?? []) {
- sceneSegment.start += diff(sceneSegment.start);
- sceneSegment.end += diff(sceneSegment.end);
++ sceneSegment.start = mapOutputTime(sceneSegment.start);
++ sceneSegment.end = mapOutputTime(sceneSegment.end);
+ }
- for (const textSegment of timeline.textSegments) {
- textSegment.start = mapOutputTime(textSegment.start);
- textSegment.end = mapOutputTime(textSegment.end);
- }
+ for (const maskSegment of timeline.maskSegments) {
- maskSegment.start += diff(maskSegment.start);
- maskSegment.end += diff(maskSegment.end);
++ maskSegment.start = mapOutputTime(maskSegment.start);
++ maskSegment.end = mapOutputTime(maskSegment.end);
+ }
- for (const audioSegment of timeline.audioSegments ?? []) {
- audioSegment.start = mapOutputTime(audioSegment.start);
- audioSegment.end = mapOutputTime(audioSegment.end);
- }
+ for (const textSegment of timeline.textSegments) {
- textSegment.start += diff(textSegment.start);
- textSegment.end += diff(textSegment.end);
++ textSegment.start = mapOutputTime(textSegment.start);
++ textSegment.end = mapOutputTime(textSegment.end);
+ }
- for (const captionSegment of timeline.captionSegments ?? []) {
- captionSegment.start = mapOutputTime(captionSegment.start);
- captionSegment.end = mapOutputTime(captionSegment.end);
- }
+ for (const audioSegment of timeline.audioSegments ?? []) {
- audioSegment.start += diff(audioSegment.start);
- audioSegment.end += diff(audioSegment.end);
++ audioSegment.start = mapOutputTime(audioSegment.start);
++ audioSegment.end = mapOutputTime(audioSegment.end);
+ }
- mapKeyboardTrackTimes(
- timeline.keyboardSegments ?? [],
- mapOutputTime,
- );
+ for (const captionSegment of timeline.captionSegments ?? []) {
- captionSegment.start += diff(captionSegment.start);
- captionSegment.end += diff(captionSegment.end);
++ captionSegment.start = mapOutputTime(captionSegment.start);
++ captionSegment.end = mapOutputTime(captionSegment.end);
+ }
- for (const keyboardSegment of timeline.keyboardSegments ?? []) {
- keyboardSegment.start += diff(keyboardSegment.start);
- keyboardSegment.end += diff(keyboardSegment.end);
- }
- for (const camera3dSegment of timeline.camera3dSegments ?? []) {
- const previousDuration =
- camera3dSegment.end - camera3dSegment.start;
- camera3dSegment.start = mapOutputTime(camera3dSegment.start);
- camera3dSegment.end = mapOutputTime(camera3dSegment.end);
- // Keyframe times are relative to the segment start, so they
- // have to follow the segment's new length rather than the
- // absolute shift the other tracks use.
- const nextDuration = camera3dSegment.end - camera3dSegment.start;
- if (previousDuration <= 0 || nextDuration === previousDuration)
- continue;
- scaleKeyframeTimes(
- camera3dSegment.tracks,
- nextDuration / previousDuration,
++ mapKeyboardTrackTimes(
++ timeline.keyboardSegments ?? [],
++ mapOutputTime,
+ );
- }
- }),
- );
- },
- setClipSegmentSpeedAudioMode: (
- index: number,
- speedAudioMode: ClipSpeedAudioMode,
- ) => {
- setProject(
- "timeline",
- "segments",
- index,
- "speedAudioMode",
- speedAudioMode,
- );
- },
- };
- let projectSaveTimeout: number | undefined;
- let saveInFlight: ReturnType<typeof commands.setProjectConfig> | undefined;
- let persistedProject: string | undefined;
+ for (const camera3dSegment of timeline.camera3dSegments ?? []) {
+ const previousDuration =
+ camera3dSegment.end - camera3dSegment.start;
- camera3dSegment.start += diff(camera3dSegment.start);
- camera3dSegment.end += diff(camera3dSegment.end);
++ camera3dSegment.start = mapOutputTime(camera3dSegment.start);
++ camera3dSegment.end = mapOutputTime(camera3dSegment.end);
+ // Keyframe times are relative to the segment start, so they
+ // have to follow the segment's new length rather than the
+ // absolute shift the other tracks use.
+ const nextDuration =
+ camera3dSegment.end - camera3dSegment.start;
+ if (previousDuration <= 0 || nextDuration === previousDuration)
+ continue;
+ scaleKeyframeTimes(
+ camera3dSegment.tracks,
+ nextDuration / previousDuration,
+ );
+ }
+ }),
+ );
+ },
+ setClipSegmentSpeedAudioMode: (
+ index: number,
+ speedAudioMode: ClipSpeedAudioMode,
+ ) => {
+ setProject(
+ "timeline",
+ "segments",
+ index,
+ "speedAudioMode",
+ speedAudioMode,
+ );
+ },
+ };
- const flushProjectConfig = async () => {
- if (projectSaveTimeout !== undefined) {
- clearTimeout(projectSaveTimeout);
- projectSaveTimeout = undefined;
- }
- while (true) {
- if (saveInFlight) {
- await saveInFlight;
- continue;
- }
- const config = serializeProjectConfiguration(project);
- const serialized = JSON.stringify(config);
- if (serialized === persistedProject) return;
- const saving = commands.setProjectConfig(config);
- saveInFlight = saving;
- try {
- await saving;
- persistedProject = serialized;
- } finally {
- if (saveInFlight === saving) saveInFlight = undefined;
- }
- }
- };
+ const projectSave = createProjectConfigSave({
+ trackChanges: () => {
+ trackStore(project);
+ },
+ getConfig: () => serializeProjectConfiguration(project),
+ save: async (config) => {
+ await commands.setProjectConfig(config);
+ },
+ onError: (error) => {
+ console.error("Failed to persist project config", error);
+ },
+ });
- const saveProjectConfig = () => {
- void flushProjectConfig().catch((error) =>
- console.error("Failed to persist project config", error),
- );
- };
+ const [storedSettings] = createResource(() => generalSettingsStore.get());
+ const initialPreviewQuality = createMemo((): EditorPreviewQuality => {
+ const stored = storedSettings()?.editorPreviewQuality;
+ if (stored === "quarter" || stored === "half" || stored === "full") {
+ return stored;
+ }
+ return DEFAULT_PREVIEW_QUALITY;
+ });
- const scheduleProjectConfigSave = () => {
- if (projectSaveTimeout !== undefined) clearTimeout(projectSaveTimeout);
- projectSaveTimeout = window.setTimeout(
- saveProjectConfig,
- PROJECT_SAVE_DEBOUNCE_MS,
- );
- };
+ const [previewQuality, _setPreviewQuality] =
+ createSignal<EditorPreviewQuality>(DEFAULT_PREVIEW_QUALITY);
- onCleanup(saveProjectConfig);
+ createEffect(() => {
+ const quality = initialPreviewQuality();
+ _setPreviewQuality(quality);
+ });
- createEffect(
- on(
- () => {
- trackStore(project);
- },
- () => {
- scheduleProjectConfigSave();
- },
- { defer: true },
- ),
- );
-
- const [storedSettings] = createResource(() => generalSettingsStore.get());
- const initialPreviewQuality = createMemo((): EditorPreviewQuality => {
- const stored = storedSettings()?.editorPreviewQuality;
- if (stored === "quarter" || stored === "half" || stored === "full") {
- return stored;
- }
- return DEFAULT_PREVIEW_QUALITY;
- });
-
- const [previewQuality, _setPreviewQuality] =
- createSignal<EditorPreviewQuality>(DEFAULT_PREVIEW_QUALITY);
-
- createEffect(() => {
- const quality = initialPreviewQuality();
- _setPreviewQuality(quality);
- });
-
- const setPreviewQuality = (quality: EditorPreviewQuality) => {
- _setPreviewQuality(quality);
- generalSettingsStore
- .set({ editorPreviewQuality: quality })
- .catch((error) => {
- console.error("Failed to persist preview quality setting", error);
- });
- };
+ const setPreviewQuality = (quality: EditorPreviewQuality) => {
+ _setPreviewQuality(quality);
+ generalSettingsStore
+ .set({ editorPreviewQuality: quality })
+ .catch((error) => {
+ console.error("Failed to persist preview quality setting", error);
+ });
+ };
- const previewResolutionBase = () => getPreviewResolution(previewQuality());
+ const previewResolutionBase = () =>
+ getPreviewResolution(previewQuality());
- const layoutModeStorageKey = `cap:editor:layoutMode:${props.editorInstance.path}`;
+ const layoutModeStorageKey = `cap:editor:layoutMode:${props.editorInstance.path}`;
- const readPersistedLayoutMode = (): DialogState => {
- try {
- const raw = sessionStorage.getItem(layoutModeStorageKey);
- if (!raw) return { open: false };
- const parsed = JSON.parse(raw) as { type?: CurrentDialog["type"] };
- if (parsed?.type && PERSISTED_LAYOUT_MODE_TYPES.has(parsed.type)) {
- return { open: true, type: parsed.type } as OpenLayoutMode;
+ const readPersistedLayoutMode = (): DialogState => {
+ try {
+ const raw = sessionStorage.getItem(layoutModeStorageKey);
+ if (!raw) return { open: false };
+ const parsed = JSON.parse(raw) as { type?: CurrentDialog["type"] };
+ if (parsed?.type && PERSISTED_LAYOUT_MODE_TYPES.has(parsed.type)) {
+ return { open: true, type: parsed.type } as OpenLayoutMode;
+ }
+ } catch (error) {
+ console.error("Failed to read persisted editor layout mode", error);
}
- } catch (error) {
- console.error("Failed to read persisted editor layout mode", error);
- }
- return { open: false };
- };
+ return { open: false };
+ };
- const [dialog, setDialog] = createSignal<DialogState>(
- readPersistedLayoutMode(),
- );
+ const [dialog, setDialog] = createSignal<DialogState>(
+ readPersistedLayoutMode(),
+ );
- createEffect(() => {
- const current = dialog();
- try {
- if (
- isLayoutMode(current) &&
- PERSISTED_LAYOUT_MODE_TYPES.has(current.type)
- ) {
- sessionStorage.setItem(
- layoutModeStorageKey,
- JSON.stringify({ type: current.type }),
- );
- } else {
- sessionStorage.removeItem(layoutModeStorageKey);
- }
- } catch (error) {
- console.error("Failed to persist editor layout mode", error);
- }
- });
-
- const [exportState, setExportState] = createStore<
- | { type: "idle" }
- | (
- | ({ action: "copy" } & (
- | RenderState
- | { type: "copying" }
- | { type: "done" }
- ))
- | ({ action: "save" } & (
- | RenderState
- | { type: "copying" }
- | { type: "done" }
- ))
- | ({ action: "upload" } & (
- | RenderState
- | { type: "uploading"; progress: number }
- | { type: "done" }
- ))
- )
- >({ type: "idle" });
-
- createProgressBar(() =>
- exportState?.type === "rendering"
- ? (exportState.progress.renderedCount /
- exportState.progress.totalFrames) *
- 100
- : undefined,
- );
-
- createEffect(
- on(
- () => editorState.playing,
- (active) => {
- if (!active)
- commands.setPlayheadPosition(
- Math.floor(editorState.playbackTime * FPS),
+ createEffect(() => {
+ const current = dialog();
+ try {
+ if (
+ isLayoutMode(current) &&
+ PERSISTED_LAYOUT_MODE_TYPES.has(current.type)
+ ) {
+ sessionStorage.setItem(
+ layoutModeStorageKey,
+ JSON.stringify({ type: current.type }),
);
- },
- ),
- );
-
- const totalDuration = () =>
- project.timeline
- ? clipTimelineDuration(
- project.timeline.segments,
- project.timeline.transitions ?? [],
- ) + totalHeldDuration(holdWindows(project.timeline.textSegments))
- : props.editorInstance.recordingDuration;
-
- type State = {
- zoom: number;
- position: number;
- };
+ } else {
+ sessionStorage.removeItem(layoutModeStorageKey);
+ }
+ } catch (error) {
+ console.error("Failed to persist editor layout mode", error);
+ }
+ });
- const zoomOutLimit = () => Math.min(totalDuration(), 60 * 10);
+ const [exportState, setExportState] = createStore<
+ | { type: "idle" }
+ | (
+ | ({ action: "copy" } & (
+ | RenderState
+ | { type: "copying" }
+ | { type: "done" }
+ ))
+ | ({ action: "save" } & (
+ | RenderState
+ | { type: "copying" }
+ | { type: "done" }
+ ))
+ | ({ action: "upload" } & (
+ | RenderState
+ | { type: "uploading"; progress: number }
+ | { type: "done" }
+ ))
+ )
+ >({ type: "idle" });
+
+ createProgressBar(() =>
+ exportState?.type === "rendering"
+ ? (exportState.progress.renderedCount /
+ exportState.progress.totalFrames) *
+ 100
+ : undefined,
+ );
- function updateZoom(state: State, newZoom: number, origin: number): State {
- const zoom = Math.max(Math.min(newZoom, zoomOutLimit()), MAX_ZOOM_IN);
+ createEffect(
+ on(
+ () => editorState.playing,
+ (active) => {
+ if (!active)
+ commands.setPlayheadPosition(
+ Math.floor(editorState.playbackTime * FPS),
+ );
+ },
+ ),
+ );
- const visibleOrigin = origin - state.position;
+ const totalDuration = () =>
+ project.timeline
+ ? clipTimelineDuration(
+ project.timeline.segments,
+ project.timeline.transitions ?? [],
+ ) + totalHeldDuration(holdWindows(project.timeline.textSegments))
+ : props.editorInstance.recordingDuration;
+
+ type State = {
+ zoom: number;
+ position: number;
+ };
- const originPercentage = Math.min(1, visibleOrigin / state.zoom);
+ const zoomOutLimit = () => Math.min(totalDuration(), 60 * 10);
- const newVisibleOrigin = zoom * originPercentage;
- const newPosition = origin - newVisibleOrigin;
+ function updateZoom(
+ state: State,
+ newZoom: number,
+ origin: number,
+ ): State {
+ const zoom = Math.max(Math.min(newZoom, zoomOutLimit()), MAX_ZOOM_IN);
- return {
- zoom,
- position: newPosition,
- };
- }
-
- const initialMaskTrackCount = getUsedTrackCount(
- project.timeline?.maskSegments ?? [],
- );
- const initialTextTrackCount = getUsedTrackCount(
- project.timeline?.textSegments ?? [],
- );
- const initialAudioTrackCount = getUsedTrackCount(
- project.timeline?.audioSegments ?? [],
- );
- const initialCaptionTrackVisible =
- project.captions?.settings.enabled ??
- (project.timeline?.captionSegments?.length ?? 0) > 0;
- const initialKeyboardTrackVisible =
- project.keyboard?.settings.enabled ?? false;
- const initialCamera3DTrackVisible =
- (project.timeline?.camera3dSegments?.length ?? 0) > 0;
-
- const [editorState, setEditorState] = createStore({
- previewTime: null as number | null,
- playbackTime: 0,
- playing: false,
- // On-canvas selection of the screen recording / camera boxes.
- // Kept separate from timeline.selection, which drives the sidebar
- // selection panel and is pattern-matched by many consumers.
- canvasSelection: null as null | { type: "display" } | { type: "camera" },
- captions: {
- isGenerating: false,
- isDownloading: false,
- downloadProgress: 0,
- downloadingModel: null as string | null,
- isStale: false,
- staleDismissed: false,
- },
- timeline: {
- interactMode: "seek" as "seek" | "split",
- splitPreview: null as null | { time: number; snapped: boolean },
- selection: null as
+ const visibleOrigin = origin - state.position;
+
+ const originPercentage = Math.min(1, visibleOrigin / state.zoom);
+
+ const newVisibleOrigin = zoom * originPercentage;
+ const newPosition = origin - newVisibleOrigin;
+
+ return {
+ zoom,
+ position: newPosition,
+ };
+ }
+
+ const initialMaskTrackCount = getUsedTrackCount(
+ project.timeline?.maskSegments ?? [],
+ );
+ const initialTextTrackCount = getUsedTrackCount(
+ project.timeline?.textSegments ?? [],
+ );
+ const initialAudioTrackCount = getUsedTrackCount(
+ project.timeline?.audioSegments ?? [],
+ );
+ const initialCaptionTrackVisible =
+ project.captions?.settings.enabled ??
+ (project.timeline?.captionSegments?.length ?? 0) > 0;
+ const initialKeyboardTrackVisible =
+ project.keyboard?.settings.enabled ?? false;
+ const initialCamera3DTrackVisible =
+ (project.timeline?.camera3dSegments?.length ?? 0) > 0;
+
+ const [editorState, setEditorState] = createStore({
+ styleEditIndex: null as number | null,
+ importingImage: false,
+ previewTime: null as number | null,
+ playbackTime: 0,
+ playing: false,
+ // On-canvas selection of the screen recording / camera boxes.
+ // Kept separate from timeline.selection, which drives the sidebar
+ // selection panel and is pattern-matched by many consumers.
+ canvasSelection: null as
| null
- | { type: "zoom"; indices: number[] }
- | { type: "clip"; indices: number[] }
- | { type: "transition"; index: number }
- | { type: "scene"; indices: number[] }
- | { type: "mask"; indices: number[] }
- | { type: "caption"; indices: number[] }
- | { type: "keyboard"; indices: number[] }
- | { type: "text"; indices: number[] }
- | { type: "audio"; indices: number[] }
- | { type: "3d"; indices: number[] },
- transform: {
- // visible seconds
- zoom: zoomOutLimit(),
- updateZoom(z: number, origin: number) {
- const { zoom, position } = updateZoom(
- {
- zoom: editorState.timeline.transform.zoom,
- position: editorState.timeline.transform.position,
- },
- z,
- origin,
- );
+ | { type: "display" }
+ | { type: "camera" },
+ captions: {
+ isGenerating: false,
+ isDownloading: false,
+ downloadProgress: 0,
+ downloadingModel: null as string | null,
+ isStale: false,
+ staleDismissed: false,
+ },
+ timeline: {
+ interactMode: "seek" as "seek" | "split",
+ splitPreview: null as null | { time: number; snapped: boolean },
+ selection: null as
+ | null
+ | { type: "style"; indices: number[] }
+ | { type: "image"; indices: number[] }
+ | { type: "zoom"; indices: number[] }
+ | { type: "clip"; indices: number[] }
+ | { type: "transition"; index: number }
+ | { type: "scene"; indices: number[] }
+ | { type: "mask"; indices: number[] }
+ | { type: "caption"; indices: number[] }
+ | { type: "keyboard"; indices: number[] }
+ | { type: "text"; indices: number[] }
+ | { type: "audio"; indices: number[] }
+ | { type: "3d"; indices: number[] },
+ transform: {
+ // visible seconds
+ zoom: zoomOutLimit(),
+ updateZoom(z: number, origin: number) {
+ const { zoom, position } = updateZoom(
+ {
+ zoom: editorState.timeline.transform.zoom,
+ position: editorState.timeline.transform.position,
+ },
+ z,
+ origin,
+ );
- const transform = editorState.timeline.transform;
+ const transform = editorState.timeline.transform;
+ batch(() => {
+ setEditorState("timeline", "transform", "zoom", zoom);
+ if (transform.zoom !== zoom) return;
+ transform.setPosition(position);
+ });
+ },
+ // number of seconds of leftmost point
+ position: 0,
+ setPosition(p: number) {
+ setEditorState(
+ "timeline",
+ "transform",
+ "position",
+ Math.min(
+ Math.max(p, 0),
+ Math.max(zoomOutLimit(), totalDuration()) +
+ 4 -
+ editorState.timeline.transform.zoom,
+ ),
+ );
+ },
+ },
+ tracks: {
+ style: getUsedTrackCount(project.timeline?.styleSegments ?? []),
+ image: getUsedTrackCount(project.timeline?.imageSegments ?? []),
+ clip: true,
+ caption: initialCaptionTrackVisible,
+ keyboard: initialKeyboardTrackVisible,
+ zoom: true,
+ scene: true,
+ "3d": initialCamera3DTrackVisible,
+ mask: initialMaskTrackCount,
+ text: initialTextTrackCount,
+ audio: initialAudioTrackCount,
+ },
+ hoveredTrack: null as null | TimelineTrackType,
+ hoveredMaskIndex: null as number | null,
+ hoveredMaskTime: null as number | null,
+ audioPicker: null as number | null,
+ audioReplace: null as number | null,
- // The empty 3D track's setup flow: the scene and shot count the
- // sidebar is currently offering, previewed live on the track.
- camera3dSetup: null as null | { sceneId: string; shots: number },
++ camera3dSetup: null as Camera3DSetup | null,
+ // Index of a just-created text segment that should open its
+ // inline canvas editor as soon as its overlay mounts (set by the
+ // Add-track picker, consumed by TextOverlay).
+ pendingTextEdit: null as number | null,
+ },
+ });
+
++ createEffect(
++ on(
++ () => editorState.timeline.selection,
++ (selection) => {
++ if (!selection) return;
+ batch(() => {
- setEditorState("timeline", "transform", "zoom", zoom);
- if (transform.zoom !== zoom) return;
- transform.setPosition(position);
++ setEditorState("timeline", "audioPicker", null);
++ setEditorState("timeline", "audioReplace", null);
++ setEditorState("timeline", "camera3dSetup", null);
+ });
+ },
- // number of seconds of leftmost point
- position: 0,
- setPosition(p: number) {
- setEditorState(
- "timeline",
- "transform",
- "position",
- Math.min(
- Math.max(p, 0),
- Math.max(zoomOutLimit(), totalDuration()) +
- 4 -
- editorState.timeline.transform.zoom,
- ),
- );
++ ),
++ );
++
+ let selectedStyleIdentity: StyleSegment | undefined;
+ const selectedStyle = () =>
+ editorState.styleEditIndex === null
+ ? undefined
+ : project.timeline?.styleSegments[editorState.styleEditIndex];
+ const styleScopeToken = createMemo(() => ({
+ index: editorState.styleEditIndex,
+ segment: selectedStyle(),
+ }));
+ const enterStyleScope = (index: number) => {
+ selectedStyleIdentity = project.timeline?.styleSegments[index];
+ setEditorState("styleEditIndex", selectedStyleIdentity ? index : null);
+ };
+ createEffect(
+ on(
+ () => {
+ const selection = editorState.timeline.selection;
+ return selection?.type === "style"
+ ? (selection.indices[0] ?? null)
+ : null;
},
+ (index) => {
+ if (index !== null) enterStyleScope(index);
++ else {
++ selectedStyleIdentity = undefined;
++ setEditorState("styleEditIndex", null);
++ }
+ },
+ ),
+ );
+ createEffect(() => {
+ if (
+ editorState.styleEditIndex !== null &&
+ (!selectedStyle() || selectedStyle() !== selectedStyleIdentity)
+ )
+ setEditorState("styleEditIndex", null);
+ });
+ const styleProject = new Proxy(project, {
+ get(target, key, receiver) {
+ if (key === "background" || key === "camera" || key === "cursor")
+ return selectedStyle()?.overrides[key] ?? target[key];
+ return Reflect.get(target, key, receiver);
},
- tracks: {
- clip: true,
- caption: initialCaptionTrackVisible,
- keyboard: initialKeyboardTrackVisible,
- zoom: true,
- scene: true,
- "3d": initialCamera3DTrackVisible,
- mask: initialMaskTrackCount,
- text: initialTextTrackCount,
- audio: initialAudioTrackCount,
- },
- hoveredTrack: null as null | TimelineTrackType,
- hoveredMaskIndex: null as number | null,
- hoveredMaskTime: null as number | null,
- audioPicker: null as number | null,
- audioReplace: null as number | null,
- // The empty 3D track's setup flow: the scene and shot count the
- // sidebar is currently offering, previewed live on the track.
- camera3dSetup: null as null | { sceneId: string; shots: number },
- // Index of a just-created text segment that should open its
- // inline canvas editor as soon as its overlay mounts (set by the
- // Add-track picker, consumed by TextOverlay).
- pendingTextEdit: null as number | null,
- },
- });
-
- // Active smart-guide lines while an overlay drag is snapping; published
- // by whichever overlay owns the drag, rendered once above the canvas.
- const [snapGuides, setSnapGuides] = createSignal<SnapGuide[]>([]);
-
- // Plain signals, not resources: audio decodes in the background after
- // the editor opens, so these can resolve late — they must never suspend
- // the editor UI back to the skeleton. Waveforms simply appear once
- // decoded.
- const [micWaveforms, setMicWaveforms] = createSignal<number[][]>();
- const [systemAudioWaveforms, setSystemAudioWaveforms] =
- createSignal<number[][]>();
- onMount(() => {
- commands
- .getMicWaveforms()
- .then(setMicWaveforms)
- .catch((error) =>
- console.error("Failed to load mic waveforms:", error),
+ });
+ const setStyleProject = ((...args: unknown[]) => {
+ const selected = selectedStyle();
+ const index = editorState.styleEditIndex;
+ if (index === null || args[0] === "timeline")
+ return Reflect.apply(setProject, undefined, args);
+ if (!selected) return;
+ const group = args[0];
+ if (group !== "background" && group !== "camera" && group !== "cursor")
+ return;
+ if (selected.overrides[group] == null) return;
+ const [draft, setDraft] = createStore({
+ background: structuredClone(unwrap(styleProject.background)),
+ camera: structuredClone(unwrap(styleProject.camera)),
+ cursor: structuredClone(unwrap(styleProject.cursor)),
+ });
+ Reflect.apply(setDraft, undefined, args);
+ setProject(
+ "timeline",
+ "styleSegments",
+ index,
+ "overrides",
+ produce((overrides) => {
+ if (group === "background")
+ overrides.background = unwrap(draft.background);
+ if (group === "camera") overrides.camera = unwrap(draft.camera);
+ if (group === "cursor") overrides.cursor = unwrap(draft.cursor);
+ }),
);
- commands
- .getSystemAudioWaveforms()
- .then(setSystemAudioWaveforms)
- .catch((error) =>
- console.error("Failed to load system audio waveforms:", error),
+ }) as typeof setProject;
+ const createStyleProjectSetter = () => {
+ const token = styleScopeToken();
+ return ((...args: unknown[]) => {
+ if (token !== styleScopeToken()) return;
+ return Reflect.apply(setStyleProject, undefined, args);
+ }) as typeof setProject;
+ };
+ const toggleStyleGroup = (group: StyleGroup, enabled: boolean) => {
+ const index = editorState.styleEditIndex;
+ if (index === null) return;
+ setProject(
+ "timeline",
+ "styleSegments",
+ index,
+ "overrides",
+ produce((overrides) => {
+ if (group === "background")
+ overrides.background = enabled
+ ? structuredClone(unwrap(project.background))
+ : null;
+ if (group === "camera")
+ overrides.camera = enabled
+ ? structuredClone(unwrap(project.camera))
+ : null;
+ if (group === "cursor")
+ overrides.cursor = enabled
+ ? structuredClone(unwrap(project.cursor))
+ : null;
+ }),
);
- });
- const customDomain = createCustomDomainQuery();
- const hasRecordedKeyboardEvents = createMemo(() => {
- const meta = props.meta();
- if (meta.type === "single") return false;
- return meta.segments.some((segment) => !!segment.keyboard);
- });
- const [didInitializeKeyboardSegments, setDidInitializeKeyboardSegments] =
- createSignal(false);
-
- createEffect(() => {
- if (didInitializeKeyboardSegments()) return;
- if (!project.timeline) return;
- if (!hasRecordedKeyboardEvents()) {
- setDidInitializeKeyboardSegments(true);
- return;
- }
- if ((project.timeline?.keyboardSegments?.length ?? 0) > 0) {
+ };
+ const exitStyleScope = () =>
+ batch(() => {
+ setEditorState("styleEditIndex", null);
+ if (editorState.timeline.selection?.type === "style")
+ setEditorState("timeline", "selection", null);
+ });
+ const previewStyle = createMemo(() =>
+ resolveStyle(
+ project,
+ project.timeline?.styleSegments ?? [],
+ editorState.previewTime ?? editorState.playbackTime,
+ ),
+ );
+ // Active smart-guide lines while an overlay drag is snapping; published
+ // by whichever overlay owns the drag, rendered once above the canvas.
+ const [snapGuides, setSnapGuides] = createSignal<SnapGuide[]>([]);
+
+ // Plain signals, not resources: audio decodes in the background after
+ // the editor opens, so these can resolve late — they must never suspend
+ // the editor UI back to the skeleton. Waveforms simply appear once
+ // decoded.
+ const [micWaveforms, setMicWaveforms] = createSignal<number[][]>();
+ const [systemAudioWaveforms, setSystemAudioWaveforms] =
+ createSignal<number[][]>();
+ onMount(() => {
+ commands
+ .getMicWaveforms()
+ .then(setMicWaveforms)
+ .catch((error) =>
+ console.error("Failed to load mic waveforms:", error),
+ );
+ commands
+ .getSystemAudioWaveforms()
+ .then(setSystemAudioWaveforms)
+ .catch((error) =>
+ console.error("Failed to load system audio waveforms:", error),
+ );
+ });
+ const customDomain = createCustomDomainQuery();
+ const hasRecordedKeyboardEvents = createMemo(() => {
+ const meta = props.meta();
+ if (meta.type === "single") return false;
+ return meta.segments.some((segment) => !!segment.keyboard);
+ });
+ const [didInitializeKeyboardSegments, setDidInitializeKeyboardSegments] =
+ createSignal(false);
+
+ createEffect(() => {
+ if (didInitializeKeyboardSegments()) return;
+ if (!project.timeline) return;
+ if (!hasRecordedKeyboardEvents()) {
+ setDidInitializeKeyboardSegments(true);
+ return;
+ }
+ if ((project.timeline?.keyboardSegments?.length ?? 0) > 0) {
+ setDidInitializeKeyboardSegments(true);
+ return;
+ }
+
setDidInitializeKeyboardSegments(true);
- return;
- }
- setDidInitializeKeyboardSegments(true);
+ void (async () => {
+ try {
- const segments = await commands.generateKeyboardSegments(
- defaultKeyboardSettings.groupingThresholdMs,
- defaultKeyboardSettings.lingerDuration * 1000,
- defaultKeyboardSettings.showModifiers,
- defaultKeyboardSettings.showSpecialKeys,
++ const segments = await generateForStableKeyboardTimeline(
++ () => keyboardTimelineSignature(project.timeline),
++ async () => {
++ await projectSave.flush();
++ return commands.generateKeyboardSegments(
++ defaultKeyboardSettings.groupingThresholdMs,
++ defaultKeyboardSettings.lingerDuration * 1000,
++ defaultKeyboardSettings.showModifiers,
++ defaultKeyboardSettings.showSpecialKeys,
++ );
++ },
+ );
- void (async () => {
- try {
- const segments = await generateForStableKeyboardTimeline(
- () => keyboardTimelineSignature(project.timeline),
- async () => {
- await flushProjectConfig();
- return commands.generateKeyboardSegments(
- defaultKeyboardSettings.groupingThresholdMs,
- defaultKeyboardSettings.lingerDuration * 1000,
- defaultKeyboardSettings.showModifiers,
- defaultKeyboardSettings.showSpecialKeys,
++ if (!segments) {
++ toast.error(
++ "The timeline changed while keyboard events were generated. Try again.",
+ );
- },
- );
++ return;
++ }
+ if (segments.length < 1) return;
- if (!segments) {
- toast.error(
- "The timeline changed while keyboard events were generated. Try again.",
- );
- return;
+ batch(() => {
+ if (!project.keyboard) {
+ setProject("keyboard", {
+ settings: defaultKeyboardSettings,
+ });
+ }
+ setProject("timeline", "keyboardSegments", segments);
+ });
+ } catch (error) {
+ console.error("Failed to initialize keyboard segments", error);
++ toast.error("Unable to generate keyboard events");
}
- if (segments.length < 1) return;
+ })();
+ });
- batch(() => {
- if (!project.keyboard) {
- setProject("keyboard", {
- settings: defaultKeyboardSettings,
- });
- }
- setProject("timeline", "keyboardSegments", segments);
+ const captionRecordingSegments = props.editorInstance.recordings.segments;
+
+ // One-time migration: legacy projects stored caption segments in
+ // already-edited output time. Invert them back to source/recording time
+ // so the render track can be derived from them. For unedited timelines
+ // this is a no-op; for edited ones it makes the current positions a fixed
+ // point and lets future edits stay aligned.
+ if (project.captions && !project.captions.sourceTimed) {
+ const timeline = project.timeline;
+ const segments = project.captions.segments ?? [];
+ if (timeline && segments.length > 0) {
+ const toSource = (time: number) =>
+ mapEditedTimeToSource(
+ time,
+ timeline.segments,
+ captionRecordingSegments,
+ timeline.transitions ?? [],
+ undefined,
+ "incoming",
++ timeline.textSegments,
+ );
+ const inverted = segments.flatMap((segment) => {
+ const start = toSource(segment.start);
+ const end = toSource(segment.end);
+ if (start === null || end === null) return [];
+ const words = (segment.words ?? []).flatMap((word) => {
+ const wordStart = toSource(word.start);
+ const wordEnd = toSource(word.end);
+ return wordStart !== null && wordEnd !== null
+ ? [{ ...word, start: wordStart, end: wordEnd }]
+ : [];
+ });
+ return [{ ...segment, start, end, words }];
});
- } catch (error) {
- console.error("Failed to initialize keyboard segments", error);
- toast.error("Unable to generate keyboard events");
+ inverted.sort((a, b) => a.start - b.start);
+ setProject("captions", "segments", inverted);
}
- })();
- });
-
- const captionRecordingSegments = props.editorInstance.recordings.segments;
-
- // One-time migration: legacy projects stored caption segments in
- // already-edited output time. Invert them back to source/recording time
- // so the render track can be derived from them. For unedited timelines
- // this is a no-op; for edited ones it makes the current positions a fixed
- // point and lets future edits stay aligned.
- if (project.captions && !project.captions.sourceTimed) {
- const timeline = project.timeline;
- const segments = project.captions.segments ?? [];
- if (timeline && segments.length > 0) {
- const toSource = (time: number) =>
- mapEditedTimeToSource(
- time,
- timeline.segments,
- captionRecordingSegments,
- timeline.transitions ?? [],
- undefined,
- "incoming",
- timeline.textSegments,
- );
- const inverted = segments.flatMap((segment) => {
- const start = toSource(segment.start);
- const end = toSource(segment.end);
- if (start === null || end === null) return [];
- const words = (segment.words ?? []).flatMap((word) => {
- const wordStart = toSource(word.start);
- const wordEnd = toSource(word.end);
- return wordStart !== null && wordEnd !== null
- ? [{ ...word, start: wordStart, end: wordEnd }]
- : [];
- });
- return [{ ...segment, start, end, words }];
- });
- inverted.sort((a, b) => a.start - b.start);
- setProject("captions", "segments", inverted);
+ if (project.captions) setProject("captions", "sourceTimed", true);
}
- if (project.captions) setProject("captions", "sourceTimed", true);
- }
-
- // Keep the rendered caption track (output time) projected from the
- // source-time caption master through the current edit list, so captions
- // follow clip trims/deletes/reorders/inserts 1:1 with no re-transcription.
- createEffect(
- on(
- () => {
- const segments = project.captions?.segments;
- const timeline = project.timeline;
- if (!segments || segments.length === 0 || !timeline) return null;
- const captionsSig = segments
- .map(
- (s) =>
- `${s.id}|${s.start}|${s.end}|${s.text}|${(s.words ?? [])
- .map((w) => `${w.start}:${w.end}:${w.text}`)
- .join("~")}`,
- )
- .join(",");
- const timelineSig = timeline.segments
- .map(
- (s) =>
- `${s.start}|${s.end}|${s.timescale}|${s.recordingSegment ?? 0}`,
- )
- .join(",");
- const transitionSig = (timeline.transitions ?? [])
- .map(
- (transition) =>
- `${transition.segmentIndex}|${transition.type}|${transition.duration}`,
- )
- .join(",");
- // Fullscreen-text holds shift the projected track's output
- // times, so moving/resizing one must re-derive too.
- const holdSig = holdWindows(timeline.textSegments)
- .map(([start, end]) => `${start}|${end}`)
- .join(",");
- return `${captionsSig}@@${timelineSig}@@${transitionSig}@@${holdSig}`;
- },
- () => {
- const timeline = project.timeline;
- const segments = project.captions?.segments;
- if (!timeline || !segments) return;
- const derived = deriveCaptionTrackSegments(
- segments,
- timeline.segments,
- captionRecordingSegments,
- timeline.captionSegments ?? [],
- timeline.transitions ?? [],
- timeline.textSegments,
- );
- setProject(
- "timeline",
- "captionSegments",
- reconcile(derived, { key: "id" }),
- );
- // Push the refreshed caption track to the renderer immediately.
- // The store (and timeline strip) update reactively, but the
- // renderer only reflects config that is explicitly pushed, and
- // the editor's config-push effect doesn't run on initial load,
- // so without this the rendered frame keeps stale caption
- // positions until the next unrelated edit.
- if (!editorState.playing) {
- const frameNumber = Math.max(
- Math.floor(editorState.playbackTime * FPS),
- 0,
- );
- commands
- .updateProjectConfigInMemory(
- serializeProjectConfiguration(project),
- frameNumber,
- FPS,
- previewResolutionBase(),
+ // Keep the rendered caption track (output time) projected from the
+ // source-time caption master through the current edit list, so captions
+ // follow clip trims/deletes/reorders/inserts 1:1 with no re-transcription.
+ createEffect(
+ on(
+ () => {
+ const segments = project.captions?.segments;
+ const timeline = project.timeline;
+ if (!segments || segments.length === 0 || !timeline) return null;
+ const captionsSig = segments
+ .map(
+ (s) =>
+ `${s.id}|${s.start}|${s.end}|${s.text}|${(s.words ?? [])
+ .map((w) => `${w.start}:${w.end}:${w.text}`)
+ .join("~")}`,
)
- .catch((error) => {
- console.error(
- "Failed to refresh caption preview config",
- error,
- );
- });
- }
+ .join(",");
+ const timelineSig = timeline.segments
+ .map(
+ (s) =>
+ `${s.start}|${s.end}|${s.timescale}|${s.recordingSegment ?? 0}`,
+ )
+ .join(",");
+ const transitionSig = (timeline.transitions ?? [])
+ .map(
+ (transition) =>
+ `${transition.segmentIndex}|${transition.type}|${transition.duration}`,
+ )
+ .join(",");
+ // Fullscreen-text holds shift the projected track's output
+ // times, so moving/resizing one must re-derive too.
+ const holdSig = holdWindows(timeline.textSegments)
+ .map(([start, end]) => `${start}|${end}`)
+ .join(",");
+ return `${captionsSig}@@${timelineSig}@@${transitionSig}@@${holdSig}`;
+ },
+ () => {
+ const timeline = project.timeline;
+ const segments = project.captions?.segments;
+ if (!timeline || !segments) return;
+ const derived = deriveCaptionTrackSegments(
+ segments,
+ timeline.segments,
+ captionRecordingSegments,
+ timeline.captionSegments ?? [],
+ timeline.transitions ?? [],
+ timeline.textSegments,
+ );
+ setProject(
+ "timeline",
+ "captionSegments",
+ reconcile(derived, { key: "id" }),
+ );
+
+ // Push the refreshed caption track to the renderer immediately.
+ // The store (and timeline strip) update reactively, but the
+ // renderer only reflects config that is explicitly pushed, and
+ // the editor's config-push effect doesn't run on initial load,
+ // so without this the rendered frame keeps stale caption
+ // positions until the next unrelated edit.
+ if (!editorState.playing) {
+ const frameNumber = Math.max(
+ Math.floor(editorState.playbackTime * FPS),
+ 0,
+ );
+ commands
+ .updateProjectConfigInMemory(
+ serializeProjectConfiguration(project),
+ frameNumber,
+ FPS,
+ previewResolutionBase(),
+ )
+ .catch((error) => {
+ console.error(
+ "Failed to refresh caption preview config",
+ error,
+ );
+ });
+ }
+ },
+ ),
+ );
+
+ return {
+ ...editorInstanceContext,
+ meta() {
+ return props.meta();
},
- ),
- );
-
- return {
- ...editorInstanceContext,
- flushProjectConfig,
- meta() {
- return props.meta();
- },
- customDomain,
- refetchMeta: () => props.refetchMeta(),
- editorInstance: props.editorInstance,
- dialog,
- setDialog,
- project,
- setProject,
- projectActions,
- camera3DScenePreview,
- projectHistory: createStoreHistory(project, setProject),
- editorState,
- setEditorState,
- snapGuides,
- setSnapGuides,
- totalDuration,
- zoomOutLimit,
- exportState,
- setExportState,
- micWaveforms,
- systemAudioWaveforms,
- previewQuality,
- setPreviewQuality,
- previewResolutionBase,
- };
- },
- // biome-ignore lint/style/noNonNullAssertion: it's ok
- null!,
-);
+ customDomain,
+ refetchMeta: () => props.refetchMeta(),
+ editorInstance: props.editorInstance,
+ dialog,
+ setDialog,
+ project,
+ setProject,
+ projectActions,
+ flushProjectConfig: projectSave.flush,
+ projectRevision: projectSave.revision,
+ baseProject: project,
+ styleProject,
+ styleScopeToken,
+ createStyleProjectSetter,
+ setStyleProject,
+ selectedStyle,
+ toggleStyleGroup,
+ exitStyleScope,
+ previewStyle,
+ camera3DScenePreview,
+ projectHistory: createStoreHistory(project, setProject, () => {
+ exitStyleScope();
+ setEditorState("timeline", "selection", null);
+ }),
+ editorState,
+ setEditorState,
+ snapGuides,
+ setSnapGuides,
+ totalDuration,
+ zoomOutLimit,
+ exportState,
+ setExportState,
+ micWaveforms,
+ systemAudioWaveforms,
+ previewQuality,
+ setPreviewQuality,
+ previewResolutionBase,
+ };
+ },
+ // biome-ignore lint/style/noNonNullAssertion: it's ok
+ null!,
+ );
+
+export const EditorStyleContext =
+ createContext<ReturnType<typeof useBaseEditorContext>>();
+
+export function useEditorContext() {
+ return useContext(EditorStyleContext) ?? useBaseEditorContext();
+}
export type { CanvasControls, FrameData } from "~/utils/socket";
export type { EditorPreviewQuality } from "~/utils/tauri";
diff --cc apps/desktop/src/routes/editor/editor-skeleton.tsx
index 94b57eaac,94b57eaac..a3ab1f23e
--- a/apps/desktop/src/routes/editor/editor-skeleton.tsx
+++ b/apps/desktop/src/routes/editor/editor-skeleton.tsx
@@@ -2,26 -2,26 +2,12 @@@ import { type as ostype } from "@tauri-
import { cx } from "cva";
import CaptionControlsWindows11 from "~/components/titlebar/controls/CaptionControlsWindows11";
--const DEFAULT_TIMELINE_HEIGHT = 260;
--const MIN_PLAYER_HEIGHT = 336;
--const RESIZE_HANDLE_HEIGHT = 16;
++const MIN_PLAYER_HEIGHT = 320;
++const TIMELINE_SKELETON_HEIGHT = 22 + 26 + 4 + 2 * 44 + 6;
function SkeletonPulse(props: { class?: string }) {
return (
-- <div
-- class={cx(
-- "animate-pulse rounded-sm bg-gray-3 dark:bg-gray-4",
-- props.class,
-- )}
-- />
-- );
--}
--
--function SkeletonButton(props: { class?: string; width?: string }) {
-- return (
-- <SkeletonPulse
-- class={cx("h-9 rounded-lg", props.width ?? "w-9", props.class)}
-- />
++ <div class={cx("animate-pulse rounded-sm bg-ed-ctl-hover", props.class)} />
);
}
@@@ -29,116 -29,116 +15,69 @@@ function HeaderSkeleton()
return (
<div
data-tauri-drag-region
-- class="flex relative flex-row items-center w-full h-14"
++ class="flex relative flex-row items-center w-full h-13 pr-3"
>
<div
data-tauri-drag-region
-- class="flex flex-row flex-1 gap-2 items-center px-4 h-full"
++ class="flex flex-row flex-1 gap-1.5 items-center h-full"
>
-- {ostype() === "macos" && <div class="h-full w-16" />}
-- <SkeletonButton />
-- <SkeletonButton />
-- <SkeletonPulse class="h-5 w-32" />
-- <SkeletonPulse class="h-5 w-8" />
++ {ostype() === "macos" && <div class="h-full w-[92px] shrink-0" />}
++ {ostype() === "windows" && <div class="w-3 shrink-0" />}
++ <SkeletonPulse class="h-4 w-40" />
++ <SkeletonPulse class="h-4 w-7" />
++ <SkeletonPulse class="ml-1.5 size-7 rounded-[7px]" />
++ <SkeletonPulse class="size-7 rounded-[7px]" />
<div data-tauri-drag-region class="flex-1 h-full" />
-- <SkeletonButton />
-- <SkeletonButton />
-- </div>
--
-- <div
-- data-tauri-drag-region
-- class="flex flex-col justify-center px-4 border-x border-black-transparent-10"
-- >
-- <SkeletonPulse class="h-9 w-28 rounded-lg" />
</div>
--
-- <div
-- data-tauri-drag-region
-- class={cx(
-- "flex-1 h-full flex flex-row items-center gap-2 pl-2",
-- ostype() !== "windows" && "pr-2",
-- )}
-- >
-- <SkeletonButton />
-- <SkeletonButton />
-- <div data-tauri-drag-region class="flex-1 h-full" />
-- <SkeletonPulse class="h-[40px] w-[100px] rounded-lg" />
-- {ostype() === "windows" && <CaptionControlsWindows11 />}
++ <div class="flex flex-row gap-1 items-center">
++ <SkeletonPulse class="size-7 rounded-[7px]" />
++ <SkeletonPulse class="size-7 rounded-[7px]" />
++ <SkeletonPulse class="mx-1.5 w-px h-4" />
++ <SkeletonPulse class="h-7 w-20 rounded-[7px]" />
++ <SkeletonPulse class="h-7 w-16 rounded-[7px]" />
++ <SkeletonPulse class="ml-1.5 h-[30px] w-[92px] rounded-lg" />
</div>
++ {ostype() === "windows" && <CaptionControlsWindows11 class="shrink-0" />}
</div>
);
}
--function PlayerToolbarSkeleton() {
++function PlayerSkeleton() {
return (
-- <div class="flex items-center justify-between gap-3 p-3">
-- <div class="flex items-center gap-3">
-- <SkeletonPulse class="h-9 w-24 rounded-lg" />
-- <SkeletonPulse class="h-9 w-16 rounded-lg" />
-- </div>
-- <div class="flex items-center gap-2">
-- <SkeletonPulse class="h-4 w-24" />
-- <SkeletonPulse class="h-9 w-20 rounded-lg" />
++ <div class="flex flex-col flex-1 min-w-0 rounded-xl bg-ed-card shadow-ed-card overflow-hidden">
++ <div class="flex flex-row items-center px-3 h-11 shrink-0">
++ <div class="flex flex-row flex-1 gap-0.5 items-center">
++ <SkeletonPulse class="h-7 w-16 rounded-[7px]" />
++ <SkeletonPulse class="h-7 w-16 rounded-[7px]" />
++ <SkeletonPulse class="h-7 w-20 rounded-[7px]" />
++ </div>
++ <div class="flex flex-row gap-2 items-center">
++ <SkeletonPulse class="h-3 w-12" />
++ <SkeletonPulse class="h-7 w-40 rounded-lg" />
++ </div>
</div>
-- </div>
-- );
--}
--
--function VideoPreviewSkeleton() {
-- return (
-- <div class="relative flex-1 flex justify-center items-center">
-- <div class="relative w-full h-full flex justify-center items-center p-4">
-- <div class="relative bg-gray-3 dark:bg-gray-4 rounded-lg w-full max-w-[85%] aspect-video flex items-center justify-center">
-- <div class="animate-spin grayscale opacity-60">
-- <IconCapLogo class="size-16 text-gray-6" />
++ <div class="relative flex flex-1 min-h-0 justify-center items-center p-4">
++ <div class="flex justify-center items-center w-full max-w-[85%] rounded-md aspect-video bg-ed-ctl">
++ <div class="animate-spin opacity-60">
++ <IconCapLogo class="size-16 text-ed-text-3" />
</div>
</div>
</div>
-- </div>
-- );
--}
--
--function PlayerControlsSkeleton() {
-- return (
-- <div class="flex overflow-hidden z-10 flex-row gap-3 justify-between items-center p-5">
-- <div class="flex-1 flex items-center gap-1">
-- <SkeletonPulse class="h-4 w-12" />
-- <SkeletonPulse class="h-4 w-3" />
-- <SkeletonPulse class="h-4 w-12" />
-- </div>
-- <div class="flex flex-row items-center justify-center gap-8">
-- <SkeletonPulse class="size-3 rounded-sm" />
-- <SkeletonPulse class="size-9 rounded-full" />
-- <SkeletonPulse class="size-3 rounded-sm" />
-- </div>
-- <div class="flex flex-row flex-1 gap-4 justify-end items-center">
-- <div class="flex-1" />
-- <SkeletonButton />
-- <SkeletonPulse class="w-px h-8 rounded-full" />
-- <SkeletonPulse class="size-5 rounded-sm" />
-- <SkeletonPulse class="size-5 rounded-sm" />
-- <SkeletonPulse class="w-24 h-2 rounded-full" />
-- </div>
-- </div>
-- );
--}
--
--function PlayerSkeleton() {
-- return (
-- <div class="flex flex-col flex-1 rounded-xl border bg-gray-1 dark:bg-gray-2 border-gray-3 overflow-hidden">
-- <div class="flex flex-col flex-1 min-h-0">
-- <PlayerToolbarSkeleton />
-- <VideoPreviewSkeleton />
-- <PlayerControlsSkeleton />
-- </div>
-- <div
-- class="flex-none shrink-0 border-t border-gray-4 dark:border-gray-5 bg-gray-2/95 dark:bg-gray-3/55"
-- style={{ height: `${RESIZE_HANDLE_HEIGHT}px` }}
-- >
-- <div class="flex flex-col gap-0.5 justify-center items-center h-full w-full">
-- <div class="h-0.5 w-20 max-w-[85%] rounded-full bg-gray-6 dark:bg-gray-7 shadow-[0_1px_0_rgb(0_0_0_/0.06)]" />
-- <div class="h-0.5 w-20 max-w-[85%] rounded-full bg-gray-6 dark:bg-gray-7 shadow-[0_1px_0_rgb(0_0_0_/0.06)]" />
-- <div class="h-0.5 w-20 max-w-[85%] rounded-full bg-gray-6 dark:bg-gray-7 shadow-[0_1px_0_rgb(0_0_0_/0.06)]" />
++ <div class="flex flex-row items-center px-3.5 h-12 shrink-0">
++ <div class="flex flex-row flex-1 items-center">
++ <SkeletonPulse class="h-4 w-24" />
++ </div>
++ <div class="flex flex-row gap-3.5 items-center">
++ <SkeletonPulse class="size-3.5 rounded-sm" />
++ <SkeletonPulse class="size-8 rounded-full" />
++ <SkeletonPulse class="size-3.5 rounded-sm" />
++ </div>
++ <div class="flex flex-row flex-1 gap-0.5 justify-end items-center">
++ <SkeletonPulse class="size-7 rounded-[7px]" />
++ <SkeletonPulse class="mx-1.5 w-px h-4" />
++ <SkeletonPulse class="size-7 rounded-[7px]" />
++ <SkeletonPulse class="mx-1 w-[72px] h-[3px] rounded-full" />
++ <SkeletonPulse class="size-7 rounded-[7px]" />
</div>
</div>
</div>
@@@ -147,34 -147,34 +86,56 @@@
function SidebarSkeleton() {
return (
-- <div class="flex flex-col min-h-0 shrink-0 flex-1 max-w-104 overflow-hidden rounded-xl z-10 bg-gray-1 dark:bg-gray-2 border border-gray-3">
-- <div class="flex overflow-hidden sticky top-0 z-60 flex-row items-center justify-center gap-4 h-16 border-b border-gray-3 shrink-0 bg-gray-1 dark:bg-gray-2">
-- <SkeletonPulse class="size-9 rounded-lg" />
-- <SkeletonPulse class="size-9 rounded-lg" />
-- <SkeletonPulse class="size-9 rounded-lg" />
-- <SkeletonPulse class="size-9 rounded-lg" />
-- <SkeletonPulse class="size-9 rounded-lg" />
-- <SkeletonPulse class="size-9 rounded-lg" />
-- </div>
-- <div class="flex-1 p-4 space-y-4 overflow-hidden">
-- <SkeletonPulse class="h-4 w-20" />
-- <div class="flex gap-2">
-- <SkeletonPulse class="h-16 flex-1 rounded-lg" />
-- <SkeletonPulse class="h-16 flex-1 rounded-lg" />
-- <SkeletonPulse class="h-16 flex-1 rounded-lg" />
-- <SkeletonPulse class="h-16 flex-1 rounded-lg" />
-- </div>
-- <SkeletonPulse class="h-px w-full" />
-- <SkeletonPulse class="h-4 w-16" />
-- <div class="grid grid-cols-4 gap-2">
-- <SkeletonPulse class="aspect-video rounded-sm" />
-- <SkeletonPulse class="aspect-video rounded-sm" />
-- <SkeletonPulse class="aspect-video rounded-sm" />
-- <SkeletonPulse class="aspect-video rounded-sm" />
-- <SkeletonPulse class="aspect-video rounded-sm" />
-- <SkeletonPulse class="aspect-video rounded-sm" />
-- <SkeletonPulse class="aspect-video rounded-sm" />
-- <SkeletonPulse class="aspect-video rounded-sm" />
++ <div class="flex flex-col min-h-0 w-104 min-w-104 flex-none overflow-hidden rounded-xl bg-ed-card shadow-ed-card">
++ <div class="flex flex-row justify-around items-center px-2.5 h-[46px] border-b border-ed-line shrink-0">
++ <SkeletonPulse class="w-10 h-[30px] rounded-[9px]" />
++ <SkeletonPulse class="w-10 h-[30px] rounded-[9px]" />
++ <SkeletonPulse class="w-10 h-[30px] rounded-[9px]" />
++ <SkeletonPulse class="w-10 h-[30px] rounded-[9px]" />
++ <SkeletonPulse class="w-10 h-[30px] rounded-[9px]" />
++ <SkeletonPulse class="w-10 h-[30px] rounded-[9px]" />
++ </div>
++ <div class="flex flex-col flex-1 gap-3.5 px-4 pt-3.5 pb-4 overflow-hidden">
++ <div class="flex justify-between items-center h-5">
++ <SkeletonPulse class="h-3 w-20" />
++ <SkeletonPulse class="h-5 w-12 rounded-md" />
++ </div>
++ <SkeletonPulse class="h-[30px] w-full rounded-lg" />
++ <div class="flex gap-1">
++ <SkeletonPulse class="h-6 w-16 rounded-[7px]" />
++ <SkeletonPulse class="h-6 w-12 rounded-[7px]" />
++ <SkeletonPulse class="h-6 w-12 rounded-[7px]" />
++ <SkeletonPulse class="h-6 w-14 rounded-[7px]" />
++ </div>
++ <div class="grid grid-cols-6 gap-1.5">
++ <SkeletonPulse class="h-[34px] rounded-md" />
++ <SkeletonPulse class="h-[34px] rounded-md" />
++ <SkeletonPulse class="h-[34px] rounded-md" />
++ <SkeletonPulse class="h-[34px] rounded-md" />
++ <SkeletonPulse class="h-[34px] rounded-md" />
++ <SkeletonPulse class="h-[34px] rounded-md" />
++ <SkeletonPulse class="h-[34px] rounded-md" />
++ <SkeletonPulse class="h-[34px] rounded-md" />
++ <SkeletonPulse class="h-[34px] rounded-md" />
++ <SkeletonPulse class="h-[34px] rounded-md" />
++ <SkeletonPulse class="h-[34px] rounded-md" />
++ <SkeletonPulse class="h-[34px] rounded-md" />
++ </div>
++ <div class="h-px w-full bg-ed-line" />
++ <SkeletonPulse class="h-3 w-14" />
++ <div class="flex items-center gap-3 h-[34px]">
++ <SkeletonPulse class="h-3.5 w-16" />
++ <SkeletonPulse class="flex-1 h-[3px] rounded-full" />
++ <SkeletonPulse class="h-3 w-8" />
++ </div>
++ <div class="flex items-center gap-3 h-[34px]">
++ <SkeletonPulse class="h-3.5 w-14" />
++ <SkeletonPulse class="flex-1 h-[3px] rounded-full" />
++ <SkeletonPulse class="h-3 w-8" />
++ </div>
++ <div class="flex items-center justify-between h-[34px]">
++ <SkeletonPulse class="h-3.5 w-16" />
++ <SkeletonPulse class="h-5 w-[34px] rounded-full" />
</div>
</div>
</div>
@@@ -183,38 -183,38 +144,36 @@@
function TimelineTrackSkeleton() {
return (
-- <div class="flex items-center gap-2 h-13">
-- <div class="w-16 flex items-center justify-center">
-- <SkeletonPulse class="size-4 rounded-sm" />
-- </div>
-- <div class="flex-1 h-full py-1">
-- <SkeletonPulse class="h-full w-full rounded-lg" />
++ <div class="flex items-center h-11 rounded-lg bg-ed-ctl">
++ <div class="flex gap-1.5 items-center pl-2 w-[104px] shrink-0">
++ <SkeletonPulse class="size-[22px] rounded-md" />
++ <SkeletonPulse class="h-3 w-10" />
</div>
++ <SkeletonPulse class="flex-1 h-full rounded-r-lg" />
</div>
);
}
function TimelineSkeleton() {
return (
-- <div class="h-full rounded-xl border bg-gray-1 dark:bg-gray-2 border-gray-3 overflow-hidden">
-- <div class="pt-8 relative flex flex-col gap-2 h-full px-4">
-- <div class="relative h-[32px] flex items-end">
-- <div class="flex items-center gap-8 w-full pl-16">
-- <SkeletonPulse class="h-3 w-8" />
-- <SkeletonPulse class="h-3 w-8" />
-- <SkeletonPulse class="h-3 w-8" />
-- <SkeletonPulse class="h-3 w-8" />
-- <SkeletonPulse class="h-3 w-8" />
-- </div>
-- <div class="absolute bottom-0 left-0">
-- <SkeletonPulse class="size-8 rounded-lg" />
-- </div>
++ <div class="flex flex-col h-full rounded-xl bg-ed-card shadow-ed-card overflow-hidden px-3 pt-2.5 pb-3">
++ <div class="flex items-end h-[26px] shrink-0">
++ <div class="w-[104px] pl-1 shrink-0">
++ <SkeletonPulse class="h-6 w-[88px] rounded-md" />
</div>
-- <div class="relative flex-1 min-h-0 space-y-1">
-- <TimelineTrackSkeleton />
-- <TimelineTrackSkeleton />
++ <div class="flex flex-1 gap-[92px] items-end pb-2.5">
++ <SkeletonPulse class="h-2.5 w-7" />
++ <SkeletonPulse class="h-2.5 w-7" />
++ <SkeletonPulse class="h-2.5 w-7" />
++ <SkeletonPulse class="h-2.5 w-7" />
++ <SkeletonPulse class="h-2.5 w-7" />
++ <SkeletonPulse class="h-2.5 w-7" />
</div>
</div>
++ <div class="flex flex-col gap-1.5 mt-1">
++ <TimelineTrackSkeleton />
++ <TimelineTrackSkeleton />
++ </div>
</div>
);
}
@@@ -225,26 -225,26 +184,20 @@@ export function EditorSkeleton()
<HeaderSkeleton />
<div
data-tauri-drag-region
-- class="flex overflow-y-hidden flex-col flex-1 gap-2 pb-4 w-full min-h-0 leading-5"
++ class="flex overflow-y-hidden flex-col flex-1 gap-2 pb-2 w-full min-h-0 leading-5"
>
-- <div class="flex overflow-hidden flex-col flex-1 min-h-0">
-- <div
-- class="flex overflow-y-hidden flex-row flex-1 min-h-0 gap-2 px-2"
-- style={{
-- "min-height": `${MIN_PLAYER_HEIGHT}px`,
-- }}
-- >
-- <PlayerSkeleton />
-- <SidebarSkeleton />
-- </div>
-- <div
-- class="flex-none min-h-0 px-2 pb-0.5 overflow-hidden relative"
-- style={{ height: `${DEFAULT_TIMELINE_HEIGHT}px` }}
-- >
-- <div class="h-full">
-- <TimelineSkeleton />
-- </div>
-- </div>
++ <div
++ class="flex overflow-y-hidden flex-row flex-1 min-h-0 gap-2 px-2"
++ style={{ "min-height": `${MIN_PLAYER_HEIGHT}px` }}
++ >
++ <PlayerSkeleton />
++ <SidebarSkeleton />
++ </div>
++ <div
++ class="flex-none min-h-0 px-2 overflow-hidden"
++ style={{ height: `${TIMELINE_SKELETON_HEIGHT}px` }}
++ >
++ <TimelineSkeleton />
</div>
</div>
</div>
diff --cc apps/desktop/src/routes/editor/image-overlay.tsx
index 45d78e384,000000000..cea636d8a
mode 100644,000000..100644
--- a/apps/desktop/src/routes/editor/image-overlay.tsx
+++ b/apps/desktop/src/routes/editor/image-overlay.tsx
@@@ -1,246 -1,0 +1,290 @@@
+import { createEventListener } from "@solid-primitives/event-listener";
+import { For, onCleanup, Show } from "solid-js";
+import { unwrap } from "solid-js/store";
+import { useCanvasSnapTargets } from "./CanvasElementsOverlay";
+import { useEditorContext } from "./context";
+import { resizeImage } from "./images";
+import { SNAP_PX, snapMovingRect } from "./snapping";
++import { getOverlayZIndex } from "./timelineTracks";
+
+export function ImageOverlay(props: {
+ size: { width: number; height: number };
+}) {
+ const {
+ project,
+ setProject,
+ editorState,
+ setEditorState,
+ projectHistory,
+ setSnapGuides,
+ } = useEditorContext();
+ const snapTargets = useCanvasSnapTargets();
+ const time = () => editorState.previewTime ?? editorState.playbackTime;
+ const visible = () =>
+ (project.timeline?.imageSegments ?? [])
+ .map((segment, index) => ({ segment, index }))
+ .filter(
+ ({ segment }) =>
+ segment.enabled && time() >= segment.start && time() < segment.end,
+ )
+ .sort((a, b) => a.segment.track - b.segment.track || a.index - b.index);
+ const selected = (index: number) =>
+ editorState.timeline.selection?.type === "image" &&
+ editorState.timeline.selection.indices.includes(index);
+ let endDrag: (() => void) | undefined;
+ onCleanup(() => endDrag?.());
+
+ function drag(
+ event: MouseEvent,
+ index: number,
+ mode: "move" | "rotate" | { x: number; y: number },
+ ) {
+ if (event.button !== 0 || editorState.playing) return;
+ event.preventDefault();
+ event.stopPropagation();
+ endDrag?.();
+ const source = project.timeline?.imageSegments[index];
+ if (!source) return;
+ setEditorState("timeline", "selection", {
+ type: "image",
+ indices: [index],
+ });
+ const initial = structuredClone(unwrap(source));
+ const canvas = { ...props.size };
+ const rect = (event.currentTarget as HTMLElement)
+ .closest("[data-image-overlay]")
+ ?.getBoundingClientRect();
+ const center = rect
+ ? { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }
+ : { x: event.clientX, y: event.clientY };
+ const startAngle = Math.atan2(
+ event.clientY - center.y,
+ event.clientX - center.x,
+ );
+ const targets = snapTargets({ image: index });
+ const resume = projectHistory.pause();
+ let moved = false;
++ let frame: number | undefined;
++ let pending: MouseEvent | undefined;
+ const move = (next: MouseEvent) => {
+ if (project.timeline?.imageSegments[index] !== source) return;
+ const delta = {
+ x: next.clientX - event.clientX,
+ y: next.clientY - event.clientY,
+ };
+ if (!moved && Math.hypot(delta.x, delta.y) < 2) return;
+ moved = true;
+ if (mode === "rotate") {
+ let rotation =
+ initial.rotation +
+ ((Math.atan2(next.clientY - center.y, next.clientX - center.x) -
+ startAngle) *
+ 180) /
+ Math.PI;
+ if (next.shiftKey) rotation = Math.round(rotation / 15) * 15;
+ setProject(
+ "timeline",
+ "imageSegments",
+ index,
+ "rotation",
+ ((((rotation + 180) % 360) + 360) % 360) - 180,
+ );
+ } else if (mode === "move") {
+ const radians = (initial.rotation * Math.PI) / 180;
+ const width = initial.size.x * canvas.width;
+ const height = initial.size.y * canvas.height;
+ const w =
+ (Math.abs(width * Math.cos(radians)) +
+ Math.abs(height * Math.sin(radians))) /
+ canvas.width;
+ const h =
+ (Math.abs(width * Math.sin(radians)) +
+ Math.abs(height * Math.cos(radians))) /
+ canvas.height;
+ const raw = {
+ x: initial.center.x + delta.x / canvas.width - w / 2,
+ y: initial.center.y + delta.y / canvas.height - h / 2,
+ w,
+ h,
+ };
+ const snap = next.shiftKey
+ ? { dx: 0, dy: 0, guides: [] }
+ : snapMovingRect(
+ raw,
+ targets,
+ SNAP_PX / canvas.width,
+ SNAP_PX / canvas.height,
+ );
+ setSnapGuides(snap.guides);
+ setProject("timeline", "imageSegments", index, "center", {
+ x: Math.max(0, Math.min(1, raw.x + w / 2 + snap.dx)),
+ y: Math.max(0, Math.min(1, raw.y + h / 2 + snap.dy)),
+ });
+ } else
+ setProject(
+ "timeline",
+ "imageSegments",
+ index,
+ resizeImage(initial, delta, mode, canvas),
+ );
+ };
- const finish = (next?: MouseEvent) => {
++ const scheduleMove = (next: MouseEvent) => {
++ pending = next;
++ if (frame !== undefined) return;
++ frame = requestAnimationFrame(() => {
++ frame = undefined;
++ const latest = pending;
++ pending = undefined;
++ if (latest) move(latest);
++ });
++ };
++ const finish = (next?: MouseEvent, cancelled = false) => {
+ if (!endDrag) return;
++ if (frame !== undefined) cancelAnimationFrame(frame);
++ frame = undefined;
++ pending = undefined;
+ if (next) move(next);
- window.removeEventListener("mousemove", move);
++ window.removeEventListener("mousemove", scheduleMove);
+ window.removeEventListener("mouseup", finish);
+ window.removeEventListener("blur", cancel);
++ window.removeEventListener("keydown", keydown, true);
+ endDrag = undefined;
++ if (
++ cancelled &&
++ moved &&
++ project.timeline?.imageSegments[index] === source
++ )
++ setProject("timeline", "imageSegments", index, {
++ center: initial.center,
++ size: initial.size,
++ rotation: initial.rotation,
++ });
+ setSnapGuides([]);
+ resume();
+ };
- const cancel = () => finish();
++ const cancel = () => finish(undefined, true);
++ const keydown = (next: KeyboardEvent) => {
++ if (next.key !== "Escape") return;
++ next.preventDefault();
++ next.stopImmediatePropagation();
++ cancel();
++ };
+ endDrag = cancel;
- window.addEventListener("mousemove", move);
++ window.addEventListener("mousemove", scheduleMove);
+ window.addEventListener("mouseup", finish);
+ window.addEventListener("blur", cancel);
++ window.addEventListener("keydown", keydown, true);
+ }
+
+ createEventListener(window, "keydown", (event) => {
+ if (
+ editorState.playing ||
+ (event.target instanceof HTMLElement &&
+ (event.target.isContentEditable ||
+ ["INPUT", "TEXTAREA", "SELECT"].includes(event.target.tagName)))
+ )
+ return;
++ if (
++ event.key === "Escape" &&
++ editorState.timeline.selection?.type === "image"
++ ) {
++ event.preventDefault();
++ setEditorState("timeline", "selection", null);
++ return;
++ }
+ const direction = {
+ ArrowLeft: [-1, 0],
+ ArrowRight: [1, 0],
+ ArrowUp: [0, -1],
+ ArrowDown: [0, 1],
+ }[event.key];
+ if (!direction) return;
+ const items = visible().filter(({ index }) => selected(index));
+ if (!items.length) return;
+ event.preventDefault();
++ event.stopPropagation();
+ const resume = projectHistory.pause();
+ for (const { segment, index } of items) {
+ const step = event.shiftKey ? 10 : 1;
+ setProject("timeline", "imageSegments", index, "center", {
+ x: Math.max(
+ 0,
+ Math.min(
+ 1,
+ segment.center.x + (direction[0] * step) / props.size.width,
+ ),
+ ),
+ y: Math.max(
+ 0,
+ Math.min(
+ 1,
+ segment.center.y + (direction[1] * step) / props.size.height,
+ ),
+ ),
+ });
+ }
+ resume();
+ });
+
+ return (
+ <div class="pointer-events-none absolute inset-0">
+ <Show when={!editorState.playing}>
+ <For each={visible()}>
+ {({ segment, index }) => (
+ <div
+ data-image-overlay
+ class="group/image absolute pointer-events-auto cursor-move"
+ style={{
++ "z-index": getOverlayZIndex(project, "image", segment.track),
+ left: `${segment.center.x * 100}%`,
+ top: `${segment.center.y * 100}%`,
+ width: `${segment.size.x * 100}%`,
+ height: `${segment.size.y * 100}%`,
+ transform: `translate(-50%, -50%) rotate(${segment.rotation}deg)`,
+ }}
+ onMouseDown={(event) => drag(event, index, "move")}
+ >
+ <div
+ class={`pointer-events-none absolute inset-0 border-2 ${selected(index) ? "border-blue-9" : "border-transparent group-hover/image:border-blue-7"}`}
+ />
+ <Show when={selected(index)}>
+ <span class="pointer-events-none absolute -top-6 left-0 max-w-full truncate rounded bg-blue-9 px-1.5 text-[11px] text-white">
+ {segment.name}
+ </span>
+ <button
+ type="button"
+ aria-label="Rotate image"
+ class="absolute -top-7 left-1/2 size-3 -translate-x-1/2 rounded-full border border-white bg-blue-9 cursor-crosshair"
+ onMouseDown={(event) => drag(event, index, "rotate")}
+ />
+ <For
+ each={[
+ { x: -1, y: -1 },
+ { x: 1, y: -1 },
+ { x: -1, y: 1 },
+ { x: 1, y: 1 },
+ ]}
+ >
+ {(corner) => (
+ <button
+ type="button"
+ aria-label="Resize image"
+ class="absolute size-3 -translate-x-1/2 -translate-y-1/2 rounded-full border border-white bg-blue-9"
+ style={{
+ left: corner.x < 0 ? "0" : "100%",
+ top: corner.y < 0 ? "0" : "100%",
+ cursor:
+ corner.x === corner.y ? "nwse-resize" : "nesw-resize",
+ }}
+ onMouseDown={(event) => drag(event, index, corner)}
+ />
+ )}
+ </For>
+ </Show>
+ </div>
+ )}
+ </For>
+ </Show>
+ </div>
+ );
+}
diff --cc apps/desktop/src/routes/editor/image-segment-config.tsx
index 9325f5038,000000000..98b98b9bf
mode 100644,000000..100644
--- a/apps/desktop/src/routes/editor/image-segment-config.tsx
+++ b/apps/desktop/src/routes/editor/image-segment-config.tsx
@@@ -1,283 -1,0 +1,236 @@@
+import { convertFileSrc } from "@tauri-apps/api/core";
- import { createEffect, createSignal, For, Show } from "solid-js";
++import { createEffect, createSignal, Show } from "solid-js";
+import { Toggle } from "~/components/Toggle";
++import IconLucideCrosshair from "~icons/lucide/crosshair";
+import { useEditorContext } from "./context";
+import { imageAssetPath } from "./images";
- import { EditorButton, Field, Slider } from "./ui";
++import { EditorButton, Field, SectionLabel, Slider } from "./ui";
+
+export function ImageSegmentConfig(props: { index: number }) {
+ const { project, setProject, editorInstance, projectActions, editorState } =
+ useEditorContext();
+ const segment = () => project.timeline?.imageSegments[props.index];
+ const path = () => imageAssetPath(editorInstance.path, segment()?.path ?? "");
+ const [failed, setFailed] = createSignal(false);
+ createEffect(() => {
+ path();
+ setFailed(false);
+ });
+ return (
+ <Show when={segment()}>
+ {(image) => (
- <div class="space-y-4 p-4">
++ <div class="flex flex-col gap-3.5 p-4">
+ <div class="flex gap-2">
+ <input
+ aria-label="Image name"
- class="min-w-0 flex-1 rounded border border-gray-5 bg-gray-2 px-2 py-1"
++ class="h-8 min-w-0 flex-1 rounded-[7px] border-0 bg-ed-ctl px-2 text-[13px] text-ed-text-1 caret-ed-accent outline-hidden transition-colors duration-150 placeholder:text-ed-text-3 hover:bg-ed-ctl-hover focus:bg-ed-ctl-hover focus:ring-1 focus:ring-ed-accent"
+ value={image().name}
+ onChange={(event) =>
+ setProject(
+ "timeline",
+ "imageSegments",
+ props.index,
+ "name",
+ event.currentTarget.value.trim() || "Image",
+ )
+ }
+ />
+ <Toggle
+ checked={image().enabled}
+ onChange={(value) =>
+ setProject(
+ "timeline",
+ "imageSegments",
+ props.index,
+ "enabled",
+ value,
+ )
+ }
+ />
+ </div>
+ <Show
+ when={path() && !failed()}
+ fallback={
+ <p
+ role="status"
- class="rounded bg-orange-3 p-3 text-sm text-gray-12"
++ class="rounded-lg bg-orange-3 p-3 text-[13px] text-ed-text-1"
+ >
+ Image unavailable. Replace it to restore this layer.
+ </p>
+ }
+ >
+ <img
+ src={convertFileSrc(path() ?? "")}
+ alt={image().name}
- class="h-28 w-full rounded object-contain bg-gray-3"
++ class="h-28 w-full rounded-lg object-contain bg-ed-ctl"
+ onError={() => setFailed(true)}
+ />
+ </Show>
+ <div class="flex justify-between gap-2">
+ <EditorButton
+ disabled={editorState.importingImage}
+ onClick={() =>
+ void projectActions.importImageSegment(
+ image().track,
+ image().start,
+ props.index,
+ )
+ }
+ >
+ {editorState.importingImage ? "Importing…" : "Replace image"}
+ </EditorButton>
+ <EditorButton
+ variant="danger"
+ onClick={() =>
+ projectActions.deleteOverlaySegments("image", [props.index])
+ }
+ >
+ Delete
+ </EditorButton>
+ </div>
- <Field name="Position (% of canvas)">
- <div class="grid grid-cols-2 gap-2">
- <For each={["x", "y"] as const}>
- {(axis) => (
- <label class="flex items-center gap-2 text-xs text-gray-11">
- {axis.toUpperCase()}
- <input
- type="number"
- aria-label={`Image center ${axis} (%)`}
- class="min-w-0 w-full rounded border border-gray-5 bg-gray-2 px-2 py-1"
- min={0}
- max={100}
- step={0.1}
- value={Math.round(image().center[axis] * 1000) / 10}
- onChange={(event) => {
- const value = event.currentTarget.valueAsNumber;
- if (Number.isFinite(value))
- setProject(
- "timeline",
- "imageSegments",
- props.index,
- "center",
- axis,
- Math.min(100, Math.max(0, value)) / 100,
- );
- }}
- />
- </label>
- )}
- </For>
- </div>
- </Field>
- <Field name="Size (% of canvas)">
- <div class="grid grid-cols-2 gap-2">
- <For each={["x", "y"] as const}>
- {(axis) => (
- <label class="flex items-center gap-2 text-xs text-gray-11">
- {axis === "x" ? "W" : "H"}
- <input
- type="number"
- aria-label={`Image ${axis === "x" ? "width" : "height"} (%)`}
- class="min-w-0 w-full rounded border border-gray-5 bg-gray-2 px-2 py-1"
- min={0.1}
- max={400}
- step={0.1}
- value={Math.round(image().size[axis] * 1000) / 10}
- onChange={(event) => {
- const value = event.currentTarget.valueAsNumber;
- if (!Number.isFinite(value)) return;
- const next = Math.min(400, Math.max(0.1, value)) / 100;
- const current = image().size;
- const scale = next / Math.max(0.001, current[axis]);
- setProject(
- "timeline",
- "imageSegments",
- props.index,
- "size",
- image().lockAspect
- ? { x: current.x * scale, y: current.y * scale }
- : { ...current, [axis]: next },
- );
- }}
- />
- </label>
- )}
- </For>
- </div>
- </Field>
- <Field name="Opacity">
- <Slider
- value={[image().opacity * 100]}
- minValue={0}
- maxValue={100}
- step={1}
- formatTooltip="%"
- onChange={(value) =>
- setProject(
- "timeline",
- "imageSegments",
- props.index,
- "opacity",
- value[0] / 100,
- )
- }
- />
- </Field>
- <Field name="Rotation">
- <Slider
- value={[image().rotation]}
- minValue={-180}
- maxValue={180}
- step={1}
- formatTooltip={(value) => `${value}°`}
- onChange={(value) =>
- setProject(
- "timeline",
- "imageSegments",
- props.index,
- "rotation",
- value[0],
- )
- }
- />
- </Field>
- <Field name="Rounded corners">
- <Slider
- value={[image().rounding]}
- minValue={0}
- maxValue={100}
- step={1}
- formatTooltip="%"
- onChange={(value) =>
- setProject(
- "timeline",
- "imageSegments",
- props.index,
- "rounding",
- value[0],
- )
++ <div class="flex flex-col gap-2.5 rounded-lg bg-ed-card-2 p-3">
++ <SectionLabel name="Arrange on canvas" />
++ <p class="text-[11px] leading-relaxed text-ed-text-3">
++ Drag the image to move it. Pull a corner to resize, or use the
++ rotation handle to turn it. Arrow keys nudge it into place.
++ </p>
++ <EditorButton
++ class="w-full justify-center"
++ leftIcon={<IconLucideCrosshair class="size-4" />}
++ onClick={() =>
++ setProject("timeline", "imageSegments", props.index, "center", {
++ x: 0.5,
++ y: 0.5,
++ })
+ }
- />
- </Field>
- <Field
- name="Lock aspect ratio"
- value={
++ >
++ Center on canvas
++ </EditorButton>
++ </div>
++ <div class="flex flex-col">
++ <Field
++ inline
++ name="Opacity"
++ value={`${(image().opacity * 100).toFixed(1)}%`}
++ >
++ <Slider
++ value={[image().opacity * 100]}
++ minValue={0}
++ maxValue={100}
++ step={1}
++ formatTooltip="%"
++ onChange={(value) =>
++ setProject(
++ "timeline",
++ "imageSegments",
++ props.index,
++ "opacity",
++ value[0] / 100,
++ )
++ }
++ />
++ </Field>
++ <Field inline name="Rotation" value={`${image().rotation}°`}>
++ <Slider
++ value={[image().rotation]}
++ minValue={-180}
++ maxValue={180}
++ step={1}
++ formatTooltip={(value) => `${value}°`}
++ onChange={(value) =>
++ setProject(
++ "timeline",
++ "imageSegments",
++ props.index,
++ "rotation",
++ value[0],
++ )
++ }
++ />
++ </Field>
++ <Field
++ inline
++ name="Rounded corners"
++ value={`${image().rounding.toFixed(1)}%`}
++ >
++ <Slider
++ value={[image().rounding]}
++ minValue={0}
++ maxValue={100}
++ step={1}
++ formatTooltip="%"
++ onChange={(value) =>
++ setProject(
++ "timeline",
++ "imageSegments",
++ props.index,
++ "rounding",
++ value[0],
++ )
++ }
++ />
++ </Field>
++ <Field inline name="Lock aspect ratio">
+ <Toggle
+ checked={image().lockAspect}
+ onChange={(value) =>
+ setProject(
+ "timeline",
+ "imageSegments",
+ props.index,
+ "lockAspect",
+ value,
+ )
+ }
+ />
- }
- />
- <Field
- name="Flip horizontally"
- value={
++ </Field>
++ <Field inline name="Flip horizontally">
+ <Toggle
+ checked={image().flipX}
+ onChange={(value) =>
+ setProject(
+ "timeline",
+ "imageSegments",
+ props.index,
+ "flipX",
+ value,
+ )
+ }
+ />
- }
- />
- <Field
- name="Flip vertically"
- value={
++ </Field>
++ <Field inline name="Flip vertically">
+ <Toggle
+ checked={image().flipY}
+ onChange={(value) =>
+ setProject(
+ "timeline",
+ "imageSegments",
+ props.index,
+ "flipY",
+ value,
+ )
+ }
+ />
- }
- />
++ </Field>
++ </div>
+ <EditorButton
+ onClick={() =>
+ setProject("timeline", "imageSegments", props.index, {
+ center: { x: 0.5, y: 0.5 },
+ rotation: 0,
+ flipX: false,
+ flipY: false,
+ })
+ }
+ >
+ Center and reset rotation
+ </EditorButton>
- <p class="text-xs text-gray-10">
++ <p class="text-[11px] leading-relaxed text-ed-text-3">
+ Drag the image to move it. Drag a corner to resize. Shift
+ temporarily disables snapping.
+ </p>
+ </div>
+ )}
+ </Show>
+ );
+}
diff --cc apps/desktop/src/routes/editor/index.tsx
index b4cabd2d1,b4cabd2d1..7044a4e68
--- a/apps/desktop/src/routes/editor/index.tsx
+++ b/apps/desktop/src/routes/editor/index.tsx
@@@ -45,7 -45,7 +45,7 @@@ export default function ()
return (
<div
class={cx(
-- "flex flex-col w-screen h-screen dark:bg-gray-1 bg-gray-2",
++ "flex flex-col w-screen h-screen bg-ed-window text-ed-text-1",
!(
ostype() === "windows" || !generalSettings.data?.windowTransparency
) && "bg-transparent-window",
diff --cc apps/desktop/src/routes/editor/keyboard-timing.test.ts
index 000000000,bcf37402e..3cae3064b
mode 000000,100644..100644
--- a/apps/desktop/src/routes/editor/keyboard-timing.test.ts
+++ b/apps/desktop/src/routes/editor/keyboard-timing.test.ts
@@@ -1,0 -1,332 +1,334 @@@
+ import { describe, expect, it } from "vitest";
+ import type { KeyboardTrackSegment, SegmentRecordings } from "~/utils/tauri";
+ import { mapEditedTimeToSource } from "./captions";
+ import { timelineShiftAfterClipDurationChange } from "./clip-transitions";
+ import {
+ generateForStableKeyboardTimeline,
+ mapKeyboardTrackTimes,
+ rippleDeleteKeyboardTrack,
+ rippleKeyboardTrack,
+ splitKeyboardSegment,
+ } from "./keyboard-timing";
+ import { defaultTextSegment } from "./text";
+ import { defaultCamera3DTracks } from "./three-d";
+ import {
+ deleteClipAndRippleAllTracks,
+ rippleDeleteAllTracks,
+ rippleDeleteFromTrack,
+ } from "./timeline-utils";
+
+ function keyboardSegment(
+ start: number,
+ end: number,
+ displayText: string,
+ offsets: number[],
+ ): KeyboardTrackSegment {
+ return {
+ id: "keyboard-1",
+ start,
+ end,
+ displayText,
+ keys: offsets.map((timeOffset, index) => ({
+ key: displayText[index] ?? "Key",
+ timeOffset,
+ })),
+ };
+ }
+
+ describe("keyboard output timing", () => {
+ it("moves a source-time key at 8s to output time 7s after deleting 5s to 6s", () => {
+ const timeline = {
+ segments: [{ start: 0, end: 10, timescale: 1 }],
+ transitions: [],
+ keyboardSegments: [keyboardSegment(8, 9, "a", [0])],
+ };
+
+ rippleDeleteAllTracks(timeline, 5, 6);
+
+ expect(timeline.keyboardSegments[0]).toMatchObject({
+ start: 7,
+ end: 8,
+ keys: [{ timeOffset: 0 }],
+ });
+ });
+
+ it("filters a cut from a one-character-per-key group and rebases later keys", () => {
+ const segments = [keyboardSegment(4, 8, "abc", [0, 1500, 2500])];
+
+ rippleDeleteKeyboardTrack(segments, 5, 6);
+
+ expect(segments).toHaveLength(1);
+ expect(segments[0]).toMatchObject({
+ start: 4,
+ end: 7,
+ displayText: "ac",
+ keys: [{ timeOffset: 0 }, { timeOffset: 1500 }],
+ });
+ });
+
+ it("removes an atomic shortcut instead of corrupting its display text", () => {
+ const segment = keyboardSegment(4, 8, "ab", [0, 1500, 2500]);
+ segment.displayText = "⌘K";
+ const segments = [segment];
+
+ rippleDeleteKeyboardTrack(segments, 5, 6);
+
+ expect(segments).toEqual([]);
+ });
+
+ it("scales per-key offsets with a 2x clip speed change", () => {
+ const segments = [keyboardSegment(0, 4, "abc", [0, 1000, 2000])];
+ const shift = (time: number) =>
+ timelineShiftAfterClipDurationChange(time, 0, 0, 0, 4, 2);
+
+ mapKeyboardTrackTimes(segments, (time) => time + shift(time));
+
+ expect(segments[0]).toMatchObject({
+ start: 0,
+ end: 2,
+ keys: [{ timeOffset: 0 }, { timeOffset: 500 }, { timeOffset: 1000 }],
+ });
+ });
+
+ it("rebases key offsets when a transition changes", () => {
+ const segments = [keyboardSegment(4, 7, "ab", [0, 2000])];
+
+ rippleKeyboardTrack(segments, 5, -1);
+
+ expect(segments[0]).toMatchObject({
+ start: 4,
+ end: 6,
+ keys: [{ timeOffset: 0 }, { timeOffset: 1000 }],
+ });
+ });
+
+ it("leaves a keyboard segment ending at a transition boundary unchanged", () => {
+ const segments = [keyboardSegment(4, 5, "a", [0])];
+
+ rippleKeyboardTrack(segments, 5, -1);
+
+ expect(segments[0]).toMatchObject({
+ start: 4,
+ end: 5,
+ keys: [{ timeOffset: 0 }],
+ });
+ });
+
+ it("maps a retained right tail to the shifted cut end", () => {
+ const segments = [keyboardSegment(5.5, 8, "a", [500])];
+ const overlays = [{ start: 5.5, end: 8 }];
+
+ rippleDeleteKeyboardTrack(segments, 5, 6, 0.5);
+ rippleDeleteFromTrack(overlays, 5, 6, 0.5);
+
+ expect(segments[0]).toMatchObject({
+ start: 5.5,
+ end: 7.5,
+ keys: [{ timeOffset: 0 }],
+ });
+ expect(overlays).toEqual([{ start: 5.5, end: 7.5 }]);
+ });
+
+ it("whole-clip deletion removes holds and uses the actual transition duration", () => {
+ const timeline = {
+ segments: [
+ { start: 0, end: 4, timescale: 1 },
+ { start: 0, end: 4, timescale: 1 },
+ { start: 0, end: 4, timescale: 1 },
+ ],
+ transitions: [
+ { segmentIndex: 1, type: "cross-fade" as const, duration: 1 },
+ { segmentIndex: 2, type: "cross-fade" as const, duration: 1 },
+ ],
+ textSegments: [
+ { start: 4, end: 5, enabled: true, layout: "fullscreen" as const },
+ { start: 7, end: 8, enabled: true, layout: "fullscreen" as const },
+ ],
++ styleSegments: [{ start: 10, end: 11 }],
+ zoomSegments: [{ start: 10, end: 11 }],
+ keyboardSegments: [keyboardSegment(3, 9, "abc", [500, 2500, 5500])],
+ audioSegments: [{ start: 5, end: 10, trimStart: 2, fadeIn: 1 }],
+ maskSegments: [
+ {
+ start: 5,
+ end: 10,
+ keyframes: {
+ position: [{ time: 1 }, { time: 4 }, { time: 4.5 }],
+ },
+ },
+ ],
+ camera3dSegments: [
+ { start: 4, end: 5, tracks: defaultCamera3DTracks() },
+ {
+ start: 10,
+ end: 14,
+ tracks: {
+ ...defaultCamera3DTracks(),
+ zoom: [{ time: 2, value: 1, outEasing: null, inEasing: null }],
+ },
+ },
+ ],
+ };
+
+ expect(deleteClipAndRippleAllTracks(timeline, 1)).toBe(true);
+ expect(timeline.segments).toHaveLength(2);
+ expect(timeline.transitions).toEqual([]);
+ expect(timeline.textSegments).toEqual([
+ { start: 4, end: 5, enabled: true, layout: "fullscreen" },
+ ]);
++ expect(timeline.styleSegments).toEqual([{ start: 7, end: 8 }]);
+ expect(timeline.zoomSegments).toEqual([{ start: 7, end: 8 }]);
+ expect(timeline.keyboardSegments[0]).toMatchObject({
+ start: 3,
+ end: 6,
+ displayText: "ac",
+ keys: [{ timeOffset: 500 }, { timeOffset: 2500 }],
+ });
+ expect(timeline.audioSegments).toEqual([
+ { start: 4, end: 7, trimStart: 4, fadeIn: 0 },
+ ]);
+ expect(timeline.maskSegments[0]).toMatchObject({
+ start: 4,
+ end: 7,
+ keyframes: { position: [{ time: 2 }, { time: 2.5 }] },
+ });
+ expect(timeline.camera3dSegments).toHaveLength(1);
+ expect(timeline.camera3dSegments[0]).toMatchObject({
+ start: 7,
+ end: 11,
+ tracks: { zoom: [{ time: 2, value: 1 }] },
+ });
+ });
+
+ it("cuts camera keyframes without rescaling retained source timing", () => {
+ const tracks = defaultCamera3DTracks();
+ tracks.zoom = [
+ {
+ time: 2,
+ value: 2,
+ outEasing: [0, 0],
+ inEasing: null,
+ },
+ {
+ time: 5,
+ value: 5,
+ outEasing: [0, 0],
+ inEasing: [1, 1],
+ },
+ {
+ time: 8,
+ value: 8,
+ outEasing: null,
+ inEasing: [1, 1],
+ },
+ ];
+ const timeline = {
+ segments: [{ start: 0, end: 10, timescale: 1 }],
+ camera3dSegments: [
+ {
+ start: 0,
+ end: 10,
+ tracks,
+ transitionIn: 0.2,
+ transitionOut: 0.3,
+ },
+ ],
+ };
+
+ rippleDeleteAllTracks(timeline, 3, 6);
+
+ expect(timeline.camera3dSegments[0]).toMatchObject({
+ start: 0,
+ end: 7,
+ transitionIn: 0.2,
+ transitionOut: 0.3,
+ tracks: {
+ zoom: [
+ { time: 2, value: 2, outEasing: [0, 0], inEasing: null },
+ { time: 3, value: 3, outEasing: null, inEasing: [1, 1] },
+ { time: 3, value: 6, outEasing: [0, 0], inEasing: null },
+ { time: 5, value: 8, outEasing: null, inEasing: [1, 1] },
+ ],
+ },
+ });
+ });
+
+ it("retains the last clip", () => {
+ const timeline = {
+ segments: [{ start: 0, end: 4, timescale: 1 }],
+ keyboardSegments: [keyboardSegment(1, 2, "a", [0])],
+ };
+
+ expect(deleteClipAndRippleAllTracks(timeline, 0)).toBe(false);
+ expect(timeline.segments).toHaveLength(1);
+ expect(timeline.keyboardSegments).toHaveLength(1);
+
+ rippleDeleteAllTracks(timeline, 0, 4, 0);
+ expect(timeline.segments).toHaveLength(1);
+ expect(timeline.keyboardSegments).toHaveLength(1);
+ });
+
+ it("manual split partitions generated keys and preserves static segments", () => {
+ const generated = keyboardSegment(10, 13, "abc", [0, 1000, 2000]);
+ const generatedParts = splitKeyboardSegment(generated, 11, "keyboard-2");
+ expect(generatedParts?.[0]).toMatchObject({
+ id: "kb-edit-keyboard-1",
+ end: 11,
+ displayText: "a",
+ keys: [{ timeOffset: 0 }],
+ });
+ expect(generatedParts?.[1]).toMatchObject({
+ id: "kb-edit-keyboard-2",
+ start: 11,
+ displayText: "bc",
+ keys: [{ timeOffset: 0 }, { timeOffset: 1000 }],
+ });
+
+ const manual = keyboardSegment(10, 13, "Custom", []);
+ const manualParts = splitKeyboardSegment(manual, 11, "kb-edit-keyboard-3");
+ expect(manualParts?.map((part) => part.id)).toEqual([
+ "kb-edit-keyboard-1",
+ "kb-edit-keyboard-3",
+ ]);
+ expect(manualParts?.map((part) => part.displayText)).toEqual([
+ "Custom",
+ "Custom",
+ ]);
+ });
+
+ it("retries generation once when the timeline changes during the command", async () => {
+ let signature = "first";
+ let callCount = 0;
+ const result = await generateForStableKeyboardTimeline(
+ () => signature,
+ async () => {
+ callCount++;
+ if (callCount === 1) signature = "second";
+ return callCount;
+ },
+ );
+
+ expect(result).toBe(2);
+ expect(callCount).toBe(2);
+ });
+
+ it("inverts legacy caption output time through fullscreen holds", () => {
+ const hold = {
+ ...defaultTextSegment(2, 4),
+ layout: "fullscreen" as const,
+ };
+ const recordings = [{ display: { duration: 10 } } as SegmentRecordings];
+
+ expect(
+ mapEditedTimeToSource(
+ 5,
+ [{ start: 0, end: 10, timescale: 1 }],
+ recordings,
+ [],
+ undefined,
+ "incoming",
+ [hold],
+ ),
+ ).toBe(3);
+ });
+ });
diff --cc apps/desktop/src/routes/editor/style-segment-config.tsx
index 9305f3baf,000000000..562c6f2f8
mode 100644,000000..100644
--- a/apps/desktop/src/routes/editor/style-segment-config.tsx
+++ b/apps/desktop/src/routes/editor/style-segment-config.tsx
@@@ -1,159 -1,0 +1,167 @@@
+import { Show } from "solid-js";
+import { Toggle } from "~/components/Toggle";
+import { useEditorContext } from "./context";
+import type { StyleGroup } from "./style";
- import { EditorButton, Field, Slider } from "./ui";
++import { EditorButton, Field, Section, Slider } from "./ui";
+
+export function StyleGroupToggle(props: { group: StyleGroup }) {
+ const { selectedStyle, toggleStyleGroup } = useEditorContext();
+ return (
+ <Show when={selectedStyle()}>
+ {(style) => (
+ <Field
- name={`Override ${props.group}`}
++ name={`Customize ${props.group}`}
+ value={
+ <Toggle
+ checked={style().overrides[props.group] != null}
+ onChange={(value) => toggleStyleGroup(props.group, value)}
+ />
+ }
+ >
- <p class="text-xs text-gray-10">
++ <p class="text-[11px] leading-relaxed text-ed-text-3">
+ {style().overrides[props.group] == null
- ? "Inherits earlier styles, then global settings. Enable to copy global settings into this style."
- : "Changes apply to this style only. Disable to inherit earlier styles and global settings."}
++ ? "Uses the styles underneath, then your global settings. Turn on to customize."
++ : "Changes apply only during this style. Turn off to use the styles underneath."}
+ </p>
+ </Field>
+ )}
+ </Show>
+ );
+}
+
+export function StyleSegmentConfig() {
+ const {
+ selectedStyle,
+ editorState,
+ setEditorState,
+ setProject,
+ exitStyleScope,
+ projectActions,
+ } = useEditorContext();
+ const index = () => editorState.styleEditIndex;
+ return (
+ <Show when={selectedStyle()}>
+ {(style) => (
+ <div
- class="shrink-0 space-y-3 border-b border-purple-7/40 bg-purple-3/40 p-3"
++ class="shrink-0 border-b border-purple-7/40 bg-purple-3/40 p-3"
+ data-style-scope
+ >
- <div class="flex items-center justify-between gap-2">
- <span class="text-xs font-semibold text-gray-12">
- Editing Style · {style().start.toFixed(2)}–
- {style().end.toFixed(2)}s
- </span>
- <EditorButton onClick={exitStyleScope}>
- Global settings
- </EditorButton>
- </div>
- <div class="flex items-center gap-2">
- <input
- aria-label="Style name"
- class="min-w-0 flex-1 rounded border border-gray-5 bg-gray-2 px-2 py-1 text-sm"
- value={style().name}
- onChange={(event) => {
- const i = index();
- if (i !== null)
- setProject(
- "timeline",
- "styleSegments",
- i,
- "name",
- event.currentTarget.value.trim() || "Style",
- );
- }}
- />
- <Toggle
- checked={style().enabled}
- onChange={(value) => {
- const i = index();
- if (i !== null)
- setProject("timeline", "styleSegments", i, "enabled", value);
- }}
- />
- </div>
- <Field
- name="Override camera-only padding"
- value={
- <Toggle
- checked={style().overrides.cameraOnlyPadding != null}
- onChange={(enabled) => {
- const i = index();
- if (i !== null)
- setProject(
- "timeline",
- "styleSegments",
- i,
- "overrides",
- "cameraOnlyPadding",
- enabled ? 10 : null,
- );
- }}
- />
++ <Section
++ name={`Editing style · ${style().start.toFixed(2)}–${style().end.toFixed(2)}s`}
++ action={
++ <EditorButton size="sm" onClick={exitStyleScope}>
++ Global settings
++ </EditorButton>
+ }
+ >
- <p class="text-xs text-gray-10">
- Use a Camera Only scene. Padding reveals the background around the
- camera.
- </p>
- <Show when={style().overrides.cameraOnlyPadding != null}>
- <Slider
- value={[style().overrides.cameraOnlyPadding ?? 0]}
- minValue={0}
- maxValue={40}
- step={0.1}
- formatTooltip="%"
- onChange={(value) => {
- const i = index();
- if (i !== null)
- setProject(
- "timeline",
- "styleSegments",
- i,
- "overrides",
- "cameraOnlyPadding",
- Math.min(40, Math.max(0, value[0])),
- );
- }}
- />
- </Show>
- </Field>
- <div class="flex items-center justify-between">
- <EditorButton
- onClick={() => {
- setEditorState("playbackTime", style().start);
- setEditorState("previewTime", null);
- }}
- >
- View style
- </EditorButton>
- <EditorButton
- variant="danger"
- onClick={() => {
- const i = index();
- if (i !== null)
- projectActions.deleteOverlaySegments("style", [i]);
- }}
- >
- Delete style
- </EditorButton>
- </div>
- <p class="text-[11px] text-gray-10">
- Larger lane numbers take priority. Within a lane, later styles win.
- Groups without an override inherit earlier styles, then global
- settings.
- </p>
++ <div class="flex flex-col gap-3">
++ <div class="flex items-center gap-2">
++ <input
++ aria-label="Style name"
++ class="h-8 min-w-0 flex-1 rounded-[7px] border-0 bg-ed-ctl px-2 text-[13px] text-ed-text-1 caret-ed-accent outline-hidden transition-colors duration-150 placeholder:text-ed-text-3 hover:bg-ed-ctl-hover focus:bg-ed-ctl-hover focus:ring-1 focus:ring-ed-accent"
++ value={style().name}
++ onChange={(event) => {
++ const i = index();
++ if (i !== null)
++ setProject(
++ "timeline",
++ "styleSegments",
++ i,
++ "name",
++ event.currentTarget.value.trim() || "Style",
++ );
++ }}
++ />
++ <Toggle
++ checked={style().enabled}
++ onChange={(value) => {
++ const i = index();
++ if (i !== null)
++ setProject(
++ "timeline",
++ "styleSegments",
++ i,
++ "enabled",
++ value,
++ );
++ }}
++ />
++ </div>
++ <Field
++ name="Override camera-only padding"
++ value={
++ <Toggle
++ checked={style().overrides.cameraOnlyPadding != null}
++ onChange={(enabled) => {
++ const i = index();
++ if (i !== null)
++ setProject(
++ "timeline",
++ "styleSegments",
++ i,
++ "overrides",
++ "cameraOnlyPadding",
++ enabled ? 10 : null,
++ );
++ }}
++ />
++ }
++ >
++ <p class="text-[11px] leading-relaxed text-ed-text-3">
++ Use a Camera Only scene. Padding reveals the background around
++ the camera.
++ </p>
++ <Show when={style().overrides.cameraOnlyPadding != null}>
++ <Slider
++ value={[style().overrides.cameraOnlyPadding ?? 0]}
++ minValue={0}
++ maxValue={40}
++ step={0.1}
++ formatTooltip="%"
++ onChange={(value) => {
++ const i = index();
++ if (i !== null)
++ setProject(
++ "timeline",
++ "styleSegments",
++ i,
++ "overrides",
++ "cameraOnlyPadding",
++ Math.min(40, Math.max(0, value[0])),
++ );
++ }}
++ />
++ </Show>
++ </Field>
++ <div class="flex items-center justify-between">
++ <EditorButton
++ onClick={() => {
++ setEditorState("playbackTime", style().start);
++ setEditorState("previewTime", null);
++ }}
++ >
++ View style
++ </EditorButton>
++ <EditorButton
++ variant="danger"
++ onClick={() => {
++ const i = index();
++ if (i !== null)
++ projectActions.deleteOverlaySegments("style", [i]);
++ }}
++ >
++ Delete style
++ </EditorButton>
++ </div>
++ <p class="text-[11px] leading-relaxed text-ed-text-3">
++ Styles higher in the timeline take priority. Drag a track handle
++ to change the order. Settings you leave unchanged come from the
++ styles underneath.
++ </p>
++ </div>
++ </Section>
+ </div>
+ )}
+ </Show>
+ );
+}
diff --cc apps/desktop/src/routes/editor/three-d.test.ts
index 0146d9945,0146d9945..fe0bfcaaa
--- a/apps/desktop/src/routes/editor/three-d.test.ts
+++ b/apps/desktop/src/routes/editor/three-d.test.ts
@@@ -11,12 -11,12 +11,14 @@@ import
CAMERA3D_MIN_SHOT_DURATION,
CAMERA3D_PROPERTY_KEYS,
CAMERA3D_SCENES,
++ CAMERA3D_STARTER_SCENES,
CAMERA3D_TRACK_KEYS,
type Camera3DKeyframe,
type Camera3DProperties,
type Camera3DScene,
type Camera3DSegment,
camera3DPosesEqual,
++ camera3DSceneRange,
DEFAULT_IN_EASING,
DEFAULT_OUT_EASING,
defaultCamera3DSegment,
@@@ -1062,3 -1062,3 +1064,71 @@@ describe("flipCamera3DSegment", () =>
expect(segment.blur.focusY).toBeCloseTo(0.64, 9);
});
});
++
++describe("3D scene creation", () => {
++ it("starts at the playhead and fits the end of short recordings", () => {
++ expect(camera3DSceneRange([], 4, 6, 30)).toEqual({ start: 4, end: 10 });
++ expect(camera3DSceneRange([], 9, 6, 10)).toEqual({ start: 4, end: 10 });
++ expect(camera3DSceneRange([], 0, 6, 0.3)).toEqual({ start: 0, end: 0.3 });
++ });
++
++ it("preserves existing scenes and shortens to the available gap", () => {
++ const existing = [
++ { start: 8, end: 12 },
++ { start: 0, end: 3 },
++ ];
++ expect(camera3DSceneRange(existing, 3, 6, 20)).toEqual({
++ start: 3,
++ end: 8,
++ });
++ expect(camera3DSceneRange(existing, 12, 6, 20)).toEqual({
++ start: 12,
++ end: 18,
++ });
++ expect(camera3DSceneRange(existing, 9, 6, 20)).toBeNull();
++ expect(camera3DSceneRange([{ start: 0, end: 20 }], 20, 6, 20)).toBeNull();
++ expect(existing).toEqual([
++ { start: 8, end: 12 },
++ { start: 0, end: 3 },
++ ]);
++ });
++
++ it("rejects invalid times and gaps too small to use", () => {
++ for (const value of [
++ Number.NaN,
++ Number.POSITIVE_INFINITY,
++ Number.NEGATIVE_INFINITY,
++ ]) {
++ expect(camera3DSceneRange([], value, 6, 20)).toBeNull();
++ expect(camera3DSceneRange([], 0, value, 20)).toBeNull();
++ expect(camera3DSceneRange([], 0, 6, value)).toBeNull();
++ }
++ expect(camera3DSceneRange([], 0, 0, 20)).toBeNull();
++ expect(camera3DSceneRange([], 0, 6, 0)).toBeNull();
++ expect(
++ camera3DSceneRange(
++ [
++ { start: 0, end: 3 },
++ { start: 3.2, end: 6 },
++ ],
++ 3,
++ 6,
++ 20,
++ ),
++ ).toBeNull();
++ });
++
++ it("creates a complete animated move from each starter", () => {
++ expect(CAMERA3D_STARTER_SCENES.map((scene) => scene.id)).toEqual([
++ "glide-across",
++ "unfold",
++ "pull-back",
++ ]);
++ for (const scene of CAMERA3D_STARTER_SCENES) {
++ const segments = applySceneToRange(scene, 4, 10);
++ expect(segments).toHaveLength(1);
++ expect(segments[0]).toMatchObject({ start: 4, end: 10, enabled: true });
++ expect(hasCamera3DMotion(segments[0])).toBe(true);
++ }
++ });
++});
diff --cc apps/desktop/src/routes/editor/three-d.ts
index e2fb93ccf,e2fb93ccf..87358adfd
--- a/apps/desktop/src/routes/editor/three-d.ts
+++ b/apps/desktop/src/routes/editor/three-d.ts
@@@ -795,6 -795,6 +795,61 @@@ export const CAMERA3D_SCENES: Camera3DS
},
];
++export const CAMERA3D_STARTER_SCENES = [
++ "glide-across",
++ "unfold",
++ "pull-back",
++].map((id): Camera3DScene => {
++ const template = motionTemplateById(id);
++ return { id, name: template.name, shots: [templateShot(template, 1)] };
++});
++
++export const CAMERA3D_SCENE_DESCRIPTIONS: Record<string, string> = {
++ "glide-across": "Move smoothly across the details",
++ unfold: "Reveal your screen with a gentle tilt",
++ "pull-back": "Pull out to show the bigger picture",
++ showcase: "Close-up, overhead sweep, then zoom in",
++ "product-tour": "Reveal, orbit, then settle on your screen",
++ "punch-in": "Zoom into a detail, then pull back",
++};
++
++export type Camera3DSetup = {
++ sceneId: string;
++ start: number;
++ duration: number;
++};
++
++export const findCamera3DScene = (id: string) =>
++ [...CAMERA3D_STARTER_SCENES, ...CAMERA3D_SCENES].find(
++ (scene) => scene.id === id,
++ );
++
++export function camera3DSceneRange(
++ segments: readonly { start: number; end: number }[],
++ time: number,
++ duration: number,
++ total: number,
++): { start: number; end: number } | null {
++ if (
++ ![time, duration, total].every(Number.isFinite) ||
++ duration <= 0 ||
++ total <= 0
++ )
++ return null;
++ const start = Math.min(Math.max(time, 0), total);
++ let gapStart = 0;
++ let gapEnd = total;
++ for (const segment of segments) {
++ if (segment.start <= start && start < segment.end) return null;
++ if (segment.end <= start) gapStart = Math.max(gapStart, segment.end);
++ else gapEnd = Math.min(gapEnd, segment.start);
++ }
++ const length = Math.min(duration, gapEnd - gapStart);
++ if (length < Math.min(0.5, total)) return null;
++ const fittedStart = Math.max(gapStart, Math.min(start, gapEnd - length));
++ return { start: fittedStart, end: fittedStart + length };
++}
++
/**
* The scene's leading `count` shots with their weights renormalized, so a
* shorter sequence still fills the whole range it is laid onto. Asking for
diff --cc apps/desktop/src/routes/editor/timeline-tracks.test.ts
index 000000000,000000000..2910126a1
new file mode 100644
--- /dev/null
+++ b/apps/desktop/src/routes/editor/timeline-tracks.test.ts
@@@ -1,0 -1,0 +1,129 @@@
++import { describe, expect, it } from "vitest";
++import {
++ getOverlayTrackRows,
++ getOverlayZIndex,
++ moveOverlayTrack,
++ moveTrackLane,
++ type OverlayTrack,
++ removeOverlayTrack,
++ resolveOverlayOrder,
++ trackInsertionIndex,
++} from "./timelineTracks";
++
++const segments = () => [
++ { name: "back", track: 0, start: 0, end: 4 },
++ { name: "middle", track: 1, start: 1, end: 5 },
++ { name: "front", track: 2, start: 0, end: 4 },
++ { name: "later front", track: 2, start: 5, end: 8 },
++];
++
++describe("layer order", () => {
++ it("moves a whole lane to the front without changing timing or selection indices", () => {
++ const items = segments();
++ const selected = items[1];
++ moveTrackLane(items, 0, 2);
++ expect(items.map((item) => item.track)).toEqual([2, 0, 1, 1]);
++ expect(items[1]).toBe(selected);
++ expect(items.map(({ start, end }) => [start, end])).toEqual([
++ [0, 4],
++ [1, 5],
++ [0, 4],
++ [5, 8],
++ ]);
++ });
++
++ it("moves a lane behind its siblings and can restore the original order", () => {
++ const items = segments();
++ moveTrackLane(items, 2, 0);
++ expect(items.map((item) => item.track)).toEqual([1, 2, 0, 0]);
++ moveTrackLane(items, 0, 2);
++ expect(items).toEqual(segments());
++ });
++
++ it("supports empty lanes without collapsing them", () => {
++ const items = [segments()[0], segments()[2]];
++ moveTrackLane(items, 1, 2);
++ expect(items.map((item) => item.track)).toEqual([0, 1]);
++ });
++
++ it("ignores invalid drops", () => {
++ for (const [from, to] of [
++ [0, 0],
++ [-1, 0],
++ [0, -1],
++ [0.5, 1],
++ [0, Number.NaN],
++ ]) {
++ const items = segments();
++ moveTrackLane(items, from, to);
++ expect(items).toEqual(segments());
++ }
++ });
++});
++
++const visualStack: OverlayTrack[] = [
++ { kind: "text", track: 0 },
++ { kind: "image", track: 0 },
++ { kind: "mask", track: 0 },
++];
++
++describe("mixed visual layers", () => {
++ it("preserves legacy compositing order when no custom order exists", () => {
++ expect(resolveOverlayOrder(visualStack)).toEqual(visualStack);
++ });
++
++ it("moves an image above text without renumbering either lane", () => {
++ const moved = moveOverlayTrack(visualStack, visualStack[1], 0);
++ expect(moved).toEqual([visualStack[1], visualStack[0], visualStack[2]]);
++ expect(moveOverlayTrack(moved, visualStack[1], 1)).toEqual(visualStack);
++ });
++
++ it("discards stale and duplicate entries and places newly added layers in front", () => {
++ const added: OverlayTrack = { kind: "image", track: 1 };
++ const saved: OverlayTrack[] = [
++ visualStack[1],
++ visualStack[1],
++ { kind: "mask", track: 9 },
++ visualStack[0],
++ ];
++ expect(resolveOverlayOrder([added, ...visualStack], saved)).toEqual([
++ added,
++ visualStack[2],
++ visualStack[1],
++ visualStack[0],
++ ]);
++ });
++
++ it("preserves inactive layers and matches canvas hit order", () => {
++ const project = {
++ overlayOrder: [visualStack[1], visualStack[0]],
++ timeline: {
++ textSegments: [{ track: 0, start: 0, end: 1 }],
++ imageSegments: [{ track: 0, start: 10, end: 11 }],
++ },
++ };
++ expect(getOverlayTrackRows(project)).toEqual([
++ visualStack[1],
++ visualStack[0],
++ ]);
++ expect(getOverlayZIndex(project, "image", 0)).toBeGreaterThan(
++ getOverlayZIndex(project, "text", 0),
++ );
++ });
++
++ it("remaps references when an entire lane is deleted", () => {
++ const order: OverlayTrack[] = [{ kind: "image", track: 2 }, ...visualStack];
++ expect(removeOverlayTrack(order, "image", 0)).toEqual([
++ { kind: "image", track: 1 },
++ visualStack[0],
++ visualStack[2],
++ ]);
++ });
++
++ it("accepts gaps and outside row centers as insertion slots", () => {
++ expect(trackInsertionIndex([100, 160, 220], 50)).toBe(0);
++ expect(trackInsertionIndex([100, 160, 220], 130)).toBe(1);
++ expect(trackInsertionIndex([100, 160, 220], 190)).toBe(2);
++ expect(trackInsertionIndex([100, 160, 220], 270)).toBe(3);
++ });
++});
diff --cc apps/desktop/src/routes/editor/timeline-utils.ts
index e500fe001,dd82410ed..fdd616d13
--- a/apps/desktop/src/routes/editor/timeline-utils.ts
+++ b/apps/desktop/src/routes/editor/timeline-utils.ts
@@@ -154,15 -328,14 +328,16 @@@ export function rippleDeleteAllTracks
timeline: {
segments: Array<{ timescale: number; start: number; end: number }>;
transitions?: ClipTransition[] | null;
+ styleSegments?: Array<{ start: number; end: number }> | null;
+ imageSegments?: Array<{ start: number; end: number }> | null;
zoomSegments?: Array<{ start: number; end: number }> | null;
sceneSegments?: Array<{ start: number; end: number }> | null;
- maskSegments?: Array<{ start: number; end: number }> | null;
+ maskSegments?: RippleMaskSegment[] | null;
textSegments?: Array<HoldSourceSegment> | null;
captionSegments?: Array<{ start: number; end: number }> | null;
- keyboardSegments?: Array<{ start: number; end: number }> | null;
- audioSegments?: Array<{ start: number; end: number }> | null;
+ keyboardSegments?: KeyboardTrackSegment[] | null;
+ audioSegments?: RippleAudioSegment[] | null;
+ camera3dSegments?: RippleCamera3DSegment[] | null;
},
cutStart: number,
cutEnd: number,
@@@ -188,22 -376,36 +378,45 @@@
cutEnd,
requestedSegmentIndex,
);
+ timeline.transitions = nextTransitions;
+ const clipChanged =
+ previousSegments.length !== timeline.segments.length ||
+ previousSegments.some((segment, index) => {
+ const current = timeline.segments[index];
+ return (
+ !current ||
+ segment.start !== current.start ||
+ segment.end !== current.end ||
+ segment.timescale !== current.timescale
+ );
+ }) ||
+ previousTransitions.length !== nextTransitions.length ||
+ previousTransitions.some((transition, index) => {
+ const current = nextTransitions[index];
+ return (
+ !current ||
+ transition.segmentIndex !== current.segmentIndex ||
+ transition.type !== current.type ||
+ transition.duration !== current.duration
+ );
+ });
+ if (!clipChanged) return;
const shiftDuration = Math.max(
0,
- durationBefore -
- clipTimelineDuration(timeline.segments, timeline.transitions),
+ durationBefore - clipTimelineDuration(timeline.segments, nextTransitions),
);
const overlayShift =
- shiftDuration + (overlayCutEnd - overlayCutStart - (cutEnd - cutStart));
+ shiftDuration +
+ (overlayCutEnd - overlayCutStart - (trackCutEnd - trackCutStart));
+ for (const track of [timeline.styleSegments, timeline.imageSegments]) {
+ if (track)
+ rippleDeleteFromTrack(
+ track,
+ overlayCutStart,
+ overlayCutEnd,
+ overlayShift,
+ );
+ }
if (timeline.zoomSegments)
rippleDeleteFromTrack(
timeline.zoomSegments,
diff --cc apps/desktop/src/routes/editor/timelineTracks.ts
index ef4b07c63,ef4b07c63..b98eb401a
--- a/apps/desktop/src/routes/editor/timelineTracks.ts
+++ b/apps/desktop/src/routes/editor/timelineTracks.ts
@@@ -1,3 -1,3 +1,7 @@@
++import type { OverlayTrack, OverlayTrackKind } from "~/utils/tauri";
++
++export type { OverlayTrack, OverlayTrackKind } from "~/utils/tauri";
++
type TrackSegment = {
start: number;
end: number;
@@@ -94,3 -94,3 +98,124 @@@ export function getTrackRowsWithCount<
}
return rows;
}
++
++export function moveTrackLane<T extends TrackSegment>(
++ segments: T[],
++ from: number,
++ to: number,
++) {
++ if (
++ !Number.isInteger(from) ||
++ !Number.isInteger(to) ||
++ from < 0 ||
++ to < 0 ||
++ from === to
++ )
++ return;
++ for (const segment of segments) {
++ const lane = getSegmentTrack(segment);
++ if (lane === from) segment.track = to;
++ else if (from < to && lane > from && lane <= to) segment.track = lane - 1;
++ else if (from > to && lane >= to && lane < from) segment.track = lane + 1;
++ }
++}
++
++type OverlayProject = {
++ overlayOrder?: OverlayTrack[];
++ timeline?: {
++ textSegments?: TrackSegment[];
++ imageSegments?: TrackSegment[];
++ maskSegments?: TrackSegment[];
++ } | null;
++};
++
++export function isOverlayTrackKind(kind: string): kind is OverlayTrackKind {
++ return kind === "text" || kind === "image" || kind === "mask";
++}
++
++export function sameOverlayTrack(a: OverlayTrack, b: OverlayTrack) {
++ return a.kind === b.kind && a.track === b.track;
++}
++
++export function resolveOverlayOrder(
++ available: OverlayTrack[],
++ saved: OverlayTrack[] = [],
++) {
++ const ordered: OverlayTrack[] = [];
++ for (const track of available) {
++ if (
++ !saved.some((item) => sameOverlayTrack(item, track)) &&
++ !ordered.some((item) => sameOverlayTrack(item, track))
++ )
++ ordered.push(track);
++ }
++ for (const track of saved) {
++ if (
++ available.some((item) => sameOverlayTrack(item, track)) &&
++ !ordered.some((item) => sameOverlayTrack(item, track))
++ )
++ ordered.push(track);
++ }
++ return ordered;
++}
++
++export function getOverlayTrackRows(
++ project: OverlayProject,
++ counts?: Partial<Record<OverlayTrackKind, number>>,
++) {
++ const timeline = project.timeline;
++ const available: OverlayTrack[] = [];
++ for (const kind of ["text", "image", "mask"] as const) {
++ const segments = timeline?.[`${kind}Segments`] ?? [];
++ for (const track of getTrackRowsWithCount(
++ segments,
++ counts?.[kind] ?? 0,
++ ).reverse())
++ available.push({ kind, track });
++ }
++ return resolveOverlayOrder(available, project.overlayOrder);
++}
++
++export function moveOverlayTrack(
++ order: OverlayTrack[],
++ from: OverlayTrack,
++ insertionIndex: number,
++) {
++ if (!Number.isInteger(insertionIndex)) return order;
++ const source = order.find((track) => sameOverlayTrack(track, from));
++ if (!source) return order;
++ const next = order.filter((track) => !sameOverlayTrack(track, from));
++ next.splice(Math.max(0, Math.min(next.length, insertionIndex)), 0, source);
++ return next;
++}
++
++export function removeOverlayTrack(
++ order: OverlayTrack[] | undefined,
++ kind: OverlayTrackKind,
++ lane: number,
++) {
++ return (order ?? [])
++ .filter((track) => track.kind !== kind || track.track !== lane)
++ .map((track) =>
++ track.kind === kind && track.track > lane
++ ? { ...track, track: track.track - 1 }
++ : track,
++ );
++}
++
++export function getOverlayZIndex(
++ project: OverlayProject,
++ kind: OverlayTrackKind,
++ track: number,
++) {
++ const order = getOverlayTrackRows(project);
++ const index = order.findIndex(
++ (item) => item.kind === kind && item.track === track,
++ );
++ return 100 + order.length - Math.max(0, index);
++}
++
++export function trackInsertionIndex(centers: number[], pointerY: number) {
++ const index = centers.findIndex((center) => pointerY < center);
++ return index < 0 ? centers.length : index;
++}
diff --cc apps/desktop/src/routes/editor/ui.tsx
index 789fc3b1c,789fc3b1c..3dd6577f8
--- a/apps/desktop/src/routes/editor/ui.tsx
+++ b/apps/desktop/src/routes/editor/ui.tsx
@@@ -10,11 -10,11 +10,13 @@@ import { cva, cx, type VariantProps } f
import {
type ComponentProps,
++ children,
createRoot,
createSignal,
type JSX,
mergeProps,
type ParentProps,
++ Show,
splitProps,
type ValidComponent,
} from "solid-js";
@@@ -22,6 -22,6 +24,60 @@@ import Tooltip from "~/components/Toolt
import { useEditorContext } from "./context";
import { TextInput } from "./TextInput";
++export function Section(
++ props: ParentProps<{ name: string; action?: JSX.Element; class?: string }>,
++) {
++ return (
++ <div class={cx("flex flex-col gap-2.5", props.class)}>
++ <div class="flex flex-row gap-2 items-center min-h-[22px]">
++ <SectionLabel name={props.name} />
++ <Show when={props.action}>
++ <div class="ml-auto flex flex-row gap-1 items-center">
++ {props.action}
++ </div>
++ </Show>
++ </div>
++ {props.children}
++ </div>
++ );
++}
++
++export function SectionLabel(props: { name: string; class?: string }) {
++ return (
++ <span class={cx("text-[12px] font-medium text-ed-text-2", props.class)}>
++ {props.name}
++ </span>
++ );
++}
++
++function FieldLabel(props: {
++ name: string;
++ badge?: string;
++ disabled?: boolean;
++ icon?: JSX.Element;
++ class?: string;
++}) {
++ return (
++ <span
++ data-disabled={props.disabled}
++ class={cx(
++ "flex flex-row items-center gap-1.5 text-[13px] font-normal text-ed-text-1 data-[disabled='true']:text-ed-text-3",
++ props.class,
++ )}
++ >
++ {props.icon}
++ {props.name}
++ <Show when={props.badge}>
++ {(badge) => (
++ <span class="px-1.5 py-0.5 text-[10px] font-medium rounded-full bg-ed-ctl text-ed-text-2">
++ {badge()}
++ </span>
++ )}
++ </Show>
++ </span>
++ );
++}
++
export function Field(
props: ParentProps<{
name: string;
@@@ -30,25 -30,25 +86,46 @@@
badge?: string;
class?: string;
disabled?: boolean;
++ inline?: boolean;
}>,
) {
return (
-- <div class={cx("flex flex-col gap-4", props.class)}>
-- <span
-- data-disabled={props.disabled}
-- class="flex flex-row items-center gap-1.5 text-gray-12 data-[disabled='true']:text-gray-10 font-medium text-sm"
-- >
-- {props.icon}
-- {props.name}
-- {props.badge && (
-- <span class="text-[10px] px-1.5 py-0.5 bg-gray-3 rounded-full text-gray-11 font-medium">
-- {props.badge}
-- </span>
-- )}
-- {props.value && <div class="ml-auto">{props.value}</div>}
-- </span>
-- {props.children}
-- </div>
++ <Show
++ when={props.inline}
++ fallback={
++ <div class={cx("flex flex-col gap-2", props.class)}>
++ <div class="flex flex-row gap-1.5 items-center">
++ <FieldLabel
++ name={props.name}
++ badge={props.badge}
++ disabled={props.disabled}
++ icon={props.icon}
++ />
++ <Show when={props.value}>
++ <div class="ml-auto">{props.value}</div>
++ </Show>
++ </div>
++ {props.children}
++ </div>
++ }
++ >
++ <div class={cx("flex flex-row gap-2 items-center h-[34px]", props.class)}>
++ <FieldLabel
++ name={props.name}
++ badge={props.badge}
++ disabled={props.disabled}
++ class="min-w-24 shrink-0 whitespace-nowrap"
++ />
++ <div class="flex flex-row flex-1 gap-2 justify-end items-center min-w-0 [&>.ed-slider]:flex-1">
++ {props.children}
++ </div>
++ <Show when={props.value}>
++ <div class="shrink-0 min-w-9 text-[11px] text-right tabular-nums text-ed-text-3">
++ {props.value}
++ </div>
++ </Show>
++ </div>
++ </Show>
);
}
@@@ -56,8 -56,8 +133,13 @@@ export function Subfield
props: ParentProps<{ name: string; class?: string; required?: boolean }>,
) {
return (
-- <div class={cx("flex flex-row justify-between items-center", props.class)}>
-- <span class="font-medium text-gray-12">
++ <div
++ class={cx(
++ "flex flex-row gap-2 justify-between items-center h-[34px]",
++ props.class,
++ )}
++ >
++ <span class="text-[13px] font-normal text-ed-text-1">
{props.name}
{props.required && (
<span class="ml-[2px] text-xs text-blue-500">*</span>
@@@ -69,11 -69,11 +151,13 @@@
}
export function Slider(
-- props: ComponentProps<typeof KSlider> & {
++ _props: ComponentProps<typeof KSlider> & {
formatTooltip?: string | ((v: number) => string);
history?: { pause: () => () => void };
++ thumbClass?: string;
},
) {
++ const [local, props] = splitProps(_props, ["thumbClass"]);
const context = useEditorContext();
const history = props.history ?? context?.projectHistory;
@@@ -90,7 -90,7 +174,7 @@@
<KSlider
{...props}
class={cx(
-- "relative px-1 h-8 flex flex-row justify-stretch items-center",
++ "ed-slider relative px-1 h-8 flex flex-row justify-stretch items-center",
props.class,
)}
onChange={(v) => {
@@@ -104,7 -104,7 +188,7 @@@
}}
>
<KSlider.Track
-- class="h-[0.3rem] transition-[height] relative mx-1 bg-gray-4 rounded-full w-full before:content-[''] before:absolute before:inset-0 before:-top-3 before:-bottom-3"
++ class="h-[3px] transition-[height] relative mx-1 bg-ed-ctl-active rounded-full w-full before:content-[''] before:absolute before:inset-0 before:-top-3 before:-bottom-3"
onPointerDown={() => {
setDragging(true);
createRoot((dispose) => {
@@@ -115,7 -115,7 +199,7 @@@
});
}}
>
-- <KSlider.Fill class="absolute -ml-2 h-full rounded-full bg-blue-9 data-disabled:bg-gray-8" />
++ <KSlider.Fill class="absolute -ml-2 h-full rounded-full bg-ed-accent data-disabled:bg-ed-ctl-active" />
<Tooltip
open={dragging() ? true : undefined}
getAnchorRect={() => {
@@@ -145,7 -145,7 +229,8 @@@
setDragging(false);
}}
class={cx(
-- "bg-gray-1 dark:bg-gray-12 border border-gray-6 shadow-md rounded-full outline-hidden size-4 -top-[6.3px] data-disabled:bg-gray-9 after:content-[''] after:absolute after:inset-0 after:-m-3",
++ "bg-ed-thumb rounded-full outline-hidden size-3.5 -top-[5.5px] shadow-[0_1px_3px_rgba(0,0,0,.25),0_0_0_.5px_rgba(0,0,0,.1)] data-disabled:opacity-50 after:content-[''] after:absolute after:inset-0 after:-m-3",
++ local.thumbClass,
)}
/>
</Tooltip>
@@@ -159,7 -159,7 +244,7 @@@ export function Input(props: ComponentP
<TextInput
{...props}
class={cx(
-- "rounded-lg bg-gray-2 hover:ring-1 py-[18px] hover:ring-gray-5 h-8 font-normal placeholder:text-black-transparent-40 text-xs caret-gray-500 transition-shadow duration-200 focus:ring-offset-1 focus:bg-gray-3 focus:ring-offset-gray-100 focus:ring-1 focus:ring-gray-10 px-2 w-full outline-hidden text-gray-12",
++ "rounded-[7px] bg-ed-ctl border-0 py-[18px] h-8 font-normal placeholder:text-ed-text-3 text-xs caret-ed-accent transition-shadow duration-200 hover:bg-ed-ctl-hover focus:bg-ed-ctl-hover focus:ring-1 focus:ring-ed-accent px-2 w-full outline-hidden text-ed-text-1",
props.class,
)}
/>
@@@ -184,7 -184,7 +269,7 @@@ export const Dialog =
<KDialog.Content
class={cx(
props.contentClass,
-- "z-50 text-sm rounded-[1.25rem] overflow-hidden border border-gray-3 bg-gray-1 min-w-88 data-expanded:animate-in data-expanded:fade-in data-expanded:zoom-in-95 origin-top data-closed:animate-out data-closed:fade-out data-closed:zoom-out-95",
++ "z-50 text-sm rounded-[1.25rem] overflow-hidden border-0 bg-ed-card shadow-ed-pop min-w-88 data-expanded:animate-in data-expanded:fade-in data-expanded:zoom-in-95 origin-top data-closed:animate-out data-closed:fade-out data-closed:zoom-out-95",
(props.size ?? "sm") === "sm" ? "max-w-96" : "max-w-3xl",
)}
>
@@@ -236,7 -236,7 +321,7 @@@
return (
<div
{...props}
-- class={cx("p-4 flex flex-col border-y border-gray-3", props.class)}
++ class={cx("p-4 flex flex-col border-y border-ed-line", props.class)}
/>
);
},
@@@ -254,7 -254,7 +339,7 @@@ export function DialogContent
return (
<>
<Dialog.Header>
-- <KDialog.Title class="text-gray-12">{props.title}</KDialog.Title>
++ <KDialog.Title class="text-ed-text-1">{props.title}</KDialog.Title>
</Dialog.Header>
<Dialog.Content class={props.class}>{props.children}</Dialog.Content>
<Dialog.Footer
@@@ -278,7 -278,7 +363,7 @@@ export function MenuItem<T extends Vali
class={cx(
props.class,
"flex flex-row shrink-0 items-center gap-1.5 px-[0.675rem] py-1.5 rounded-lg outline-hidden text-nowrap overflow-hidden text-ellipsis w-full max-w-full",
-- "text-[0.875rem] text-gray-10 disabled:text-gray-10 data-highlighted:bg-gray-3 data-highlighted:text-gray-12",
++ "text-[13px] text-ed-text-2 disabled:text-ed-text-3 data-highlighted:bg-ed-ctl-hover data-highlighted:text-ed-text-1",
)}
/>
);
@@@ -316,34 -316,34 +401,34 @@@ export function MenuItemList<T extends
const editorButtonStyles = cva(
[
-- "group flex flex-row items-center px-1.5 gap-1.5 h-8 rounded-lg text-[0.875rem]",
++ "group flex flex-row items-center justify-center shrink-0 gap-1.5 rounded-[7px] font-medium",
"focus:outline-solid focus:outline-2 focus:outline-offset-2 focus-visible:outline-solid focus-visible:outline-2 focus-visible:outline-offset-2 transition-colors duration-100",
-- "disabled:opacity-50 disabled:text-gray-11",
++ "disabled:opacity-45",
++ "[&_svg]:shrink-0",
],
{
variants: {
++ size: {
++ sm: "h-[22px] min-w-[22px] text-[12px] [&_svg]:size-3.5",
++ md: "h-7 min-w-7 text-[13px] [&_svg]:size-4",
++ },
variant: {
primary:
-- "text-gray-12 enabled:hover:not-data-pressed:bg-gray-3 data-expanded:bg-gray-3 outline-blue-300 focus:bg-transparent",
++ "text-ed-text-2 enabled:hover:not-data-pressed:bg-ed-ctl-hover enabled:hover:not-data-pressed:text-ed-text-1 enabled:active:not-data-pressed:bg-ed-ctl-active data-expanded:bg-ed-ctl-hover data-expanded:text-ed-text-1 outline-ed-accent focus:bg-transparent",
++ text: "text-ed-text-1 enabled:hover:not-data-pressed:bg-ed-ctl-hover enabled:active:not-data-pressed:bg-ed-ctl-active data-expanded:bg-ed-ctl-hover outline-ed-accent focus:bg-transparent",
danger:
-- "text-gray-12 enabled:hover:not-data-pressed:bg-gray-3 data-expanded:bg-red-300 data-pressed:bg-red-300 data-expanded:text-gray-1 data-pressed:text-gray-1 outline-red-300",
++ "text-ed-text-2 enabled:hover:not-data-pressed:bg-ed-ctl-hover enabled:hover:not-data-pressed:text-ed-text-1 data-expanded:bg-red-300 data-pressed:bg-red-300 data-expanded:text-white data-pressed:text-white outline-red-300",
},
},
-- defaultVariants: { variant: "primary" },
++ defaultVariants: { variant: "primary", size: "md" },
},
);
--const editorButtonLeftIconStyles = cva("transition-colors duration-100", {
-- variants: {
-- variant: {
-- primary:
-- "text-gray-12 enabled:group-hover:not-data-group-disabled:text-gray-12 data-group-expanded:text-gray-12",
-- danger:
-- "text-gray-12 group-hover:enabled:text-gray-12 data-group-expanded:text-gray-1 data-group-pressed:text-gray-1",
-- },
-- },
-- defaultVariants: { variant: "primary" },
--});
++const editorButtonLeftIconStyles =
++ "flex items-center text-current transition-colors duration-100";
++
++const editorButtonRightIconStyles =
++ "flex items-center text-ed-text-3 [&_svg]:size-2.5!";
type EditorButtonProps<T extends ValidComponent = "button"> =
PolymorphicProps<T> & {
@@@ -360,7 -360,7 +445,10 @@@ export function EditorButton<T extends
props: EditorButtonProps<T>,
) {
const [local, cvaProps, others] = splitProps(
-- mergeProps({ variant: "primary" }, props) as unknown as EditorButtonProps,
++ mergeProps(
++ { variant: "primary", size: "md" },
++ props,
++ ) as unknown as EditorButtonProps,
[
"children",
"leftIcon",
@@@ -371,23 -371,23 +459,54 @@@
"comingSoon",
"rightIconEnd",
],
-- ["class", "variant"],
++ ["class", "variant", "size"],
);
++ // Resolve children once. Reading local.children directly inside the
++ // reactive buttonClass() below would re-resolve a render-prop child (e.g.
++ // a Kobalte <Select.Value>) on every class recompute, and that child's own
++ // reactivity re-invalidates the class binding — an unbounded synchronous
++ // re-entry that overflows the stack the instant such a trigger opens.
++ const resolvedChildren = children(() => local.children as JSX.Element);
++ const iconOnly = () => !resolvedChildren() && !local.rightIcon;
++
const buttonContent = (
<>
-- <span class={editorButtonLeftIconStyles({ variant: cvaProps.variant })}>
-- {local.leftIcon}
-- </span>
-- {local.children && <span>{local.children}</span>}
++ {local.leftIcon && (
++ <span class={editorButtonLeftIconStyles}>{local.leftIcon}</span>
++ )}
++ {resolvedChildren() && <span>{resolvedChildren()}</span>}
{local.rightIcon && (
-- <span class={local.rightIconEnd ? "ml-auto" : ""}>
++ <span
++ class={cx(
++ editorButtonRightIconStyles,
++ local.rightIconEnd && "ml-auto",
++ )}
++ >
{local.rightIcon}
</span>
)}
</>
);
++ const buttonClass = () =>
++ cx(
++ editorButtonStyles({
++ ...cvaProps,
++ class: cx(
++ iconOnly()
++ ? cvaProps.size === "sm"
++ ? "w-[22px]"
++ : "w-7"
++ : cvaProps.size === "sm"
++ ? "px-1.5"
++ : "px-[7px]",
++ cvaProps.class,
++ ),
++ }),
++ local.rightIconEnd && "justify-between",
++ );
++
return (
<>
{local.tooltipText || local.comingSoon ? (
@@@ -398,24 -398,24 +517,14 @@@
<Polymorphic
as="button"
{...others}
-- class={cx(
-- editorButtonStyles({ ...cvaProps, class: cvaProps.class }),
-- local.rightIconEnd && "justify-between",
-- )}
++ class={buttonClass()}
disabled={local.comingSoon}
>
{buttonContent}
</Polymorphic>
</Tooltip>
) : (
-- <Polymorphic
-- as="button"
-- {...others}
-- class={cx(
-- editorButtonStyles({ ...cvaProps, class: cvaProps.class }),
-- local.rightIconEnd && "justify-between",
-- )}
-- >
++ <Polymorphic as="button" {...others} class={buttonClass()}>
{buttonContent}
</Polymorphic>
)}
@@@ -424,7 -424,7 +533,7 @@@
}
export const dropdownContainerClasses =
-- "z-60 flex flex-col rounded-xl border border-gray-3 bg-gray-1 shadow-s overflow-y-hidden outline-hidden";
++ "z-60 flex flex-col rounded-xl bg-ed-card shadow-ed-pop overflow-y-hidden outline-hidden";
export const topLeftAnimateClasses =
"data-expanded:animate-in data-expanded:fade-in data-expanded:zoom-in-95 data-closed:animate-out data-closed:fade-out data-closed:zoom-out-95 origin-top-left";
diff --cc apps/desktop/src/routes/in-progress-recording.tsx
index def3c10c5,d7ed801a8..a8ae9bcfd
--- a/apps/desktop/src/routes/in-progress-recording.tsx
+++ b/apps/desktop/src/routes/in-progress-recording.tsx
@@@ -911,8 -845,12 +911,12 @@@ function InProgressRecordingInner()
</div>
}
>
- <button
+ <RecordingControlButton
- disabled={stopRequested() || isCountdown()}
+ disabled={
+ stopRequested() ||
+ stopRecording.isPending ||
+ isCountdown()
+ }
class="flex flex-row items-center gap-1 rounded-lg py-1 px-2 text-red-300 transition-colors duration-100 hover:bg-red-500/8 active:bg-red-500/12 disabled:opacity-60 disabled:hover:bg-transparent"
type="button"
onPointerDown={(event) => {
diff --cc apps/desktop/src/routes/screenshot-editor/useScreenshotExport.ts
index 1e4a0eb5d,dad984452..ddaba7911
--- a/apps/desktop/src/routes/screenshot-editor/useScreenshotExport.ts
+++ b/apps/desktop/src/routes/screenshot-editor/useScreenshotExport.ts
@@@ -1,7 -1,6 +1,5 @@@
--import { save } from "@tauri-apps/plugin-dialog";
import { writeFile } from "@tauri-apps/plugin-fs";
- import { type as ostype } from "@tauri-apps/plugin-os";
-import { createSignal } from "solid-js";
+import { createSignal, onCleanup } from "solid-js";
import { unwrap } from "solid-js/store";
import toast from "solid-toast";
import { commands } from "~/utils/tauri";
@@@ -206,18 -200,10 +204,12 @@@ export function useScreenshotExport()
if (destination === "file") {
const buffer = await blob.arrayBuffer();
const uint8Array = new Uint8Array(buffer);
- const savePath = await save({
- filters: [{ name: "PNG Image", extensions: ["png"] }],
- defaultPath: `${editorCtx.prettyName}.png`,
- });
+ if (disposed || editorCtx.editorInstance() !== owner) return;
- const savePath =
- ostype() === "linux"
- ? await commands.saveFileDialog(
- `${editorCtx.prettyName}.png`,
- "png",
- )
- : await save({
- filters: [{ name: "PNG Image", extensions: ["png"] }],
- defaultPath: `${editorCtx.prettyName}.png`,
- });
++ const savePath = await commands.saveFileDialog(
++ `${editorCtx.prettyName}.png`,
++ "png",
++ );
+ if (disposed || editorCtx.editorInstance() !== owner) return;
if (savePath) {
await writeFile(savePath, uint8Array);
toast.success("Screenshot saved!");
diff --cc apps/desktop/src/styles/theme.css
index ef5a9ed4b,330b4fd12..166b2ebf9
--- a/apps/desktop/src/styles/theme.css
+++ b/apps/desktop/src/styles/theme.css
@@@ -20,19 -20,17 +20,48 @@@
@tailwind utilities;
/* Single source of truth for timeline track colours. Both the timeline
-- * segments and the "Add track" picker read these, so they always match. */
++ * segments and the "Add track" picker read these, so they always match.
++ * Segments paint these as tints (see --ed-seg-*), so every hue is a mid-tone
++ * that still reads when mixed into the card surface. */
:root {
-- --track-clip: #3f8ae0; /* blue */
-- --track-zoom: #4a4f5c; /* slate */
-- --track-caption: #6f747d;
-- --track-keyboard: #d4742c; /* orange */
- --track-style: #9361d7;
- --track-image: #d68a32;
-- --track-text: #2898ac; /* teal */
-- --track-mask: #d2444b; /* red */
-- --track-scene: #975cfa; /* purple */
-- --track-audio: var(--jade-9); /* green */
-- --track-3d: #7c6ff0; /* violet */
++ --track-clip: #3b82f6;
++ --track-zoom: #64748b;
++ --track-caption: #0ea5e9;
++ --track-keyboard: #f97316;
++ --track-style: #ec4899;
++ --track-image: #f59e0b;
++ --track-text: #14b8a6;
++ --track-mask: #ef4444;
++ --track-scene: #8b5cf6;
++ --track-audio: #22c55e;
++ --track-3d: #6366f1;
++
++ /* Editor surfaces: a layered, low-contrast system (window < card < control)
++ * with one accent. Mirrored 1:1 by EditorPalette in
++ * apps/desktop-gpui/src/theme.rs; change both. */
++ --ed-window: #f1f1f3;
++ --ed-card: #ffffff;
++ --ed-card-2: #f6f6f7;
++ --ed-stage: #e9e9ec;
++ --ed-line: rgba(0, 0, 0, 0.075);
++ --ed-line-strong: rgba(0, 0, 0, 0.12);
++ --ed-text-1: #1c1c1e;
++ --ed-text-2: #6e6e75;
++ --ed-text-3: #a0a0a8;
++ --ed-ctl: rgba(0, 0, 0, 0.045);
++ --ed-ctl-hover: rgba(0, 0, 0, 0.075);
++ --ed-ctl-active: rgba(0, 0, 0, 0.11);
++ --ed-accent: #007aff;
++ --ed-accent-2: #2b8cff;
++ --ed-playhead: #ff3b30;
++ --ed-thumb: #ffffff;
++ --ed-seg-tint: 13%;
++ --ed-seg-line: 34%;
++ --ed-seg-label-base: #000000;
++ --ed-seg-label-mix: 58%;
++ --ed-card-shadow: 0 1px 2px rgba(0, 0, 0, 0.04), 0 0 0 1px var(--ed-line);
++ --ed-pop-shadow:
++ 0 12px 32px -12px rgba(0, 0, 0, 0.25), 0 0 0 1px var(--ed-line);
}
:root {
@@@ -169,6 -167,6 +198,32 @@@
--gray-5: #3a3a3a;
--gray-6: #444444;
--gray-11: #a1a1a1;
++
++ --ed-window: #131315;
++ --ed-card: #1b1b1e;
++ --ed-card-2: #202024;
++ --ed-stage: #121214;
++ --ed-line: rgba(255, 255, 255, 0.08);
++ --ed-line-strong: rgba(255, 255, 255, 0.13);
++ --ed-text-1: #f4f4f5;
++ --ed-text-2: #9a9aa3;
++ --ed-text-3: #62626a;
++ --ed-ctl: rgba(255, 255, 255, 0.06);
++ --ed-ctl-hover: rgba(255, 255, 255, 0.09);
++ --ed-ctl-active: rgba(255, 255, 255, 0.13);
++ --ed-accent: #0a84ff;
++ --ed-accent-2: #3d9bff;
++ --ed-playhead: #ff453a;
++ --ed-thumb: #e8e8ea;
++ --ed-seg-tint: 20%;
++ --ed-seg-line: 42%;
++ --ed-seg-label-base: #ffffff;
++ --ed-seg-label-mix: 55%;
++ --ed-card-shadow:
++ 0 1px 2px rgba(0, 0, 0, 0.3), 0 0 0 1px var(--ed-line), inset 0 1px 0
++ rgba(255, 255, 255, 0.03);
++ --ed-pop-shadow:
++ 0 16px 40px -12px rgba(0, 0, 0, 0.6), 0 0 0 1px var(--ed-line);
}
.dark .dark-button-shadow {
diff --cc apps/desktop/src/utils/createPresets.ts
index 9f24113b1,9f24113b1..0fd07af71
--- a/apps/desktop/src/utils/createPresets.ts
+++ b/apps/desktop/src/utils/createPresets.ts
@@@ -31,6 -31,6 +31,7 @@@ export function createPresets()
const config = {
...preset.config,
timeline: null,
++ overlayOrder: [],
clips: [],
};
@@@ -51,7 -51,7 +52,7 @@@
store.default = store.default - 1;
}
}),
-- setDefault: (index: number) =>
++ setDefault: (index: number | null) =>
updatePresets((store) => {
store.default = index;
}),
@@@ -67,6 -67,6 +68,7 @@@
store.presets[index].config = {
...config,
timeline: null,
++ overlayOrder: [],
clips: [],
};
}),
diff --cc apps/desktop/src/utils/pricing.ts
index 000000000,000000000..50ead2496
new file mode 100644
--- /dev/null
+++ b/apps/desktop/src/utils/pricing.ts
@@@ -1,0 -1,0 +1,12 @@@
++import toast from "solid-toast";
++import { commands } from "./tauri";
++
++export async function openPricingPage() {
++ try {
++ await commands.showWindow("Upgrade");
++ } catch {
++ toast.error(
++ "Couldn't open your browser. Visit cap.so/pricing to view plans.",
++ );
++ }
++}
diff --cc apps/desktop/src/utils/queries.ts
index e689502f5,62637fec1..50a37d566
--- a/apps/desktop/src/utils/queries.ts
+++ b/apps/desktop/src/utils/queries.ts
@@@ -332,7 -332,7 +332,8 @@@ export function createLicenseQuery()
const settings = await generalSettingsStore.get();
const auth = await authStore.get();
-- if (auth?.plan?.upgraded) return { type: "pro" as const, ...auth.plan };
++ if (auth?.plan?.upgraded || auth?.plan?.manual)
++ return { type: "pro" as const, ...auth.plan };
if (settings?.commercialLicense)
return {
type: "commercial" as const,
diff --cc apps/desktop/src/utils/recording.ts
index 12636bdaa,ce1ef9f06..137849023
--- a/apps/desktop/src/utils/recording.ts
+++ b/apps/desktop/src/utils/recording.ts
@@@ -2,48 -2,8 +2,48 @@@ import { emit } from "@tauri-apps/api/e
import * as dialog from "@tauri-apps/plugin-dialog";
import { revealItemInDir } from "@tauri-apps/plugin-opener";
import type { createOptionsQuery } from "./queries";
-import { commands, type RecordingAction, type RecordingMode } from "./tauri";
+import {
+ commands,
+ type RecordingAction,
+ type RecordingMeta,
+ type RecordingMode,
+} from "./tauri";
+
- export function isRecordingStartCancelled(error: unknown): boolean {
- const message = error instanceof Error ? error.message : error;
- return message === "Recording cancelled before starting.";
- }
-
+export function isRecordingStorageError(error: unknown): boolean {
+ const message = error instanceof Error ? error.message : error;
+ return (
+ typeof message === "string" &&
+ message.startsWith("Not enough space to finish this recording.")
+ );
+}
+
+export function recordingMetaNeedsRecovery(meta: RecordingMeta): boolean {
+ const status =
+ "status" in meta
+ ? meta.status
+ : "inner" in meta
+ ? meta.inner.status
+ : undefined;
+ if (!status || typeof status !== "object" || !("status" in status))
+ return false;
+ return status.status === "InProgress" || status.status === "NeedsRemux";
+}
+
+export function recordingOpenErrorMessage(
+ error: unknown,
+ projectPath: string,
+): string {
+ if (isRecordingStorageError(error)) {
+ return `Not enough space to finish this recording. Your recording files have been kept at ${projectPath}. Free up space, then open the recording again.`;
+ }
+ return error instanceof Error ? error.message : String(error);
+}
+
++export function isRecordingStartCancelled(error: unknown): boolean {
++ const message = error instanceof Error ? error.message : error;
++ return message === "Recording cancelled before starting.";
++}
+
export function handleRecordingResult(
result: Promise<RecordingAction>,
setOptions: ReturnType<typeof createOptionsQuery>["setOptions"] | undefined,
diff --cc apps/desktop/src/utils/tauri.ts
index 9dccba57e,a4b575601..f070f4294
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@@ -100,6 -100,6 +100,9 @@@ async takeScreenshot(target: ScreenCapt
async importCurrentDesktopBackground(projectPath: string) : Promise<string> {
return await TAURI_INVOKE("import_current_desktop_background", { projectPath });
},
++async getDefaultProjectConfig() : Promise<ProjectConfiguration> {
++ return await TAURI_INVOKE("get_default_project_config");
++},
async listCameras() : Promise<CameraInfo[]> {
return await TAURI_INVOKE("list_cameras");
},
@@@ -1121,6 -1120,6 +1124,8 @@@ export type OSPermissionsCheck = { scre
export type OnEscapePress = null
export type Organization = { id: string; name: string; ownerId: string; role?: string; canEditBrand?: boolean; iconUrl?: string | null; brandColors?: OrganizationBrandColors }
export type OrganizationBrandColors = { primary: string | null; secondary: string | null; accent: string | null; background: string | null }
++export type OverlayTrack = { kind: OverlayTrackKind; track: number }
++export type OverlayTrackKind = "mask" | "image" | "text"
export type Phase = "awaitingShortcut" | "starting" | "recording" | "pausing" | "paused" | "resuming" | "resumeFailed" | "restarting" | "stopping" | "restoring"
export type PhysicalSize = { width: number; height: number }
export type Plan = { upgraded: boolean; manual: boolean; last_checked: number }
@@@ -1129,7 -1128,7 +1134,7 @@@ export type PostDeletionBehaviour = "do
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; overlayOrder: OverlayTrack[]; captions: CaptionsData | null; keyboard: KeyboardData | null; clips: ClipConfiguration[]; annotations: Annotation[]; screenMotionBlur?: number; screenMovementSpring?: ScreenMovementSpring;
/**
* Per-layer cinematic color grades. Field-level default keeps old
* project files (and old saved presets) deserializing to the identity
diff --cc apps/web/content/changelog/desktop/103.mdx
index 000000000,000000000..99371dd3e
new file mode 100644
--- /dev/null
+++ b/apps/web/content/changelog/desktop/103.mdx
@@@ -1,0 -1,0 +1,70 @@@
++---
++title: Native App Preview, 3D Scenes, Animated Text & Cursor Effects
++app: Cap Desktop
++publishedAt: "2026-08-31"
++version: 0.6.0
++image:
++---
++
++This release brings an optional native app preview and a major expansion of Studio Mode: 3D camera moves, color correction, animated text, moving gradient backgrounds, and new cursor styles and click effects. It also adds freehand screenshot drawing, faster timeline editing, and fixes across recording recovery, audio, exports, and all three desktop platforms.
++
++## Features
++
++- **Native app preview** - The new app is built with GPUI for a faster, more responsive recording and editing experience with a native feel. Enable **Cap GPUI** in Settings → Experimental to try it. It shares your recordings and settings with the existing app, and you can switch back from its Experimental settings. This is an optional preview with some features still missing.
++- **3D camera moves** - Give screen recordings depth with a new 3D camera track. Choose ready-made scenes and motion presets or build your own shots with start and end positions, rotation, perspective, easing, and focus blur, then combine multiple shots on the timeline.
++- **Color correction** - Adjust the screen and camera separately with presets and controls for exposure, contrast, saturation, temperature, tint, fade, vignette, and grain. Control the strength of each look and whether the cursor follows the screen's colors.
++- **Animated text** - Add styled titles and callouts with fonts installed on your computer, text presets, alignment, spacing, shadows, and entrance and exit animations.
++- **Full-screen title cards** - Turn a text segment into a full-screen card between parts of your recording. The recorded video and audio pause while the title is shown, background music continues, and the recording resumes where it left off.
++- **Animated gradient backgrounds** - Choose a gradient preset or build your own with editable colors and positions, then add motion to the background. Save favorites or randomize a gradient for a different look.
++- **Cursor styles** - Choose macOS, macOS Tahoe, Windows, or a simple circle. Replacement cursors follow pointer shape changes, including text selection, links, and resizing.
++- **Click ripples** - Make clicks easier to follow with animated ripples. Adjust their color, size, duration, and strength, including when the cursor is frozen in place.
++- **Draw on screenshots** - Use the new Draw tool, or press **D**, to circle, underline, and sketch freehand. Change stroke color, width, and opacity, keep drawing multiple strokes, and move or resize them afterward. Drawings are included when you copy, save, or share the image.
++- **Faster timeline editing** - Drag the time ruler to scrub, use the minimap to navigate long recordings, and snap cuts to the playhead or other segment boundaries. Select all segments on the current track with **Cmd/Ctrl+A**, edit multiple zoom segments together, and change clip speed and audio behavior directly from the timeline.
++- **Frames in the native editor** - Add a macOS, Windows, browser, or MacBook frame from the native editor, with light and dark appearances and editable browser URLs or macOS window titles.
++- **Default zoom amount** - Choose your preferred zoom strength in General settings for newly added zoom segments and automatically generated zooms.
++- **Product demos with agents** - The agent installer now includes a companion `cap-demo` skill that helps an agent turn a website into a recorded product demo with 3D shots, a matching background, cursor movement, and music. This workflow currently supports macOS on Apple Silicon and has additional setup requirements.
++- **Diagnostic reports** - Run Studio and Instant Mode audio/video sync tests from Settings → Feedback, with an optional microphone check. Inspect the saved report, including device details and recent recording diagnostics, before choosing to send it to Cap.
++- **Local-currency upgrade prices** - The classic desktop app's upgrade screen now displays Cap Pro and commercial-license prices in pounds, euros, or dollars based on your location.
++
++## Fixes
++
++- **Disconnected microphones and cameras** - Cap remembers a selected device when it is unplugged, shows that it is not connected, and selects it again when it returns. Missing devices no longer trap recording startup in a restore loop, and renamed Bluetooth microphones are matched more reliably.
++- **More reliable recording recovery** - Interrupted recordings can recover complete fragments that were left out of their saved manifest. Incomplete fragments are rejected, fragment paths are resolved correctly, and stopping a recording avoids a shutdown deadlock that could leave saving stuck.
++- **Safer low-storage recording in the native app** - The native app now leaves extra disk space to finish saving a recording, shows low-storage warnings, and makes it clear when saving is still in progress. This helps protect the footage already captured when space runs short.
++- **Audio starts with the picture** - Editor playback waits for audio to start before advancing the video, reducing the delay between what you see and hear at the beginning of playback.
++- **Muted clips stay muted** - Muting a normal-speed clip now carries through playback and export, including across split segments. The native timeline also makes muted clips easier to spot with a muted label and icon.
++- **Native playback shortcut** - The spacebar consistently starts and pauses playback after clicking editor controls, while text fields still accept spaces normally.
++- **Text, captions, and zooms stay aligned** - Captions, transcript seeking, and overlay tracks now account for pauses introduced by full-screen titles. Deleting a section keeps those tracks aligned, and zoom target previews use the correct point in the recording after cuts, speed changes, and title cards.
++- **Cleaner background blur** - Fixed visible grid and comb-like artifacts in blurred backgrounds.
++- **Static recordings finish correctly** - Recordings with little or no screen movement now retain the full duration up to when you stop. Instant Mode in the native app and on Linux uploads recording segments as they become available.
++- **Native Windows export previews** - Fixed black previews when preparing an export in the native Windows app.
++- **macOS recording startup** - Improved screen and window discovery, capture startup, camera-device handling, and permission refreshes, including returning from system permission settings.
++- **Native app crash recovery** - Fixed macOS crashes involving window visibility and graphics surfaces. After an unexpected native app exit, the next launch returns to the classic app.
++- **Safer updates and app switching** - Updating, restarting, or switching between the native and classic apps now checks for active recordings, exports, and other work before proceeding. Single-instance handling and app handoffs are more reliable.
++- **Native Windows window behavior** - Improved display scaling, window controls, snapping, taskbar and tray behavior, and restoring the native app after it has been hidden.
++- **Windows camera compatibility** - Improved support for capture cards and virtual cameras that need a fallback capture method. A camera that fails to initialize no longer hides the remaining devices in the picker.
++- **Windows window screenshots** - Added a fallback capture method for window screenshots when the usual capture API fails.
++- **Linux recording and audio** - Improved Wayland capture selection and X11 window recording, including following resized windows without capturing overlapping apps. CLI recordings gain camera compositing, while PipeWire system audio and microphone capture stay separate and use more compatible buffering.
++- **Linux screenshot privacy** - Wayland screenshots respect the selected target and avoid falling back to a capture that could include other windows. Screenshot and automation notifications are delivered more reliably.
++- **Linux installation and updates** - Added packaging support for DEB, RPM, AppImage, and Arch, with automatic updates for DEB and AppImage and package-manager guidance for RPM and Arch. AppImage CLI launchers also preserve your working directory and relative paths.
++- **Native account and app integration** - Improved account, profile, settings, and tray synchronization, along with clipboard actions, sign-in links, and opening Cap from other apps.
++- **Safer support logs** - Uploaded logs remove sensitive credentials from URLs, and caption text is kept out of normal release logs.
++
++## Performance
++
++- **Faster Windows editor startup** - The editor uses Microsoft's newer shader compiler to reduce the long graphics setup delay that affected some Windows GPUs.
++- **Lower Windows background usage** - Camera discovery no longer repeatedly opens capture devices and leaks their resources. Device polling also pauses while the app is hidden in the tray.
++- **Smoother playback and scrubbing** - The editor limits audio and video caches, cancels outdated frame requests, and keeps timeline work responsive during playback and rapid seeking, particularly in larger projects.
++- **Lighter recording and exports on macOS** - More of the capture, preview, and export pipeline reuses graphics surfaces directly, reducing repeated frame copies and temporary allocations.
++- **Faster media imports** - The classic and native editors reuse decoded frames when building imported clips and previews.
++- **More efficient camera blur** - Camera background effects reuse processing buffers and graphics resources to reduce repeated work.
++- **Hardware encoding on supported Linux systems** - Cap can use NVIDIA encoding when the local encoder passes its compatibility check, with a software fallback when it is unavailable.
++
++## Sharing
++
++- **Uploads recover more reliably** - Upload retries reuse the recording's reserved share link, and processing waits and retries when the server is busy. Stalled jobs have broader recovery coverage, and bulk imports leave capacity available for regular recordings.
++- **Better playback on phones** - Fixed encoding timing that could stop shared videos from playing on mobile after an online edit.
++- **Recordings without speech** - Cloud transcription recognizes recordings with no spoken audio and skips them instead of repeatedly reporting a transcription failure.
++- **More reliable AI results** - Titles, summaries, chapters, and transcript translations can retry with another configured AI provider when a request fails or returns unusable results.
++- **Custom-domain link previews** - Shared recordings on verified custom domains now show the correct preview images in Slack and other apps that display link previews.
++- **Monthly sharing allowance** - Accounts without Cap Pro now have an allowance of 25 video share links per calendar month. Local recordings, screenshots, and videos created before August 19 are unaffected. Each new month gives you a fresh allowance; links created over a previous month's limit stay locked unless you upgrade or delete earlier videos from that month to free up the allowance.
diff --cc crates/editor/Cargo.toml
index 747fc926e,e88d32ad0..116181b53
--- a/crates/editor/Cargo.toml
+++ b/crates/editor/Cargo.toml
@@@ -23,6 -23,6 +23,7 @@@ name = "editor-startup-benchmark
path = "examples/editor-startup-benchmark.rs"
[dependencies]
++cap-utils = { path = "../utils" }
cap-media = { path = "../media" }
cap-project = { path = "../project" }
cap-rendering = { path = "../rendering" }
@@@ -49,5 -49,4 +50,5 @@@ workspace-hack = { version = "0.1", pat
windows = { workspace = true, features = ["Win32_Media"] }
[dev-dependencies]
- serde_json.workspace = true
++serde_json = "1.0"
tempfile = "3"
diff --cc crates/editor/src/editor_instance.rs
index abc2c9267,cba0b63e3..0529e187a
--- a/crates/editor/src/editor_instance.rs
+++ b/crates/editor/src/editor_instance.rs
@@@ -648,7 -644,7 +658,13 @@@ impl EditorInstance
audio_output: self.audio_output.clone(),
telemetry: None,
})
-- .start(fps, resolution_base)
++ .start_with_diagnostics(
++ fps,
++ resolution_base,
++ Some(cap_utils::operation_diagnostics::resource_id(
++ &self.project_path,
++ )),
++ )
.await
{
Ok(handle) => handle,
diff --cc crates/editor/src/playback.rs
index 2ebbde60d,33a042bf7..fb442e743
--- a/crates/editor/src/playback.rs
+++ b/crates/editor/src/playback.rs
@@@ -6,6 -6,6 +6,7 @@@ use cap_rendering::
RecordingSegmentDecoders, RenderVideoConstants, ZoomTransformTimeline,
spring_mass_damper::SpringMassDamperSimulationConfig,
};
++use cap_utils::operation_diagnostics::{Field, Operation};
use futures::stream::{FuturesUnordered, StreamExt};
use lru::LruCache;
use std::{
@@@ -509,15 -509,15 +510,40 @@@ fn transition_decode_request
impl Playback {
pub async fn start(
++ self,
++ fps: u32,
++ resolution_base: XY<u32>,
++ ) -> Result<PlaybackHandle, PlaybackStartError> {
++ self.start_with_diagnostics(fps, resolution_base, None)
++ .await
++ }
++
++ pub async fn start_with_diagnostics(
mut self,
fps: u32,
resolution_base: XY<u32>,
++ resource: Option<u64>,
) -> Result<PlaybackHandle, PlaybackStartError> {
let start_call = Instant::now();
++ let mut diagnostic = Operation::start(
++ "editor_playback",
++ &[
++ Field::number("requested_fps", fps as u64),
++ Field::number("requested_width", resolution_base.x as u64),
++ Field::number("requested_height", resolution_base.y as u64),
++ Field::number("start_frame", self.start_frame_number as u64),
++ Field::number("source_segments", self.segment_medias.len() as u64),
++ Field::flag("music", !self.music.is_empty()),
++ ],
++ );
++ if let Some(resource) = resource {
++ diagnostic.field(Field::identifier("resource", resource));
++ }
let fps_f64 = fps as f64;
if !(fps_f64.is_finite() && fps_f64 > 0.0) {
warn!(fps, "Invalid FPS provided for playback start");
++ diagnostic.finish(false);
return Err(PlaybackStartError::InvalidFps);
}
@@@ -795,6 -795,6 +821,7 @@@
// Resolve the background audio decodes before entering the sync
// playback thread. This only waits when playback starts before the
// decode kicked off at editor open has finished.
++ diagnostic.stage("waiting_for_audio_decode");
let audio_wait_start = Instant::now();
let audio_segments = get_audio_segments(&self.segment_medias).await;
if let Some(telemetry) = &self.telemetry {
@@@ -803,6 -803,6 +830,11 @@@
});
}
++ diagnostic.field(Field::number(
++ "audio_decode_wait_ms",
++ audio_wait_start.elapsed().as_millis() as u64,
++ ));
++ diagnostic.stage("preparing_playback");
let playback_body = move || {
let duration = self
.project
@@@ -811,6 -811,6 +843,8 @@@
.as_ref()
.and_then(|timeline| valid_playback_duration(timeline.duration()));
let Some(duration) = duration else {
++ diagnostic.stage("invalid_timeline");
++ diagnostic.finish(false);
warn!("Playback: No valid timeline duration found");
stop_tx.send(true).ok();
event_tx.send(PlaybackEvent::Stop).ok();
@@@ -1165,6 -1165,6 +1199,11 @@@
// Attach this playback's audio to the session's persistent output
// stream. Blocks until the live callback is consuming the source,
// so the clock below never runs ahead of audible audio.
++ diagnostic.field(Field::number(
++ "warmup_ms",
++ warmup_start.elapsed().as_millis() as u64,
++ ));
++ diagnostic.stage("initializing_audio_output");
let audio_spawn_start = Instant::now();
let _ = audio_playhead_tx.send(playback_start_frame as f64 / fps_f64);
let audio_generation = if !has_playback_audio(&audio_segments, !self.music.is_empty()) {
@@@ -1190,6 -1190,6 +1229,16 @@@
elapsed: start_call.elapsed(),
});
}
++ diagnostic.field(Field::number(
++ "audio_output_init_ms",
++ audio_spawn_start.elapsed().as_millis() as u64,
++ ));
++ diagnostic.field(Field::number(
++ "clock_start_ms",
++ start_call.elapsed().as_millis() as u64,
++ ));
++ diagnostic.field(Field::flag("audio_output_started", has_audio));
++ diagnostic.stage("playing");
let mut start = Instant::now();
let mut clock_anchor_frame = playback_start_frame;
@@@ -1724,6 -1724,6 +1773,9 @@@
}
}
++ diagnostic.field(Field::number("frames_skipped", total_frames_skipped));
++ diagnostic.stage("loop_ended");
++ diagnostic.finish(true);
if let Some(generation) = audio_generation {
self.audio_output.stop_playback(generation);
}
diff --cc crates/export/src/gif.rs
index f7cc4627f,f7cc4627f..22fca9875
--- a/crates/export/src/gif.rs
+++ b/crates/export/src/gif.rs
@@@ -35,6 -35,6 +35,40 @@@ impl Default for GifExportSettings
impl GifExportSettings {
pub async fn export(
++ self,
++ base: ExporterBase,
++ on_progress: impl FnMut(u32) -> bool + Send + 'static,
++ ) -> Result<PathBuf, String> {
++ use cap_utils::operation_diagnostics::{Field, observe};
++ observe(
++ "export_gif",
++ &[
++ Field::number("requested_fps", self.fps as u64),
++ Field::number("requested_width", self.resolution_base.x as u64),
++ Field::number("requested_height", self.resolution_base.y as u64),
++ Field::identifier(
++ "resource",
++ cap_utils::operation_diagnostics::resource_id(&base.project_path),
++ ),
++ Field::number(
++ "source_width",
++ base.render_constants.options.screen_size.x as u64,
++ ),
++ Field::number(
++ "source_height",
++ base.render_constants.options.screen_size.y as u64,
++ ),
++ Field::number("source_segments", base.segments.len() as u64),
++ Field::number("clips", base.project_config.clips.len() as u64),
++ Field::flag("captions", base.project_config.captions.is_some()),
++ Field::flag("streaming_audio", base.streaming_audio.is_some()),
++ ],
++ self.export_inner(base, on_progress),
++ )
++ .await
++ }
++
++ async fn export_inner(
self,
base: ExporterBase,
mut on_progress: impl FnMut(u32) -> bool + Send + 'static,
diff --cc crates/export/src/mov.rs
index ad6adb810,ad6adb810..e4560f01d
--- a/crates/export/src/mov.rs
+++ b/crates/export/src/mov.rs
@@@ -19,6 -19,6 +19,40 @@@ pub struct MovExportSettings
impl MovExportSettings {
pub async fn export(
++ self,
++ base: ExporterBase,
++ on_progress: impl FnMut(u32) -> bool + Send + 'static,
++ ) -> Result<PathBuf, String> {
++ use cap_utils::operation_diagnostics::{Field, observe};
++ observe(
++ "export_mov",
++ &[
++ Field::number("requested_fps", self.fps as u64),
++ Field::number("requested_width", self.resolution_base.x as u64),
++ Field::number("requested_height", self.resolution_base.y as u64),
++ Field::identifier(
++ "resource",
++ cap_utils::operation_diagnostics::resource_id(&base.project_path),
++ ),
++ Field::number(
++ "source_width",
++ base.render_constants.options.screen_size.x as u64,
++ ),
++ Field::number(
++ "source_height",
++ base.render_constants.options.screen_size.y as u64,
++ ),
++ Field::number("source_segments", base.segments.len() as u64),
++ Field::number("clips", base.project_config.clips.len() as u64),
++ Field::flag("captions", base.project_config.captions.is_some()),
++ Field::flag("streaming_audio", base.streaming_audio.is_some()),
++ ],
++ self.export_inner(base, on_progress),
++ )
++ .await
++ }
++
++ async fn export_inner(
self,
base: ExporterBase,
mut on_progress: impl FnMut(u32) -> bool + Send + 'static,
diff --cc crates/export/src/mp4.rs
index aeb1f4f93,aeb1f4f93..300f373d8
--- a/crates/export/src/mp4.rs
+++ b/crates/export/src/mp4.rs
@@@ -209,6 -209,6 +209,40 @@@ impl Mp4ExportSettings
self,
base: ExporterBase,
on_progress: impl FnMut(u32) -> bool + Send + 'static,
++ ) -> Result<PathBuf, String> {
++ use cap_utils::operation_diagnostics::{Field, observe};
++ observe(
++ "export_mp4",
++ &[
++ Field::number("requested_fps", self.fps as u64),
++ Field::number("requested_width", self.resolution_base.x as u64),
++ Field::number("requested_height", self.resolution_base.y as u64),
++ Field::identifier(
++ "resource",
++ cap_utils::operation_diagnostics::resource_id(&base.project_path),
++ ),
++ Field::number(
++ "source_width",
++ base.render_constants.options.screen_size.x as u64,
++ ),
++ Field::number(
++ "source_height",
++ base.render_constants.options.screen_size.y as u64,
++ ),
++ Field::number("source_segments", base.segments.len() as u64),
++ Field::number("clips", base.project_config.clips.len() as u64),
++ Field::flag("captions", base.project_config.captions.is_some()),
++ Field::flag("streaming_audio", base.streaming_audio.is_some()),
++ ],
++ self.export_inner(base, on_progress),
++ )
++ .await
++ }
++
++ async fn export_inner(
++ self,
++ base: ExporterBase,
++ on_progress: impl FnMut(u32) -> bool + Send + 'static,
) -> Result<PathBuf, String> {
info!("Exporting mp4 with settings: {:?}", &self);
info!("Expected to render {} frames", base.total_frames(self.fps));
diff --cc crates/project/src/configuration.rs
index 293dce7e2,43403a526..df1421d62
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@@ -2411,6 -2307,6 +2411,21 @@@ impl Annotation
}
}
++#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)]
++#[serde(rename_all = "camelCase")]
++pub enum OverlayTrackKind {
++ Mask,
++ Image,
++ Text,
++}
++
++#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)]
++#[serde(rename_all = "camelCase")]
++pub struct OverlayTrack {
++ pub kind: OverlayTrackKind,
++ pub track: u32,
++}
++
#[derive(Type, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase", default)]
pub struct ProjectConfiguration {
@@@ -2421,6 -2317,6 +2436,8 @@@
pub cursor: CursorConfiguration,
pub hotkeys: HotkeysConfiguration,
pub timeline: Option<TimelineConfiguration>,
++ #[serde(default, skip_serializing_if = "Vec::is_empty")]
++ pub overlay_order: Vec<OverlayTrack>,
pub captions: Option<CaptionsData>,
pub keyboard: Option<KeyboardData>,
pub clips: Vec<ClipConfiguration>,
@@@ -2476,6 -2372,6 +2493,7 @@@ impl Default for ProjectConfiguration
cursor: Default::default(),
hotkeys: Default::default(),
timeline: Default::default(),
++ overlay_order: Vec::new(),
captions: Default::default(),
keyboard: Default::default(),
clips: Default::default(),
@@@ -2491,80 -2387,6 +2509,138 @@@
}
impl ProjectConfiguration {
++ pub fn resolved_overlay_order(&self, available: &[OverlayTrack]) -> Vec<OverlayTrack> {
++ let mut ordered = Vec::with_capacity(available.len());
++ for track in available {
++ if !self.overlay_order.contains(track) && !ordered.contains(track) {
++ ordered.push(*track);
++ }
++ }
++ for track in &self.overlay_order {
++ if available.contains(track) && !ordered.contains(track) {
++ ordered.push(*track);
++ }
++ }
++ ordered
++ }
++
++ pub fn overlay_tracks(&self) -> Vec<OverlayTrack> {
++ let Some(timeline) = &self.timeline else {
++ return Vec::new();
++ };
++ let mut available = Vec::new();
++ for (kind, mut tracks) in [
++ (
++ OverlayTrackKind::Text,
++ timeline
++ .text_segments
++ .iter()
++ .map(|segment| segment.track)
++ .collect::<Vec<_>>(),
++ ),
++ (
++ OverlayTrackKind::Image,
++ timeline
++ .image_segments
++ .iter()
++ .map(|segment| segment.track)
++ .collect::<Vec<_>>(),
++ ),
++ (
++ OverlayTrackKind::Mask,
++ timeline
++ .mask_segments
++ .iter()
++ .map(|segment| segment.track)
++ .collect::<Vec<_>>(),
++ ),
++ ] {
++ tracks.sort_unstable();
++ tracks.dedup();
++ available.extend(
++ tracks
++ .into_iter()
++ .rev()
++ .map(|track| OverlayTrack { kind, track }),
++ );
++ }
++ self.resolved_overlay_order(&available)
++ }
++
+ fn style_override_at<T>(
+ &self,
+ time: f64,
+ select: impl Fn(&StyleOverrides) -> Option<&T>,
+ ) -> Option<&T> {
+ self.timeline
+ .as_ref()?
+ .style_segments
+ .iter()
+ .enumerate()
+ .filter(|(_, segment)| segment.is_active_at(time))
+ .filter_map(|(index, segment)| {
+ select(&segment.overrides).map(|value| (index, segment, value))
+ })
+ .max_by(|(left_index, left, _), (right_index, right, _)| {
+ left.track
+ .cmp(&right.track)
+ .then_with(|| {
+ left.start
+ .partial_cmp(&right.start)
+ .unwrap_or(std::cmp::Ordering::Equal)
+ })
+ .then_with(|| left_index.cmp(right_index))
+ })
+ .map(|(_, _, value)| value)
+ }
+
+ pub fn cursor_at(&self, time: f64) -> &CursorConfiguration {
+ self.style_override_at(time, |overrides| overrides.cursor.as_ref())
+ .unwrap_or(&self.cursor)
+ }
+
+ pub fn style_at(&self, time: f64) -> Cow<'_, Self> {
+ let mut configuration = Cow::Borrowed(self);
+ if let Some(background) =
+ self.style_override_at(time, |overrides| overrides.background.as_ref())
+ {
+ configuration.to_mut().background = background.clone();
+ }
+ if let Some(camera) = self.style_override_at(time, |overrides| overrides.camera.as_ref()) {
+ configuration.to_mut().camera = camera.clone();
+ }
+ if let Some(cursor) = self.style_override_at(time, |overrides| overrides.cursor.as_ref()) {
+ configuration.to_mut().cursor = cursor.clone();
+ }
+ configuration
+ }
+
+ pub fn camera_only_padding_at(&self, time: f64) -> f64 {
+ self.style_override_at(time, |overrides| {
+ overrides
+ .camera_only_padding
+ .as_ref()
+ .filter(|padding| padding.is_finite())
+ })
+ .copied()
+ .unwrap_or(0.0)
+ .clamp(0.0, 40.0)
+ }
+
+ pub fn requires_camera(&self) -> bool {
+ !self.camera.hide
+ || self.timeline.as_ref().is_some_and(|timeline| {
+ timeline.style_segments.iter().any(|segment| {
+ segment.is_active_at(segment.start)
+ && segment
+ .overrides
+ .camera
+ .as_ref()
+ .is_some_and(|camera| !camera.hide)
+ })
+ })
+ }
+
fn default_screen_motion_blur() -> f32 {
// Screen Studio's default blur amount is 1.0; with length-based blur
// semantics (amount scales the smear length, output fully blurred)
@@@ -4218,3 -3536,3 +4294,54 @@@ mod tests
);
}
}
++
++#[cfg(test)]
++mod overlay_order_tests {
++ use super::{OverlayTrack, OverlayTrackKind, ProjectConfiguration};
++
++ fn layer(kind: OverlayTrackKind, track: u32) -> OverlayTrack {
++ OverlayTrack { kind, track }
++ }
++
++ #[test]
++ fn old_projects_keep_the_default_stack() {
++ let project: ProjectConfiguration = serde_json::from_str("{}").unwrap();
++ let available = [
++ layer(OverlayTrackKind::Text, 0),
++ layer(OverlayTrackKind::Image, 0),
++ layer(OverlayTrackKind::Mask, 0),
++ ];
++ assert_eq!(project.resolved_overlay_order(&available), available);
++ }
++
++ #[test]
++ fn custom_stack_roundtrips_and_ignores_stale_duplicate_entries() {
++ let text = layer(OverlayTrackKind::Text, 0);
++ let image = layer(OverlayTrackKind::Image, 0);
++ let project = ProjectConfiguration {
++ overlay_order: vec![image, image, layer(OverlayTrackKind::Mask, 9), text],
++ ..Default::default()
++ };
++ let restored: ProjectConfiguration =
++ serde_json::from_str(&serde_json::to_string(&project).unwrap()).unwrap();
++ assert_eq!(
++ restored.resolved_overlay_order(&[text, image]),
++ [image, text]
++ );
++ }
++
++ #[test]
++ fn new_layers_appear_above_the_saved_stack() {
++ let text = layer(OverlayTrackKind::Text, 0);
++ let image = layer(OverlayTrackKind::Image, 0);
++ let new_image = layer(OverlayTrackKind::Image, 1);
++ let project = ProjectConfiguration {
++ overlay_order: vec![image, text],
++ ..Default::default()
++ };
++ assert_eq!(
++ project.resolved_overlay_order(&[text, new_image, image]),
++ [new_image, image, text]
++ );
++ }
++}
diff --cc crates/recording/src/instant_recording.rs
index 686081926,686081926..3b9248e6d
--- a/crates/recording/src/instant_recording.rs
+++ b/crates/recording/src/instant_recording.rs
@@@ -377,6 -377,6 +377,7 @@@ impl Drop for ActorHandle
#[derive(kameo::Actor)]
pub struct Actor {
++ diagnostic: Option<cap_utils::operation_diagnostics::Operation>,
recording_dir: PathBuf,
output_dir: PathBuf,
capture_target: ScreenCaptureTarget,
@@@ -486,6 -486,6 +487,30 @@@ impl Message<Stop> for Actor
type Reply = anyhow::Result<CompletedRecording>;
async fn handle(&mut self, _: Stop, _: &mut Context<Self, Self::Reply>) -> Self::Reply {
++ if let Some(diagnostic) = &mut self.diagnostic {
++ diagnostic.stage("finalizing");
++ }
++ let result = self.complete_recording().await;
++ if let Some(mut diagnostic) = self.diagnostic.take() {
++ if let Ok(recording) = &result {
++ diagnostic.field(cap_utils::operation_diagnostics::Field::label(
++ "output_health",
++ match recording.health {
++ crate::RecordingHealth::Healthy => "healthy",
++ crate::RecordingHealth::Repaired { .. } => "repaired",
++ crate::RecordingHealth::Degraded { .. } => "degraded",
++ crate::RecordingHealth::Damaged { .. } => "damaged",
++ },
++ ));
++ }
++ diagnostic.finish(result.is_ok());
++ }
++ result
++ }
++}
++
++impl Actor {
++ async fn complete_recording(&mut self) -> anyhow::Result<CompletedRecording> {
if let Some(pause_start) = self.pause_started_at.take() {
let pause_elapsed = current_time_f64() - pause_start;
if pause_elapsed > 0.0 {
@@@ -586,6 -586,6 +611,11 @@@ impl Message<Pause> for Actor
state
});
++ if matches!(self.state, ActorState::Paused { .. })
++ && let Some(diagnostic) = &mut self.diagnostic
++ {
++ diagnostic.stage("paused");
++ }
}
}
@@@ -619,6 -619,6 +649,11 @@@ impl Message<Resume> for Actor
state
});
++ if matches!(self.state, ActorState::Recording { .. })
++ && let Some(diagnostic) = &mut self.diagnostic
++ {
++ diagnostic.stage("recording");
++ }
}
}
@@@ -628,7 -628,7 +663,14 @@@ impl Message<Cancel> for Actor
type Reply = anyhow::Result<()>;
async fn handle(&mut self, _: Cancel, _: &mut Context<Self, Self::Reply>) -> Self::Reply {
-- self.stop().await
++ if let Some(diagnostic) = &mut self.diagnostic {
++ diagnostic.stage("cancelling");
++ }
++ let result = self.stop().await;
++ if let Some(diagnostic) = self.diagnostic.take() {
++ diagnostic.finish(result.is_ok());
++ }
++ result
}
}
@@@ -1073,6 -1073,6 +1115,47 @@@ async fn build_instant_recording_actor
#[cfg(target_os = "linux")] camera: LinuxCameraConfig,
#[cfg(target_os = "linux")] lifecycle: InstantLifecycle,
) -> anyhow::Result<ActorHandle> {
++ use cap_utils::operation_diagnostics::{Field, Operation};
++ let mut diagnostic = Operation::start(
++ "instant_recording",
++ &[
++ Field::identifier(
++ "resource",
++ cap_utils::operation_diagnostics::resource_id(&recording_dir),
++ ),
++ Field::number("requested_fps", max_fps as u64),
++ Field::flag("system_audio", inputs.capture_system_audio),
++ Field::flag("microphone", inputs.mic_feed.is_some()),
++ Field::flag("camera", inputs.camera_feed.is_some()),
++ ],
++ );
++ if let Some(microphone) = &inputs.mic_feed {
++ let info = microphone.audio_info();
++ diagnostic.field(Field::number(
++ "microphone_sample_rate",
++ info.sample_rate as u64,
++ ));
++ diagnostic.field(Field::number("microphone_channels", info.channels as u64));
++ diagnostic.field(Field::flag(
++ "microphone_wireless",
++ info.is_wireless_transport,
++ ));
++ }
++ if let Some(camera) = &inputs.camera_feed {
++ let info = camera.video_info();
++ diagnostic.field(Field::number("camera_width", info.width as u64));
++ diagnostic.field(Field::number("camera_height", info.height as u64));
++ diagnostic.field(Field::number(
++ "camera_fps_numerator",
++ info.frame_rate.0 as u64,
++ ));
++ diagnostic.field(Field::number(
++ "camera_fps_denominator",
++ info.frame_rate.1 as u64,
++ ));
++ }
++ diagnostic.stage("initializing_capture");
++
#[cfg(target_os = "linux")]
anyhow::ensure!(
!matches!(inputs.capture_target, ScreenCaptureTarget::CameraOnly)
@@@ -1309,7 -1309,7 +1392,9 @@@
#[cfg(target_os = "linux")]
let done_fut = lifecycle.done_fut();
let health_rx = pipeline.video.take_health_rx();
++ diagnostic.stage("recording");
let actor_ref = Actor::spawn(Actor {
++ diagnostic: Some(diagnostic),
recording_dir,
output_dir,
capture_target: inputs.capture_target.clone(),
@@@ -1482,6 -1482,6 +1567,7 @@@ mod tests
#[tokio::test]
async fn actor_retains_terminal_error_after_internal_stop() {
let mut actor = Actor {
++ diagnostic: None,
recording_dir: PathBuf::new(),
output_dir: PathBuf::new(),
capture_target: ScreenCaptureTarget::CameraOnly,
@@@ -1808,6 -1808,6 +1894,7 @@@ mod quiescence_tests
let video_done = video.done_fut();
let audio_done = audio.as_ref().map(OutputPipeline::done_fut);
let actor_ref = Actor::spawn(Actor {
++ diagnostic: None,
recording_dir: directory.to_path_buf(),
output_dir: directory.join("display"),
capture_target: ScreenCaptureTarget::CameraOnly,
@@@ -2026,6 -2026,6 +2113,7 @@@
let pipeline_cancel = video.cancel_token();
let done = video.done_fut();
let actor_ref = Actor::spawn(Actor {
++ diagnostic: None,
recording_dir: directory.to_path_buf(),
output_dir: output.clone(),
capture_target: ScreenCaptureTarget::CameraOnly,
@@@ -2739,6 -2739,6 +2827,7 @@@ mod non_linux_stop_tests
fn stopped_actor(error: Option<String>) -> Actor {
Actor {
++ diagnostic: None,
recording_dir: PathBuf::new(),
output_dir: PathBuf::new(),
capture_target: ScreenCaptureTarget::CameraOnly,
@@@ -2831,6 -2831,6 +2920,7 @@@
.unwrap();
let audio_done = audio.done_fut();
let actor = Actor::spawn(Actor {
++ diagnostic: None,
recording_dir: directory.path().to_path_buf(),
output_dir: directory.path().join("display"),
capture_target: ScreenCaptureTarget::CameraOnly,
diff --cc crates/recording/src/instant_recording/completion.rs
index 2f6ea8468,2f6ea8468..8d910ec0b
--- a/crates/recording/src/instant_recording/completion.rs
+++ b/crates/recording/src/instant_recording/completion.rs
@@@ -183,6 -183,6 +183,7 @@@ mod tests
};
let video_cancel = video.cancel_token();
let actor = Actor::spawn(Actor {
++ diagnostic: None,
recording_dir: project.to_path_buf(),
output_dir: segments_dir.clone(),
capture_target: if progressive {
diff --cc crates/recording/src/output_pipeline/core.rs
index 12431b6d7,12431b6d7..34523cd5b
--- a/crates/recording/src/output_pipeline/core.rs
+++ b/crates/recording/src/output_pipeline/core.rs
@@@ -438,6 -438,6 +438,60 @@@ fn new_health_channel() -> (HealthSende
}
pub fn emit_health(tx: &HealthSender, event: PipelineHealthEvent) {
++ use cap_utils::operation_diagnostics::{Field, health_event};
++ match &event {
++ PipelineHealthEvent::FrameDropRateHigh { rate_pct, .. } => health_event(
++ 0,
++ "high_frame_drop_rate",
++ &[Field::number(
++ "drop_rate_basis_points",
++ (rate_pct * 100.0).max(0.0) as u64,
++ )],
++ ),
++ PipelineHealthEvent::AudioGapDetected { gap_ms } => {
++ health_event(1, "audio_gap", &[Field::number("gap_ms", *gap_ms)])
++ }
++ PipelineHealthEvent::AudioDegradedToVideoOnly { .. } => {
++ health_event(2, "audio_degraded_to_video_only", &[])
++ }
++ PipelineHealthEvent::SourceRestarting => health_event(3, "source_restarting", &[]),
++ PipelineHealthEvent::SourceRestarted => health_event(4, "source_restarted", &[]),
++ PipelineHealthEvent::Stalled { waited_ms, .. } => health_event(
++ 5,
++ "pipeline_stalled",
++ &[Field::number("waited_ms", *waited_ms)],
++ ),
++ PipelineHealthEvent::MuxerCrashed { .. } => health_event(6, "muxer_crashed", &[]),
++ PipelineHealthEvent::DiskSpaceLow {
++ bytes_remaining, ..
++ } => health_event(
++ 7,
++ "disk_space_low",
++ &[Field::number("bytes_remaining", *bytes_remaining)],
++ ),
++ PipelineHealthEvent::DiskSpaceExhausted { bytes_remaining } => health_event(
++ 8,
++ "disk_space_exhausted",
++ &[Field::number("bytes_remaining", *bytes_remaining)],
++ ),
++ PipelineHealthEvent::DeviceLost { .. } => health_event(9, "device_lost", &[]),
++ PipelineHealthEvent::EncoderRebuilt { attempt, .. } => health_event(
++ 10,
++ "encoder_rebuilt",
++ &[Field::number("attempt", *attempt as u64)],
++ ),
++ PipelineHealthEvent::SourceAudioReset { starvation_ms, .. } => health_event(
++ 11,
++ "source_audio_reset",
++ &[Field::number("starvation_ms", *starvation_ms)],
++ ),
++ PipelineHealthEvent::RecoveryFragmentCorrupt { .. } => {
++ health_event(12, "recovery_fragment_corrupt", &[])
++ }
++ PipelineHealthEvent::CaptureTargetLost { .. } => {
++ health_event(13, "capture_target_lost", &[])
++ }
++ }
let _ = tx.try_send(event);
}
diff --cc crates/recording/src/studio_recording.rs
index 7f68985b6,2cb5bd5dd..e44d10182
--- a/crates/recording/src/studio_recording.rs
+++ b/crates/recording/src/studio_recording.rs
@@@ -334,6 -291,6 +334,7 @@@ pub struct ActorHandle
#[derive(kameo::Actor)]
pub struct Actor {
++ diagnostic: Option<cap_utils::operation_diagnostics::Operation>,
#[cfg(target_os = "linux")]
lifetime: StudioLifetimeOwner,
recording_dir: PathBuf,
@@@ -514,6 -487,6 +515,25 @@@ impl Actor
&mut self,
discard: bool,
ctx: &mut Context<Self, anyhow::Result<CompletedRecording>>,
++ ) -> anyhow::Result<CompletedRecording> {
++ if let Some(diagnostic) = &mut self.diagnostic {
++ diagnostic.stage(if discard { "discarding" } else { "finalizing" });
++ }
++ let result = self.handle_stop_inner(discard, ctx).await;
++ if let Some(mut diagnostic) = self.diagnostic.take() {
++ diagnostic.field(cap_utils::operation_diagnostics::Field::number(
++ "segments",
++ self.segments.len() as u64,
++ ));
++ diagnostic.finish(result.is_ok());
++ }
++ result
++ }
++
++ async fn handle_stop_inner(
++ &mut self,
++ discard: bool,
++ ctx: &mut Context<Self, anyhow::Result<CompletedRecording>>,
) -> anyhow::Result<CompletedRecording> {
#[cfg(target_os = "linux")]
self.cancel_resume().await?;
@@@ -663,6 -636,6 +683,9 @@@ impl Message<Pause> for Actor
index,
..
}) => {
++ if let Some(diagnostic) = &mut self.diagnostic {
++ diagnostic.stage("pausing");
++ }
let stopped = self
.stop_pipeline(pipeline, segment_start_time)
.await
@@@ -674,6 -647,6 +697,9 @@@
cursors,
next_cursor_id,
});
++ if let Some(diagnostic) = &mut self.diagnostic {
++ diagnostic.stage("paused");
++ }
}
Ok(_) => {
let error = anyhow!(UNCONFIRMED_CAPTURE_CLEANUP);
@@@ -846,6 -819,6 +872,9 @@@ impl Message<ResumeFinished> for Actor
segment_start_time: current_time_f64(),
segment_start_instant: Instant::now(),
});
++ if let Some(diagnostic) = &mut self.diagnostic {
++ diagnostic.stage("recording");
++ }
attempt.reply(Ok(()));
} else {
let cleanup =
@@@ -944,6 -917,6 +973,9 @@@ impl Message<Resume> for Actor
};
let ready = attempt.ready_future();
self.resume_attempt = Some(attempt);
++ if let Some(diagnostic) = &mut self.diagnostic {
++ diagnostic.stage("resuming");
++ }
let actor = ctx.actor_ref().clone();
drop(tokio::spawn(async move {
let prepared = std::panic::AssertUnwindSafe(prepare_resume_pipeline(
@@@ -998,6 -971,6 +1030,9 @@@ impl Message<Resume> for Actor
cursors,
next_cursor_id,
}) => {
++ if let Some(diagnostic) = &mut self.diagnostic {
++ diagnostic.stage("resuming");
++ }
let pipeline = self
.segment_factory
.create_next(cursors, next_cursor_id)
@@@ -1006,6 -979,6 +1041,9 @@@
let pipeline = pipeline.map_err(|error| self.preserve_windows_stop_failure(error));
let pipeline = pipeline?;
++ if let Some(diagnostic) = &mut self.diagnostic {
++ diagnostic.stage("recording");
++ }
let new_segment_start_time = current_time_f64();
Some(ActorState::Recording {
@@@ -1028,6 -1001,6 +1066,9 @@@ impl Message<Cancel> for Actor
type Reply = anyhow::Result<()>;
async fn handle(&mut self, _: Cancel, _: &mut Context<Self, Self::Reply>) -> Self::Reply {
++ if let Some(diagnostic) = &mut self.diagnostic {
++ diagnostic.stage("cancelling");
++ }
#[cfg(target_os = "linux")]
self.cancel_resume().await?;
if let Some(failure) = self.terminal_stop_failure.as_ref() {
@@@ -1077,6 -1050,6 +1118,9 @@@
if let Some(error) = self.windows_failure() {
return Err(self.preserve_windows_stop_failure(anyhow!(error)));
}
++ if let Some(diagnostic) = self.diagnostic.take() {
++ diagnostic.finish(true);
++ }
Ok(())
}
}
@@@ -2112,6 -2085,6 +2156,49 @@@ async fn spawn_studio_recording_actor
max_fps: u32,
quality: crate::StudioQuality,
) -> anyhow::Result<ActorHandle> {
++ use cap_utils::operation_diagnostics::{Field, Operation};
++ let mut diagnostic = Operation::start(
++ "studio_recording",
++ &[
++ Field::identifier(
++ "resource",
++ cap_utils::operation_diagnostics::resource_id(&recording_dir),
++ ),
++ Field::number("requested_fps", max_fps as u64),
++ Field::flag("system_audio", base_inputs.capture_system_audio),
++ Field::flag("microphone", base_inputs.mic_feed.is_some()),
++ Field::flag("camera", base_inputs.camera_feed.is_some()),
++ Field::flag("fragmented", fragmented),
++ Field::flag("out_of_process_muxer", use_oop_muxer),
++ Field::flag("custom_cursor", custom_cursor_capture),
++ ],
++ );
++ if let Some(microphone) = &base_inputs.mic_feed {
++ let info = microphone.audio_info();
++ diagnostic.field(Field::number(
++ "microphone_sample_rate",
++ info.sample_rate as u64,
++ ));
++ diagnostic.field(Field::number("microphone_channels", info.channels as u64));
++ diagnostic.field(Field::flag(
++ "microphone_wireless",
++ info.is_wireless_transport,
++ ));
++ }
++ if let Some(camera) = &base_inputs.camera_feed {
++ let info = camera.video_info();
++ diagnostic.field(Field::number("camera_width", info.width as u64));
++ diagnostic.field(Field::number("camera_height", info.height as u64));
++ diagnostic.field(Field::number(
++ "camera_fps_numerator",
++ info.frame_rate.0 as u64,
++ ));
++ diagnostic.field(Field::number(
++ "camera_fps_denominator",
++ info.frame_rate.1 as u64,
++ ));
++ }
++ diagnostic.stage("initializing_capture");
ensure_dir(&recording_dir)?;
trace!("creating recording actor");
@@@ -2167,7 -2140,7 +2254,9 @@@
#[cfg(any(target_os = "linux", target_os = "macos", windows))]
let actor_recording_dir = recording_dir.clone();
++ diagnostic.stage("recording");
let actor_ref = Actor::spawn(Actor {
++ diagnostic: Some(diagnostic),
#[cfg(target_os = "linux")]
lifetime,
#[cfg(windows)]
@@@ -3436,6 -3279,6 +3525,7 @@@ mod tests
completion_tx.clone(),
);
let mut actor = Actor {
++ diagnostic: None,
recording_dir: path.to_path_buf(),
state: None,
all_tracks_stopped: true,
@@@ -3531,6 -3374,6 +3621,7 @@@
);
let timestamps = Timestamps::now();
let actor_ref = Actor::spawn(Actor {
++ diagnostic: None,
recording_dir: path.to_path_buf(),
state: Some(ActorState::Paused {
next_index: 1,
@@@ -3706,6 -3549,6 +3797,7 @@@
lifecycle: lifecycle.clone(),
recording_dir: path.to_path_buf(),
actor_ref: Actor::spawn(Actor {
++ diagnostic: None,
lifetime: StudioLifetimeOwner {
lifecycle,
armed: true,
@@@ -5156,6 -4999,6 +5248,7 @@@
);
(
Actor {
++ diagnostic: None,
recording_dir: recording_dir.to_owned(),
cancel_error: None,
state: Some(ActorState::Recording {
@@@ -5399,6 -5242,6 +5492,7 @@@ mod windows_cancel_tests
completion_tx.clone(),
);
Actor {
++ diagnostic: None,
recording_dir: PathBuf::new(),
state: None,
all_tracks_stopped: true,
diff --cc crates/rendering/src/layers/image.rs
index 2c5ff5ab8,000000000..1fa6f2204
mode 100644,000000..100644
--- a/crates/rendering/src/layers/image.rs
+++ b/crates/rendering/src/layers/image.rs
@@@ -1,1026 -1,0 +1,1180 @@@
+use std::{
+ collections::{HashMap, HashSet},
+ fs::{File, Metadata},
+ io::{BufReader, ErrorKind},
+ path::{Path, PathBuf},
+ time::SystemTime,
+};
+
+use bytemuck::{Pod, Zeroable};
+use cap_project::ImageSegment;
+use image::{ImageDecoder, RgbaImage};
+use wgpu::util::DeviceExt;
+
+use crate::{ProjectUniforms, RenderVideoConstants};
+
+const MAX_TEXTURES: usize = 16;
+const MAX_TEXTURE_BYTES: u64 = 256 * 1024 * 1024;
+const MAX_RGBA_BYTES: u64 = 64 * 1024 * 1024;
+const MAX_DECODE_ALLOC: u64 = 512 * 1024 * 1024;
+pub const MAX_IMAGE_SOURCE_DIMENSION: u32 = 32_768;
+pub const MAX_IMAGE_SOURCE_PIXELS: u64 = 64 * 1024 * 1024;
+pub const MAX_IMAGE_SOURCE_BYTES: u64 = 256 * 1024 * 1024;
+pub const MAX_IMAGE_DECODED_BYTES: u64 = 256 * 1024 * 1024;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+enum FileVersion {
+ File {
+ length: u64,
+ modified: Option<SystemTime>,
+ created: Option<SystemTime>,
+ #[cfg(unix)]
+ identity: (u64, u64, i64, i64),
+ },
+ Unavailable(ErrorKind),
+ NotFile,
+}
+
+impl FileVersion {
+ fn from_metadata(metadata: &Metadata) -> Self {
+ if !metadata.is_file() {
+ return Self::NotFile;
+ }
+ Self::File {
+ length: metadata.len(),
+ modified: metadata.modified().ok(),
+ created: metadata.created().ok(),
+ #[cfg(unix)]
+ identity: {
+ use std::os::unix::fs::MetadataExt;
+ (
+ metadata.dev(),
+ metadata.ino(),
+ metadata.ctime(),
+ metadata.ctime_nsec(),
+ )
+ },
+ }
+ }
+
+ fn read(path: &Path) -> Self {
+ match std::fs::metadata(path) {
+ Ok(metadata) => Self::from_metadata(&metadata),
+ Err(error) => Self::Unavailable(error.kind()),
+ }
+ }
+}
+
+struct CachedTexture {
+ texture: wgpu::Texture,
+ byte_len: u64,
+ last_used: u64,
+}
+
+enum CacheState {
+ Ready(CachedTexture),
+ Evicted,
+ Failed,
+}
+
+struct CacheEntry {
+ version: FileVersion,
+ state: CacheState,
+}
+
+struct ActiveTexture {
+ version: FileVersion,
+ texture: wgpu::Texture,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy, PartialEq, Pod, Zeroable)]
+struct ImageUniforms {
+ center_size: [f32; 4],
+ rotation_opacity_radius: [f32; 4],
+ flips: [f32; 4],
+}
+
+struct CachedDraw {
+ texture: wgpu::Texture,
+ uniforms: ImageUniforms,
+ group: wgpu::BindGroup,
+}
+
+fn visible_images(
+ segments: &[ImageSegment],
+ frame_number: u32,
+ frame_rate: u32,
+ output_size: (u32, u32),
+) -> Vec<(&ImageSegment, ImageUniforms)> {
+ if frame_rate == 0 || output_size.0 == 0 || output_size.1 == 0 {
+ return Vec::new();
+ }
+ let time = f64::from(frame_number) / f64::from(frame_rate);
+ let mut images: Vec<_> = segments
+ .iter()
+ .enumerate()
+ .filter_map(|(index, segment)| {
+ if !segment.is_active_at(time)
+ || segment.path.is_empty()
+ || !segment.opacity.is_finite()
+ || segment.opacity <= 0.0
+ || !segment.rotation.is_finite()
+ || !segment.rounding.is_finite()
+ {
+ return None;
+ }
+ let center_size = [
+ (segment.center.x * f64::from(output_size.0)) as f32,
+ (segment.center.y * f64::from(output_size.1)) as f32,
+ (segment.size.x * f64::from(output_size.0)) as f32,
+ (segment.size.y * f64::from(output_size.1)) as f32,
+ ];
+ if center_size
+ .iter()
+ .any(|value| !value.is_finite() || value.abs() > 1.0e7)
+ || center_size[2] <= 0.0
+ || center_size[3] <= 0.0
+ {
+ return None;
+ }
+ let (sin, cos) = (segment.rotation % 360.0).to_radians().sin_cos();
+ let half_width = (cos.abs() * center_size[2] + sin.abs() * center_size[3]) * 0.5;
+ let half_height = (sin.abs() * center_size[2] + cos.abs() * center_size[3]) * 0.5;
+ if center_size[0] + half_width < 0.0
+ || center_size[1] + half_height < 0.0
+ || center_size[0] - half_width > output_size.0 as f32
+ || center_size[1] - half_height > output_size.1 as f32
+ {
+ return None;
+ }
+ Some((
+ index,
+ segment,
+ ImageUniforms {
+ center_size,
+ rotation_opacity_radius: [
+ cos,
+ sin,
+ segment.opacity.clamp(0.0, 1.0),
+ segment.rounding.clamp(0.0, 100.0)
+ * 0.005
+ * center_size[2].min(center_size[3]),
+ ],
+ flips: [
+ u8::from(segment.flip_x) as f32,
+ u8::from(segment.flip_y) as f32,
+ 0.0,
+ 0.0,
+ ],
+ },
+ ))
+ })
+ .collect();
+ images.sort_unstable_by_key(|(index, segment, _)| (segment.track, *index));
+ images
+ .into_iter()
+ .map(|(_, segment, uniforms)| (segment, uniforms))
+ .collect()
+}
+
+fn texture_dimensions(width: u32, height: u32, max_dimension: u32) -> (u32, u32) {
+ let scale = (MAX_RGBA_BYTES as f64 / (f64::from(width) * f64::from(height) * 4.0))
+ .sqrt()
+ .min(f64::from(max_dimension) / f64::from(width.max(height)))
+ .min(1.0);
+ (
+ ((f64::from(width) * scale) as u32).max(1),
+ ((f64::from(height) * scale) as u32).max(1),
+ )
+}
+
+fn premultiplied_mips(mut rgba: RgbaImage, max_dimension: u32) -> Vec<RgbaImage> {
+ for pixel in rgba.pixels_mut() {
+ let alpha = u16::from(pixel[3]);
+ for channel in &mut pixel.0[..3] {
+ *channel = ((u16::from(*channel) * alpha + 127) / 255) as u8;
+ }
+ }
+ let (width, height) = texture_dimensions(rgba.width(), rgba.height(), max_dimension);
+ if rgba.dimensions() != (width, height) {
+ rgba = image::imageops::resize(&rgba, width, height, image::imageops::FilterType::Triangle);
+ }
+ let mut levels = vec![rgba];
+ while let Some(previous) = levels.last() {
+ let (width, height) = previous.dimensions();
+ if width == 1 && height == 1 {
+ break;
+ }
+ levels.push(image::imageops::resize(
+ previous,
+ (width / 2).max(1),
+ (height / 2).max(1),
+ image::imageops::FilterType::Triangle,
+ ));
+ }
+ levels
+}
+
+fn decode_image(
+ path: &Path,
+ expected: &FileVersion,
+ max_dimension: u32,
+) -> anyhow::Result<Vec<RgbaImage>> {
+ let file = File::open(path)?;
+ let metadata = file.metadata()?;
+ anyhow::ensure!(
+ FileVersion::from_metadata(&metadata) == *expected,
+ "Image changed before decoding"
+ );
+ anyhow::ensure!(
+ metadata.is_file() && metadata.len() <= MAX_IMAGE_SOURCE_BYTES,
+ "Image file exceeds the decode limit"
+ );
+ let mut reader = image::ImageReader::new(BufReader::new(file)).with_guessed_format()?;
+ let mut limits = image::Limits::default();
+ limits.max_image_width = Some(MAX_IMAGE_SOURCE_DIMENSION);
+ limits.max_image_height = Some(MAX_IMAGE_SOURCE_DIMENSION);
+ limits.max_alloc = Some(MAX_DECODE_ALLOC);
+ reader.limits(limits.clone());
+ let mut decoder = reader.into_decoder()?;
+ let (width, height) = decoder.dimensions();
+ anyhow::ensure!(
+ width > 0 && height > 0 && u64::from(width) * u64::from(height) <= MAX_IMAGE_SOURCE_PIXELS,
+ "Image dimensions exceed the source pixel limit"
+ );
+ anyhow::ensure!(
+ decoder.total_bytes() <= MAX_IMAGE_DECODED_BYTES,
+ "Image exceeds the source decode allocation limit"
+ );
+ limits.reserve(decoder.total_bytes())?;
+ decoder.set_limits(limits)?;
+ let orientation = decoder.orientation()?;
+ let mut decoded = image::DynamicImage::from_decoder(decoder)?;
+ decoded.apply_orientation(orientation);
+ let levels = premultiplied_mips(decoded.into_rgba8(), max_dimension);
+ anyhow::ensure!(
+ FileVersion::read(path) == *expected,
+ "Image changed while decoding"
+ );
+ Ok(levels)
+}
+
+fn upload_texture(
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ levels: &[RgbaImage],
+) -> wgpu::Texture {
+ let texture = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("Image overlay texture"),
+ size: wgpu::Extent3d {
+ width: levels[0].width(),
+ height: levels[0].height(),
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: levels.len() as u32,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ view_formats: &[],
+ });
+ for (level, rgba) in levels.iter().enumerate() {
+ queue.write_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: &texture,
+ mip_level: level as u32,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ rgba.as_raw(),
+ wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(rgba.width() * 4),
+ rows_per_image: Some(rgba.height()),
+ },
+ wgpu::Extent3d {
+ width: rgba.width(),
+ height: rgba.height(),
+ depth_or_array_layers: 1,
+ },
+ );
+ }
+ texture
+}
+
+pub struct ImageLayer {
+ pipeline: wgpu::RenderPipeline,
+ sampler: wgpu::Sampler,
+ draws: Vec<wgpu::BindGroup>,
++ draw_tracks: Vec<u32>,
+ cached_draws: Vec<CachedDraw>,
+ cache: HashMap<PathBuf, CacheEntry>,
+ active_textures: HashMap<PathBuf, ActiveTexture>,
+ counter: u64,
+}
+
+impl ImageLayer {
+ pub fn new(device: &wgpu::Device) -> Self {
+ let shader = device.create_shader_module(wgpu::include_wgsl!("../shaders/image.wgsl"));
+ let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("Image overlay pipeline"),
+ layout: None,
+ vertex: wgpu::VertexState {
+ module: &shader,
+ entry_point: Some("vs_main"),
+ compilation_options: Default::default(),
+ buffers: &[],
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &shader,
+ entry_point: Some("fs_main"),
+ compilation_options: Default::default(),
+ targets: &[Some(wgpu::ColorTargetState {
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ }),
+ primitive: wgpu::PrimitiveState::default(),
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ multiview: None,
+ cache: None,
+ });
+ Self {
+ pipeline,
+ sampler: device.create_sampler(&wgpu::SamplerDescriptor {
+ label: Some("Image overlay sampler"),
+ address_mode_u: wgpu::AddressMode::ClampToEdge,
+ address_mode_v: wgpu::AddressMode::ClampToEdge,
+ mag_filter: wgpu::FilterMode::Linear,
+ min_filter: wgpu::FilterMode::Linear,
+ mipmap_filter: wgpu::FilterMode::Linear,
+ ..Default::default()
+ }),
+ draws: Vec::new(),
++ draw_tracks: Vec::new(),
+ cached_draws: Vec::new(),
+ cache: HashMap::new(),
+ active_textures: HashMap::new(),
+ counter: 0,
+ }
+ }
+
+ fn make_room(&mut self, byte_len: u64) {
+ loop {
+ let mut count = 0;
+ let mut used = 0;
+ let mut oldest = None;
+ for (path, entry) in &self.cache {
+ if let CacheState::Ready(texture) = &entry.state {
+ count += 1;
+ used += texture.byte_len;
+ if oldest
+ .as_ref()
+ .is_none_or(|(_, last_used)| texture.last_used < *last_used)
+ {
+ oldest = Some((path.clone(), texture.last_used));
+ }
+ }
+ }
+ if count < MAX_TEXTURES && used + byte_len <= MAX_TEXTURE_BYTES {
+ return;
+ }
+ let Some((path, _)) = oldest else {
+ return;
+ };
+ if let Some(entry) = self.cache.get_mut(&path) {
+ entry.state = CacheState::Evicted;
+ }
+ }
+ }
+
+ async fn ensure_texture(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ path: &Path,
+ version: &FileVersion,
+ reusable: Option<wgpu::Texture>,
+ ) -> Option<wgpu::Texture> {
+ let entry = self
+ .cache
+ .entry(path.to_path_buf())
+ .or_insert_with(|| CacheEntry {
+ version: version.clone(),
+ state: CacheState::Evicted,
+ });
+ if entry.version != *version {
+ entry.version = version.clone();
+ entry.state = CacheState::Evicted;
+ }
+ if matches!(entry.state, CacheState::Failed) {
+ return None;
+ }
+ if !matches!(version, FileVersion::File { .. }) {
+ tracing::warn!(path = %path.display(), ?version, "Image overlay is unavailable");
+ entry.state = CacheState::Failed;
+ return None;
+ }
+ self.counter = self.counter.saturating_add(1);
+ if let CacheState::Ready(texture) = &mut entry.state {
+ texture.last_used = self.counter;
+ return Some(texture.texture.clone());
+ }
+ if let Some(texture) = reusable {
+ self.cache_texture(path, texture.clone());
+ return Some(texture);
+ }
+ let decode_path = path.to_path_buf();
+ let decode_version = version.clone();
+ let max_dimension = device.limits().max_texture_dimension_2d;
+ let decoded = tokio::task::spawn_blocking(move || {
+ decode_image(&decode_path, &decode_version, max_dimension)
+ })
+ .await;
+ let levels = match decoded
+ .map_err(anyhow::Error::from)
+ .and_then(|result| result)
+ {
+ Ok(levels) => levels,
+ Err(error) => {
+ tracing::warn!(path = %path.display(), %error, "Failed to decode image overlay");
+ if let Some(entry) = self.cache.get_mut(path) {
+ entry.state = CacheState::Failed;
+ }
+ return None;
+ }
+ };
+ let texture = upload_texture(device, queue, &levels);
+ self.cache_texture(path, texture.clone());
+ Some(texture)
+ }
+
+ fn cache_texture(&mut self, path: &Path, texture: wgpu::Texture) {
+ let byte_len = (0..texture.mip_level_count())
+ .map(|level| {
+ u64::from((texture.width() >> level).max(1))
+ * u64::from((texture.height() >> level).max(1))
+ * 4
+ })
+ .sum();
+ self.make_room(byte_len);
+ if let Some(entry) = self.cache.get_mut(path) {
+ entry.state = CacheState::Ready(CachedTexture {
+ texture,
+ byte_len,
+ last_used: self.counter,
+ });
+ }
+ }
+
++ #[cfg(test)]
+ fn push_draw(
+ &mut self,
+ device: &wgpu::Device,
+ texture: &wgpu::Texture,
+ uniforms: ImageUniforms,
++ ) {
++ self.push_draw_with_track(device, texture, uniforms, u32::MAX);
++ }
++
++ fn push_draw_with_track(
++ &mut self,
++ device: &wgpu::Device,
++ texture: &wgpu::Texture,
++ uniforms: ImageUniforms,
++ track: u32,
+ ) {
+ let index = self.draws.len();
+ if let Some(draw) = self.cached_draws.get(index)
+ && draw.texture == *texture
+ && draw.uniforms == uniforms
+ {
+ self.draws.push(draw.group.clone());
++ self.draw_tracks.push(track);
+ return;
+ }
+ let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("Image overlay uniforms"),
+ contents: bytemuck::bytes_of(&uniforms),
+ usage: wgpu::BufferUsages::UNIFORM,
+ });
+ let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("Image overlay bind group"),
+ layout: &self.pipeline.get_bind_group_layout(0),
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(
+ &texture.create_view(&wgpu::TextureViewDescriptor::default()),
+ ),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::Sampler(&self.sampler),
+ },
+ ],
+ });
+ let draw = CachedDraw {
+ texture: texture.clone(),
+ uniforms,
+ group: group.clone(),
+ };
+ if let Some(cached) = self.cached_draws.get_mut(index) {
+ *cached = draw;
+ } else {
+ self.cached_draws.push(draw);
+ }
+ self.draws.push(group);
++ self.draw_tracks.push(track);
+ }
+
+ pub async fn prepare(&mut self, constants: &RenderVideoConstants, uniforms: &ProjectUniforms) {
+ self.draws.clear();
++ self.draw_tracks.clear();
+ let mut previous_textures = std::mem::take(&mut self.active_textures);
+ let Some(timeline) = &uniforms.project.timeline else {
+ self.cache.clear();
+ self.cached_draws.clear();
+ return;
+ };
+ let project_path = &constants.recording_meta.project_path;
+ let referenced: HashSet<_> = timeline
+ .image_segments
+ .iter()
+ .filter(|segment| !segment.path.is_empty())
+ .map(|segment| project_path.join(&segment.path))
+ .collect();
+ self.cache.retain(|path, _| referenced.contains(path));
+ let images = visible_images(
+ &timeline.image_segments,
+ uniforms.frame_number,
+ uniforms.frame_rate,
+ uniforms.output_size,
+ );
+ if images.is_empty() {
+ self.cached_draws.clear();
+ return;
+ }
+ let paths: HashSet<_> = images
+ .iter()
+ .map(|(segment, _)| project_path.join(&segment.path))
+ .collect();
+ let versions = match tokio::task::spawn_blocking(move || {
+ paths
+ .into_iter()
+ .map(|path| {
+ let version = FileVersion::read(&path);
+ (path, version)
+ })
+ .collect::<HashMap<_, _>>()
+ })
+ .await
+ {
+ Ok(versions) => versions,
+ Err(error) => {
+ tracing::warn!(%error, "Image overlay metadata task failed");
+ self.cached_draws.clear();
+ return;
+ }
+ };
+ for (segment, image_uniforms) in images {
+ let path = project_path.join(&segment.path);
+ let Some(version) = versions.get(&path) else {
+ continue;
+ };
+ let reusable = self
+ .active_textures
+ .get(&path)
+ .filter(|active| active.version == *version)
+ .map(|active| active.texture.clone())
+ .or_else(|| {
+ previous_textures
+ .remove(&path)
+ .filter(|active| active.version == *version)
+ .map(|active| active.texture)
+ });
+ if let Some(texture) = self
+ .ensure_texture(
+ &constants.device,
+ &constants.queue,
+ &path,
+ version,
+ reusable,
+ )
+ .await
+ {
+ self.active_textures.insert(
+ path,
+ ActiveTexture {
+ version: version.clone(),
+ texture: texture.clone(),
+ },
+ );
- self.push_draw(&constants.device, &texture, image_uniforms);
++ self.push_draw_with_track(
++ &constants.device,
++ &texture,
++ image_uniforms,
++ segment.track,
++ );
+ }
+ }
+ self.cached_draws.truncate(self.draws.len());
+ }
+
+ pub fn has_content(&self) -> bool {
+ !self.draws.is_empty()
+ }
+
++ pub fn has_track(&self, track: u32) -> bool {
++ self.draw_tracks.contains(&track)
++ }
++
+ pub fn render(&self, pass: &mut wgpu::RenderPass<'_>) {
+ if !self.has_content() {
+ return;
+ }
+ pass.set_pipeline(&self.pipeline);
+ for group in &self.draws {
+ pass.set_bind_group(0, group, &[]);
+ pass.draw(0..3, 0..1);
+ }
+ }
++
++ pub fn render_track(&self, pass: &mut wgpu::RenderPass<'_>, track: u32) {
++ if !self.has_content() {
++ return;
++ }
++ pass.set_pipeline(&self.pipeline);
++ for (group, draw_track) in self.draws.iter().zip(&self.draw_tracks) {
++ if *draw_track == track {
++ pass.set_bind_group(0, group, &[]);
++ pass.draw(0..3, 0..1);
++ }
++ }
++ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use cap_project::XY;
+
+ fn segment(path: &str) -> ImageSegment {
+ ImageSegment {
+ start: 1.0,
+ end: 2.0,
+ path: path.to_owned(),
+ center: XY::new(0.5, 0.5),
+ size: XY::new(0.5, 0.5),
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn image_timing_order_and_invalid_geometry() {
+ let mut images = vec![segment("top"), segment("bottom"), segment("top-later")];
+ images[0].track = 2;
+ images[1].track = 1;
+ images[2].track = 2;
+ let visible = visible_images(&images, 30, 30, (64, 64));
+ assert_eq!(
+ visible
+ .iter()
+ .map(|(image, _)| image.path.as_str())
+ .collect::<Vec<_>>(),
+ ["bottom", "top", "top-later"]
+ );
+ for frame in [0, 29, 60, 61] {
+ assert!(visible_images(&images, frame, 30, (64, 64)).is_empty());
+ }
+ assert!(visible_images(&images, 30, 0, (64, 64)).is_empty());
+ assert!(visible_images(&images, 30, 30, (0, 64)).is_empty());
+ images[0].enabled = false;
+ images[1].center.x = f64::NAN;
+ images[2].size.y = -0.1;
+ assert!(visible_images(&images, 30, 30, (64, 64)).is_empty());
+ let mut clamped = segment("clamped");
+ clamped.opacity = 2.0;
+ clamped.rounding = 200.0;
+ let clamped = [clamped];
+ let visible = visible_images(&clamped, 30, 30, (64, 64));
+ assert_eq!(visible[0].1.rotation_opacity_radius[2..], [1.0, 16.0]);
+ }
+
+ #[test]
+ fn image_mips_do_not_bleed_transparent_rgb() {
+ let rgba = RgbaImage::from_raw(2, 1, vec![255, 0, 0, 255, 0, 255, 255, 0]).unwrap();
+ let levels = premultiplied_mips(rgba.clone(), 8192);
+ assert_eq!(levels[0].get_pixel(1, 0).0, [0; 4]);
+ let mip = levels[1].get_pixel(0, 0).0;
+ assert_eq!(mip[0], mip[3]);
+ assert_eq!(&mip[1..3], &[0, 0]);
+ assert!((127..=128).contains(&mip[3]));
+ let downscaled = premultiplied_mips(rgba, 1);
+ assert_eq!(downscaled[0].dimensions(), (1, 1));
+ assert_eq!(downscaled[0].get_pixel(0, 0).0, mip);
+ }
+
+ #[test]
+ fn image_texture_size_preserves_large_sources_within_gpu_limits() {
+ assert_eq!(texture_dimensions(800, 600, 8192), (800, 600));
+ assert_eq!(texture_dimensions(8192, 8192, 8192), (4096, 4096));
+ assert_eq!(texture_dimensions(32_768, 1, 8192), (8192, 1));
+ for dimensions in [(12_000, 5_000), (5_000, 12_000), (8192, 8192)] {
+ let (width, height) = texture_dimensions(dimensions.0, dimensions.1, 4096);
+ assert!(width <= 4096 && height <= 4096);
+ assert!(u64::from(width) * u64::from(height) * 4 <= MAX_RGBA_BYTES);
+ }
+ }
+
+ fn render_pixels(device: &wgpu::Device, queue: &wgpu::Queue, layer: &ImageLayer) -> Vec<u8> {
+ let output = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("Image overlay test output"),
+ size: wgpu::Extent3d {
+ width: 64,
+ height: 64,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
+ view_formats: &[],
+ });
+ let buffer = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("Image overlay test readback"),
+ size: 64 * 64 * 4,
+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
+ mapped_at_creation: false,
+ });
+ let view = output.create_view(&Default::default());
+ let mut encoder = device.create_command_encoder(&Default::default());
+ {
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("Image overlay pixel test"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &view,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ });
+ layer.render(&mut pass);
+ }
+ encoder.copy_texture_to_buffer(
+ output.as_image_copy(),
+ wgpu::TexelCopyBufferInfo {
+ buffer: &buffer,
+ layout: wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(256),
+ rows_per_image: Some(64),
+ },
+ },
+ output.size(),
+ );
+ queue.submit([encoder.finish()]);
+ let (sender, receiver) = std::sync::mpsc::channel();
+ buffer
+ .slice(..)
+ .map_async(wgpu::MapMode::Read, move |result| {
+ sender.send(result).expect("Image readback receiver");
+ });
+ device
+ .poll(wgpu::PollType::Wait)
+ .expect("Poll image GPU test");
+ receiver.recv().unwrap().unwrap();
+ let pixels = buffer.slice(..).get_mapped_range().to_vec();
+ buffer.unmap();
+ pixels
+ }
+
++ fn render_tracks_pixels(
++ device: &wgpu::Device,
++ queue: &wgpu::Queue,
++ layer: &ImageLayer,
++ tracks: &[u32],
++ ) -> Vec<u8> {
++ let output = device.create_texture(&wgpu::TextureDescriptor {
++ label: Some("Image overlay track-order test output"),
++ size: wgpu::Extent3d {
++ width: 64,
++ height: 64,
++ depth_or_array_layers: 1,
++ },
++ mip_level_count: 1,
++ sample_count: 1,
++ dimension: wgpu::TextureDimension::D2,
++ format: wgpu::TextureFormat::Rgba8Unorm,
++ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
++ view_formats: &[],
++ });
++ let buffer = device.create_buffer(&wgpu::BufferDescriptor {
++ label: Some("Image overlay track-order test readback"),
++ size: 64 * 64 * 4,
++ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
++ mapped_at_creation: false,
++ });
++ let view = output.create_view(&Default::default());
++ let mut encoder = device.create_command_encoder(&Default::default());
++ {
++ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
++ label: Some("Image overlay track-order pixel test"),
++ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
++ view: &view,
++ resolve_target: None,
++ ops: wgpu::Operations {
++ load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
++ store: wgpu::StoreOp::Store,
++ },
++ })],
++ depth_stencil_attachment: None,
++ timestamp_writes: None,
++ occlusion_query_set: None,
++ });
++ for track in tracks {
++ layer.render_track(&mut pass, *track);
++ }
++ }
++ encoder.copy_texture_to_buffer(
++ output.as_image_copy(),
++ wgpu::TexelCopyBufferInfo {
++ buffer: &buffer,
++ layout: wgpu::TexelCopyBufferLayout {
++ offset: 0,
++ bytes_per_row: Some(256),
++ rows_per_image: Some(64),
++ },
++ },
++ output.size(),
++ );
++ queue.submit([encoder.finish()]);
++ let (sender, receiver) = std::sync::mpsc::channel();
++ buffer
++ .slice(..)
++ .map_async(wgpu::MapMode::Read, move |result| {
++ sender
++ .send(result)
++ .expect("Image track-order readback receiver");
++ });
++ device
++ .poll(wgpu::PollType::Wait)
++ .expect("Poll image track-order GPU test");
++ receiver.recv().unwrap().unwrap();
++ let pixels = buffer.slice(..).get_mapped_range().to_vec();
++ buffer.unmap();
++ pixels
++ }
++
+ fn pixel(pixels: &[u8], x: usize, y: usize) -> [u8; 4] {
+ pixels[(y * 64 + x) * 4..(y * 64 + x + 1) * 4]
+ .try_into()
+ .unwrap()
+ }
+
+ fn assert_pixel(actual: [u8; 4], expected: [u8; 4]) {
+ assert!(
+ actual.iter().zip(expected).all(|(a, b)| a.abs_diff(b) <= 2),
+ "Expected {expected:?}, got {actual:?}"
+ );
+ }
+
+ fn test_device() -> Option<(wgpu::Device, wgpu::Queue)> {
+ let instance = crate::create_wgpu_instance_sync();
+ let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else {
+ eprintln!("No GPU adapter available; skipping image overlay pixel tests");
+ return None;
+ };
+ Some(pollster::block_on(adapter.request_device(&Default::default())).unwrap())
+ }
+
+ #[test]
+ fn unchanged_image_draws_reuse_resources_without_mutating_queued_frames() {
+ let Some((device, queue)) = test_device() else {
+ return;
+ };
+ let mut layer = ImageLayer::new(&device);
+ let red = upload_texture(
+ &device,
+ &queue,
+ &[RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255]))],
+ );
+ let image = [segment("red")];
+ let uniforms = visible_images(&image, 30, 30, (64, 64))[0].1;
+ layer.push_draw(&device, &red, uniforms);
+ let original_group = layer.draws[0].clone();
+ let original_pixels = render_pixels(&device, &queue, &layer);
+ for _ in 0..120 {
+ layer.draws.clear();
+ layer.push_draw(&device, &red, uniforms);
+ assert_eq!(layer.draws[0], original_group);
+ }
+ assert_eq!(render_pixels(&device, &queue, &layer), original_pixels);
+
+ let mut moved = uniforms;
+ moved.center_size[0] = 48.0;
+ layer.draws.clear();
+ layer.push_draw(&device, &red, moved);
+ assert_ne!(layer.draws[0], original_group);
+ let moved_pixels = render_pixels(&device, &queue, &layer);
+ assert_eq!(pixel(&moved_pixels, 20, 32), [0; 4]);
+ assert_pixel(pixel(&moved_pixels, 56, 32), [255, 0, 0, 255]);
+ layer.draws[0] = original_group;
+ assert_eq!(render_pixels(&device, &queue, &layer), original_pixels);
+
+ let blue = upload_texture(
+ &device,
+ &queue,
+ &[RgbaImage::from_pixel(1, 1, image::Rgba([0, 0, 255, 255]))],
+ );
+ layer.draws.clear();
+ layer.push_draw(&device, &blue, moved);
+ assert_pixel(
+ pixel(&render_pixels(&device, &queue, &layer), 56, 32),
+ [0, 0, 255, 255],
+ );
+ }
+
+ #[test]
+ fn image_overlay_gpu_pixels() {
+ let Some((device, queue)) = test_device() else {
+ return;
+ };
+ let mut layer = ImageLayer::new(&device);
+ let rgba = RgbaImage::from_raw(2, 1, vec![255, 0, 0, 255, 0, 255, 255, 0]).unwrap();
+ let transparent = upload_texture(&device, &queue, &premultiplied_mips(rgba, 8192));
+ let mut image = segment("transparent");
+ image.center = XY::new(0.25, 0.25);
+ image.size = XY::new(0.25, 0.25);
+ image.opacity = 0.5;
+ for (_, uniforms) in visible_images(&[image], 30, 30, (64, 64)) {
+ layer.push_draw(&device, &transparent, uniforms);
+ }
+ let pixels = render_pixels(&device, &queue, &layer);
+ assert_pixel(pixel(&pixels, 10, 16), [128, 0, 0, 128]);
+ assert_eq!(pixel(&pixels, 22, 16), [0; 4]);
+ assert_eq!(pixel(&pixels, 32, 32), [0; 4]);
+ let edge = pixel(&pixels, 15, 16);
+ assert_eq!(edge[0], edge[3]);
+ assert_eq!(&edge[1..3], &[0, 0]);
+ assert!((1..128).contains(&edge[3]));
+
+ let rgba = RgbaImage::from_raw(2, 1, vec![255, 0, 0, 255, 0, 0, 255, 255]).unwrap();
+ let two_color = upload_texture(&device, &queue, &premultiplied_mips(rgba, 8192));
+ for flip in [false, true] {
+ layer.draws.clear();
+ let mut image = segment("rotated");
+ image.size = XY::new(0.5, 0.25);
+ image.rotation = 90.0;
+ image.flip_x = flip;
+ for (_, uniforms) in visible_images(&[image], 30, 30, (64, 64)) {
+ layer.push_draw(&device, &two_color, uniforms);
+ }
+ let pixels = render_pixels(&device, &queue, &layer);
+ let (top, bottom) = if flip {
+ ([0, 0, 255, 255], [255, 0, 0, 255])
+ } else {
+ ([255, 0, 0, 255], [0, 0, 255, 255])
+ };
+ assert_pixel(pixel(&pixels, 32, 20), top);
+ assert_pixel(pixel(&pixels, 32, 44), bottom);
+ assert_eq!(pixel(&pixels, 20, 32), [0; 4]);
+ }
+
+ let red = upload_texture(
+ &device,
+ &queue,
+ &[RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255]))],
+ );
+ layer.draws.clear();
+ let mut rounded = segment("rounded");
+ rounded.rounding = 100.0;
+ for (_, uniforms) in visible_images(&[rounded], 30, 30, (64, 64)) {
+ layer.push_draw(&device, &red, uniforms);
+ }
+ let pixels = render_pixels(&device, &queue, &layer);
+ assert_eq!(pixel(&pixels, 17, 17), [0; 4]);
+ assert_pixel(pixel(&pixels, 32, 32), [255, 0, 0, 255]);
+ }
+
++ #[test]
++ fn render_track_order_skips_missing_lane_metadata() {
++ let Some((device, queue)) = test_device() else {
++ return;
++ };
++ let mut layer = ImageLayer::new(&device);
++ let red = upload_texture(
++ &device,
++ &queue,
++ &[RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255]))],
++ );
++ let blue = upload_texture(
++ &device,
++ &queue,
++ &[RgbaImage::from_pixel(1, 1, image::Rgba([0, 0, 255, 255]))],
++ );
++ let mut red_segment = segment("red");
++ red_segment.track = 0;
++ let mut blue_segment = segment("blue");
++ blue_segment.track = 2;
++ let mut inactive_segment = segment("inactive");
++ inactive_segment.track = 1;
++ inactive_segment.enabled = false;
++ assert!(visible_images(&[inactive_segment], 30, 30, (64, 64)).is_empty());
++
++ let red_uniforms = visible_images(&[red_segment], 30, 30, (64, 64))[0].1;
++ let blue_uniforms = visible_images(&[blue_segment], 30, 30, (64, 64))[0].1;
++ layer.push_draw_with_track(&device, &red, red_uniforms, 0);
++ layer.push_draw_with_track(&device, &blue, blue_uniforms, 2);
++ assert!(layer.has_track(0));
++ assert!(!layer.has_track(1));
++ assert!(layer.has_track(2));
++
++ let blue_front = render_tracks_pixels(&device, &queue, &layer, &[0, 1, 2]);
++ assert_pixel(pixel(&blue_front, 32, 32), [0, 0, 255, 255]);
++ let red_front = render_tracks_pixels(&device, &queue, &layer, &[2, 1, 0]);
++ assert_pixel(pixel(&red_front, 32, 32), [255, 0, 0, 255]);
++ }
++
+ struct ImageFixture(PathBuf);
+
+ impl ImageFixture {
+ fn new() -> Self {
+ let id = SystemTime::now()
+ .duration_since(SystemTime::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos();
+ let directory =
+ std::env::temp_dir().join(format!("cap-image-test-{}-{id}", std::process::id()));
+ std::fs::create_dir(&directory).unwrap();
+ Self(directory)
+ }
+ }
+
+ impl Drop for ImageFixture {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.0);
+ }
+ }
+
+ #[test]
+ fn image_cache_retries_missing_corrupt_and_replaced_files() {
+ let Some((device, queue)) = test_device() else {
+ return;
+ };
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ runtime.block_on(async {
+ let fixture = ImageFixture::new();
+ let path = fixture.0.join("image.png");
+ let mut layer = ImageLayer::new(&device);
+ let missing = FileVersion::read(&path);
+ for _ in 0..2 {
+ assert!(
+ layer
+ .ensure_texture(&device, &queue, &path, &missing, None)
+ .await
+ .is_none()
+ );
+ assert!(matches!(layer.cache[&path].state, CacheState::Failed));
+ }
+
+ RgbaImage::from_pixel(33, 9, image::Rgba([255, 0, 0, 255]))
+ .save(&path)
+ .unwrap();
+ let original_version = FileVersion::read(&path);
+ let resized = decode_image(&path, &original_version, 16).unwrap();
+ assert_eq!(resized[0].dimensions(), (16, 4));
+ let original = layer
+ .ensure_texture(&device, &queue, &path, &original_version, None)
+ .await
+ .unwrap();
+ std::fs::write(&path, b"invalid image").unwrap();
+ assert!(
+ layer
+ .ensure_texture(&device, &queue, &path, &original_version, None)
+ .await
+ .is_some()
+ );
+ let corrupt = FileVersion::read(&path);
+ assert_ne!(corrupt, original_version);
+ for _ in 0..2 {
+ assert!(
+ layer
+ .ensure_texture(&device, &queue, &path, &corrupt, None)
+ .await
+ .is_none()
+ );
+ assert!(matches!(layer.cache[&path].state, CacheState::Failed));
+ }
+
+ let replacement = fixture.0.join("replacement.png");
+ RgbaImage::from_pixel(33, 9, image::Rgba([0, 0, 255, 255]))
+ .save(&replacement)
+ .unwrap();
+ std::fs::rename(&replacement, &path).unwrap();
+ let replaced = FileVersion::read(&path);
+ assert_ne!(replaced, corrupt);
+ let texture = layer
+ .ensure_texture(&device, &queue, &path, &replaced, None)
+ .await
+ .unwrap();
+ for (_, uniforms) in visible_images(&[segment("replaced")], 30, 30, (64, 64)) {
+ layer.push_draw(&device, &texture, uniforms);
+ }
+ assert_pixel(
+ pixel(&render_pixels(&device, &queue, &layer), 32, 32),
+ [0, 0, 255, 255],
+ );
+
+ for index in 0..=MAX_TEXTURES {
+ let path = fixture.0.join(format!("active-{index}.png"));
+ assert!(
+ layer
+ .ensure_texture(&device, &queue, &path, &replaced, Some(original.clone()))
+ .await
+ .is_some()
+ );
+ }
+ assert_eq!(
+ layer
+ .cache
+ .values()
+ .filter(|entry| matches!(entry.state, CacheState::Ready(_)))
+ .count(),
+ MAX_TEXTURES
+ );
+ let evicted = fixture.0.join("active-0.png");
+ assert!(matches!(layer.cache[&evicted].state, CacheState::Evicted));
+ assert!(
+ layer
+ .ensure_texture(&device, &queue, &evicted, &replaced, Some(original))
+ .await
+ .is_some()
+ );
+ std::fs::remove_file(&path).unwrap();
+ let removed = FileVersion::read(&path);
+ assert!(
+ layer
+ .ensure_texture(&device, &queue, &path, &removed, Some(texture))
+ .await
+ .is_none()
+ );
+ });
+ }
+}
diff --cc crates/rendering/src/layers/text.rs
index 070b3dbe7,070b3dbe7..24bf9e8b4
--- a/crates/rendering/src/layers/text.rs
+++ b/crates/rendering/src/layers/text.rs
@@@ -17,6 -17,6 +17,7 @@@ pub struct TextLayer
text_renderer: TextRenderer,
viewport: Viewport,
buffers: Vec<Buffer>,
++ tracks: Vec<u32>,
segment_renderers: Vec<TextRenderer>,
background: Option<TextBackgroundResources>,
segmented_render: bool,
@@@ -207,6 -207,6 +208,7 @@@ impl TextLayer
text_renderer,
viewport,
buffers: Vec::new(),
++ tracks: Vec::new(),
segment_renderers: Vec::new(),
background: None,
segmented_render: false,
@@@ -220,9 -220,9 +222,32 @@@
queue: &Queue,
output_size: (u32, u32),
texts: &[PreparedText],
++ ) {
++ self.prepare_with_mode(device, queue, output_size, texts, false);
++ }
++
++ pub fn prepare_mixed(
++ &mut self,
++ device: &Device,
++ queue: &Queue,
++ output_size: (u32, u32),
++ texts: &[PreparedText],
++ ) {
++ self.prepare_with_mode(device, queue, output_size, texts, true);
++ }
++
++ fn prepare_with_mode(
++ &mut self,
++ device: &Device,
++ queue: &Queue,
++ output_size: (u32, u32),
++ texts: &[PreparedText],
++ force_segmented: bool,
) {
self.buffers.clear();
++ self.tracks.clear();
self.buffers.reserve(texts.len());
++ self.tracks.reserve(texts.len());
let mut specs = Vec::with_capacity(texts.len());
for text in texts {
@@@ -371,6 -371,6 +396,7 @@@
});
self.buffers.push(buffer);
++ self.tracks.push(text.track);
specs.push(AreaSpec {
bounds,
left: origin_left,
@@@ -390,7 -390,7 +416,8 @@@
},
);
-- self.segmented_render = specs.iter().any(|spec| spec.background.is_some());
++ self.segmented_render =
++ force_segmented || specs.iter().any(|spec| spec.background.is_some());
if self.segmented_render {
self.segment_backgrounds = specs.iter().map(|spec| spec.background.is_some()).collect();
let background = self
@@@ -464,6 -464,6 +491,35 @@@
warn!("Failed to render text: {error:?}");
}
}
++
++ pub fn render_track<'a>(&'a self, pass: &mut wgpu::RenderPass<'a>, track: u32) {
++ if !self.segmented_render {
++ return;
++ }
++ let Some(background) = &self.background else {
++ return;
++ };
++ for (index, (renderer, has_background)) in self
++ .segment_renderers
++ .iter()
++ .zip(&self.segment_backgrounds)
++ .enumerate()
++ {
++ if self.tracks.get(index) != Some(&track) {
++ continue;
++ }
++ if *has_background {
++ background.render(pass, index);
++ }
++ if let Err(error) = renderer.render(&self.text_atlas, &self.viewport, pass) {
++ warn!("Failed to render text: {error:?}");
++ }
++ }
++ }
++
++ pub fn has_track(&self, track: u32) -> bool {
++ self.segmented_render && self.tracks.contains(&track)
++ }
}
#[cfg(test)]
@@@ -487,6 -487,6 +543,7 @@@ mod gpu_tests
fn text(bounds: [f32; 4], color: [f32; 4]) -> PreparedText {
PreparedText {
++ track: 0,
content: " ".to_string(),
bounds,
color: [1.0; 4],
diff --cc crates/rendering/src/lib.rs
index 1ee82c15e,f3db3a707..74e00736b
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@@ -2,8 -2,8 +2,8 @@@ use anyhow::Result
use cap_project::{
AspectRatio, Camera, CameraShape, CameraXPosition, CameraYPosition, ClipOffsets,
ClipTransitionType, CornerStyle, Crop, CursorEvents, CursorType, FrameConfiguration,
-- FrameStyle, ProjectConfiguration, RecordingMeta, SceneMode, StudioRecordingMeta,
-- TimelineFrameMapping, TimelineSource, XY,
++ FrameStyle, OverlayTrackKind, ProjectConfiguration, RecordingMeta, SceneMode,
++ StudioRecordingMeta, TimelineFrameMapping, TimelineSource, XY,
};
use composite_frame::{ColorGradeUniformParams, CompositeVideoFrameUniforms};
use core::f64;
@@@ -315,6 -315,6 +315,7 @@@ pub enum MaskRenderMode
#[derive(Debug, Clone)]
pub struct PreparedMask {
++ pub track: u32,
pub center: XY<f32>,
pub size: XY<f32>,
pub feather: f32,
@@@ -6730,14 -6290,12 +6731,23 @@@ impl RendererLayers
self.run_shared_camera_blur(&constants.device, &constants.queue, mode);
}
- self.text.prepare(
- &constants.device,
- &constants.queue,
- uniforms.output_size,
- &uniforms.texts,
- );
+ self.images.prepare(constants, uniforms).await;
+
- self.text.prepare(
- &constants.device,
- &constants.queue,
- uniforms.output_size,
- &uniforms.texts,
- );
++ if uniforms.project.overlay_order.is_empty() {
++ self.text.prepare(
++ &constants.device,
++ &constants.queue,
++ uniforms.output_size,
++ &uniforms.texts,
++ );
++ } else {
++ self.text.prepare_mixed(
++ &constants.device,
++ &constants.queue,
++ uniforms.output_size,
++ &uniforms.texts,
++ );
++ }
self.captions.prepare(
uniforms,
@@@ -6897,14 -6454,12 +6907,23 @@@
timings.camera_blur_prepare_duration = start.elapsed();
let start = Instant::now();
- self.text.prepare(
- &constants.device,
- &constants.queue,
- uniforms.output_size,
- &uniforms.texts,
- );
+ self.images.prepare(constants, uniforms).await;
+
- self.text.prepare(
- &constants.device,
- &constants.queue,
- uniforms.output_size,
- &uniforms.texts,
- );
++ if uniforms.project.overlay_order.is_empty() {
++ self.text.prepare(
++ &constants.device,
++ &constants.queue,
++ uniforms.output_size,
++ &uniforms.texts,
++ );
++ } else {
++ self.text.prepare_mixed(
++ &constants.device,
++ &constants.queue,
++ uniforms.output_size,
++ &uniforms.texts,
++ );
++ }
timings.text_prepare_duration = start.elapsed();
let start = Instant::now();
@@@ -7103,20 -6658,15 +7122,49 @@@
None => {}
}
-- if !uniforms.masks.is_empty() {
-- for mask in &uniforms.masks {
-- self.mask.render(device, queue, session, encoder, mask);
++ if uniforms.project.overlay_order.is_empty() {
++ if !uniforms.masks.is_empty() {
++ for mask in &uniforms.masks {
++ self.mask.render(device, queue, session, encoder, mask);
++ }
+ }
- }
+
- if render_display && self.images.has_content() {
- let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
- self.images.render(&mut pass);
- }
++ if render_display && self.images.has_content() {
++ let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
++ self.images.render(&mut pass);
+ }
- }
-- if !uniforms.texts.is_empty() {
-- let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
-- self.text.render(&mut pass);
++ if !uniforms.texts.is_empty() {
++ let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
++ self.text.render(&mut pass);
++ }
++ } else {
++ for overlay in uniforms.project.overlay_tracks().into_iter().rev() {
++ match overlay.kind {
++ OverlayTrackKind::Mask => {
++ for mask in uniforms
++ .masks
++ .iter()
++ .filter(|mask| mask.track == overlay.track)
++ {
++ self.mask.render(device, queue, session, encoder, mask);
++ }
++ }
++ OverlayTrackKind::Image
++ if render_display && self.images.has_track(overlay.track) =>
++ {
++ let mut pass =
++ render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
++ self.images.render_track(&mut pass, overlay.track);
++ }
++ OverlayTrackKind::Text if self.text.has_track(overlay.track) => {
++ let mut pass =
++ render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
++ self.text.render_track(&mut pass, overlay.track);
++ }
++ OverlayTrackKind::Text | OverlayTrackKind::Image => {}
++ }
++ }
}
if self.keyboard.has_content() {
diff --cc crates/rendering/src/mask.rs
index e61f12127,e61f12127..c2c753d33
--- a/crates/rendering/src/mask.rs
+++ b/crates/rendering/src/mask.rs
@@@ -74,7 -74,7 +74,12 @@@ pub fn interpolate_masks
) -> Vec<PreparedMask> {
let mut prepared = Vec::new();
-- for segment in segments.iter().filter(|s| s.enabled) {
++ let mut ordered = segments
++ .iter()
++ .filter(|segment| segment.enabled)
++ .collect::<Vec<_>>();
++ ordered.sort_by_key(|segment| segment.track);
++ for segment in ordered {
if frame_time < segment.start || frame_time > segment.end {
continue;
}
@@@ -118,6 -118,6 +123,7 @@@
let feather = (min_axis * 0.5 * segment_feather.max(0.0)).max(0.0001) as f32;
prepared.push(PreparedMask {
++ track: segment.track,
center: XY::new(
position.x.clamp(0.0, 1.0) as f32,
position.y.clamp(0.0, 1.0) as f32,
@@@ -194,6 -194,6 +200,26 @@@ mod tests
}
}
++ #[test]
++ fn mask_layers_follow_lane_order_with_stable_ties() {
++ let mut front = sample_segment();
++ front.track = 2;
++ front.center.x = 0.75;
++ let mut back = front.clone();
++ back.track = 0;
++ back.center.x = 0.25;
++ let mut later_front = front.clone();
++ later_front.center.x = 0.5;
++ let masks = interpolate_masks(XY::new(1920, 1080), 1.0, &[front, back, later_front]);
++ assert_eq!(masks.len(), 3);
++ assert_eq!(
++ masks.iter().map(|mask| mask.track).collect::<Vec<_>>(),
++ [0, 2, 2]
++ );
++ assert!(masks[0].center.x < masks[2].center.x);
++ assert!(masks[2].center.x < masks[1].center.x);
++ }
++
#[test]
fn sensitive_mask_effect_scales_with_output_height() {
let segment = sample_segment();
diff --cc crates/rendering/src/text.rs
index 921d9d1c7,921d9d1c7..6fdbd8c9a
--- a/crates/rendering/src/text.rs
+++ b/crates/rendering/src/text.rs
@@@ -11,6 -11,6 +11,7 @@@ pub const MAX_FONT_SIZE: f32 = 480.0
#[derive(Debug, Clone)]
pub struct PreparedText {
++ pub track: u32,
pub content: String,
pub bounds: [f32; 4],
pub color: [f32; 4],
@@@ -192,7 -192,7 +193,9 @@@ pub fn prepare_texts
output_size.y as f32 / REFERENCE_HEIGHT
};
-- for (i, segment) in segments.iter().enumerate() {
++ let mut ordered = segments.iter().enumerate().collect::<Vec<_>>();
++ ordered.sort_by_key(|(index, segment)| (segment.track, *index));
++ for (i, segment) in ordered {
if !segment.enabled || hidden_indices.contains(&i) {
continue;
}
@@@ -248,6 -248,6 +251,7 @@@
}
prepared.push(PreparedText {
++ track: segment.track,
content,
bounds: [left, top, right, bottom],
color: parse_color(&segment.color),
@@@ -316,6 -316,6 +320,40 @@@ mod tests
.next()
}
++ #[test]
++ fn text_layer_order_preserves_hidden_segment_identity() {
++ let mut front = segment(TextAnimation::None, TextAnimation::None);
++ front.track = 2;
++ front.content = "Front".into();
++ let mut back = front.clone();
++ back.track = 0;
++ back.content = "Back".into();
++ let mut middle = front.clone();
++ middle.track = 1;
++ middle.content = "Middle".into();
++ let segments = [front, back, middle];
++ let prepared = prepare_texts(XY::new(1920, 1080), 5.0, &segments, &[]);
++ assert_eq!(
++ prepared
++ .iter()
++ .map(|text| text.content.as_str())
++ .collect::<Vec<_>>(),
++ ["Back", "Middle", "Front"]
++ );
++ assert_eq!(
++ prepared.iter().map(|text| text.track).collect::<Vec<_>>(),
++ [0, 1, 2]
++ );
++ let hidden = prepare_texts(XY::new(1920, 1080), 5.0, &segments, &[0]);
++ assert_eq!(
++ hidden
++ .iter()
++ .map(|text| text.content.as_str())
++ .collect::<Vec<_>>(),
++ ["Back", "Middle"]
++ );
++ }
++
#[test]
fn resting_text_has_identity_animation_state() {
let text = prepare_one(segment(TextAnimation::Fade, TextAnimation::Fade), 5.0).unwrap();
diff --cc crates/utils/Cargo.toml
index 7cbcff5b0,7cbcff5b0..622f6ca94
--- a/crates/utils/Cargo.toml
+++ b/crates/utils/Cargo.toml
@@@ -35,6 -35,6 +35,7 @@@ aho-corasick.workspace = tru
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
++tracing-appender = "0.2.3"
tempfile = "3"
[lints]
diff --cc crates/utils/src/diagnostic_writer.rs
index 000000000,000000000..db84ba5f1
new file mode 100644
--- /dev/null
+++ b/crates/utils/src/diagnostic_writer.rs
@@@ -1,0 -1,0 +1,261 @@@
++use std::{
++ fs::{File, OpenOptions},
++ io::{self, Write},
++ path::{Path, PathBuf},
++ sync::atomic::{AtomicU64, Ordering},
++};
++
++pub const RECORD_PREFIX: &[u8] = b"CAP_DIAGNOSTIC ";
++pub const MAX_RECORD_BYTES: usize = 4096;
++pub const MAX_FILE_BYTES: u64 = 4_500_000 / 2;
++static WRITE_FAILURES: AtomicU64 = AtomicU64::new(0);
++
++pub fn write_failures() -> u64 {
++ WRITE_FAILURES.load(Ordering::Relaxed)
++}
++
++pub struct DiagnosticWriter<W, J = Journal> {
++ ordinary: W,
++ journal: J,
++}
++
++impl<W> DiagnosticWriter<W> {
++ pub fn new(ordinary: W, directory: &Path, prefix: &str) -> Self {
++ Self {
++ ordinary,
++ journal: Journal {
++ current: directory.join(format!("{prefix}.diagnostic-current.jsonl")),
++ previous: directory.join(format!("{prefix}.diagnostic-previous.jsonl")),
++ file: None,
++ bytes: 0,
++ disabled: false,
++ },
++ }
++ }
++}
++
++impl<W: Write, J: Write> Write for DiagnosticWriter<W, J> {
++ fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
++ if bytes.starts_with(RECORD_PREFIX) {
++ if bytes.len() > MAX_RECORD_BYTES || self.journal.write_all(bytes).is_err() {
++ WRITE_FAILURES.fetch_add(1, Ordering::Relaxed);
++ }
++ Ok(bytes.len())
++ } else {
++ self.ordinary.write(bytes)
++ }
++ }
++
++ fn flush(&mut self) -> io::Result<()> {
++ if self.journal.flush().is_err() {
++ WRITE_FAILURES.fetch_add(1, Ordering::Relaxed);
++ }
++ self.ordinary.flush()
++ }
++}
++
++pub struct Journal {
++ current: PathBuf,
++ previous: PathBuf,
++ file: Option<File>,
++ bytes: u64,
++ disabled: bool,
++}
++
++fn reject_non_regular(path: &Path) -> io::Result<()> {
++ match std::fs::symlink_metadata(path) {
++ Ok(metadata) if !metadata.file_type().is_file() => Err(io::Error::other(
++ "Diagnostic destination is not a regular file",
++ )),
++ Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error),
++ _ => Ok(()),
++ }
++}
++
++impl Journal {
++ fn open(&mut self) -> io::Result<()> {
++ reject_non_regular(&self.current)?;
++ let mut options = OpenOptions::new();
++ options.create(true).append(true);
++ #[cfg(unix)]
++ {
++ use std::os::unix::fs::OpenOptionsExt;
++ options.mode(0o600).custom_flags(libc::O_NOFOLLOW);
++ }
++ let mut file = options.open(&self.current)?;
++ self.bytes = file.metadata()?.len();
++ if self.bytes > 0 && self.bytes < MAX_FILE_BYTES {
++ file.write_all(b"\n")?;
++ self.bytes += 1;
++ }
++ self.file = Some(file);
++ Ok(())
++ }
++
++ fn append(&mut self, bytes: &[u8]) -> io::Result<()> {
++ if self.file.is_none() {
++ self.open()?;
++ }
++ if self.bytes.saturating_add(bytes.len() as u64) > MAX_FILE_BYTES {
++ self.file = None;
++ reject_non_regular(&self.previous)?;
++ match std::fs::remove_file(&self.previous) {
++ Err(error) if error.kind() != io::ErrorKind::NotFound => return Err(error),
++ _ => {}
++ }
++ std::fs::rename(&self.current, &self.previous)?;
++ self.open()?;
++ }
++ if let Some(file) = &mut self.file {
++ file.write_all(bytes)?;
++ self.bytes = self.bytes.saturating_add(bytes.len() as u64);
++ }
++ Ok(())
++ }
++}
++
++impl Write for Journal {
++ fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
++ if self.disabled {
++ return Err(io::Error::other("Diagnostic journal is unavailable"));
++ }
++ if bytes.len() > MAX_RECORD_BYTES {
++ return Err(io::Error::other(
++ "Diagnostic record exceeded its size limit",
++ ));
++ }
++ if let Err(error) = self.append(bytes) {
++ self.disabled = true;
++ self.file = None;
++ return Err(error);
++ }
++ Ok(bytes.len())
++ }
++
++ fn flush(&mut self) -> io::Result<()> {
++ Ok(())
++ }
++}
++
++#[cfg(test)]
++mod tests {
++ use super::*;
++
++ #[test]
++ fn a_stalled_disk_worker_drops_queued_records_without_blocking_the_caller() {
++ struct StalledWriter(std::sync::mpsc::Receiver<()>);
++ impl Write for StalledWriter {
++ fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
++ let _ = self.0.recv();
++ Ok(bytes.len())
++ }
++ fn flush(&mut self) -> io::Result<()> {
++ Ok(())
++ }
++ }
++ let (release, blocked) = std::sync::mpsc::channel();
++ let (mut writer, guard) = tracing_appender::non_blocking::NonBlockingBuilder::default()
++ .buffered_lines_limit(1)
++ .lossy(true)
++ .finish(StalledWriter(blocked));
++ let errors = writer.error_counter();
++ for _ in 0..1000 {
++ writer.write_all(b"CAP_DIAGNOSTIC {}\n").unwrap();
++ }
++ assert!(errors.dropped_lines() > 0);
++ drop(release);
++ drop(guard);
++ }
++
++ #[test]
++ fn interrupted_record_does_not_corrupt_the_next_process_record() {
++ let dir = tempfile::tempdir().unwrap();
++ let path = dir.path().join("cap-test.log.diagnostic-current.jsonl");
++ std::fs::write(&path, b"CAP_DIAGNOSTIC {\"partial\":").unwrap();
++ let mut writer = DiagnosticWriter::new(Vec::new(), dir.path(), "cap-test.log");
++ writer
++ .write_all(b"CAP_DIAGNOSTIC {\"complete\":true}\n")
++ .unwrap();
++ let text = std::fs::read_to_string(path).unwrap();
++ let complete = text
++ .lines()
++ .filter_map(|line| line.strip_prefix("CAP_DIAGNOSTIC "))
++ .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
++ .collect::<Vec<_>>();
++ assert_eq!(complete, vec![serde_json::json!({"complete": true})]);
++ }
++
++ #[test]
++ fn rotation_bounds_storage_and_preserves_the_previous_file() {
++ let dir = tempfile::tempdir().unwrap();
++ let mut writer = DiagnosticWriter::new(Vec::new(), dir.path(), "cap-test.log");
++ let mut record = RECORD_PREFIX.to_vec();
++ record.extend(std::iter::repeat_n(
++ b'x',
++ MAX_RECORD_BYTES - record.len() - 1,
++ ));
++ record.push(b'\n');
++ for _ in 0..(MAX_FILE_BYTES as usize / MAX_RECORD_BYTES) * 3 + 1 {
++ writer.write_all(&record).unwrap();
++ }
++ writer.write_all(b"ordinary log\n").unwrap();
++ assert_eq!(writer.ordinary, b"ordinary log\n");
++ let files: Vec<_> = std::fs::read_dir(dir.path()).unwrap().collect();
++ assert_eq!(files.len(), 2);
++ for file in files {
++ let metadata = file.unwrap().metadata().unwrap();
++ assert!(metadata.len() <= MAX_FILE_BYTES);
++ }
++ }
++
++ #[test]
++ fn disk_failure_does_not_fail_or_swallow_ordinary_logging() {
++ struct FullDisk;
++ impl Write for FullDisk {
++ fn write(&mut self, _: &[u8]) -> io::Result<usize> {
++ Err(io::Error::from_raw_os_error(28))
++ }
++ fn flush(&mut self) -> io::Result<()> {
++ Err(io::Error::from_raw_os_error(28))
++ }
++ }
++ let mut writer = DiagnosticWriter {
++ ordinary: Vec::new(),
++ journal: FullDisk,
++ };
++ writer.write_all(b"CAP_DIAGNOSTIC {}\n").unwrap();
++ writer.write_all(b"recording is still running\n").unwrap();
++ writer.flush().unwrap();
++ assert_eq!(writer.ordinary, b"recording is still running\n");
++ }
++
++ #[test]
++ fn unavailable_destination_disables_only_diagnostic_writes() {
++ let dir = tempfile::tempdir().unwrap();
++ let blocked = dir.path().join("cap-test.log.diagnostic-current.jsonl");
++ std::fs::create_dir(&blocked).unwrap();
++ let mut writer = DiagnosticWriter::new(Vec::new(), dir.path(), "cap-test.log");
++ writer.write_all(b"CAP_DIAGNOSTIC {}\n").unwrap();
++ assert!(writer.journal.disabled);
++ writer.write_all(b"ordinary log").unwrap();
++ assert!(blocked.is_dir());
++ assert_eq!(writer.ordinary, b"ordinary log");
++ }
++
++ #[cfg(unix)]
++ #[test]
++ fn diagnostic_files_never_follow_a_symlink() {
++ let dir = tempfile::tempdir().unwrap();
++ let original = dir.path().join("original");
++ std::fs::write(&original, "preserve me").unwrap();
++ std::os::unix::fs::symlink(
++ &original,
++ dir.path().join("cap-test.log.diagnostic-current.jsonl"),
++ )
++ .unwrap();
++ let mut writer = DiagnosticWriter::new(Vec::new(), dir.path(), "cap-test.log");
++ writer.write_all(b"CAP_DIAGNOSTIC {}\n").unwrap();
++ assert!(writer.journal.disabled);
++ assert_eq!(std::fs::read_to_string(original).unwrap(), "preserve me");
++ }
++}
diff --cc crates/utils/src/lib.rs
index 8587bafe4,62f66283b..16cebda77
--- a/crates/utils/src/lib.rs
+++ b/crates/utils/src/lib.rs
@@@ -9,6 -9,6 +9,7 @@@ use std::
use aho_corasick::{AhoCorasickBuilder, MatchKind};
use tracing::Instrument;
++pub mod diagnostic_writer;
pub mod disk_space;
#[cfg(any(target_os = "linux", test))]
pub mod linux_package;
@@@ -16,9 -16,8 +17,11 @@@
pub mod linux_recording_stop;
#[cfg(any(target_os = "linux", test))]
pub mod linux_runtime;
+pub mod local_captions;
++pub mod log_upload;
#[cfg(target_os = "macos")]
pub mod macos_qos;
++pub mod operation_diagnostics;
/// Wrapper around tokio::spawn that inherits the current tracing subscriber and span.
pub fn spawn_actor<F>(future: F) -> tokio::task::JoinHandle<F::Output>
diff --cc crates/utils/src/log_upload.rs
index 000000000,000000000..2e23ffc5c
new file mode 100644
--- /dev/null
+++ b/crates/utils/src/log_upload.rs
@@@ -1,0 -1,0 +1,361 @@@
++use serde::Serialize;
++use std::{
++ io::{Read, Seek, SeekFrom},
++ path::Path,
++};
++
++pub const MAX_LOG_BYTES: usize = 512 * 1024;
++pub const MAX_REQUEST_BYTES: usize = 4 * 1024 * 1024;
++const REQUEST_HEADROOM: usize = 64 * 1024;
++const MAX_METADATA_BYTES: usize = 512 * 1024;
++const MAX_REPORT_BYTES: usize = 2 * 1024 * 1024;
++const OMITTED_ATTACHMENT: &str = r#"{"capLogUploadOmission":"size_limit"}"#;
++const MAX_FILES: usize = 2;
++
++#[derive(Serialize)]
++#[serde(rename_all = "camelCase")]
++pub struct LogBundle {
++ #[serde(skip_serializing)]
++ pub text: String,
++ #[serde(skip_serializing)]
++ ordinary_end: usize,
++ pub files: Vec<LogFile>,
++ pub directory_entries_scanned: usize,
++ pub directory_available: bool,
++}
++
++pub struct PreparedUpload {
++ pub log: String,
++ pub context: String,
++ pub diagnostics: Option<String>,
++ pub report: Option<String>,
++}
++
++fn bound_attachment(value: String, limit: usize) -> String {
++ if value.len() > limit {
++ OMITTED_ATTACHMENT.to_string()
++ } else {
++ value
++ }
++}
++
++fn bound_tail(text: &mut String, limit: usize) -> usize {
++ if text.len() <= limit {
++ return 0;
++ }
++ let marker = "[Earlier bytes omitted to fit the upload budget]\n";
++ let mut start = text
++ .len()
++ .saturating_sub(limit.saturating_sub(marker.len()));
++ while !text.is_char_boundary(start) {
++ start += 1;
++ }
++ start = text[start..]
++ .find('\n')
++ .map_or(text.len(), |offset| start + offset + 1);
++ text.drain(..start);
++ if limit >= marker.len() {
++ text.insert_str(0, marker);
++ }
++ start
++}
++
++pub fn prepare_upload(
++ log: LogBundle,
++ mut context: serde_json::Value,
++ diagnostics: Option<&str>,
++ report: Option<&str>,
++ redact: impl Fn(&str) -> String,
++) -> PreparedUpload {
++ let diagnostics = diagnostics.map(|value| bound_attachment(redact(value), MAX_METADATA_BYTES));
++ let report = report.map(|value| bound_attachment(redact(value), MAX_REPORT_BYTES));
++ let mut ordinary = redact(&log.text[..log.ordinary_end]);
++ let mut journal = redact(&log.text[log.ordinary_end..]);
++ if let Some(object) = context.as_object_mut() {
++ let _ = object.insert(
++ "logCoverage".into(),
++ serde_json::to_value(&log).unwrap_or_default(),
++ );
++ }
++ let mut context = bound_attachment(
++ redact(&serde_json::to_string(&context).unwrap_or_default()),
++ MAX_METADATA_BYTES,
++ );
++ let metadata_bytes = context.len()
++ + diagnostics.as_ref().map_or(0, String::len)
++ + report.as_ref().map_or(0, String::len);
++ let log_budget = MAX_REQUEST_BYTES.saturating_sub(REQUEST_HEADROOM + metadata_bytes);
++ let omitted_ordinary = bound_tail(&mut ordinary, MAX_LOG_BYTES.min(log_budget));
++ let omitted_journal = bound_tail(&mut journal, log_budget.saturating_sub(ordinary.len()));
++ let omitted = omitted_ordinary.saturating_add(omitted_journal);
++ if omitted > 0
++ && let Ok(serde_json::Value::Object(mut object)) = serde_json::from_str(&context)
++ {
++ let _ = object.insert("redactedLogBytesOmittedForUpload".into(), omitted.into());
++ context = bound_attachment(
++ serde_json::to_string(&object).unwrap_or_default(),
++ MAX_METADATA_BYTES,
++ );
++ }
++ ordinary.push_str(&journal);
++ PreparedUpload {
++ log: ordinary,
++ context,
++ diagnostics,
++ report,
++ }
++}
++
++#[derive(Serialize)]
++#[serde(rename_all = "camelCase")]
++pub struct LogFile {
++ pub name: String,
++ pub original_bytes: u64,
++ pub bytes_read: usize,
++ pub truncated: bool,
++ pub readable: bool,
++}
++
++fn read_tail(path: &Path, budget: usize) -> std::io::Result<(String, u64, usize)> {
++ let mut options = std::fs::OpenOptions::new();
++ options.read(true);
++ #[cfg(unix)]
++ {
++ use std::os::unix::fs::OpenOptionsExt;
++ options.custom_flags(libc::O_NOFOLLOW);
++ }
++ let mut file = options.open(path)?;
++ let metadata = file.metadata()?;
++ if !metadata.is_file() {
++ return Err(std::io::Error::other("Log is not a regular file"));
++ }
++ let length = metadata.len();
++ let offset = length.saturating_sub(budget as u64);
++ file.seek(SeekFrom::Start(offset))?;
++ let mut bytes = Vec::new();
++ file.take(length.saturating_sub(offset))
++ .read_to_end(&mut bytes)?;
++ let bytes_read = bytes.len();
++ let start = if offset > 0 {
++ bytes
++ .iter()
++ .position(|byte| *byte == b'\n')
++ .map_or(bytes.len(), |index| index + 1)
++ } else {
++ 0
++ };
++ let mut text = String::from_utf8_lossy(&bytes[start..]).into_owned();
++ if text.len() > budget {
++ let mut end = budget;
++ while !text.is_char_boundary(end) {
++ end = end.saturating_sub(1);
++ }
++ text.truncate(end);
++ }
++ Ok((text, length, bytes_read))
++}
++
++pub fn collect(dir: &Path, prefix: &str) -> LogBundle {
++ let mut bundle = LogBundle {
++ text: String::new(),
++ ordinary_end: 0,
++ files: Vec::new(),
++ directory_entries_scanned: 0,
++ directory_available: false,
++ };
++ let Ok(entries) = std::fs::read_dir(dir) else {
++ bundle.text.push_str("Log directory is unavailable.\n");
++ return bundle;
++ };
++ bundle.directory_available = true;
++ let mut candidates = Vec::new();
++ for entry in entries {
++ bundle.directory_entries_scanned = bundle.directory_entries_scanned.saturating_add(1);
++ let Ok(entry) = entry else { continue };
++ let name = entry.file_name();
++ let Some(name) = name.to_str() else { continue };
++ let Some(suffix) = name.strip_prefix(prefix) else {
++ continue;
++ };
++ if !suffix
++ .bytes()
++ .all(|byte| byte.is_ascii_digit() || matches!(byte, b'.' | b'-'))
++ || !entry.file_type().is_ok_and(|kind| kind.is_file())
++ {
++ continue;
++ }
++ candidates.push((name.to_string(), entry.path()));
++ candidates.sort_unstable_by(|left, right| right.0.cmp(&left.0));
++ candidates.truncate(MAX_FILES);
++ }
++ let normal_budget = MAX_LOG_BYTES / candidates.len().max(1);
++ let mut selected: Vec<_> = candidates
++ .into_iter()
++ .rev()
++ .map(|(name, path)| (name, path, normal_budget))
++ .collect();
++ for suffix in ["diagnostic-previous.jsonl", "diagnostic-current.jsonl"] {
++ let name = format!("{prefix}.{suffix}");
++ let path = dir.join(&name);
++ if std::fs::symlink_metadata(&path).is_ok_and(|metadata| metadata.file_type().is_file()) {
++ selected.push((
++ name,
++ path,
++ crate::diagnostic_writer::MAX_FILE_BYTES as usize,
++ ));
++ }
++ }
++ for (name, path, budget) in selected {
++ let is_journal = name.ends_with(".jsonl");
++ match read_tail(&path, budget) {
++ Ok((text, original_bytes, bytes_read)) => {
++ bundle.text.push_str(&format!("\n--- {name} ---\n"));
++ if original_bytes > bytes_read as u64 {
++ bundle.text.push_str("[Earlier log bytes omitted]\n");
++ }
++ bundle.text.push_str(&text);
++ bundle.files.push(LogFile {
++ name,
++ original_bytes,
++ bytes_read,
++ truncated: original_bytes > bytes_read as u64,
++ readable: true,
++ });
++ }
++ Err(_) => {
++ bundle
++ .text
++ .push_str(&format!("\n--- {name}: unavailable ---\n"));
++ bundle.files.push(LogFile {
++ name,
++ original_bytes: 0,
++ bytes_read: 0,
++ truncated: false,
++ readable: false,
++ });
++ }
++ }
++ if !is_journal {
++ bundle.ordinary_end = bundle.text.len();
++ }
++ }
++ if bundle.files.is_empty() {
++ bundle.text.push_str("No matching log files were found.\n");
++ }
++ bundle
++}
++
++#[cfg(test)]
++mod tests {
++ use super::*;
++ use std::io::Write;
++
++ #[test]
++ fn retained_history_fits_with_large_metadata_and_recent_events() {
++ let dir = tempfile::tempdir().unwrap();
++ std::fs::write(dir.path().join("cap.log"), "ordinary error\n").unwrap();
++ for suffix in ["previous", "current"] {
++ let mut text =
++ "event\n".repeat(crate::diagnostic_writer::MAX_FILE_BYTES as usize / 6 - 10);
++ text.push_str(&format!("latest {suffix}\n"));
++ std::fs::write(
++ dir.path()
++ .join(format!("cap.log.diagnostic-{suffix}.jsonl")),
++ text,
++ )
++ .unwrap();
++ }
++ let bundle = collect(dir.path(), "cap.log");
++ assert!(bundle.text.len() > 2 * crate::diagnostic_writer::MAX_FILE_BYTES as usize - 1024);
++ let diagnostics =
++ serde_json::json!({ "data": "d".repeat(MAX_METADATA_BYTES - 1024) }).to_string();
++ let report = serde_json::json!({ "data": "r".repeat(MAX_REPORT_BYTES - 1024) }).to_string();
++ let context = serde_json::json!({ "data": "c".repeat(MAX_METADATA_BYTES - 4096) });
++ let prepared = prepare_upload(
++ bundle,
++ context,
++ Some(&diagnostics),
++ Some(&report),
++ str::to_string,
++ );
++ let total = prepared.log.len()
++ + prepared.context.len()
++ + prepared.diagnostics.as_ref().unwrap().len()
++ + prepared.report.as_ref().unwrap().len();
++ assert!(total < MAX_REQUEST_BYTES);
++ assert!(prepared.log.contains("ordinary error"));
++ assert!(prepared.log.ends_with("latest current\n"));
++ let context: serde_json::Value = serde_json::from_str(&prepared.context).unwrap();
++ assert!(
++ context["redactedLogBytesOmittedForUpload"]
++ .as_u64()
++ .unwrap()
++ > 0
++ );
++ }
++
++ #[test]
++ fn redaction_expansion_and_oversized_optional_reports_cannot_overfill_an_upload() {
++ let dir = tempfile::tempdir().unwrap();
++ std::fs::write(dir.path().join("cap.log"), "a\n".repeat(MAX_LOG_BYTES / 2)).unwrap();
++ let bundle = collect(dir.path(), "cap.log");
++ let prepared = prepare_upload(
++ bundle,
++ serde_json::json!({}),
++ None,
++ Some(&"x".repeat(MAX_REPORT_BYTES + 1)),
++ |value| value.replace('a', "[REDACTED]"),
++ );
++ assert!(prepared.log.len() <= MAX_LOG_BYTES);
++ assert_eq!(prepared.report.as_deref(), Some(OMITTED_ATTACHMENT));
++ assert!(prepared.log.contains("[REDACTED]"));
++ }
++
++ #[test]
++ fn reads_only_the_tail_of_a_large_file() {
++ let mut file = tempfile::NamedTempFile::new().unwrap();
++ file.as_file_mut().set_len(4 * 1024 * 1024 * 1024).unwrap();
++ file.seek(SeekFrom::End(0)).unwrap();
++ file.write_all(b"\nlast event\n").unwrap();
++ let (text, length, read) = read_tail(file.path(), 1024).unwrap();
++ assert!(length > 4 * 1024 * 1024 * 1024);
++ assert_eq!(read, 1024);
++ assert_eq!(text, "last event\n");
++ }
++
++ #[test]
++ fn collects_two_recent_files_with_a_fixed_read_budget() {
++ let dir = tempfile::tempdir().unwrap();
++ for day in ["2026-09-06", "2026-09-07", "2026-09-08"] {
++ std::fs::write(dir.path().join(format!("cap-desktop.log.{day}")), "event\n").unwrap();
++ }
++ std::fs::write(dir.path().join("cap-desktop.log.secret-title"), "private").unwrap();
++ let bundle = collect(dir.path(), "cap-desktop.log");
++ assert_eq!(bundle.files.len(), 2);
++ assert!(bundle.files[1].name.ends_with("2026-09-08"));
++ assert!(!bundle.text.contains("private"));
++ assert!(
++ bundle
++ .files
++ .iter()
++ .map(|file| file.bytes_read)
++ .sum::<usize>()
++ <= MAX_LOG_BYTES
++ );
++ }
++
++ #[test]
++ fn handles_partial_utf8_missing_logs_and_scan_limits() {
++ let dir = tempfile::tempdir().unwrap();
++ let path = dir.path().join("cap.log");
++ std::fs::write(&path, "éééé\ncomplete\n").unwrap();
++ assert_eq!(read_tail(&path, 12).unwrap().0, "complete\n");
++ for index in 0..150 {
++ std::fs::write(dir.path().join(format!("unrelated-{index}")), "").unwrap();
++ }
++ let bundle = collect(dir.path(), "cap.log");
++ assert_eq!(bundle.directory_entries_scanned, 151);
++ assert!(bundle.files.iter().any(|file| file.name == "cap.log"));
++ assert!(!collect(&dir.path().join("missing"), "cap.log").directory_available);
++ }
++}
diff --cc crates/utils/src/operation_diagnostics.rs
index 000000000,000000000..2ce49793c
new file mode 100644
--- /dev/null
+++ b/crates/utils/src/operation_diagnostics.rs
@@@ -1,0 -1,0 +1,951 @@@
++use serde::{Deserialize, Serialize};
++use std::{
++ collections::hash_map::RandomState,
++ hash::BuildHasher,
++ io::Write,
++ path::Path,
++ sync::{
++ Mutex, OnceLock,
++ atomic::{AtomicU64, Ordering},
++ },
++ time::{Instant, SystemTime, UNIX_EPOCH},
++};
++
++const CAPACITY: usize = 64;
++const MAX_FIELDS: usize = 16;
++static HISTORY: History = History::new();
++type DiagnosticSink = Box<dyn Fn(&[u8]) + Send + Sync>;
++static SINK: OnceLock<DiagnosticSink> = OnceLock::new();
++static APP: OnceLock<AppInfo> = OnceLock::new();
++static PARENT: OnceLock<Option<OperationId>> = OnceLock::new();
++static SESSION: OnceLock<u64> = OnceLock::new();
++static RESOURCE_HASH: OnceLock<RandomState> = OnceLock::new();
++static OMITTED_RECORDS: AtomicU64 = AtomicU64::new(0);
++static EMISSION_EPOCH: OnceLock<Instant> = OnceLock::new();
++static EMISSION_BUDGET: ByteBudget = ByteBudget(AtomicU64::new(0));
++pub const MAX_BYTES_PER_SECOND: u32 = 32 * 1024;
++type QueueLossCounter = Box<dyn Fn() -> usize + Send + Sync>;
++static QUEUE_LOSS_COUNTER: OnceLock<QueueLossCounter> = OnceLock::new();
++const HEALTH_KINDS: usize = 16;
++static HEALTH_COUNTS: [AtomicU64; HEALTH_KINDS] = [const { AtomicU64::new(0) }; HEALTH_KINDS];
++static HEALTH_LAST_MS: [AtomicU64; HEALTH_KINDS] = [const { AtomicU64::new(0) }; HEALTH_KINDS];
++
++pub fn health_event(kind: usize, name: &'static str, fields: &[Field]) {
++ let (Some(count), Some(last)) = (HEALTH_COUNTS.get(kind), HEALTH_LAST_MS.get(kind)) else {
++ return;
++ };
++ let occurrences = count.fetch_add(1, Ordering::Relaxed).saturating_add(1);
++ let now = unix_ms();
++ let previous = last.load(Ordering::Relaxed);
++ if previous != 0 && now.saturating_sub(previous) < 60_000 {
++ return;
++ }
++ if last
++ .compare_exchange(previous, now, Ordering::Relaxed, Ordering::Relaxed)
++ .is_err()
++ {
++ return;
++ }
++ let mut event = Operation::new_in(&HISTORY, "process_health", fields);
++ event.field(Field::label("event", name));
++ event.field(Field::number("occurrences_in_process", occurrences));
++ event.record.outcome = Outcome::Observed;
++ event.finished = true;
++ event.publish();
++}
++
++#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
++#[serde(rename_all = "camelCase")]
++pub struct OperationId {
++ session: u64,
++ process: u32,
++ sequence: u64,
++}
++
++#[derive(Clone, Copy, Debug, Serialize)]
++#[serde(rename_all = "camelCase")]
++pub struct AppInfo {
++ pub flavor: &'static str,
++ pub version: &'static str,
++ pub source_revision: Option<&'static str>,
++ pub debug_build: bool,
++ pub source_dirty: Option<bool>,
++}
++
++pub fn install_sink(app: AppInfo, sink: impl Fn(&[u8]) + Send + Sync + 'static) {
++ let _ = APP.set(app);
++ let _ = RESOURCE_HASH.set(RandomState::new());
++ let _ = SESSION.set(unix_ms());
++ let _ = EMISSION_EPOCH.set(Instant::now());
++ let _ = PARENT.set(
++ std::env::var("CAP_DIAGNOSTIC_PARENT")
++ .ok()
++ .filter(|value| value.len() <= 160)
++ .and_then(|value| serde_json::from_str(&value).ok()),
++ );
++ let _ = SINK.set(Box::new(sink));
++}
++
++struct ByteBudget(AtomicU64);
++
++impl ByteBudget {
++ fn acquire(&self, second: u32, bytes: u32) -> bool {
++ let mut previous = self.0.load(Ordering::Relaxed);
++ for _ in 0..4 {
++ if previous >> 32 > u64::from(second) {
++ return false;
++ }
++ let used = if previous >> 32 == u64::from(second) {
++ previous as u32
++ } else {
++ 0
++ };
++ let next = used.saturating_add(bytes);
++ if next > MAX_BYTES_PER_SECOND {
++ return false;
++ }
++ let state = (u64::from(second) << 32) | u64::from(next);
++ match self.0.compare_exchange_weak(
++ previous,
++ state,
++ Ordering::Relaxed,
++ Ordering::Relaxed,
++ ) {
++ Ok(_) => return true,
++ Err(actual) => previous = actual,
++ }
++ }
++ false
++ }
++}
++
++fn emit_bytes(sink: &DiagnosticSink, bytes: &[u8]) {
++ let second = EMISSION_EPOCH.get_or_init(Instant::now).elapsed().as_secs() as u32;
++ if EMISSION_BUDGET.acquire(second, bytes.len() as u32) {
++ sink(bytes);
++ } else {
++ OMITTED_RECORDS.fetch_add(1, Ordering::Relaxed);
++ }
++}
++
++pub fn install_queue_loss_counter(counter: impl Fn() -> usize + Send + Sync + 'static) {
++ let _ = QUEUE_LOSS_COUNTER.set(Box::new(counter));
++}
++
++fn unix_ms() -> u64 {
++ SystemTime::now()
++ .duration_since(UNIX_EPOCH)
++ .unwrap_or_default()
++ .as_millis()
++ .min(u64::MAX as u128) as u64
++}
++
++pub fn resource_id(path: &Path) -> u64 {
++ RESOURCE_HASH.get_or_init(RandomState::new).hash_one(path)
++}
++
++struct RecordBuffer {
++ bytes: [u8; crate::diagnostic_writer::MAX_RECORD_BYTES],
++ length: usize,
++}
++
++impl Write for RecordBuffer {
++ fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
++ let remaining = self.bytes.len().saturating_sub(self.length);
++ if bytes.len() > remaining {
++ return Err(std::io::Error::other(
++ "Diagnostic record exceeded its budget",
++ ));
++ }
++ self.bytes[self.length..self.length + bytes.len()].copy_from_slice(bytes);
++ self.length += bytes.len();
++ Ok(bytes.len())
++ }
++ fn flush(&mut self) -> std::io::Result<()> {
++ Ok(())
++ }
++}
++
++fn emit(record: &Record) {
++ let Some(sink) = SINK.get() else { return };
++ let mut buffer = RecordBuffer {
++ bytes: [0; crate::diagnostic_writer::MAX_RECORD_BYTES],
++ length: 0,
++ };
++ let result = (|| {
++ buffer.write_all(crate::diagnostic_writer::RECORD_PREFIX)?;
++ serde_json::to_writer(&mut buffer, record)?;
++ buffer.write_all(b"\n")
++ })();
++ if result.is_ok() {
++ emit_bytes(sink, &buffer.bytes[..buffer.length]);
++ } else {
++ OMITTED_RECORDS.fetch_add(1, Ordering::Relaxed);
++ }
++}
++
++pub fn relay_worker_record(line: &str) -> bool {
++ let prefix = crate::diagnostic_writer::RECORD_PREFIX;
++ if !line.as_bytes().starts_with(prefix)
++ || line.len() >= crate::diagnostic_writer::MAX_RECORD_BYTES
++ {
++ return false;
++ }
++ let Some(sink) = SINK.get() else { return false };
++ let mut buffer = RecordBuffer {
++ bytes: [0; crate::diagnostic_writer::MAX_RECORD_BYTES],
++ length: 0,
++ };
++ if buffer
++ .write_all(line.as_bytes())
++ .and_then(|_| buffer.write_all(b"\n"))
++ .is_ok()
++ {
++ emit_bytes(sink, &buffer.bytes[..buffer.length]);
++ true
++ } else {
++ false
++ }
++}
++
++pub fn checkpoint_active() {
++ let captured = HISTORY.snapshot_records();
++ if let Some(records) = captured {
++ for mut record in records
++ .into_iter()
++ .flatten()
++ .filter(|record| matches!(record.outcome, Outcome::InProgress))
++ {
++ record.elapsed_ms = record.started.elapsed().as_millis().min(u64::MAX as u128) as u64;
++ emit(&record);
++ }
++ }
++}
++
++pub async fn run_checkpoints() {
++ loop {
++ tokio::time::sleep(std::time::Duration::from_secs(60)).await;
++ checkpoint_active();
++ }
++}
++
++#[derive(Clone, Copy, Debug, Serialize)]
++#[serde(untagged)]
++pub enum Value {
++ Number(u64),
++ Identifier(#[serde(serialize_with = "serialize_identifier")] u64),
++ Flag(bool),
++ Label(&'static str),
++}
++
++fn serialize_identifier<S: serde::Serializer>(
++ value: &u64,
++ serializer: S,
++) -> Result<S::Ok, S::Error> {
++ serializer.collect_str(&format_args!("{value:016x}"))
++}
++
++#[derive(Clone, Copy, Debug, Serialize)]
++pub struct Field {
++ name: &'static str,
++ value: Value,
++}
++
++impl Field {
++ pub const fn number(name: &'static str, value: u64) -> Self {
++ Self {
++ name,
++ value: Value::Number(value),
++ }
++ }
++
++ pub const fn identifier(name: &'static str, value: u64) -> Self {
++ Self {
++ name,
++ value: Value::Identifier(value),
++ }
++ }
++
++ pub const fn flag(name: &'static str, value: bool) -> Self {
++ Self {
++ name,
++ value: Value::Flag(value),
++ }
++ }
++
++ pub const fn label(name: &'static str, value: &'static str) -> Self {
++ Self {
++ name,
++ value: Value::Label(value),
++ }
++ }
++}
++
++#[derive(Clone, Copy, Debug, Serialize)]
++#[serde(rename_all = "snake_case")]
++pub enum Outcome {
++ InProgress,
++ ReturnedOk,
++ ReturnedError,
++ Incomplete,
++ Observed,
++}
++
++#[derive(Clone, Copy, Debug, Serialize)]
++#[serde(rename_all = "camelCase")]
++struct Record {
++ schema_version: u32,
++ id: u64,
++ revision: u64,
++ operation_id: OperationId,
++ parent_operation_id: Option<OperationId>,
++ app: Option<AppInfo>,
++ os: &'static str,
++ binary_architecture: &'static str,
++ #[serde(skip)]
++ started: Instant,
++ operation: &'static str,
++ started_at_unix_ms: u64,
++ elapsed_ms: u64,
++ stage: &'static str,
++ outcome: Outcome,
++ fields: [Option<Field>; MAX_FIELDS],
++ omitted_fields: usize,
++}
++
++struct History {
++ records: Mutex<[Option<Record>; CAPACITY]>,
++ active_sequences: [AtomicU64; CAPACITY],
++ sequence: AtomicU64,
++ dropped_updates: AtomicU64,
++}
++
++impl History {
++ const fn new() -> Self {
++ Self {
++ records: Mutex::new([None; CAPACITY]),
++ active_sequences: [const { AtomicU64::new(0) }; CAPACITY],
++ sequence: AtomicU64::new(0),
++ dropped_updates: AtomicU64::new(0),
++ }
++ }
++
++ fn is_active(&self, index: usize, record: Record) -> bool {
++ matches!(record.outcome, Outcome::InProgress)
++ && self.active_sequences[index].load(Ordering::Relaxed) == record.id.wrapping_add(1)
++ }
++
++ fn retire(&self, index: usize, id: u64) {
++ let _ = self.active_sequences[index].compare_exchange(
++ id.wrapping_add(1),
++ 0,
++ Ordering::Relaxed,
++ Ordering::Relaxed,
++ );
++ }
++
++ fn publish(&self, record: Record) -> Option<usize> {
++ let index = if let Ok(mut records) = self.records.try_lock() {
++ let index = records
++ .iter()
++ .position(|slot| slot.is_some_and(|previous| previous.id == record.id))
++ .or_else(|| records.iter().position(Option::is_none))
++ .or_else(|| {
++ records
++ .iter()
++ .enumerate()
++ .filter_map(|(index, slot)| {
++ slot.filter(|previous| !self.is_active(index, *previous))
++ .map(|previous| (index, previous.id))
++ })
++ .min_by_key(|(_, id)| *id)
++ .map(|(index, _)| index)
++ });
++ if let Some(index) = index {
++ self.active_sequences[index].store(
++ if matches!(record.outcome, Outcome::InProgress) {
++ record.id.wrapping_add(1)
++ } else {
++ 0
++ },
++ Ordering::Relaxed,
++ );
++ records[index] = Some(record);
++ } else {
++ self.dropped_updates.fetch_add(1, Ordering::Relaxed);
++ }
++ index
++ } else {
++ self.dropped_updates.fetch_add(1, Ordering::Relaxed);
++ None
++ };
++ emit(&record);
++ index
++ }
++
++ fn snapshot_records(&self) -> Option<[Option<Record>; CAPACITY]> {
++ let mut captured = self.records.try_lock().ok().map(|records| *records)?;
++ for (index, slot) in captured.iter_mut().enumerate() {
++ if slot.is_some_and(|record| {
++ matches!(record.outcome, Outcome::InProgress) && !self.is_active(index, record)
++ }) {
++ *slot = None;
++ }
++ }
++ Some(captured)
++ }
++
++ fn snapshot(&self) -> Snapshot {
++ let captured = self.snapshot_records();
++ let mut records: Vec<_> = captured.into_iter().flatten().flatten().collect();
++ records.sort_unstable_by_key(|record| record.id);
++ Snapshot {
++ schema_version: 2,
++ scope: "current_process_only",
++ outcome_semantics: "return_value_only_not_media_validation",
++ status: if captured.is_some() {
++ "available"
++ } else {
++ "busy"
++ },
++ process_id: std::process::id(),
++ capacity: CAPACITY,
++ storage_bytes: std::mem::size_of::<Self>(),
++ total_started: self.sequence.load(Ordering::Relaxed),
++ dropped_updates: self.dropped_updates.load(Ordering::Relaxed),
++ journal_sink_installed: SINK.get().is_some(),
++ journal_write_failures: crate::diagnostic_writer::write_failures(),
++ logger_dropped_messages: QUEUE_LOSS_COUNTER.get().map(|counter| counter()),
++ omitted_records: OMITTED_RECORDS.load(Ordering::Relaxed),
++ records,
++ }
++ }
++}
++
++#[derive(Serialize)]
++#[serde(rename_all = "camelCase")]
++pub struct Snapshot {
++ schema_version: u32,
++ scope: &'static str,
++ outcome_semantics: &'static str,
++ status: &'static str,
++ process_id: u32,
++ capacity: usize,
++ storage_bytes: usize,
++ total_started: u64,
++ dropped_updates: u64,
++ journal_sink_installed: bool,
++ journal_write_failures: u64,
++ logger_dropped_messages: Option<usize>,
++ omitted_records: u64,
++ records: Vec<Record>,
++}
++
++pub fn snapshot() -> Snapshot {
++ HISTORY.snapshot()
++}
++
++pub struct Operation {
++ history: &'static History,
++ history_slot: Option<usize>,
++ started: Instant,
++ record: Record,
++ finished: bool,
++}
++
++impl Operation {
++ pub fn start(operation: &'static str, fields: &[Field]) -> Self {
++ Self::start_in(&HISTORY, operation, fields)
++ }
++
++ fn start_in(history: &'static History, operation: &'static str, fields: &[Field]) -> Self {
++ let mut value = Self::new_in(history, operation, fields);
++ value.publish();
++ value
++ }
++
++ fn new_in(history: &'static History, operation: &'static str, fields: &[Field]) -> Self {
++ let id = history.sequence.fetch_add(1, Ordering::Relaxed);
++ let started = Instant::now();
++ let mut record = Record {
++ schema_version: 2,
++ id,
++ revision: 0,
++ operation_id: OperationId {
++ session: *SESSION.get_or_init(unix_ms),
++ process: std::process::id(),
++ sequence: id,
++ },
++ parent_operation_id: PARENT.get().copied().flatten(),
++ app: APP.get().copied(),
++ os: std::env::consts::OS,
++ binary_architecture: std::env::consts::ARCH,
++ started,
++ operation,
++ started_at_unix_ms: SystemTime::now()
++ .duration_since(UNIX_EPOCH)
++ .unwrap_or_default()
++ .as_millis()
++ .min(u64::MAX as u128) as u64,
++ elapsed_ms: 0,
++ stage: "started",
++ outcome: Outcome::InProgress,
++ fields: [None; MAX_FIELDS],
++ omitted_fields: fields.len().saturating_sub(MAX_FIELDS),
++ };
++ for (slot, field) in record.fields.iter_mut().zip(fields) {
++ *slot = Some(*field);
++ }
++ Self {
++ history,
++ history_slot: None,
++ started,
++ record,
++ finished: false,
++ }
++ }
++
++ pub fn id(&self) -> OperationId {
++ self.record.operation_id
++ }
++
++ pub fn set_parent(&mut self, parent: OperationId) {
++ self.record.parent_operation_id = Some(parent);
++ self.publish();
++ }
++
++ pub fn stage(&mut self, stage: &'static str) {
++ self.record.stage = stage;
++ self.publish();
++ }
++
++ pub fn field(&mut self, field: Field) {
++ if let Some(slot) = self
++ .record
++ .fields
++ .iter_mut()
++ .find(|slot| slot.is_some_and(|value| value.name == field.name))
++ {
++ *slot = Some(field);
++ } else if let Some(slot) = self.record.fields.iter_mut().find(|slot| slot.is_none()) {
++ *slot = Some(field);
++ } else {
++ self.record.omitted_fields = self.record.omitted_fields.saturating_add(1);
++ }
++ }
++
++ pub fn finish(mut self, succeeded: bool) {
++ self.record.outcome = if succeeded {
++ Outcome::ReturnedOk
++ } else {
++ Outcome::ReturnedError
++ };
++ self.publish();
++ self.finished = true;
++ }
++
++ fn publish(&mut self) {
++ if !matches!(self.record.outcome, Outcome::InProgress)
++ && let Some(index) = self.history_slot
++ {
++ self.history.retire(index, self.record.id);
++ }
++ self.record.revision = self.record.revision.saturating_add(1);
++ self.record.elapsed_ms = self.started.elapsed().as_millis().min(u64::MAX as u128) as u64;
++ if let Some(index) = self.history.publish(self.record) {
++ self.history_slot = Some(index);
++ }
++ }
++}
++
++impl Drop for Operation {
++ fn drop(&mut self) {
++ if !self.finished {
++ self.record.outcome = Outcome::Incomplete;
++ self.publish();
++ }
++ }
++}
++
++pub async fn observe<T, E>(
++ operation: &'static str,
++ fields: &[Field],
++ future: impl Future<Output = Result<T, E>>,
++) -> Result<T, E> {
++ let diagnostic = Operation::start(operation, fields);
++ let result = future.await;
++ diagnostic.finish(result.is_ok());
++ result
++}
++
++#[cfg(test)]
++mod tests {
++ use super::*;
++
++ #[test]
++ fn event_storms_have_a_fixed_byte_budget_without_waiting() {
++ let budget = ByteBudget(AtomicU64::new(0));
++ for _ in 0..MAX_BYTES_PER_SECOND / 1024 {
++ assert!(budget.acquire(0, 1024));
++ }
++ for _ in 0..10_000 {
++ assert!(!budget.acquire(0, 1024));
++ }
++ assert!(budget.acquire(1, 1024));
++ assert!(!budget.acquire(1, MAX_BYTES_PER_SECOND));
++ assert!(!budget.acquire(0, 1024));
++ }
++
++ struct ChildGuard(std::process::Child);
++
++ impl Drop for ChildGuard {
++ fn drop(&mut self) {
++ let _ = self.0.kill();
++ let _ = self.0.wait();
++ }
++ }
++
++ #[test]
++ fn killed_process_leaves_context_in_the_upload() {
++ let dir = tempfile::tempdir().unwrap();
++ let child = std::process::Command::new(std::env::current_exe().unwrap())
++ .args([
++ "--ignored",
++ "--exact",
++ "operation_diagnostics::tests::diagnostic_child",
++ "--nocapture",
++ ])
++ .env("CAP_DIAGNOSTIC_TEST_DIRECTORY", dir.path())
++ .env("CAP_DIAGNOSTIC_TEST_MODE", "crash")
++ .stdout(std::process::Stdio::null())
++ .stderr(std::process::Stdio::null())
++ .spawn()
++ .unwrap();
++ let mut child = ChildGuard(child);
++ let started = Instant::now();
++ loop {
++ let bundle = crate::log_upload::collect(dir.path(), "cap-test.log");
++ if bundle.text.contains("waiting_for_encoder") {
++ break;
++ }
++ assert!(
++ started.elapsed() < std::time::Duration::from_secs(10),
++ "child did not persist its checkpoint"
++ );
++ std::thread::sleep(std::time::Duration::from_millis(20));
++ }
++ child.0.kill().unwrap();
++ child.0.wait().unwrap();
++ let bundle = crate::log_upload::collect(dir.path(), "cap-test.log");
++ let records: Vec<serde_json::Value> = bundle
++ .text
++ .lines()
++ .filter_map(|line| line.strip_prefix("CAP_DIAGNOSTIC "))
++ .map(|line| serde_json::from_str(line).unwrap())
++ .collect();
++ assert!(records.len() >= 2);
++ assert!(
++ records
++ .iter()
++ .any(|record| record["stage"] == "waiting_for_encoder")
++ );
++ assert!(
++ records
++ .iter()
++ .all(|record| record["outcome"] == "in_progress")
++ );
++ assert!(
++ records
++ .iter()
++ .all(|record| record["operationId"] == records[0]["operationId"])
++ );
++ assert_eq!(records[0]["app"]["version"], "test-build");
++ assert!(
++ bundle
++ .files
++ .iter()
++ .any(|file| file.name.ends_with("diagnostic-current.jsonl"))
++ );
++ }
++
++ #[test]
++ fn worker_records_keep_the_parent_operation_identity() {
++ let dir = tempfile::tempdir().unwrap();
++ let parent = OperationId {
++ session: 123,
++ process: 456,
++ sequence: 789,
++ };
++ let output = std::process::Command::new(std::env::current_exe().unwrap())
++ .args([
++ "--ignored",
++ "--exact",
++ "operation_diagnostics::tests::diagnostic_child",
++ "--nocapture",
++ ])
++ .env("CAP_DIAGNOSTIC_TEST_DIRECTORY", dir.path())
++ .env("CAP_DIAGNOSTIC_TEST_MODE", "complete")
++ .env(
++ "CAP_DIAGNOSTIC_PARENT",
++ serde_json::to_string(&parent).unwrap(),
++ )
++ .output()
++ .unwrap();
++ assert!(
++ output.status.success(),
++ "{}",
++ String::from_utf8_lossy(&output.stderr)
++ );
++ let bundle = crate::log_upload::collect(dir.path(), "cap-test.log");
++ let records: Vec<serde_json::Value> = bundle
++ .text
++ .lines()
++ .filter_map(|line| line.strip_prefix("CAP_DIAGNOSTIC "))
++ .map(|line| serde_json::from_str(line).unwrap())
++ .collect();
++ assert!(
++ records
++ .iter()
++ .any(|record| record["outcome"] == "returned_ok")
++ );
++ assert!(
++ records
++ .iter()
++ .all(|record| record["parentOperationId"] == serde_json::to_value(parent).unwrap())
++ );
++ }
++
++ #[test]
++ #[ignore]
++ fn diagnostic_child() {
++ let Some(directory) = std::env::var_os("CAP_DIAGNOSTIC_TEST_DIRECTORY") else {
++ return;
++ };
++ let writer = crate::diagnostic_writer::DiagnosticWriter::new(
++ std::io::sink(),
++ Path::new(&directory),
++ "cap-test.log",
++ );
++ let (writer, guard) = tracing_appender::non_blocking(writer);
++ install_sink(
++ AppInfo {
++ flavor: "test",
++ version: "test-build",
++ source_revision: Some("test-revision"),
++ debug_build: cfg!(debug_assertions),
++ source_dirty: Some(false),
++ },
++ move |bytes| {
++ let _ = writer.clone().write_all(bytes);
++ },
++ );
++ let mut operation = Operation::start(
++ "recording",
++ &[
++ Field::number("requested_fps", 60),
++ Field::flag("microphone", true),
++ ],
++ );
++ operation.stage("waiting_for_encoder");
++ checkpoint_active();
++ if std::env::var("CAP_DIAGNOSTIC_TEST_MODE").as_deref() == Ok("crash") {
++ loop {
++ std::thread::sleep(std::time::Duration::from_secs(1));
++ }
++ }
++ operation.finish(true);
++ drop(guard);
++ }
++
++ fn history() -> &'static History {
++ Box::leak(Box::new(History::new()))
++ }
++
++ #[test]
++ fn history_stays_bounded_and_keeps_recent_operations() {
++ let history = history();
++ for _ in 0..CAPACITY * 20 {
++ Operation::start_in(history, "export", &[]).finish(true);
++ }
++ let snapshot = history.snapshot();
++ assert_eq!(snapshot.records.len(), CAPACITY);
++ assert_eq!(snapshot.total_started, (CAPACITY * 20) as u64);
++ assert_eq!(snapshot.records[0].id, (CAPACITY * 19) as u64);
++ assert!(snapshot.storage_bytes < 64 * 1024);
++ }
++
++ #[test]
++ fn contention_drops_diagnostics_without_waiting() {
++ let history = history();
++ let guard = history.records.lock().unwrap();
++ Operation::start_in(history, "recording", &[]).finish(false);
++ assert_eq!(history.snapshot().status, "busy");
++ drop(guard);
++ assert_eq!(history.snapshot().dropped_updates, 2);
++ }
++
++ #[test]
++ fn lost_completions_cannot_checkpoint_forever_or_exhaust_history() {
++ let history = history();
++ for _ in 0..CAPACITY * 2 {
++ let operation = Operation::start_in(history, "recording", &[]);
++ let guard = history.records.lock().unwrap();
++ operation.finish(true);
++ drop(guard);
++ assert!(
++ history
++ .snapshot_records()
++ .unwrap()
++ .into_iter()
++ .all(|slot| slot.is_none())
++ );
++ }
++ Operation::start_in(history, "recent_export", &[]).finish(false);
++ let snapshot = history.snapshot();
++ assert_eq!(snapshot.dropped_updates, (CAPACITY * 2) as u64);
++ assert_eq!(snapshot.records.len(), 1);
++ assert_eq!(snapshot.records[0].operation, "recent_export");
++ assert!(matches!(
++ snapshot.records[0].outcome,
++ Outcome::ReturnedError
++ ));
++ }
++
++ #[test]
++ fn cancelled_operations_retire_while_history_is_busy() {
++ let history = history();
++ let operation = Operation::start_in(history, "export", &[]);
++ let guard = history.records.lock().unwrap();
++ drop(operation);
++ drop(guard);
++ assert!(history.snapshot().records.is_empty());
++ assert_eq!(history.snapshot().dropped_updates, 1);
++ }
++
++ #[test]
++ fn active_operations_survive_recent_completed_operations() {
++ let history = history();
++ let old = Operation::start_in(history, "old", &[]);
++ for _ in 0..CAPACITY {
++ Operation::start_in(history, "new", &[]).finish(true);
++ }
++ old.finish(false);
++ let snapshot = history.snapshot();
++ assert!(
++ snapshot
++ .records
++ .iter()
++ .any(|record| record.operation == "old")
++ );
++ assert_eq!(snapshot.records.len(), CAPACITY);
++ assert_eq!(snapshot.dropped_updates, 0);
++ }
++
++ #[test]
++ fn dropped_operations_and_missing_fields_are_explicit() {
++ let history = history();
++ let fields = [Field::number("fps", 60); MAX_FIELDS + 3];
++ let mut operation = Operation::start_in(history, "playback", &fields);
++ operation.stage("audio_initialization");
++ drop(operation);
++ let snapshot = history.snapshot();
++ let record = snapshot.records[0];
++ assert!(matches!(record.outcome, Outcome::Incomplete));
++ assert_eq!(record.omitted_fields, 3);
++ assert_eq!(record.stage, "audio_initialization");
++ serde_json::to_string(&snapshot).unwrap();
++ }
++
++ #[tokio::test]
++ async fn observation_preserves_results_and_cancellation() {
++ let error = String::from("original error");
++ let pointer = error.as_ptr();
++ let result = observe("test", &[], async { Err::<(), _>(error) }).await;
++ let returned_error = result.unwrap_err();
++ assert_eq!(returned_error.as_ptr(), pointer);
++ let result = observe("test", &[], async { Ok::<_, ()>(42) }).await;
++ assert_eq!(result, Ok(42));
++ let mut pending = Box::pin(observe(
++ "test_pending",
++ &[],
++ std::future::pending::<Result<(), ()>>(),
++ ));
++ assert!(futures::poll!(pending.as_mut()).is_pending());
++ drop(pending);
++ }
++
++ #[test]
++ #[ignore]
++ fn operation_boundary_overhead() {
++ let history = history();
++ let fields = [Field::number("measurement", 60); MAX_FIELDS];
++ let measure = |paced: bool| {
++ let mut samples = Vec::with_capacity(100);
++ for _ in 0..100 {
++ if paced {
++ std::thread::sleep(std::time::Duration::from_millis(100));
++ }
++ let started = Instant::now();
++ let mut operation = Operation::start_in(history, "export", &fields);
++ operation.stage("encoding");
++ operation.finish(true);
++ samples.push(started.elapsed().as_nanos());
++ }
++ samples.sort_unstable();
++ serde_json::json!({
++ "p50Ns": samples[50],
++ "p95Ns": samples[95],
++ "p99Ns": samples[99],
++ "maxNs": samples[99],
++ "meanNs": samples.iter().sum::<u128>() / samples.len() as u128,
++ })
++ };
++ let without_sink = measure(false);
++ let dir = tempfile::tempdir().unwrap();
++ let writer = crate::diagnostic_writer::DiagnosticWriter::new(
++ std::io::sink(),
++ dir.path(),
++ "cap-benchmark.log",
++ );
++ let (writer, guard) = tracing_appender::non_blocking(writer);
++ let errors = writer.error_counter();
++ let bytes_emitted = std::sync::Arc::new(AtomicU64::new(0));
++ let emitted = bytes_emitted.clone();
++ install_sink(
++ AppInfo {
++ flavor: "benchmark",
++ version: "test",
++ source_revision: None,
++ debug_build: cfg!(debug_assertions),
++ source_dirty: Some(true),
++ },
++ move |bytes| {
++ emitted.fetch_add(bytes.len() as u64, Ordering::Relaxed);
++ let _ = writer.clone().write_all(bytes);
++ },
++ );
++ let with_disk_sink = measure(true);
++ drop(guard);
++ let retained_bytes: u64 = std::fs::read_dir(dir.path())
++ .unwrap()
++ .map(|entry| entry.unwrap().metadata().unwrap().len())
++ .sum();
++ assert!(retained_bytes <= 2 * crate::diagnostic_writer::MAX_FILE_BYTES);
++ println!(
++ "{}",
++ serde_json::json!({
++ "unit": "one_start_stage_finish_with_16_fields",
++ "iterations": 100,
++ "operationsPerSecond": 10,
++ "omittedRecords": OMITTED_RECORDS.load(Ordering::Relaxed),
++ "withoutSink": without_sink,
++ "withAsyncDiskSink": with_disk_sink,
++ "emittedBytes": bytes_emitted.load(Ordering::Relaxed),
++ "retainedBytes": retained_bytes,
++ "droppedMessages": errors.dropped_lines(),
++ "fixedHistoryBytes": std::mem::size_of::<History>(),
++ "debugBuild": cfg!(debug_assertions),
++ })
++ );
++ }
++}
diff --cc packages/ui-solid/src/auto-imports.d.ts
index 151b31391,151b31391..8a71a74d2
--- a/packages/ui-solid/src/auto-imports.d.ts
+++ b/packages/ui-solid/src/auto-imports.d.ts
@@@ -81,6 -81,6 +81,7 @@@ declare global
const IconLucideClapperboard: typeof import('~icons/lucide/clapperboard.jsx')['default']
const IconLucideClock: typeof import('~icons/lucide/clock.jsx')['default']
const IconLucideColumns2: typeof import('~icons/lucide/columns2.jsx')['default']
++ const IconLucideCrosshair: typeof import('~icons/lucide/crosshair.jsx')['default']
const IconLucideEdit: typeof import('~icons/lucide/edit.jsx')['default']
const IconLucideEyeOff: typeof import('~icons/lucide/eye-off.jsx')['default']
const IconLucideFastForward: typeof import('~icons/lucide/fast-forward.jsx')['default']
diff --cc packages/ui-solid/src/main.css
index 16d8c9140,16d8c9140..9d7bec55f
--- a/packages/ui-solid/src/main.css
+++ b/packages/ui-solid/src/main.css
@@@ -60,6 -60,6 +60,24 @@@
--color-transparent: rgba(0, 0, 0, 0);
--color-solid-white: #ffffff;
++ --color-ed-window: var(--ed-window);
++ --color-ed-card: var(--ed-card);
++ --color-ed-card-2: var(--ed-card-2);
++ --color-ed-stage: var(--ed-stage);
++ --color-ed-line: var(--ed-line);
++ --color-ed-line-strong: var(--ed-line-strong);
++ --color-ed-text-1: var(--ed-text-1);
++ --color-ed-text-2: var(--ed-text-2);
++ --color-ed-text-3: var(--ed-text-3);
++ --color-ed-ctl: var(--ed-ctl);
++ --color-ed-ctl-hover: var(--ed-ctl-hover);
++ --color-ed-ctl-active: var(--ed-ctl-active);
++ --color-ed-accent: var(--ed-accent);
++ --color-ed-accent-2: var(--ed-accent-2);
++ --color-ed-playhead: var(--ed-playhead);
++ --color-ed-thumb: var(--ed-thumb);
++ --shadow-ed-card: var(--ed-card-shadow);
++ --shadow-ed-pop: var(--ed-pop-shadow);
--color-transparent-window: var(--transparent-window);
--color-gray-1: var(--gray-1);
diff --cc scripts/diagnostic-build.rs
index 000000000,000000000..787821ebc
new file mode 100644
--- /dev/null
+++ b/scripts/diagnostic-build.rs
@@@ -1,0 -1,0 +1,44 @@@
++use std::{path::Path, process::Command};
++
++pub fn emit() {
++ let Ok(directory) = std::env::var("CARGO_MANIFEST_DIR") else {
++ return;
++ };
++ let git = |args: &[&str]| {
++ Command::new("git")
++ .args(args)
++ .current_dir(&directory)
++ .output()
++ .ok()
++ };
++ if let Some(output) = git(&["rev-parse", "HEAD"])
++ && output.status.success()
++ {
++ let revision = String::from_utf8_lossy(&output.stdout);
++ let revision = revision.trim();
++ if (revision.len() == 40 || revision.len() == 64)
++ && revision.bytes().all(|byte| byte.is_ascii_hexdigit())
++ {
++ println!("cargo:rustc-env=CAP_BUILD_REVISION={revision}");
++ }
++ }
++ if let Some(output) = git(&["diff-index", "--quiet", "HEAD", "--"]) {
++ match output.status.code() {
++ Some(0) => println!("cargo:rustc-env=CAP_BUILD_DIRTY=false"),
++ Some(1) => println!("cargo:rustc-env=CAP_BUILD_DIRTY=true"),
++ _ => {}
++ }
++ }
++ for entry in ["HEAD", "refs", "index"] {
++ if let Some(output) = git(&["rev-parse", "--git-path", entry])
++ && output.status.success()
++ {
++ let path = String::from_utf8_lossy(&output.stdout);
++ println!(
++ "cargo:rerun-if-changed={}",
++ Path::new(&directory).join(path.trim()).display()
++ );
++ }
++ }
++ println!("cargo:rerun-if-changed=src");
++}