Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
perf(gpui): keep complex editor playback and scrubbing responsive
Richie McIlroy8ff0035eee80
diff --git a/apps/desktop-gpui/src/editor_canvas.rs b/apps/desktop-gpui/src/editor_canvas.rsindex 8de366858..35274a209 100644--- a/apps/desktop-gpui/src/editor_canvas.rs+++ b/apps/desktop-gpui/src/editor_canvas.rs@@ -601,7 +601,7 @@ impl EditorWindow {if exclude == CanvasSelection::Text(index) {continue;}- if !(t >= segment.start && t < segment.end) || !segment.enabled {+ if !(t >= segment.start && t < segment.end && segment.enabled) {continue;}let center = segment.center;@@ -1173,7 +1173,7 @@ impl EditorWindow {}}for (index, segment) in timeline.text_segments.iter().enumerate() {- if !(time >= segment.start && time < segment.end) || !segment.enabled {+ if !(time >= segment.start && time < segment.end && segment.enabled) {continue;}let element = CanvasSelection::Text(index);diff --git a/apps/desktop-gpui/src/editor_edits.rs b/apps/desktop-gpui/src/editor_edits.rsindex ea6944896..7d3b89770 100644--- a/apps/desktop-gpui/src/editor_edits.rs+++ b/apps/desktop-gpui/src/editor_edits.rs@@ -1894,6 +1894,8 @@ mod tests {use super::*;use crate::editor_timeline::{SegmentDetail, TimelineModel};+ const OVERLAPPING_SEGMENT_END: f64 = 314.0 / 100.0;+fn config(json: serde_json::Value) -> ProjectConfiguration {serde_json::from_value(json).expect("fixture parses")}@@ -2333,7 +2335,7 @@ mod tests {let overlapping = config(serde_json::json!({"timeline": {"segments": [- { "recordingSegment": 0, "timescale": 1.0, "start": 2.54, "end": 3.14 },+ { "recordingSegment": 0, "timescale": 1.0, "start": 2.54, "end": OVERLAPPING_SEGMENT_END },{ "recordingSegment": 0, "timescale": 1.0, "start": 2.14, "end": 3.29 },{ "recordingSegment": 0, "timescale": 1.0, "start": 3.29, "end": 6.68 },{ "recordingSegment": 0, "timescale": 1.0, "start": 5.83, "end": 6.98 }@@ -2398,7 +2400,7 @@ mod tests {let overlapping = config(serde_json::json!({"timeline": {"segments": [- { "recordingSegment": 0, "timescale": 1.0, "start": 2.54, "end": 3.14 },+ { "recordingSegment": 0, "timescale": 1.0, "start": 2.54, "end": OVERLAPPING_SEGMENT_END },{ "recordingSegment": 0, "timescale": 1.0, "start": 2.14, "end": 3.29 }],"zoomSegments": []@@ -2411,7 +2413,7 @@ mod tests {assert_eq!(clip_trim_end(timeline, 0, 2.6, spp, &displays, recording),- Some(3.14)+ Some(OVERLAPPING_SEGMENT_END));assert_eq!(clip_trim_start(timeline, 0, 3.0, spp, &displays, recording),diff --git a/apps/desktop-gpui/src/editor_export.rs b/apps/desktop-gpui/src/editor_export.rsindex 69febb468..bb684f7a4 100644--- a/apps/desktop-gpui/src/editor_export.rs+++ b/apps/desktop-gpui/src/editor_export.rs@@ -140,7 +140,7 @@ pub enum ExportPhase {}impl ExportPhase {- fn is_busy(self) -> bool {+ pub(crate) fn is_busy(self) -> bool {matches!(self,Self::Starting | Self::Rendering | Self::Copying | Self::Uploading@@ -473,7 +473,7 @@ impl EditorWindow {}));}- fn start_export(&mut self, window: &mut Window, cx: &mut Context<Self>) {+ pub(crate) fn start_export(&mut self, window: &mut Window, cx: &mut Context<Self>) {let pretty_name = self.summary().map(|summary| summary.pretty_name.clone())@@ -528,7 +528,9 @@ impl EditorWindow {"mp4"};let default = format!("{pretty_name}.{ext}");- let chosen = platform::save_file_panel(&default, &[ext]);+ 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 _ = this.update(cx, |this, cx| {if let Some(ui) = this.export.as_mut() {@@ -593,6 +595,7 @@ impl EditorWindow {match export.await {Ok(Ok(path)) => {+ tracing::info!(path = %path.display(), "editor export completed");if destination == ExportDestination::Clipboard {let _ = this.update(cx, |this, cx| {if let Some(ui) = this.export.as_mut() {@@ -633,6 +636,7 @@ impl EditorWindow {}}Ok(Err(error)) => {+ tracing::error!(error, "editor export failed");let cancelled = error == "Export cancelled" || cancel.load(Ordering::Relaxed);let _ = this.update(cx, |this, cx| {if let Some(ui) = this.export.as_mut() {diff --git a/apps/desktop-gpui/src/editor_sidebar.rs b/apps/desktop-gpui/src/editor_sidebar.rsindex b7c431c1f..366ec90dc 100644--- a/apps/desktop-gpui/src/editor_sidebar.rs+++ b/apps/desktop-gpui/src/editor_sidebar.rs@@ -462,24 +462,34 @@ pub fn wallpapers_for_theme(theme: &str) -> Vec<&'static str> {/// installed Cap.app (whose paths are byte-identical to what the shipping app/// would write) and falling back to the repository the dev build runs from.pub fn wallpaper_dir() -> Option<PathBuf> {- if let Ok(path) = std::env::var("CAP_GPUI_WALLPAPERS_DIR") {- let path = PathBuf::from(path);- if path.is_dir() {- return Some(path);- }- }+ let override_dir = std::env::var_os("CAP_GPUI_WALLPAPERS_DIR").map(PathBuf::from);+ wallpaper_dir_from(+ &crate::store::bundled_resource_dirs(),+ override_dir.as_deref(),+ Path::new(env!("CARGO_MANIFEST_DIR")),+ )+}- let mut candidates = Vec::with_capacity(3);- if let Ok(executable) = std::env::current_exe()- && let Some(contents) = executable.parent().and_then(Path::parent)+fn wallpaper_dir_from(+ resource_dirs: &[PathBuf],+ override_dir: Option<&Path>,+ manifest: &Path,+) -> Option<PathBuf> {+ if let Some(path) = override_dir+ && path.is_dir(){- candidates.push(contents.join("Resources/assets/backgrounds"));+ return Some(path.to_path_buf());}++ let mut candidates = resource_dirs+ .iter()+ .map(|directory| directory.join("assets/backgrounds"))+ .collect::<Vec<_>>();candidates.push(PathBuf::from("/Applications/Cap.app/Contents/Resources/assets/backgrounds",));candidates.push(- PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ manifest.join("../desktop/src-tauri/assets/backgrounds").clean(),);@@ -510,6 +520,9 @@ impl Clean for PathBuf {}pub fn wallpaper_path(id: &str) -> Option<PathBuf> {+ if !WALLPAPER_NAMES.contains(&id) {+ return None;+ }let path = wallpaper_dir()?.join(format!("{id}.jpg"));path.is_file().then_some(path)}@@ -1699,8 +1712,18 @@ impl EditorWindow {fn decode_scaled_rgba(path: &Path, max: u32) -> Option<image::RgbaImage> {let bytes = std::fs::read(path).ok()?;let format = image::guess_format(&bytes).ok()?;- let decoded = image::load_from_memory_with_format(&bytes, format).ok()?;- let (width, height) = (decoded.width().max(1), decoded.height().max(1));+ let (decoded, width, height) = if format == image::ImageFormat::Jpeg {+ decode_jpeg_thumbnail(&bytes, max).or_else(|| {+ let decoded = image::load_from_memory_with_format(&bytes, format).ok()?;+ let dimensions = (decoded.width(), decoded.height());+ Some((decoded, dimensions.0, dimensions.1))+ })?+ } else {+ let decoded = image::load_from_memory_with_format(&bytes, format).ok()?;+ let dimensions = (decoded.width(), decoded.height());+ (decoded, dimensions.0, dimensions.1)+ };+ let (width, height) = (width.max(1), height.max(1));let scale = (max as f32 / width.max(height) as f32).min(1.);let target_width = ((width as f32 * scale).round() as u32).max(1);let target_height = ((height as f32 * scale).round() as u32).max(1);@@ -1724,6 +1747,25 @@ fn decode_scaled_rgba(path: &Path, max: u32) -> Option<image::RgbaImage> {})}+fn decode_jpeg_thumbnail(bytes: &[u8], max: u32) -> Option<(image::DynamicImage, u32, u32)> {+ let mut decoder = jpeg_decoder::Decoder::new(bytes);+ decoder.read_info().ok()?;+ let info = decoder.info()?;+ let requested = max.clamp(1, u16::MAX as u32) as u16;+ let (width, height) = decoder.scale(requested, requested).ok()?;+ let pixels = decoder.decode().ok()?;+ let decoded = match info.pixel_format {+ jpeg_decoder::PixelFormat::RGB24 => image::DynamicImage::ImageRgb8(+ image::RgbImage::from_raw(width as u32, height as u32, pixels)?,+ ),+ jpeg_decoder::PixelFormat::L8 => image::DynamicImage::ImageLuma8(+ image::GrayImage::from_raw(width as u32, height as u32, pixels)?,+ ),+ _ => return None,+ };+ Some((decoded, info.width as u32, info.height as u32))+}+/// [`decode_scaled_rgba`] in gpui's BGRA order.fn decode_scaled(path: &Path, max: u32) -> Option<Arc<RenderImage>> {decode_scaled_rgba(path, max).map(library::rgba_to_render_image)@@ -1931,7 +1973,7 @@ impl EditorWindow {}self.sidebar.wallpaper_task = Some(cx.spawn_in(window, async move |this, cx| {let (_decodes, results) =- library::spawn_decode_pool(cx.background_executor(), wanted, |id| {+ library::spawn_decode_pool_limited(cx.background_executor(), wanted, 2, |id| {decode_wallpaper_thumbnail(id).map(|image| (id, image))});while let Ok(first) = results.recv_async().await {@@ -3904,6 +3946,69 @@ mod tests {assert_eq!(wallpapers_for_theme("orange").len(), 9);}+ #[test]+ fn built_in_wallpapers_remain_available_from_the_development_checkout() {+ assert!(wallpaper_path("macOS/sequoia-dark").is_some());+ }++ #[test]+ fn wallpaper_jpegs_decode_at_thumbnail_dimensions() {+ let path = wallpaper_path("macOS/sequoia-dark").unwrap();+ let (width, height) = image::image_dimensions(&path).unwrap();+ let image = decode_scaled_rgba(&path, WALLPAPER_TILE_MAX).unwrap();++ assert_eq!(image.width().max(image.height()), WALLPAPER_TILE_MAX);+ assert!(+ (image.width() as f64 / image.height() as f64 - width as f64 / height as f64).abs()+ < 0.025+ );+ }++ #[test]+ fn jpeg_thumbnail_decoder_downsamples_before_allocating_pixels() {+ let original = image::RgbImage::from_pixel(1024, 512, image::Rgb([40, 120, 200]));+ let mut encoded = Vec::new();+ image::codecs::jpeg::JpegEncoder::new(&mut encoded)+ .encode_image(&original)+ .unwrap();++ let (decoded, width, height) = decode_jpeg_thumbnail(&encoded, 128).unwrap();++ assert_eq!((width, height), (1024, 512));+ assert!(decoded.width() <= 256);+ assert!(decoded.height() <= 128);+ let pixel = decoded.to_rgb8().get_pixel(0, 0).0;+ assert!(pixel[0].abs_diff(40) <= 3);+ assert!(pixel[1].abs_diff(120) <= 3);+ assert!(pixel[2].abs_diff(200) <= 3);+ }++ #[test]+ fn built_in_wallpapers_reject_unknown_and_traversal_identifiers() {+ assert_eq!(wallpaper_path("unknown/wallpaper"), None);+ assert_eq!(wallpaper_path("../macOS/sequoia-dark"), None);+ assert_eq!(wallpaper_path("/macOS/sequoia-dark"), None);+ }++ #[test]+ fn built_in_wallpapers_resolve_from_an_installed_bundle() {+ let root = std::env::temp_dir().join(format!(+ "cap-gpui-installed-wallpapers-{}",+ std::process::id()+ ));+ let resources = root.join("Cap.app/Contents/Resources");+ let backgrounds = resources.join("assets/backgrounds");+ let wallpaper = backgrounds.join("macOS/sequoia-dark.jpg");+ std::fs::create_dir_all(wallpaper.parent().unwrap()).unwrap();+ std::fs::write(&wallpaper, b"test wallpaper").unwrap();++ let found = wallpaper_dir_from(&[resources], None, &root.join("missing"));+ assert_eq!(found, Some(backgrounds));+ assert!(found.unwrap().join("macOS/sequoia-dark.jpg").is_file());++ std::fs::remove_dir_all(root).unwrap();+ }+#[test]fn hex_parsing_matches_the_apps() {assert_eq!(hex_to_rgb("#4785FF"), Some([71, 133, 255, 255]));diff --git a/apps/desktop-gpui/src/editor_timeline.rs b/apps/desktop-gpui/src/editor_timeline.rsindex 3eeb28989..befb28a95 100644--- a/apps/desktop-gpui/src/editor_timeline.rs+++ b/apps/desktop-gpui/src/editor_timeline.rs@@ -1723,7 +1723,7 @@ fn render_track_content(let mut content = div().relative().size_full();if !segments.iter().any(|segment| segment.lane == row.lane)- && !(row.kind == TrackKind::ThreeD && !model.camera3d_setup_ghosts.is_empty())+ && (row.kind != TrackKind::ThreeD || model.camera3d_setup_ghosts.is_empty())&& let Some(empty) = render_empty_track(theme,row.kind,diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rsindex 105731b3d..b5bd74046 100644--- a/apps/desktop-gpui/src/editor_window.rs+++ b/apps/desktop-gpui/src/editor_window.rs@@ -204,6 +204,15 @@ pub fn letterbox(container: (f32, f32), frame: (f32, f32)) -> (f32, f32) {}}+fn frame_layout_requires_editor_invalidation(+ first_frame: bool,+ playing: bool,+ layout_changed: bool,+ cleared_drag_rect: bool,+) -> bool {+ first_frame || cleared_drag_rect || (!playing && layout_changed)+}+// ---------------------------------------------------------------------------// Loading a project// ---------------------------------------------------------------------------@@ -213,6 +222,7 @@ pub fn letterbox(container: (f32, f32), frame: (f32, f32)) -> (f32, f32) {/// whose disabled state is data-driven.#[derive(Debug, Clone)]pub struct ProjectSummary {+ pub recordings: Arc<ProjectRecordingsMeta>,/// `meta().prettyName` -- the header's editable name.pub pretty_name: String,/// Every track the timeline draws, derived from the bundle's own@@ -262,8 +272,7 @@ pub struct ProjectSummary {/// unwinds out of the renderer's task. It is a plain synchronous function,/// so running it here under `catch_unwind` -- on a background thread, in/// Rust-only frames, never across an objc boundary -- converts the panic-/// into a message. `EditorInstance::new` then repeats the same construction-/// with input already known to be good.+/// into a message. The validated metadata is reused by `EditorInstance`.////// Blocking; callers run it on the background executor.pub fn preflight(path: &std::path::Path) -> Result<ProjectSummary, String> {@@ -314,6 +323,7 @@ pub fn preflight(path: &std::path::Path) -> Result<ProjectSummary, String> {"This recording's video tracks could not be opened. The bundle looks damaged.".to_string()})?.map_err(|error| format!("Failed to read this recording's media: {error}"))?;+ let recordings = Arc::new(recordings);// `RecordingMeta::project_config()` loads `project-config.json` (falling// back to the default) and overlays `captions.json` -- the same read@@ -358,6 +368,7 @@ pub fn preflight(path: &std::path::Path) -> Result<ProjectSummary, String> {let duration = timeline.total_duration;Ok(ProjectSummary {+ recordings: recordings.clone(),pretty_name: meta.pretty_name.clone(),timeline,duration: duration.max(0.0),@@ -4776,7 +4787,12 @@ impl EditorWindow {if let Some(stats) = &self.stats {stats.presented.fetch_add(1, Ordering::Relaxed);}- if layout_changed || cleared_drag_rect {+ if frame_layout_requires_editor_invalidation(+ first_frame,+ self.playing,+ layout_changed,+ cleared_drag_rect,+ ) {cx.notify();}// `refresh()` is a whole-window invalidation, so calling it per frame on@@ -8724,7 +8740,14 @@ pub fn make_frame_callback() -> cap_editor::EditorFrameCallback {Box::new(move |output, layout| {stats.rendered.fetch_add(1, Ordering::Relaxed);- if tx.try_send((output, layout)).is_err() {+ #[cfg(target_os = "windows")]+ let sent = tx+ .send_timeout((output, layout), Duration::from_millis(100))+ .is_ok();+ #[cfg(not(target_os = "windows"))]+ let sent = tx.try_send((output, layout)).is_ok();++ if !sent {stats.dropped.fetch_add(1, Ordering::Relaxed);}})@@ -8809,6 +8832,31 @@ mod tests {assert!((width / height - 992. / 492.).abs() < 0.001);}+ #[test]+ fn animated_frame_layout_does_not_invalidate_editor_during_playback() {+ assert!(!frame_layout_requires_editor_invalidation(+ false, true, true, false+ ));+ assert!(!frame_layout_requires_editor_invalidation(+ false, true, false, false+ ));+ assert!(!frame_layout_requires_editor_invalidation(+ false, false, false, false+ ));+ assert!(frame_layout_requires_editor_invalidation(+ false, false, true, false+ ));+ assert!(frame_layout_requires_editor_invalidation(+ true, true, true, false+ ));+ assert!(frame_layout_requires_editor_invalidation(+ false, true, false, true+ ));+ assert!(frame_layout_requires_editor_invalidation(+ false, true, true, true+ ));+ }+/// Every failure `EditorInstance::new` would return, plus the one it would/// panic on, has to come back as a message.#[test]