Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: stabilize recording controls and editor loading

Richie McIlroyebb6b4b8658c
diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rs
index c430f9767..a7e7ad9b2 100644
--- a/apps/desktop-gpui/src/editor_window.rs
+++ b/apps/desktop-gpui/src/editor_window.rs
@@ -59,11 +59,11 @@ use core_foundation::base::TCFType;
#[cfg(target_os = "macos")]
use core_video::pixel_buffer::{CVPixelBuffer, CVPixelBufferRef};
use gpui::{
- AppContext as _, Bounds, Context, Entity, FocusHandle, FontWeight, Hsla, InteractiveElement,
- IntoElement, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels,
- Point, Render, RenderImage, SharedString, StatefulInteractiveElement as _, StyleRefinement,
- Styled, StyledImage as _, Subscription, WeakEntity, Window, div, point, prelude::FluentBuilder,
- px, svg,
+ Animation, AnimationExt as _, AppContext as _, Bounds, Context, Entity, FocusHandle,
+ FontWeight, Hsla, InteractiveElement, IntoElement, MouseButton, MouseDownEvent, MouseMoveEvent,
+ MouseUpEvent, ParentElement, Pixels, Point, Render, RenderImage, SharedString,
+ StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription, WeakEntity, Window,
+ div, point, prelude::FluentBuilder, px, svg,
};
use crate::{
@@ -133,8 +133,6 @@ pub fn default_preview_resolution() -> XY<u32> {
// Shell metrics (`routes/editor/Editor.tsx:77-82`)
// ---------------------------------------------------------------------------
-/// 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.;
/// The reference height the player/timeline split scales against on a short
/// viewport. It is not the floor -- see [`timeline::MIN_HUG_HEIGHT`].
@@ -573,31 +571,6 @@ pub fn frame_image(frame: &RenderedFrame) -> Option<Arc<RenderImage>> {
])))
}
-/// The poster: the recording's own first-frame JPEG, decoded to at most the
-/// canvas's retina size. `thumbnail` (a box filter) over `resize` because the
-/// picture is on screen for well under a second.
-fn decode_poster(path: &std::path::Path) -> Option<Arc<RenderImage>> {
- let bytes = std::fs::read(path).ok()?;
- let image = image::load_from_memory(&bytes).ok()?;
- let (width, height) = (image.width().max(1), image.height().max(1));
- let scale = (1920. / width as f32).min(1080. / height as f32).min(1.);
- let mut scaled = if scale < 1. {
- image::imageops::thumbnail(
- &image.into_rgba8(),
- ((width as f32 * scale) as u32).max(1),
- ((height as f32 * scale) as u32).max(1),
- )
- } else {
- image.into_rgba8()
- };
- for pixel in scaled.pixels_mut() {
- pixel.0.swap(0, 2);
- }
- Some(Arc::new(RenderImage::new(smallvec::smallvec![
- image::Frame::new(scaled)
- ])))
-}
-
/// What the frame pump hands the window.
#[derive(Clone)]
pub(crate) enum EditorPreviewFrame {
@@ -1396,13 +1369,6 @@ pub struct EditorWindow {
preparing_frame_presented: bool,
preparing_seed: Option<Arc<crate::editor_preparing::presentation::PreparingTimelineSeed>>,
pub(crate) latest_frame: Option<EditorPreviewFrame>,
- /// The bundle's `screenshots/display.jpg`, letterboxed into the canvas
- /// until the first composed frame lands -- decoded in parallel with
- /// `EditorInstance` construction, so the editor opens onto a picture
- /// rather than "Loading project...". The Solid app hides the same wait
- /// behind a skeleton; a poster is the native equivalent with the added
- /// courtesy of showing the recording itself.
- poster: Option<Arc<RenderImage>>,
preview: Entity<PreviewFrameView>,
header: Entity<EditorSectionView>,
toolbar: Entity<EditorSectionView>,
@@ -1607,6 +1573,7 @@ pub struct EditorWindow {
/// 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>,
+ initial_timeline_rows: Option<usize>,
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,
@@ -1725,27 +1692,6 @@ impl EditorWindow {
true
});
- // Decode the poster off-thread immediately: it races EditorInstance
- // construction and reliably wins, so the first paint has a picture.
- let poster_path = project_path.join("screenshots").join("display.jpg");
- cx.spawn_in(window, async move |this, cx| {
- let Some(poster) = cx
- .background_executor()
- .spawn(async move { decode_poster(&poster_path) })
- .await
- else {
- return;
- };
- this.update(cx, |this, cx| {
- if this.latest_frame.is_none() {
- this.poster = Some(poster);
- cx.notify();
- }
- })
- .ok();
- })
- .detach();
-
let name_input = cx.new(|cx| {
let mut input = ui::TextInputState::single_line(window, cx);
input.set_disabled(true, cx);
@@ -1942,11 +1888,11 @@ impl EditorWindow {
audio_picker: None,
camera3d_setup: None,
timeline_height_override: None,
+ initial_timeline_rows: None,
timeline_resize: None,
presets_menu: None,
preset_dialog: None,
caption_sync_signature: None,
- poster: None,
export: None,
clips: crate::editor_clips::ClipsState::default(),
}
@@ -2403,6 +2349,14 @@ impl EditorWindow {
self.selection.as_ref()
}
+ fn visual_ready(&self) -> bool {
+ self.project_ready()
+ && self.latest_frame.is_some()
+ && self.preparing_consumer.is_none()
+ && self.ordinary_handoff_frame.is_none()
+ && self.preparing_candidate_frame.is_none()
+ }
+
pub(crate) fn project_ready(&self) -> bool {
self.instance.is_some() && matches!(&self.state, LoadState::Ready(_))
}
@@ -2656,6 +2610,7 @@ impl EditorWindow {
}
pub fn set_instance(&mut self, instance: Arc<EditorInstance>) {
+ self.initial_timeline_rows = Some(self.timeline.rows.len());
self.preparing_retry_pending = false;
self.preparing_candidate_frame = None;
self.ordinary_handoff_frame = self
@@ -3034,6 +2989,16 @@ impl EditorWindow {
window: &mut Window,
cx: &mut Context<Self>,
) {
+ if !self.visual_ready() {
+ let key = &event.keystroke;
+ let close = (key.key == "w" && (key.modifiers.platform || key.modifiers.control))
+ || (key.key == "f4" && key.modifiers.alt);
+ if !close {
+ window.prevent_default();
+ cx.stop_propagation();
+ }
+ return;
+ }
if !is_playback_shortcut(
&event.keystroke,
ui::text_input_has_focus(window, cx),
@@ -3056,7 +3021,7 @@ impl EditorWindow {
/// (`useEditorShortcuts.ts:10`) and `e.repeat` is ignored there
/// (`:42`) as `is_held` is here.
fn on_key(&mut self, event: &gpui::KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
- if !self.project_ready() {
+ if !self.visual_ready() {
return;
}
if self.frame_controls.is_open() && event.keystroke.key == "escape" {
@@ -4911,17 +4876,12 @@ impl EditorWindow {
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())
- }
+ DEFAULT_TIMELINE_HEIGHT
+ + self.initial_timeline_rows.map_or(0., |initial| {
+ timeline::hug_height(self.timeline.rows.len()) - timeline::hug_height(initial)
+ })
})
}
@@ -5836,8 +5796,6 @@ impl EditorWindow {
frame.layout.output_size[1] as f32,
);
self.latest_frame = Some(frame.frame.clone());
- // The composed frame supersedes the poster; free its atlas memory.
- self.poster = None;
let previous = self.preview.update(cx, |preview, cx| {
preview.set_frame(frame.frame, frame_size, self.stats.clone(), cx)
});
@@ -8506,6 +8464,7 @@ impl EditorWindow {
ui::EditorButton::plain(&theme, "open-recording-bundle")
.left_icon("icons/folder.svg")
.tooltip(&theme, "Open recording bundle")
+ .disabled(!self.visual_ready())
.on_click(cx.listener(|this, _, _window, cx| {
this.open_recording_bundle(cx);
})),
@@ -8514,6 +8473,7 @@ impl EditorWindow {
ui::EditorButton::plain(&theme, "delete-recording")
.left_icon("icons/trash.svg")
.tooltip(&theme, "Delete recording")
+ .disabled(!self.visual_ready())
.on_click(cx.listener(|this, _, window, cx| {
this.delete_recording(window, cx);
})),
@@ -8555,7 +8515,16 @@ impl EditorWindow {
.when(self.sharing.is_some(), |group| {
group.child(self.render_reupload_button(cx))
})
- .child(self.render_export_button(cx)),
+ .child(self.render_export_button(cx))
+ .relative()
+ .children((!self.visual_ready()).then(|| {
+ div()
+ .absolute()
+ .inset_0()
+ .occlude()
+ .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
+ .on_mouse_down(MouseButton::Right, |_, _, cx| cx.stop_propagation())
+ })),
);
#[cfg(target_os = "windows")]
@@ -8924,37 +8893,19 @@ impl EditorWindow {
.clone()
.cached(StyleRefinement::default().size_full())
.into_any_element(),
- (state, false) => {
- if let Some(poster) = self.poster.clone() {
- div()
- .absolute()
- .inset_0()
- .flex()
- .items_center()
- .justify_center()
- .child(
- gpui::img(poster)
- .size_full()
- .object_fit(gpui::ObjectFit::Contain),
- )
- .into_any_element()
- } else {
- div()
- .absolute()
- .inset_0()
- .flex()
- .items_center()
- .justify_center()
- .text_size(px(13.))
- .text_color(Hsla::from(theme.editor.text_2))
- .child(if matches!(state, LoadState::Loading) {
- "Loading project..."
- } else {
- "Rendering first frame..."
- })
- .into_any_element()
- }
- }
+ (_, false) => div()
+ .absolute()
+ .inset_0()
+ .flex()
+ .items_center()
+ .justify_center()
+ .child(
+ svg()
+ .path("icons/video.svg")
+ .size(px(48.))
+ .text_color(Hsla::from(theme.editor.text_3)),
+ )
+ .into_any_element(),
};
div()
@@ -8964,25 +8915,17 @@ impl EditorWindow {
.overflow_hidden()
.bg(Hsla::from(theme.editor.card))
.child(body)
- .children(
- (!self.project_ready() && self.latest_frame.is_some()).then(|| {
- div()
- .absolute()
- .bottom(px(12.))
- .left(px(12.))
- .px(px(10.))
- .py(px(6.))
- .rounded(px(6.))
- .bg(Hsla::from(theme.editor.card))
- .text_size(px(12.))
- .text_color(Hsla::from(theme.editor.text_2))
- .child(if self.preparing_consumer.is_some() {
- "Preparing recording…"
- } else {
- "Opening editor…"
- })
- }),
- )
+ .children(self.latest_frame.is_some().then(|| {
+ div()
+ .absolute()
+ .inset_0()
+ .bg(Hsla::from(theme.editor.card))
+ .with_animation(
+ "editor-preview-reveal",
+ Animation::new(Duration::from_millis(300)),
+ |veil, progress| veil.opacity(1. - progress),
+ )
+ }))
// `CanvasElementsOverlay` + `SnapGuidesOverlay`
// (`Player.tsx:636-643`), both mounted inside the letterbox
// wrapper and only while a frame exists.
@@ -10159,6 +10102,11 @@ fn is_playback_shortcut(
impl Render for EditorWindow {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.sync_appearance(window, cx);
+ let title_disabled = !self.visual_ready();
+ if self.name_input.read(cx).is_disabled() != title_disabled {
+ self.name_input
+ .update(cx, |input, cx| input.set_disabled(title_disabled, cx));
+ }
// Fields first: a field created this frame has no text yet, and gpui
// only renders on invalidation, so syncing before creating would leave
// a brand-new box empty until something else asked for a frame.
@@ -10593,6 +10541,29 @@ impl Render for EditorWindow {
}))
// The open `KSelect` menu, painted last of all so it is over the
// sidebar and the drag layers alike.
+ .children((!matches!(self.state, LoadState::Failed(_))).then(|| {
+ let veil = div()
+ .absolute()
+ .top(px(HEADER_HEIGHT))
+ .bottom_0()
+ .left_0()
+ .right_0()
+ .bg(Hsla::from(theme.editor.window).opacity(0.45));
+ if self.visual_ready() {
+ veil.with_animation(
+ "editor-controls-reveal",
+ Animation::new(Duration::from_millis(300)),
+ |veil, progress| veil.opacity(1. - progress),
+ )
+ .into_any_element()
+ } else {
+ veil.occlude()
+ .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
+ .on_mouse_down(MouseButton::Right, |_, _, cx| cx.stop_propagation())
+ .on_scroll_wheel(|_, _, cx| cx.stop_propagation())
+ .into_any_element()
+ }
+ }))
.children(self.with_style_controls(|this| this.render_sidebar_menu(cx)))
.children(self.render_toolbar_menu(cx))
.children(self.render_frame_controls(window, cx))
diff --git a/apps/desktop/src-tauri/src/fake_window.rs b/apps/desktop/src-tauri/src/fake_window.rs
index edf20ad9d..1b6d6302a 100644
--- a/apps/desktop/src-tauri/src/fake_window.rs
+++ b/apps/desktop/src-tauri/src/fake_window.rs
@@ -16,6 +16,8 @@ use tracing::{debug, instrument};
use crate::{App, ArcLock, RecordingState};
const RECORDING_CONTROLS_LABEL: &str = "in-progress-recording";
+#[cfg(any(target_os = "macos", test))]
+const RECORDING_CONTROLS_BOUNDS_NAME: &str = "recording-controls-interactive-area";
const RECORDING_CONTROLS_WIDTH: f64 = 320.0;
const RECORDING_CONTROLS_HEIGHT: f64 = 150.0;
const RECORDING_CONTROLS_BAR_HEIGHT: f64 = 40.0;
@@ -58,25 +60,27 @@ impl FakeWindowListeners {
(id, token)
}
- fn finish(&self, label: &str, id: u64) {
+ fn finish(&self, label: &str, id: u64) -> bool {
let mut guard = self.tokens.lock().unwrap_or_else(|e| e.into_inner());
if let Some(current) = guard.get(label)
&& current.id == id
{
guard.remove(label);
+ return true;
}
+ false
}
pub fn cancel(&self, label: &str) {
- let mut guard = self.tokens.lock().unwrap_or_else(|e| e.into_inner());
- if let Some(entry) = guard.remove(label) {
+ let guard = self.tokens.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some(entry) = guard.get(label) {
entry.token.cancel();
}
}
pub fn cancel_all(&self) {
- let mut guard = self.tokens.lock().unwrap_or_else(|e| e.into_inner());
- for (_, entry) in guard.drain() {
+ let guard = self.tokens.lock().unwrap_or_else(|e| e.into_inner());
+ for entry in guard.values() {
entry.token.cancel();
}
}
@@ -259,6 +263,118 @@ fn spawn_recording_controls_sanity_checks(app: AppHandle, window: WebviewWindow)
});
}
+#[cfg(any(target_os = "macos", test))]
+fn ensure_recording_controls_bounds(
+ bounds: &mut HashMap<String, LogicalBounds>,
+ width: f64,
+ height: f64,
+) {
+ bounds
+ .entry(RECORDING_CONTROLS_BOUNDS_NAME.to_string())
+ .or_insert_with(|| {
+ LogicalBounds::new(
+ scap_targets::bounds::LogicalPosition::new(
+ RECORDING_CONTROLS_BOTTOM_PADDING,
+ height - RECORDING_CONTROLS_BOTTOM_PADDING - RECORDING_CONTROLS_BAR_HEIGHT,
+ ),
+ scap_targets::bounds::LogicalSize::new(
+ width - RECORDING_CONTROLS_BOTTOM_PADDING * 2.0,
+ RECORDING_CONTROLS_BAR_HEIGHT,
+ ),
+ )
+ });
+}
+
+#[cfg(any(target_os = "macos", test))]
+fn preserve_pointer_gesture(ignore: bool, pressed: bool, was_ignoring: bool) -> bool {
+ ignore && (!pressed || was_ignoring)
+}
+
+#[cfg(target_os = "macos")]
+async fn update_recording_controls_hit_test(
+ window: &WebviewWindow,
+ mut bounds: HashMap<String, LogicalBounds>,
+ token: CancellationToken,
+) -> Option<bool> {
+ use objc2_app_kit::{NSEvent, NSWindow};
+ use objc2_foundation::NSSize;
+
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ let handle = window.clone();
+ window
+ .run_on_main_thread(move || {
+ if tx.is_closed() || token.is_cancelled() {
+ return;
+ }
+ let result = objc2::rc::autoreleasepool(|_| {
+ let ptr = handle.ns_window().ok()? as *const NSWindow;
+ let native = unsafe { ptr.as_ref()? };
+ let view = native.contentView()?;
+ let frame = native.frame();
+ let scale = native.backingScaleFactor();
+ let small = recording_controls_size_allows_default_interaction(
+ tauri::LogicalSize::new(frame.size.width, frame.size.height).to_physical(scale),
+ scale,
+ );
+ let pressed = unsafe { NSEvent::pressedMouseButtons() } & 1 != 0;
+ if !small {
+ native.setIgnoresMouseEvents(true);
+ native.setContentSize(NSSize::new(
+ RECORDING_CONTROLS_WIDTH,
+ RECORDING_CONTROLS_HEIGHT,
+ ));
+ return Some(pressed);
+ }
+ let point = view.convertPoint_fromView(
+ unsafe { native.mouseLocationOutsideOfEventStream() },
+ None,
+ );
+ let view_bounds = view.bounds();
+ ensure_recording_controls_bounds(
+ &mut bounds,
+ view_bounds.size.width,
+ view_bounds.size.height,
+ );
+ let y = if view.isFlipped() {
+ point.y - view_bounds.origin.y
+ } else {
+ view_bounds.origin.y + view_bounds.size.height - point.y
+ };
+ let ignore = should_ignore_cursor_events(
+ tauri::PhysicalPosition::new(0, 0),
+ tauri::PhysicalPosition::new(
+ (point.x - view_bounds.origin.x) * scale,
+ y * scale,
+ ),
+ scale,
+ &bounds,
+ false,
+ true,
+ );
+ // Keep the mouse-up routed to this panel when a drag crosses its hit area.
+ let ignore = preserve_pointer_gesture(ignore, pressed, unsafe {
+ native.ignoresMouseEvents()
+ });
+ if unsafe { native.ignoresMouseEvents() } != ignore {
+ native.setIgnoresMouseEvents(ignore);
+ debug!(
+ ignore,
+ pressed,
+ bounds = bounds.len(),
+ "Recording controls hit test changed"
+ );
+ }
+ Some(pressed)
+ });
+ let _ = tx.send(result);
+ })
+ .ok()?;
+ tokio::time::timeout(Duration::from_millis(250), rx)
+ .await
+ .ok()?
+ .ok()?
+}
+
fn get_display_id_for_cursor() -> Option<DisplayId> {
Display::get_containing_cursor().map(|d| d.id())
}
@@ -391,7 +507,26 @@ pub fn spawn_fake_window_listener(app: AppHandle, window: WebviewWindow) {
break;
}
- if is_recording_controls {
+ #[cfg(target_os = "macos")]
+ let controls_pressed = if is_recording_controls {
+ let bounds = state
+ .0
+ .read()
+ .await
+ .get(&label)
+ .cloned()
+ .unwrap_or_default();
+ match update_recording_controls_hit_test(&window, bounds, token.clone()).await {
+ Some(pressed) => pressed,
+ None => continue,
+ }
+ } else {
+ false
+ };
+ #[cfg(not(target_os = "macos"))]
+ let controls_pressed = false;
+
+ if is_recording_controls && !controls_pressed {
let capture_target = app.state::<ArcLock<App>>().try_read().ok().and_then(|s| {
match &s.recording_state {
RecordingState::Pending { target, .. } => Some(target.clone()),
@@ -444,9 +579,14 @@ pub fn spawn_fake_window_listener(app: AppHandle, window: WebviewWindow) {
}
}
- let map = state.0.read().await;
+ #[cfg(target_os = "macos")]
+ if is_recording_controls {
+ continue;
+ }
+
+ let windows = state.0.read().await.get(&label).cloned();
- let Some(windows) = map.get(&label) else {
+ let Some(windows) = windows else {
let ignore = if is_recording_controls {
!prepare_recording_controls_default_interaction(&window)
} else {
@@ -518,7 +658,7 @@ pub fn spawn_fake_window_listener(app: AppHandle, window: WebviewWindow) {
window_position,
mouse_position,
scale_factor,
- windows,
+ &windows,
default_ignore,
allow_default_interaction,
);
@@ -535,15 +675,8 @@ pub fn spawn_fake_window_listener(app: AppHandle, window: WebviewWindow) {
}
}
- if is_recording_controls {
- let ignore = !prepare_recording_controls_default_interaction(&window);
- let _ = window.set_ignore_cursor_events(ignore);
- }
-
- listeners.finish(&label, listener_id);
-
- {
- let mut map = state.0.write().await;
+ let mut map = state.0.write().await;
+ if listeners.finish(&label, listener_id) && !app.webview_windows().contains_key(&label) {
map.remove(&label);
}
});
@@ -571,6 +704,65 @@ mod tests {
use super::*;
use scap_targets::bounds::{LogicalPosition, LogicalSize};
+ #[test]
+ fn tooltip_only_bounds_do_not_disable_the_recording_bar() {
+ let mut registered = HashMap::from([("tooltip".into(), bounds(30.0, 60.0, 80.0, 24.0))]);
+ ensure_recording_controls_bounds(&mut registered, 320.0, 150.0);
+ for (x, y, ignore) in [(24.0, 110.0, false), (40.0, 70.0, false), (4.0, 30.0, true)] {
+ assert_eq!(
+ should_ignore_cursor_events(
+ tauri::PhysicalPosition::new(0, 0),
+ tauri::PhysicalPosition::new(x, y),
+ 1.0,
+ &registered,
+ false,
+ true,
+ ),
+ ignore,
+ );
+ }
+ }
+
+ #[test]
+ fn registered_issue_panel_bounds_are_preserved() {
+ let issue = bounds(12.0, 40.0, 296.0, 98.0);
+ let mut registered = HashMap::from([(RECORDING_CONTROLS_BOUNDS_NAME.into(), issue)]);
+ ensure_recording_controls_bounds(&mut registered, 320.0, 150.0);
+ let actual = registered[RECORDING_CONTROLS_BOUNDS_NAME];
+ assert_eq!(actual.position().x(), issue.position().x());
+ assert_eq!(actual.position().y(), issue.position().y());
+ assert_eq!(actual.size().width(), issue.size().width());
+ assert_eq!(actual.size().height(), issue.size().height());
+ }
+
+ #[test]
+ fn replaced_listener_cannot_finish_the_current_listener() {
+ let listeners = FakeWindowListeners::default();
+ let (old, old_token) = listeners.register("controls".into());
+ let (current, current_token) = listeners.register("controls".into());
+ assert!(old_token.is_cancelled());
+ assert!(!listeners.finish("controls", old));
+ assert!(!current_token.is_cancelled());
+ assert!(listeners.finish("controls", current));
+ }
+
+ #[test]
+ fn cancelled_listener_retains_ownership_until_cleanup() {
+ let listeners = FakeWindowListeners::default();
+ let (id, token) = listeners.register("controls".into());
+ listeners.cancel("controls");
+ assert!(token.is_cancelled());
+ assert!(listeners.finish("controls", id));
+ }
+
+ #[test]
+ fn pointer_gesture_remains_interactive_until_release() {
+ assert!(!preserve_pointer_gesture(true, true, false));
+ assert!(preserve_pointer_gesture(true, false, false));
+ assert!(preserve_pointer_gesture(true, true, true));
+ assert!(!preserve_pointer_gesture(false, true, true));
+ }
+
fn bounds(x: f64, y: f64, width: f64, height: f64) -> LogicalBounds {
LogicalBounds::new(LogicalPosition::new(x, y), LogicalSize::new(width, height))
}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index ef91be562..5d1afbf50 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -8633,7 +8633,7 @@ async fn resume_uploads(app: AppHandle, mark_crashed: bool) -> Result<(), String
Ok(Some(candidate)) => candidate,
Ok(None) => continue,
Err(error) => {
- warn!(%error, "Recording upload state could not be read; files retained");
+ warn!(%error, recording = %path.display(), "Recording upload state could not be read; files retained");
continue;
}
};
diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsx
index 721bfb843..c38f3ca2b 100644
--- a/apps/desktop/src/routes/editor/Editor.tsx
+++ b/apps/desktop/src/routes/editor/Editor.tsx
@@ -52,6 +52,7 @@ import {
useEditorInstanceContext,
} from "./context";
import { EditorErrorScreen } from "./EditorErrorScreen";
+import { DEFAULT_TIMELINE_HEIGHT, editorVerticalLayout } from "./editor-layout";
import { EditorSkeleton } from "./editor-skeleton";
import { Header, type TitleSaveRegistration } from "./Header";
import { ImportProgress } from "./ImportProgress";
@@ -391,6 +392,7 @@ function Inner(props: {
}) {
const {
project,
+ canvasControls,
flushProjectConfig,
editorInstance,
editorState,
@@ -402,6 +404,26 @@ function Inner(props: {
handoffPlaybackPending,
} = useEditorContext();
+ const preparingSession = usePreparingEditor();
+ const editorReady = () =>
+ preparingSession?.ordinaryReady() ??
+ canvasControls()?.hasRenderedFrame() ??
+ false;
+ onMount(() => {
+ const blockPreparingKeys = (event: KeyboardEvent) => {
+ if (editorReady()) return;
+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "w")
+ return;
+ if (event.altKey && event.key === "F4") return;
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ };
+ window.addEventListener("keydown", blockPreparingKeys, true);
+ onCleanup(() =>
+ window.removeEventListener("keydown", blockPreparingKeys, true),
+ );
+ });
+
const registerEditorSave = (
registration: TitleSaveRegistration | undefined,
) => {
@@ -543,6 +565,13 @@ function Inner(props: {
const [timelineContentHeight, setTimelineContentHeight] = createSignal(
DEFAULT_TIMELINE_CONTENT_HEIGHT,
);
+ const [initialTimelineContentHeight, setInitialTimelineContentHeight] =
+ createSignal<number>();
+ const updateTimelineContentHeight = (height: number) => {
+ if (!editorReady() || initialTimelineContentHeight() === undefined)
+ setInitialTimelineContentHeight(height);
+ setTimelineContentHeight(height);
+ };
const [timelineViewportOverflow, setTimelineViewportOverflow] = createSignal<{
overflow: number;
visibleTrackCount: number;
@@ -557,8 +586,10 @@ function Inner(props: {
(layoutBounds.height ?? fullHeight + LAYOUT_GUTTERS) - LAYOUT_GUTTERS,
0,
);
- const minPlayerHeight =
- MIN_PLAYER_HEIGHT * Math.min(1, available / fullHeight);
+ const { minPlayerHeight } = editorVerticalLayout(
+ available,
+ DEFAULT_TIMELINE_HEIGHT,
+ );
const maxTimelineHeight = Math.floor(
Math.max(0, available - minPlayerHeight),
);
@@ -593,7 +624,12 @@ function Inner(props: {
const timelineHeight = createMemo(() =>
Math.round(
- clampTimelineHeight(userTimelineHeight() ?? huggedTimelineHeight()),
+ clampTimelineHeight(
+ userTimelineHeight() ??
+ DEFAULT_TIMELINE_HEIGHT +
+ timelineContentHeight() -
+ (initialTimelineContentHeight() ?? timelineContentHeight()),
+ ),
),
);
@@ -839,10 +875,18 @@ function Inner(props: {
</Suspense>
}
>
- <div class="flex flex-col flex-1 min-h-0">
- <Header registerTitleSave={registerEditorSave} />
+ <div
+ class="relative flex flex-col flex-1 min-h-0"
+ aria-busy={!editorReady()}
+ >
+ <Header
+ registerTitleSave={registerEditorSave}
+ disabled={!editorReady()}
+ />
<div
- class="flex overflow-y-hidden flex-col flex-1 gap-2 w-full min-h-0 leading-5"
+ inert={!editorReady()}
+ class="flex overflow-y-hidden flex-col flex-1 gap-2 w-full min-h-0 leading-5 transition-opacity duration-300 ease-out motion-reduce:transition-none"
+ style={{ opacity: editorReady() ? 1 : 0.55 }}
data-tauri-drag-region
>
<div
@@ -942,7 +986,7 @@ function Inner(props: {
<div class="h-full">
<Timeline
onViewportOverflowChange={setTimelineViewportOverflow}
- onContentHeightChange={setTimelineContentHeight}
+ onContentHeightChange={updateTimelineContentHeight}
/>
</div>
</div>
diff --git a/apps/desktop/src/routes/editor/Header.tsx b/apps/desktop/src/routes/editor/Header.tsx
index 2a4efd9d1..db72fa9ac 100644
--- a/apps/desktop/src/routes/editor/Header.tsx
+++ b/apps/desktop/src/routes/editor/Header.tsx
@@ -50,7 +50,10 @@ export type TitleSaveRegistration = {
type RegisterTitleSave = (save: TitleSaveRegistration | undefined) => void;
-export function Header(props: { registerTitleSave: RegisterTitleSave }) {
+export function Header(props: {
+ registerTitleSave: RegisterTitleSave;
+ disabled?: boolean;
+}) {
const {
editorInstance,
project,
@@ -107,17 +110,20 @@ export function Header(props: { registerTitleSave: RegisterTitleSave }) {
)}
{ostype() === "windows" && <div class="w-3 shrink-0" />}
- <div class="flex gap-1.5 items-center min-w-0">
+ <div inert={props.disabled} class="flex gap-1.5 items-center min-w-0">
<NameEditor
name={meta().prettyName}
registerTitleSave={props.registerTitleSave}
- readOnly={titleReadOnly()}
+ readOnly={titleReadOnly() || props.disabled === true}
setReadOnly={setTitleReadOnly}
/>
<span class="shrink-0 text-[13px] text-ed-text-3">.cap</span>
</div>
- <div class="flex gap-0.5 items-center ml-1.5 shrink-0">
+ <div
+ inert={props.disabled}
+ class="flex gap-0.5 items-center ml-1.5 shrink-0"
+ >
<EditorButton
onClick={() => {
clearTimelineSelection();
@@ -149,6 +155,7 @@ export function Header(props: { registerTitleSave: RegisterTitleSave }) {
<div
data-tauri-drag-region
+ inert={props.disabled}
class="flex shrink-0 flex-row items-center gap-1 max-[900px]:justify-end"
>
<EditorButton
diff --git a/apps/desktop/src/routes/editor/Player.tsx b/apps/desktop/src/routes/editor/Player.tsx
index 92e396c57..9b443fb56 100644
--- a/apps/desktop/src/routes/editor/Player.tsx
+++ b/apps/desktop/src/routes/editor/Player.tsx
@@ -685,8 +685,11 @@ function PreviewCanvas() {
</div>
</Show>
<div
- class="flex overflow-hidden absolute inset-0 justify-center items-center h-full"
- style={{ visibility: hasFrame() ? "visible" : "hidden" }}
+ class="flex overflow-hidden absolute inset-0 justify-center items-center h-full transition-opacity duration-300 ease-out motion-reduce:transition-none"
+ style={{
+ visibility: hasFrame() ? "visible" : "hidden",
+ opacity: preparing?.model.rendered() || hasRenderedFrame() ? 1 : 0,
+ }}
>
<div
class="relative"
diff --git a/apps/desktop/src/routes/editor/editor-layout.test.ts b/apps/desktop/src/routes/editor/editor-layout.test.ts
new file mode 100644
index 000000000..efd1379fd
--- /dev/null
+++ b/apps/desktop/src/routes/editor/editor-layout.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from "vitest";
+import { DEFAULT_TIMELINE_HEIGHT, editorVerticalLayout } from "./editor-layout";
+
+describe("editor startup layout", () => {
+ it("preserves player space when the startup split is constrained", () => {
+ for (const height of [360, 560, 720, 1000]) {
+ const loading = editorVerticalLayout(height, DEFAULT_TIMELINE_HEIGHT);
+ expect(loading.timelineHeight).toBeLessThanOrEqual(
+ DEFAULT_TIMELINE_HEIGHT,
+ );
+ expect(
+ loading.timelineHeight + loading.minPlayerHeight,
+ ).toBeLessThanOrEqual(height);
+ }
+ });
+ it("keeps the saved user split when it fits", () => {
+ expect(editorVerticalLayout(900, 410).timelineHeight).toBe(410);
+ });
+ it("handles a collapsed window without negative dimensions", () => {
+ expect(editorVerticalLayout(0, 260)).toEqual({
+ minPlayerHeight: 0,
+ timelineHeight: 0,
+ });
+ });
+});
diff --git a/apps/desktop/src/routes/editor/editor-layout.ts b/apps/desktop/src/routes/editor/editor-layout.ts
new file mode 100644
index 000000000..521c62f3e
--- /dev/null
+++ b/apps/desktop/src/routes/editor/editor-layout.ts
@@ -0,0 +1,12 @@
+export const DEFAULT_TIMELINE_HEIGHT = 260;
+
+export function editorVerticalLayout(available: number, preferred: number) {
+ const height = Math.max(0, available);
+ const minPlayerHeight = 320 * Math.min(1, height / 560);
+ return {
+ minPlayerHeight,
+ timelineHeight: Math.round(
+ Math.min(Math.max(0, preferred), Math.floor(height - minPlayerHeight)),
+ ),
+ };
+}
diff --git a/apps/desktop/src/routes/editor/editor-skeleton.tsx b/apps/desktop/src/routes/editor/editor-skeleton.tsx
index c2a04c2f4..091b59d4f 100644
--- a/apps/desktop/src/routes/editor/editor-skeleton.tsx
+++ b/apps/desktop/src/routes/editor/editor-skeleton.tsx
@@ -1,7 +1,10 @@
+import { createElementBounds } from "@solid-primitives/bounds";
+import { makePersisted } from "@solid-primitives/storage";
import { type as ostype } from "@tauri-apps/plugin-os";
-import { For, Show } from "solid-js";
+import { createSignal, For, Show } from "solid-js";
import CaptionControlsMacOS from "~/components/titlebar/controls/CaptionControlsMacOS";
import CaptionControlsWindows11 from "~/components/titlebar/controls/CaptionControlsWindows11";
+import { DEFAULT_TIMELINE_HEIGHT, editorVerticalLayout } from "./editor-layout";
import { usePreparingEditorModel } from "./preparing-editor-context";
import {
type PreparingEditorModel,
@@ -167,7 +170,7 @@ function PreparingSidebar() {
<div>
<h2 class="text-[12px] font-medium text-ed-text-2">Background</h2>
<p class="mt-2 text-[12px] text-ed-text-3">
- Your recording’s appearance is being prepared.
+ Choose a background for your recording.
</p>
</div>
<div class="h-px bg-ed-line" />
@@ -175,13 +178,10 @@ function PreparingSidebar() {
{(name) => (
<div class="flex items-center justify-between h-[34px] text-[12px] text-ed-text-3">
<span>{name}</span>
- <span class="text-[11px]">Available when ready</span>
+ <span class="h-1 w-24 rounded-full bg-ed-ctl-hover" />
</div>
)}
</For>
- <p class="text-[11px] text-ed-text-3">
- Editing and export will be available when preparation finishes.
- </p>
</div>
</div>
);
@@ -189,27 +189,40 @@ function PreparingSidebar() {
export function EditorSkeleton() {
const model = usePreparingEditorModel();
+ const [layoutRef, setLayoutRef] = createSignal<HTMLDivElement>();
+ const bounds = createElementBounds(layoutRef);
+ const [savedHeight] = makePersisted(createSignal<number | null>(null), {
+ name: "editorTimelineHeightOverride",
+ });
+ const layout = () =>
+ editorVerticalLayout(
+ (bounds.height ?? 576) - 16,
+ savedHeight() ?? DEFAULT_TIMELINE_HEIGHT,
+ );
return (
<div
class="flex flex-col flex-1 min-h-0"
+ aria-busy="true"
aria-label="Recording editor"
data-preparing-editor
>
<PreparingHeader model={model} />
<div
+ ref={setLayoutRef}
data-tauri-drag-region
- class="flex overflow-y-hidden flex-col flex-1 gap-2 pb-2 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 opacity-55"
+ inert
>
<div
class="flex overflow-y-hidden flex-row flex-1 min-h-0 gap-2 px-2"
- style={{ "min-height": "320px" }}
+ style={{ "min-height": `${layout().minPlayerHeight}px` }}
>
<PreparingPlayer model={model} />
<PreparingSidebar />
</div>
<div
class="flex-none min-h-0 px-2 overflow-hidden"
- style={{ height: "146px" }}
+ style={{ height: `${layout().timelineHeight}px` }}
>
<PreparingTimeline model={model} />
</div>
diff --git a/apps/desktop/src/routes/editor/preparing-frame.tsx b/apps/desktop/src/routes/editor/preparing-frame.tsx
index ca8699bbd..4e96b8ee9 100644
--- a/apps/desktop/src/routes/editor/preparing-frame.tsx
+++ b/apps/desktop/src/routes/editor/preparing-frame.tsx
@@ -27,7 +27,6 @@ export function PreparingFrame(props: { fallback?: boolean } = {}) {
>
<div class="flex flex-col gap-3 justify-center items-center w-full max-w-[85%] rounded-md aspect-video bg-ed-ctl">
<IconCapLogo class="size-12 text-ed-text-3 opacity-50" />
- <span class="text-xs text-ed-text-3">Preparing your recording</span>
</div>
</Show>
</div>