Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: restore desktop title and recording window interactions

Richie McIlroy900301dd1ce8
diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rs
index 43ac6766d..b5979bc0f 100644
--- a/apps/desktop-gpui/src/app_windows.rs
+++ b/apps/desktop-gpui/src/app_windows.rs
@@ -300,9 +300,9 @@ pub(crate) fn export_in_flight(cx: &App) -> bool {
})
}
-pub(crate) fn flush_pending_editor_saves(cx: &mut App) {
+pub(crate) fn flush_pending_editor_saves(cx: &mut App) -> Result<(), String> {
if !cx.has_global::<AppWindows>() {
- return;
+ return Ok(());
}
let windows = cx.global::<AppWindows>();
@@ -314,8 +314,8 @@ pub(crate) fn flush_pending_editor_saves(cx: &mut App) {
.collect();
for handle in editors {
- if let Ok(pending) = handle.update(cx, |editor, _, _| editor.pending_save()) {
- pending.borrow_mut().flush();
+ if let Ok(result) = handle.update(cx, |editor, _, cx| editor.flush_pending_saves(cx)) {
+ result?;
}
}
@@ -324,6 +324,7 @@ pub(crate) fn flush_pending_editor_saves(cx: &mut App) {
pending.borrow_mut().flush();
}
}
+ Ok(())
}
/// Install the registry and wire the session observer that tears the bar down
@@ -4372,6 +4373,7 @@ pub fn open_editor(project_path: PathBuf, cx: &mut App) {
appears_transparent: true,
traffic_light_position: editor_window::TRAFFIC_LIGHTS,
}),
+ app_owns_titlebar_drag: true,
// An ordinary window that activates the dock icon
// (`activates_dock()` lists Editor); no level or Spaces treatment.
kind: WindowKind::Normal,
diff --git a/apps/desktop-gpui/src/controls_window.rs b/apps/desktop-gpui/src/controls_window.rs
index b9b9c01de..44777d713 100644
--- a/apps/desktop-gpui/src/controls_window.rs
+++ b/apps/desktop-gpui/src/controls_window.rs
@@ -113,8 +113,12 @@ impl ControlsWindow {
let session = self.session.read(cx);
let starting = session.phase == Phase::Starting;
let stopping = session.phase == Phase::Stopping;
+ let countdown = session.countdown_remaining();
+ let can_stop = (!starting && !stopping) || countdown.is_some();
let error = session.error.clone();
- let label: SharedString = if starting {
+ let label: SharedString = if let Some(countdown) = countdown {
+ countdown.to_string().into()
+ } else if starting {
"Starting".into()
} else if stopping {
"Saving…".into()
@@ -143,14 +147,14 @@ impl ControlsWindow {
.py(px(4.))
.px(px(8.))
.text_color(theme.red_300)
- .when(!starting && !stopping, |this| {
+ .when(can_stop, |this| {
this.hover(|style| style.bg(Theme::with_alpha(theme.red_300, 0.08)))
.active(|style| style.bg(Theme::with_alpha(theme.red_300, 0.12)))
.on_click(cx.listener(|this, _, _, cx| {
this.session.update(cx, |session, cx| session.stop(cx));
}))
})
- .when(stopping, |this| this.opacity(0.6))
+ .when(!can_stop, |this| this.opacity(0.6))
.when_some(error, |this, error| {
this.tooltip(move |_, cx| ui::Tooltip::new(&theme, error.clone()).view(cx))
})
@@ -382,6 +386,7 @@ impl ControlsWindow {
.child(
div()
.id("drag")
+ .cursor_move()
.flex()
.items_center()
.justify_center()
diff --git a/apps/desktop-gpui/src/editor_export.rs b/apps/desktop-gpui/src/editor_export.rs
index ceab87184..516e53828 100644
--- a/apps/desktop-gpui/src/editor_export.rs
+++ b/apps/desktop-gpui/src/editor_export.rs
@@ -1007,49 +1007,77 @@ impl EditorWindow {
}));
}
- pub(crate) fn render_export_page(&self, cx: &mut Context<Self>) -> impl IntoElement {
+ pub(crate) fn render_export_page(
+ &self,
+ _window: &Window,
+ cx: &mut Context<Self>,
+ ) -> impl IntoElement {
let theme = self.theme;
let Some(ui) = self.export.as_ref() else {
return div().into_any_element();
};
+ let header = div()
+ .relative()
+ .h(px(56.))
+ .flex_none()
+ .flex()
+ .items_center()
+ .justify_center()
+ .border_b_1()
+ .border_color(Hsla::from(theme.gray_3))
+ .when(cfg!(target_os = "windows"), |header| {
+ header.window_control_area(gpui::WindowControlArea::Drag)
+ })
+ .when(!cfg!(target_os = "windows"), |header| {
+ header.on_mouse_down(gpui::MouseButton::Left, |event, window, _| {
+ if event.click_count == 2 {
+ window.titlebar_double_click();
+ } else {
+ window.start_window_move();
+ }
+ })
+ })
+ .child(
+ div()
+ .text_size(px(14.))
+ .font_weight(FontWeight::MEDIUM)
+ .text_color(Hsla::from(theme.gray_12))
+ .child("Export"),
+ );
+ #[cfg(target_os = "windows")]
+ let header = header.child(div().absolute().right_0().top_0().h_full().child(
+ ui::windows_caption_controls(
+ theme,
+ _window.is_window_active(),
+ _window.is_maximized(),
+ true,
+ true,
+ ),
+ ));
+
div()
.size_full()
.flex()
.flex_col()
.relative()
+ .child(header)
.child(
div()
- .h(px(56.))
- .flex()
- .flex_row()
- .items_center()
- .justify_center()
- .border_b_1()
- .border_color(Hsla::from(theme.gray_3))
- .child(
- div()
- .text_size(px(14.))
- .font_weight(FontWeight::MEDIUM)
- .text_color(Hsla::from(theme.gray_12))
- .child("Export"),
- ),
- )
- .child(
- div()
+ .relative()
.flex()
.flex_row()
.flex_1()
.min_h_0()
.child(self.render_export_preview_pane(ui))
- .child(self.render_export_sidebar(ui, cx)),
+ .child(self.render_export_sidebar(ui, cx))
+ .when(ui.phase.shows_progress(), |this| {
+ this.child(self.render_export_overlay(ui, cx))
+ })
+ .when(ui.phase == ExportPhase::ChoosingFile, |this| {
+ this.child(div().absolute().inset_0().occlude())
+ }),
)
- .when(ui.phase.shows_progress(), |this| {
- this.child(self.render_export_overlay(ui, cx))
- })
- .when(ui.phase == ExportPhase::ChoosingFile, |this| {
- this.child(div().absolute().inset_0().occlude())
- })
.into_any_element()
}
@@ -1656,6 +1684,18 @@ impl EditorWindow {
.flex_row()
.items_center()
.justify_between()
+ .px(px(12.))
+ .py(px(8.))
+ .rounded(px(8.))
+ .border_1()
+ .border_color(if ui.advanced_open {
+ theme.gray_5
+ } else {
+ theme.gray_4
+ })
+ .when(ui.advanced_open, |button| button.bg(theme.gray_3))
+ .hover(|style| style.bg(theme.gray_3).border_color(theme.gray_5))
+ .active(|style| style.bg(theme.gray_4))
.cursor_pointer()
.on_click(cx.listener(|this, _, _window, cx| {
if let Some(ui) = this.export.as_mut() {
@@ -1834,6 +1874,7 @@ impl EditorWindow {
div()
.absolute()
.inset_0()
+ .occlude()
.flex()
.flex_col()
.items_center()
diff --git a/apps/desktop-gpui/src/editor_timeline.rs b/apps/desktop-gpui/src/editor_timeline.rs
index 231d1a36a..8bf13e72a 100644
--- a/apps/desktop-gpui/src/editor_timeline.rs
+++ b/apps/desktop-gpui/src/editor_timeline.rs
@@ -38,8 +38,8 @@ use cap_project::{
TimelineConfiguration, ZoomMode,
};
use gpui::{
- AnyElement, FontWeight, Hsla, IntoElement, ParentElement, Pixels, SharedString, Styled, div,
- prelude::FluentBuilder, px, svg,
+ AnyElement, FontWeight, Hsla, InteractiveElement, IntoElement, ParentElement, Pixels,
+ SharedString, Styled, div, prelude::FluentBuilder, px, svg,
};
use crate::{
@@ -1559,10 +1559,101 @@ pub fn render_ruler(theme: &Theme, view: TimelineView, viewport_width: f32) -> A
.into_any_element()
}
-/// The minimap (`TL/Minimap.tsx`): a 12px pill above the ruler carrying a
-/// viewport chip and a tick per clip boundary. Hidden -- `opacity-0
-/// pointer-events-none` -- until the viewport is narrower than the whole
-/// timeline (`total - zoom > 0.01`).
+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.);
+ let chip_width = ((transform.zoom * bar_width as f64 / total) as f32)
+ .clamp(MINIMAP_MIN_CHIP_WIDTH.min(bar_width), bar_width);
+ let max_position = (total - transform.zoom).max(0.001);
+ let chip_left = ((transform.position / max_position).clamp(0., 1.) as f32)
+ * (bar_width - chip_width).max(0.);
+ (chip_left, chip_width)
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum MinimapDragKind {
+ Move,
+ Left,
+ Right,
+}
+
+#[derive(Debug, Clone, Copy)]
+pub struct MinimapDrag {
+ pub kind: MinimapDragKind,
+ start_x: f32,
+ start: Transform,
+ seconds_per_pixel: f64,
+ move_scale: f64,
+}
+
+impl MinimapDrag {
+ pub fn begin(
+ x: f32,
+ bar_left: f32,
+ bar_width: f32,
+ total: f64,
+ transform: &mut Transform,
+ ) -> Option<Self> {
+ if !x.is_finite()
+ || !bar_left.is_finite()
+ || !bar_width.is_finite()
+ || !total.is_finite()
+ || !transform.zoom.is_finite()
+ || !transform.position.is_finite()
+ || bar_width <= 0.
+ || total - transform.zoom <= 0.01
+ {
+ return None;
+ }
+ let (chip_left, chip_width) = minimap_chip(*transform, total, bar_width);
+ let offset = x - bar_left;
+ let kind = if offset < chip_left || offset > chip_left + chip_width {
+ transform.set_position(
+ offset as f64 / bar_width as f64 * total - transform.zoom / 2.,
+ total,
+ );
+ MinimapDragKind::Move
+ } else if offset < chip_left + 8. {
+ MinimapDragKind::Left
+ } else if offset > chip_left + chip_width - 8. {
+ MinimapDragKind::Right
+ } else {
+ MinimapDragKind::Move
+ };
+ Some(Self {
+ kind,
+ start_x: x,
+ start: *transform,
+ seconds_per_pixel: total / bar_width as f64,
+ move_scale: (total - transform.zoom) / (bar_width - chip_width).max(1.) as f64,
+ })
+ }
+
+ pub fn update(self, x: f32, total: f64) -> Transform {
+ let mut transform = self.start;
+ if !x.is_finite() {
+ return transform;
+ }
+ let delta = (x - self.start_x) as f64;
+ match self.kind {
+ MinimapDragKind::Move => {
+ transform.set_position(self.start.position + delta * self.move_scale, total);
+ }
+ MinimapDragKind::Left => transform.update_zoom(
+ self.start.zoom - delta * self.seconds_per_pixel,
+ self.start.position + self.start.zoom,
+ total,
+ ),
+ MinimapDragKind::Right => transform.update_zoom(
+ self.start.zoom + delta * self.seconds_per_pixel,
+ self.start.position,
+ total,
+ ),
+ }
+ transform
+ }
+}
+
pub fn render_minimap(
theme: &Theme,
model: &TimelineModel,
@@ -1571,15 +1662,8 @@ pub fn render_minimap(
) -> AnyElement {
let total = model.total_duration.max(0.001);
let bar_width = bar_width.max(1.);
- let px_per_sec = bar_width as f64 / total;
let zoomed_in = total - view.transform.zoom > 0.01;
-
- let chip_width = ((view.transform.zoom * px_per_sec) as f32)
- .max(MINIMAP_MIN_CHIP_WIDTH)
- .min(bar_width);
- let max_position = (total - view.transform.zoom).max(0.001);
- let chip_left = ((view.transform.position / max_position).min(1.) as f32)
- * (bar_width - chip_width).max(0.);
+ let (chip_left, chip_width) = minimap_chip(view.transform, total, bar_width);
let mut bar = div()
.relative()
@@ -1609,6 +1693,7 @@ pub fn render_minimap(
bar.child(
div()
+ .id("timeline-minimap-chip")
.absolute()
.top_0()
.bottom_0()
@@ -1617,7 +1702,19 @@ pub fn render_minimap(
.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)),
+ .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()
+ .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()
}
@@ -4064,18 +4161,96 @@ mod tests {
#[test]
fn the_minimap_chip_never_shrinks_below_its_floor() {
- // A 1-second viewport of an hour, on a 1000px bar: 0.28px of chip,
- // lifted to the 20px floor.
- let total = 3_600.0f64;
- let bar = 1_000.0f32;
- let zoom = 1.0f64;
- let px_per_sec = bar as f64 / total;
- let chip = ((zoom * px_per_sec) as f32)
- .max(MINIMAP_MIN_CHIP_WIDTH)
- .min(bar);
+ let (_, chip) = minimap_chip(
+ Transform {
+ zoom: 1.,
+ position: 0.,
+ },
+ 3600.,
+ 1000.,
+ );
assert_eq!(chip, MINIMAP_MIN_CHIP_WIDTH);
}
+ #[test]
+ fn minimap_drag_moves_the_viewport_and_clamps_outside_the_track() {
+ let mut transform = Transform {
+ zoom: 20.,
+ position: 20.,
+ };
+ let drag = MinimapDrag::begin(400., 100., 1000., 100., &mut transform).unwrap();
+ assert_eq!(drag.kind, MinimapDragKind::Move);
+ assert_eq!(
+ drag.update(600., 100.),
+ Transform {
+ zoom: 20.,
+ position: 40.
+ }
+ );
+ assert_eq!(drag.update(-1000., 100.).position, 0.);
+ assert_eq!(drag.update(3000., 100.).position, 84.);
+ }
+
+ #[test]
+ fn minimap_track_click_centers_then_drags_from_the_new_position() {
+ let mut transform = Transform {
+ zoom: 20.,
+ position: 0.,
+ };
+ let drag = MinimapDrag::begin(850., 100., 1000., 100., &mut transform).unwrap();
+ assert_eq!(drag.kind, MinimapDragKind::Move);
+ assert_eq!(transform.position, 65.);
+ assert_eq!(drag.update(950., 100.).position, 75.);
+ }
+
+ #[test]
+ fn minimap_resize_keeps_the_opposite_edge_fixed() {
+ let mut transform = Transform {
+ zoom: 20.,
+ position: 20.,
+ };
+ let left = MinimapDrag::begin(301., 100., 1000., 100., &mut transform).unwrap();
+ assert_eq!(left.kind, MinimapDragKind::Left);
+ let resized = left.update(251., 100.);
+ assert_eq!(
+ resized,
+ Transform {
+ zoom: 25.,
+ position: 15.
+ }
+ );
+ assert_eq!(resized.position + resized.zoom, 40.);
+ let right = MinimapDrag::begin(499., 100., 1000., 100., &mut transform).unwrap();
+ assert_eq!(right.kind, MinimapDragKind::Right);
+ assert_eq!(
+ right.update(599., 100.),
+ Transform {
+ zoom: 30.,
+ position: 20.
+ }
+ );
+ assert_eq!(
+ right.update(0., 100.),
+ Transform {
+ zoom: MAX_ZOOM_IN,
+ position: 20.
+ }
+ );
+ }
+
+ #[test]
+ fn minimap_drag_uses_the_chip_floor_without_dividing_by_zero() {
+ let mut transform = Transform {
+ zoom: 3.,
+ position: 0.,
+ };
+ let drag = MinimapDrag::begin(10., 0., 1000., 3600., &mut transform).unwrap();
+ assert_eq!(drag.kind, MinimapDragKind::Move);
+ assert!((drag.update(990., 3600.).position - 3597.).abs() < 1e-9);
+ 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]
diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rs
index 0cfbbeb62..b5579e57b 100644
--- a/apps/desktop-gpui/src/editor_window.rs
+++ b/apps/desktop-gpui/src/editor_window.rs
@@ -1346,6 +1346,7 @@ pub struct EditorWindow {
hovering_generate_zoom: bool,
clip_speed: Option<ClipSpeedMenu>,
timeline_scroll: gpui::ScrollHandle,
+ minimap_drag: Option<timeline::MinimapDrag>,
/// Magnetic edges for the live drag: playhead, clip cuts and every other
/// segment's edges, gathered once when the drag arms.
drag_snap_targets: Vec<f64>,
@@ -1515,6 +1516,12 @@ struct OpenToolbarMenu {
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();
+ }
+ })
+ .detach();
// `CapWindowId::Editor`'s `Destroyed` arm drops the window from
// `EditorWindowIds`, disposes the instance and calls
// `restore_main_windows_if_no_editors` (`lib.rs:5777-5792`). Deferred
@@ -1523,15 +1530,11 @@ impl EditorWindow {
let window_id = window.window_handle().window_id();
window.on_window_should_close(cx, move |window, cx| {
let blocked = window.root::<Self>().flatten().and_then(|editor| {
- let editor = editor.read(cx);
- if let Some(reason) = editor.busy_reason() {
- return Some(reason.to_string());
- }
- let saved = editor.pending_save.borrow_mut().try_flush();
- saved.err().map(|error| {
- format!(
- "Could not save the recording. Keep the editor open and try again: {error}"
- )
+ editor.update(cx, |editor, cx| {
+ if let Some(reason) = editor.busy_reason() {
+ return Some(reason.to_string());
+ }
+ editor.flush_pending_saves(cx).err()
})
});
if let Some(message) = blocked {
@@ -1632,6 +1635,10 @@ impl EditorWindow {
let editor = editor.clone();
move |cx| EditorSectionView::new(&editor, EditorSection::Header, cx)
});
+ text_events.push(cx.observe(&name_input, {
+ let header = header.clone();
+ move |_, _, cx| header.update(cx, |_, cx| cx.notify())
+ }));
let toolbar = cx.new({
let editor = editor.clone();
move |cx| EditorSectionView::new(&editor, EditorSection::Toolbar, cx)
@@ -1696,6 +1703,7 @@ impl EditorWindow {
hovering_generate_zoom: false,
clip_speed: None,
timeline_scroll: gpui::ScrollHandle::new(),
+ minimap_drag: None,
drag_snap_targets: Vec::new(),
drag_snap_time: None,
clip_draft: None,
@@ -1769,6 +1777,16 @@ impl EditorWindow {
self.pending_save.clone()
}
+ pub(crate) fn flush_pending_saves(&mut self, cx: &mut Context<Self>) -> Result<(), String> {
+ self.commit_pretty_name(cx)?;
+ self.pending_save.borrow_mut().try_flush().map_err(|error| {
+ format!(
+ "Could not save {}. Keep the editor open and try again: {error}",
+ self.project_path.display()
+ )
+ })
+ }
+
/// Every lazily-created field's subscription lives here for the window's
/// lifetime; dropping one would stop the field reporting.
pub(crate) fn push_text_subscription(&mut self, subscription: gpui::Subscription) {
@@ -2667,6 +2685,10 @@ impl EditorWindow {
}
"escape" => {
cx.stop_propagation();
+ if self.minimap_drag.take().is_some() {
+ cx.notify();
+ return;
+ }
if self.audio_picker.is_some() {
self.audio_picker = None;
cx.notify();
@@ -2699,6 +2721,36 @@ impl EditorWindow {
cx.notify();
}
+ fn minimap_mouse_down(
+ &mut self,
+ event: &MouseDownEvent,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if event.button != MouseButton::Left {
+ return;
+ }
+ cx.stop_propagation();
+ let width = timeline::ruler_width(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(),
+ width,
+ total,
+ &mut self.view.transform,
+ );
+ if self.minimap_drag.is_some() {
+ tracing::debug!(
+ kind = ?self.minimap_drag.map(|drag| drag.kind),
+ position = ?event.position,
+ "timeline minimap drag started"
+ );
+ self.view.preview_time = None;
+ cx.notify();
+ }
+ }
+
/// One line per transform change. The zoom anchor and the pan clamp are
/// only checkable end to end if the numbers come out of the running app,
/// so they do -- at `info`, because the frame pump's own logging is at
@@ -2830,7 +2882,7 @@ impl EditorWindow {
// writes, so a preview time set while paused survives a play rather
// than being cleared. The ghost is hidden by the render's own
// `!editorState.playing` gate instead (`TL/index.tsx:1246-1253`).
- if self.playing || self.drag.is_some() {
+ if self.playing || self.drag.is_some() || self.minimap_drag.is_some() {
return;
}
let viewport_width: f32 = window.viewport_size().width.into();
@@ -4311,6 +4363,9 @@ impl EditorWindow {
}))
.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;
@@ -4380,6 +4435,9 @@ impl EditorWindow {
.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| {
@@ -4960,20 +5018,32 @@ impl EditorWindow {
window: &mut Window,
cx: &mut Context<Self>,
) {
- match event {
- // `onKeyDown`: Enter and Escape both blur, which is what commits.
- ui::TextInputEvent::Confirmed | ui::TextInputEvent::Cancelled => {
- let focus = self.focus.clone();
- window.focus(&focus, cx);
- }
- ui::TextInputEvent::Blurred => self.commit_pretty_name(cx),
- ui::TextInputEvent::Changed => {}
+ if matches!(event, ui::TextInputEvent::Changed) {
+ return;
+ }
+ if let Err(error) = self.commit_pretty_name(cx) {
+ tracing::error!(%error, "recording title was not saved");
+ cx.spawn(async move |_, _| {
+ crate::platform::alert_dialog(
+ "Title not saved",
+ &format!("{error}\n\nYour title is still in the editor. Try saving it again."),
+ );
+ })
+ .detach();
+ return;
+ }
+ if matches!(
+ event,
+ ui::TextInputEvent::Confirmed | ui::TextInputEvent::Cancelled
+ ) {
+ let focus = self.focus.clone();
+ window.focus(&focus, cx);
}
}
- fn commit_pretty_name(&mut self, cx: &mut Context<Self>) {
+ fn commit_pretty_name(&mut self, cx: &mut Context<Self>) -> Result<(), String> {
let Some(stored) = self.summary().map(|summary| summary.pretty_name.clone()) else {
- return;
+ return Ok(());
};
let draft = self.name_input.read(cx).text().trim().to_string();
let count = draft.chars().count();
@@ -4983,7 +5053,7 @@ impl EditorWindow {
.update(cx, |input, cx| input.set_text(stored, cx));
cx.notify();
}
- return;
+ return Ok(());
}
// `set_pretty_name` (`apps/desktop/src-tauri/src/lib.rs:3175-3179`):
@@ -4993,30 +5063,27 @@ impl EditorWindow {
// history is `createStoreHistory` over the *project* store alone
// (`ED/context.ts:1920-1930`), so a rename is not undoable there either.
let path = self.project_path.clone();
- match RecordingMeta::load_for_project(&path) {
- Ok(mut meta) => {
- meta.pretty_name = draft.clone();
- match meta.save_for_project() {
- Ok(()) => {
- if let LoadState::Ready(summary) = &mut self.state {
- summary.pretty_name = draft.clone();
- }
- tracing::info!(name = %draft, "renamed project");
- }
- Err(error) => {
- tracing::error!(?error, "failed to save recording-meta.json");
- self.name_input
- .update(cx, |input, cx| input.set_text(stored, cx));
- }
- }
- }
- Err(error) => {
- tracing::error!(?error, "failed to load recording-meta.json");
- self.name_input
- .update(cx, |input, cx| input.set_text(stored, cx));
- }
+ let mut meta = RecordingMeta::load_for_project(&path).map_err(|error| {
+ format!(
+ "Could not read the recording title for {}: {error}",
+ path.display()
+ )
+ })?;
+ meta.pretty_name = draft.clone();
+ meta.save_for_project().map_err(|error| {
+ format!(
+ "Could not save the recording title for {}: {error}",
+ path.display()
+ )
+ })?;
+ if let LoadState::Ready(summary) = &mut self.state {
+ summary.pretty_name = draft.clone();
}
+ self.name_input
+ .update(cx, |input, cx| input.set_text(draft.clone(), cx));
+ tracing::info!(name = %draft, "renamed project");
cx.notify();
+ Ok(())
}
pub(crate) fn hex_input(
@@ -7181,6 +7248,15 @@ impl EditorWindow {
.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();
+ }
+ })
}),
),
)
@@ -7233,6 +7309,15 @@ impl EditorWindow {
.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]`.
@@ -7320,6 +7405,20 @@ impl EditorWindow {
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.),
+ ))
+ })
+ .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(13.))
.font_weight(FontWeight::MEDIUM)
.text_color(gpui::white())
@@ -7660,7 +7759,9 @@ impl EditorWindow {
.flex()
.items_center()
.justify_center()
- .when(live, |this| this.cursor_pointer())
+ .when(live, |this| {
+ this.cursor_pointer().hover(|style| style.opacity(0.7))
+ })
.child(
svg()
.path("icons/prev.svg")
@@ -7694,7 +7795,9 @@ impl EditorWindow {
.flex()
.items_center()
.justify_center()
- .when(live, |this| this.cursor_pointer())
+ .when(live, |this| {
+ this.cursor_pointer().hover(|style| style.opacity(0.7))
+ })
.child(
svg()
.path("icons/next.svg")
@@ -7802,18 +7905,6 @@ impl EditorWindow {
// -- Timeline ------------------------------------------------------------
- /// The timeline strip at its default 260px, 1:1 and read-only.
- ///
- /// Source order top to bottom (`TL/index.tsx:1141-1500`): the minimap
- /// floating at `top: 2px`, the 32px ruler strip with the "Add track"
- /// trigger in its bottom-left and the scrub surface over the rest of it,
- /// the hover ghost, the playhead, and then the scroll body carrying one row
- /// per visible track behind the edge fade.
- ///
- /// Editing is live: the rows carry the press and hover handlers, and the
- /// root carries the window-wide move/up pair while a drag or a scrub is
- /// running. What is still absent is the track manager's popover and the
- /// minimap's own drag.
fn render_timeline(&self, viewport_width: f32, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
let content_width = timeline::content_width(viewport_width);
@@ -7910,18 +8001,29 @@ impl EditorWindow {
.on_pinch(cx.listener(|this, event: &gpui::PinchEvent, window, cx| {
this.timeline_pinch(event, window, cx);
}))
- // The minimap: `absolute z-30` at `top: 2px`,
- // `left: 128px`, `right: 16px`, `height: 12px`
- // (`TL/index.tsx:1209-1219`). Read-only -- its drag,
- // its two 8px resize handles and its click-to-centre
- // are E4's.
.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,
@@ -8021,6 +8123,20 @@ impl EditorWindow {
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.))
.font_weight(FontWeight::MEDIUM)
.text_color(gpui::white())
@@ -8285,6 +8401,7 @@ impl EditorWindow {
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())
.on_mouse_down(
MouseButton::Left,
@@ -8448,7 +8565,6 @@ impl Render for EditorWindow {
// this window is resizable, so read them off the viewport rather than
// assuming the default width.
let viewport_width: f32 = window.viewport_size().width.into();
- let scrubbing = self.scrub.is_some() || self.drag.is_some();
// `onMount`'s `checkBounds` (`TL/index.tsx:689-703`): once the
// timeline has a width, zoom in until a segment would be at least
@@ -8472,7 +8588,7 @@ impl Render for EditorWindow {
.bg(self.root_bg())
.text_color(Hsla::from(theme.gray_12))
.track_focus(&self.focus)
- .child(self.render_export_page(cx));
+ .child(self.render_export_page(window, cx));
}
div()
@@ -8498,10 +8614,12 @@ impl Render for EditorWindow {
// land and the drag would stay armed; window-level listeners are
// not gated, and macOS keeps routing drag events to the mouse-down
// window wherever the pointer is.
- .when(scrubbing, |this| {
+ // A fast drag can finish before the next frame, so its listeners
+ // must already exist when the mouse-down arms it.
+ .child({
let move_editor = cx.entity().downgrade();
let up_editor = cx.entity().downgrade();
- this.child(gpui::canvas(
+ gpui::canvas(
|_bounds, _window, _cx| (),
move |_bounds, (), window, _cx| {
let editor = move_editor.clone();
@@ -8512,6 +8630,12 @@ impl Render for EditorWindow {
let event = event.clone();
editor
.update(cx, |this, cx| {
+ if this.scrub.is_none()
+ && this.drag.is_none()
+ && this.minimap_drag.is_none()
+ {
+ return;
+ }
if !event.dragging() {
// The release happened somewhere the
// window never heard about (another
@@ -8519,6 +8643,15 @@ impl Render for EditorWindow {
// drag at its last state.
this.window_mouse_up(cx);
this.drag_mouse_up(window, cx);
+ if this.minimap_drag.take().is_some() {
+ cx.notify();
+ }
+ return;
+ }
+ if let Some(drag) = this.minimap_drag {
+ this.view.transform = drag.update(f32::from(event.position.x), this.total_duration());
+ this.view.preview_time = None;
+ cx.notify();
return;
}
this.timeline_mouse_move(&event, window, cx);
@@ -8540,13 +8673,25 @@ impl Render for EditorWindow {
}
editor
.update(cx, |this, cx| {
+ if this.scrub.is_none()
+ && this.drag.is_none()
+ && this.minimap_drag.is_none()
+ {
+ return;
+ }
this.window_mouse_up(cx);
this.drag_mouse_up(window, cx);
+ if this.minimap_drag.take().is_some() {
+ this.note_transform("minimap", None);
+ cx.notify();
+ }
})
.ok();
});
},
- ))
+ )
+ .absolute()
+ .inset_0()
})
.child(
self.header
@@ -8704,6 +8849,18 @@ impl Render for EditorWindow {
}),
)
}))
+ .children(self.minimap_drag.map(|drag| {
+ div()
+ .id("timeline-minimap-drag")
+ .absolute()
+ .inset_0()
+ .cursor(match drag.kind {
+ timeline::MinimapDragKind::Move => gpui::CursorStyle::ClosedHand,
+ timeline::MinimapDragKind::Left | timeline::MinimapDragKind::Right => {
+ gpui::CursorStyle::ResizeLeftRight
+ }
+ })
+ }))
// The config sidebar's sliders take the same layer, for the same
// reason -- and its release is what closes the undo bracket, so a
// drag that ends outside the 32px row still records exactly one
diff --git a/apps/desktop-gpui/src/library.rs b/apps/desktop-gpui/src/library.rs
index 84291bf3f..ca5dcd2c3 100644
--- a/apps/desktop-gpui/src/library.rs
+++ b/apps/desktop-gpui/src/library.rs
@@ -542,19 +542,10 @@ fn recover_incomplete_recording_in(
Ok(recovered.project_path)
}
-/// `delete_recording_directory` (`lib.rs:4001-4046`), guards verbatim.
-///
-/// Three of them, and each one covers a hole the others leave:
-///
-/// 1. a `ParentDir` component anywhere is rejected up front, because
-/// `Path::starts_with` compares raw components and would happily accept
-/// `<recordings>/../../etc`;
-/// 2. the path must start with one of the known recordings directories, which
-/// is the same set the listing walks;
-/// 3. both sides are canonicalized before the recursive delete, so a symlink
-/// inside a recordings directory cannot point the delete somewhere else.
-///
-/// A path that does not exist is a no-op success, exactly as it is there.
+/// Existing targets and roots are canonicalized before containment is checked.
+/// This keeps symlink escapes outside the allow-list while accepting Windows
+/// editor paths whose canonical form has a `\\?\` prefix. A missing strict child
+/// of an allowed root remains a no-op success.
pub fn delete_recording_directory_in(dirs: &[PathBuf], path: &Path) -> Result<(), String> {
if path
.components()
@@ -563,25 +554,41 @@ pub fn delete_recording_directory_in(dirs: &[PathBuf], path: &Path) -> Result<()
return Err("Invalid path".to_string());
}
- if !dirs.iter().any(|dir| path.starts_with(dir)) {
+ let canonical_dirs: Vec<_> = dirs
+ .iter()
+ .filter_map(|dir| dir.canonicalize().ok())
+ .collect();
+ if dirs.iter().chain(&canonical_dirs).any(|dir| path == dir) {
return Err("Path is not inside a recordings directory".to_string());
}
- if path.exists() {
+ let canonical_path = if path
+ .try_exists()
+ .map_err(|error| format!("Failed to inspect recording path: {error}"))?
+ {
let canonical_path = path
.canonicalize()
.map_err(|error| format!("Failed to resolve recording path: {error}"))?;
-
- let inside_known_dir = dirs.iter().any(|dir| {
- dir.canonicalize()
- .map(|dir| canonical_path.starts_with(&dir))
- .unwrap_or(false)
- });
- if !inside_known_dir {
+ if canonical_dirs.iter().any(|dir| &canonical_path == dir)
+ || !canonical_dirs
+ .iter()
+ .any(|dir| canonical_path.starts_with(dir))
+ {
return Err("Path is not inside a recordings directory".to_string());
}
+ Some(canonical_path)
+ } else if dirs
+ .iter()
+ .chain(&canonical_dirs)
+ .any(|dir| path.starts_with(dir))
+ {
+ None
+ } else {
+ return Err("Path is not inside a recordings directory".to_string());
+ };
- std::fs::remove_dir_all(&canonical_path)
+ if let Some(canonical_path) = canonical_path {
+ std::fs::remove_dir_all(canonical_path)
.map_err(|error| format!("Failed to delete recording: {error}"))?;
}
@@ -1912,19 +1919,32 @@ mod tests {
std::fs::write(victim.join("recording.mp4"), b"irreplaceable").unwrap();
let escape = recordings.join("escape.cap");
#[cfg(unix)]
- std::os::unix::fs::symlink(&victim, &escape).unwrap();
+ let symlink = std::os::unix::fs::symlink(&victim, &escape);
#[cfg(windows)]
- std::os::windows::fs::symlink_dir(&victim, &escape).unwrap();
- assert_eq!(
- delete_recording_directory_in(&dirs, &escape),
- Err("Path is not inside a recordings directory".to_string()),
- "canonicalizing catches the symlink the prefix check let through"
- );
+ let symlink = std::os::windows::fs::symlink_dir(&victim, &escape);
+ match symlink {
+ Ok(()) => assert_eq!(
+ delete_recording_directory_in(&dirs, &escape),
+ Err("Path is not inside a recordings directory".to_string()),
+ "canonicalizing catches the symlink the prefix check let through"
+ ),
+ #[cfg(windows)]
+ Err(error) if error.raw_os_error() == Some(1314) => {
+ eprintln!("Skipping symlink assertion: Windows symlink privilege unavailable");
+ }
+ Err(error) => panic!("Failed to create symlink fixture: {error}"),
+ }
assert!(
victim.join("recording.mp4").is_file(),
"the symlink's target is untouched"
);
+ assert_eq!(
+ delete_recording_directory_in(&dirs, &recordings),
+ Err("Path is not inside a recordings directory".to_string())
+ );
+ assert!(recordings.is_dir(), "the recordings root survives");
+
// And the happy path still deletes.
assert_eq!(delete_recording_directory_in(&dirs, &bundle), Ok(()));
assert!(!bundle.exists());
@@ -1934,6 +1954,48 @@ mod tests {
std::fs::remove_dir_all(&root).ok();
}
+ #[test]
+ fn delete_rejects_an_allowed_root_nested_in_another_allowed_root() {
+ let root = temp_dir("delete-nested-roots");
+ let recordings = root.join("recordings");
+ let nested = recordings.join("nested");
+ let bundle = write_studio_bundle(&nested, "keep-me", 1);
+ let dirs = [recordings, nested.clone()];
+
+ for path in [&nested, &nested.canonicalize().unwrap()] {
+ assert_eq!(
+ delete_recording_directory_in(&dirs, path),
+ Err("Path is not inside a recordings directory".to_string())
+ );
+ assert!(bundle.is_dir());
+ }
+
+ assert_eq!(delete_recording_directory_in(&dirs, &bundle), Ok(()));
+ assert!(nested.is_dir());
+ std::fs::remove_dir_all(root).unwrap();
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn delete_accepts_a_canonical_windows_project_under_a_raw_root() {
+ let root = temp_dir("delete-canonical-windows");
+ let recordings = root.join("recordings");
+ let bundle = write_studio_bundle(&recordings, "delete-me", 1);
+ let canonical_bundle = bundle.canonicalize().unwrap();
+
+ assert_eq!(
+ delete_recording_directory_in(std::slice::from_ref(&recordings), &canonical_bundle),
+ Ok(())
+ );
+ assert!(!canonical_bundle.exists());
+ assert_eq!(
+ delete_recording_directory_in(&[recordings], &canonical_bundle),
+ Ok(())
+ );
+
+ std::fs::remove_dir_all(root).ok();
+ }
+
// -- The thumbnail cache ---------------------------------------------
#[test]
diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs
index 46391b8c8..84838963e 100644
--- a/apps/desktop-gpui/src/main.rs
+++ b/apps/desktop-gpui/src/main.rs
@@ -277,7 +277,11 @@ fn main() {
// rather than by AppKit, so mark the content view as app-owned
// titlebar content.
app_owns_titlebar_drag: true,
- window_background: gpui::WindowBackgroundAppearance::Transparent,
+ window_background: if cfg!(target_os = "windows") {
+ gpui::WindowBackgroundAppearance::Opaque
+ } else {
+ gpui::WindowBackgroundAppearance::Transparent
+ },
is_resizable: false,
is_minimizable: false,
..Default::default()
diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rs
index c63a19dec..a2cebbd33 100644
--- a/apps/desktop-gpui/src/main_window.rs
+++ b/apps/desktop-gpui/src/main_window.rs
@@ -2601,11 +2601,8 @@ impl Render for MainWindow {
.flex()
.flex_col()
.overflow_hidden()
- // `rounded-[16px]` on `.cap-window-shell`, matched natively by
- // `apply_squircle_corners(&window, 16.0)` in the Tauri app -- and,
- // when a material is installed, by the content-view squircle clip
- // in `platform::install_window_material`.
- .rounded(px(16.))
+ // Windows keeps its native frame, so DWM supplies the outer corners.
+ .when(!cfg!(target_os = "windows"), |shell| shell.rounded(px(16.)))
// Opaque `bg-gray-1` with no material; a translucent tint over the
// live `NSGlassEffectView`/`NSVisualEffectView` backdrop with one.
.bg(theme.shell_bg())
@@ -3369,6 +3366,8 @@ impl MainWindow {
let phase = self.session.read(cx).phase;
let stopping = phase == Phase::Stopping;
let starting = phase == Phase::Starting;
+ let countdown = self.session.read(cx).countdown_remaining();
+ let can_stop = !stopping && (!starting || countdown.is_some());
#[cfg(target_os = "linux")]
let can_resume = clean_capture_resume_available(
phase,
@@ -3391,6 +3390,15 @@ impl MainWindow {
.px(px(24.))
.pb(px(32.))
.bg(wash)
+ .when_some(countdown, |this, remaining| {
+ this.child(
+ div()
+ .mb(px(16.))
+ .text_size(px(18.))
+ .text_center()
+ .child(format!("Recording starts in {remaining}")),
+ )
+ })
.when_some(self.session.read(cx).error.clone(), |this, error| {
this.child(
div()
@@ -3462,8 +3470,8 @@ impl MainWindow {
.font_weight(FontWeight::MEDIUM)
.text_color(gpui::white())
// `disabled:opacity-60` while pending.
- .when(stopping || starting, |this| this.opacity(0.6))
- .when(!stopping && !starting, |this| {
+ .when(!can_stop, |this| this.opacity(0.6))
+ .when(can_stop, |this| {
this.hover(|style| style.bg(theme.red_10))
.on_click(cx.listener(|this, _, _window, cx| {
this.session.update(cx, |session, cx| session.stop(cx));
@@ -3476,6 +3484,7 @@ impl MainWindow {
.text_color(gpui::white()),
)
.child(match phase {
+ Phase::Starting if countdown.is_some() => "Cancel Recording",
Phase::Starting => "Starting...",
Phase::Stopping => "Stopping...",
_ => "Stop Recording",
@@ -5979,7 +5988,7 @@ impl MainWindow {
/// `BaseControls`: camera, microphone, system audio.
fn render_base_controls(&self, cx: &mut Context<Self>) -> impl IntoElement {
- let gap = if self.expanded { 10. } else { 6. };
+ let gap = if self.expanded { 10. } else { 8. };
div()
.flex()
diff --git a/apps/desktop-gpui/src/menus.rs b/apps/desktop-gpui/src/menus.rs
index 800fe1700..9eb4307f5 100644
--- a/apps/desktop-gpui/src/menus.rs
+++ b/apps/desktop-gpui/src/menus.rs
@@ -313,6 +313,10 @@ impl QuitGate {
!self.exit_committed && self.pending.is_none()
}
+ fn cancel_exit(&mut self) {
+ self.exit_committed = false;
+ }
+
fn request(&mut self, phase: Phase) -> Option<(u64, QuitAction)> {
if self.exit_committed || self.pending.is_some() {
return None;
@@ -387,13 +391,26 @@ pub(crate) fn recording_start_allowed(cx: &App) -> bool {
.is_none_or(|coordinator| coordinator.gate.recording_start_allowed())
}
+fn quit_phase(phase: Phase, ui_cleanup_pending: bool) -> Phase {
+ if phase == Phase::Idle && ui_cleanup_pending {
+ Phase::Stopping
+ } else {
+ phase
+ }
+}
+
pub fn quit(cx: &mut App) {
let session = RecordingSession::global(cx);
if !cx.has_global::<QuitCoordinator>() {
cx.set_global(QuitCoordinator::default());
}
let phase = session.read(cx).phase;
- let Some((generation, action)) = cx.global_mut::<QuitCoordinator>().gate.request(phase) else {
+ let ui_cleanup_pending = app_windows::clean_capture_owned(cx);
+ let Some((generation, action)) = cx
+ .global_mut::<QuitCoordinator>()
+ .gate
+ .request(quit_phase(phase, ui_cleanup_pending))
+ else {
return;
};
if action == QuitAction::Exit {
@@ -412,11 +429,15 @@ pub fn quit(cx: &mut App) {
})
.detach();
apply_quit_action(action, cx);
+ if phase == Phase::Idle && ui_cleanup_pending {
+ app_windows::cancel_clean_capture(cx);
+ advance_pending_quit(generation, false, cx);
+ }
}
fn advance_pending_quit(generation: u64, timed_out: bool, cx: &mut App) {
let session = RecordingSession::global(cx);
- let phase = session.read(cx).phase;
+ let phase = quit_phase(session.read(cx).phase, app_windows::clean_capture_owned(cx));
let failed = session.read(cx).error.is_some();
let action = cx
.global_mut::<QuitCoordinator>()
@@ -431,9 +452,20 @@ fn apply_quit_action(action: QuitAction, cx: &mut App) {
QuitAction::Stop => RecordingSession::global(cx).update(cx, |session, cx| session.stop(cx)),
QuitAction::Exit => {
cx.global_mut::<QuitCoordinator>().observer = None;
- #[cfg(target_os = "macos")]
- platform::permit_native_quit();
- cx.quit();
+ cx.defer(|cx| {
+ if let Err(error) = app_windows::flush_pending_editor_saves(cx) {
+ cx.global_mut::<QuitCoordinator>().gate.cancel_exit();
+ tracing::error!(%error, "quit canceled because editor changes could not be saved");
+ cx.spawn(async move |_| {
+ platform::alert_dialog("Cap is still open", &error);
+ })
+ .detach();
+ return;
+ }
+ #[cfg(target_os = "macos")]
+ platform::permit_native_quit();
+ cx.quit();
+ });
}
QuitAction::Failed | QuitAction::TimedOut => {
cx.global_mut::<QuitCoordinator>().observer = None;
@@ -599,6 +631,45 @@ fn visible_window_classes(cx: &mut App) -> (bool, bool) {
mod tests {
use super::*;
+ #[test]
+ fn quit_waits_for_recording_ui_restoration() {
+ for phase in [Phase::Idle, Phase::Starting] {
+ let mut gate = QuitGate::default();
+ let (generation, action) = gate.request(quit_phase(phase, true)).unwrap();
+ assert_ne!(action, QuitAction::Exit);
+ assert!(!gate.recording_start_allowed());
+ assert_eq!(
+ gate.advance(generation, quit_phase(Phase::Idle, true), false, false),
+ QuitAction::Wait
+ );
+ assert_eq!(
+ gate.advance(generation, quit_phase(Phase::Idle, false), false, false),
+ QuitAction::Exit
+ );
+ }
+ }
+
+ #[test]
+ fn restoration_failure_or_timeout_keeps_cap_open() {
+ for failed in [false, true] {
+ let mut gate = QuitGate::default();
+ let (generation, _) = gate.request(quit_phase(Phase::Idle, true)).unwrap();
+ assert_eq!(
+ gate.advance(generation, quit_phase(Phase::Idle, true), failed, !failed),
+ if failed {
+ QuitAction::Failed
+ } else {
+ QuitAction::TimedOut
+ }
+ );
+ assert!(gate.recording_start_allowed());
+ assert_eq!(
+ gate.advance(generation, quit_phase(Phase::Idle, false), false, false),
+ QuitAction::Wait
+ );
+ }
+ }
+
#[test]
fn quit_deadline_does_not_authorize_exit_after_a_delayed_stop() {
let mut gate = QuitGate::default();
@@ -704,6 +775,31 @@ mod tests {
assert!(gate.exit_committed);
}
+ #[test]
+ fn failed_editor_save_allows_recording_and_a_later_quit() {
+ for phase in [Phase::Idle, Phase::Stopping] {
+ let mut gate = QuitGate::default();
+ let (previous, action) = gate.request(phase).unwrap();
+ if action == QuitAction::Wait {
+ assert_eq!(
+ gate.advance(previous, Phase::Idle, false, false),
+ QuitAction::Exit
+ );
+ }
+ assert!(!gate.recording_start_allowed());
+ gate.cancel_exit();
+ assert!(gate.recording_start_allowed());
+ let (current, action) = gate.request(Phase::Idle).unwrap();
+ assert_ne!(previous, current);
+ assert_eq!(action, QuitAction::Exit);
+ assert_eq!(
+ gate.advance(previous, Phase::Idle, false, true),
+ QuitAction::Wait
+ );
+ assert!(gate.exit_committed);
+ }
+ }
+
#[test]
fn committed_exit_closes_recording_admission_before_the_native_callback() {
let mut gate = QuitGate::default();
diff --git a/apps/desktop-gpui/src/recording.rs b/apps/desktop-gpui/src/recording.rs
index d0e1f0f9b..fc4802008 100644
--- a/apps/desktop-gpui/src/recording.rs
+++ b/apps/desktop-gpui/src/recording.rs
@@ -2122,41 +2122,11 @@ pub fn recordings_dir() -> PathBuf {
crate::store::app_data_dir().join("recordings")
}
-/// `delete_recording_directory` (`src-tauri/src/lib.rs:4006-4051`), for the
-/// clip the editor-append flow just copied out of: reject `..` components,
-/// require the path to live inside the recordings library (canonically, so a
-/// symlink cannot escape it), then `remove_dir_all`. The Tauri command accepts
-/// every known storage folder; this app resolves exactly one
-/// ([`recordings_dir`]), so that one is the whole allow-list.
+/// Deletes the clip the editor-append flow just copied from, using the same
+/// guarded recursive delete as the library with the active recordings folder
+/// as its only allowed root.
pub fn delete_recording_directory(path: &std::path::Path) -> Result<(), String> {
- if path
- .components()
- .any(|component| matches!(component, std::path::Component::ParentDir))
- {
- return Err("Invalid path".to_string());
- }
-
- let recordings = recordings_dir();
- if !path.starts_with(&recordings) {
- return Err("Path is not inside the recordings directory".to_string());
- }
-
- if path.exists() {
- let canonical = path
- .canonicalize()
- .map_err(|e| format!("Failed to resolve recording path: {e}"))?;
- let inside = recordings
- .canonicalize()
- .map(|dir| canonical.starts_with(&dir))
- .unwrap_or(false);
- if !inside {
- return Err("Path is not inside the recordings directory".to_string());
- }
- std::fs::remove_dir_all(&canonical)
- .map_err(|e| format!("Failed to delete recording: {e}"))?;
- }
-
- Ok(())
+ crate::library::delete_recording_directory_in(&[recordings_dir()], path)
}
/// `format_project_name` with the default template
diff --git a/apps/desktop-gpui/src/session.rs b/apps/desktop-gpui/src/session.rs
index 4efc87d8c..e6b5b56f0 100644
--- a/apps/desktop-gpui/src/session.rs
+++ b/apps/desktop-gpui/src/session.rs
@@ -23,6 +23,29 @@ pub enum Phase {
Stopping,
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum CountdownAdvance {
+ Ignore,
+ Tick(u32),
+ Start,
+}
+
+fn countdown_advance(
+ phase: Phase,
+ current_generation: u64,
+ countdown_generation: u64,
+ remaining: Option<u32>,
+) -> CountdownAdvance {
+ if phase != Phase::Starting || current_generation != countdown_generation {
+ return CountdownAdvance::Ignore;
+ }
+ match remaining {
+ Some(remaining) if remaining > 1 => CountdownAdvance::Tick(remaining - 1),
+ Some(1) => CountdownAdvance::Start,
+ _ => CountdownAdvance::Ignore,
+ }
+}
+
#[derive(Clone, Debug, PartialEq, Eq)]
struct PauseControlTicket {
generation: u64,
@@ -350,6 +373,7 @@ pub struct RecordingSession {
storage_monitor: Option<Task<()>>,
failure_monitor: Option<Task<()>>,
recording_generation: u64,
+ countdown_remaining: Option<u32>,
pause_control: PauseControlState,
pause_control_error: Option<String>,
#[cfg(target_os = "linux")]
@@ -389,6 +413,7 @@ impl RecordingSession {
storage_monitor: None,
failure_monitor: None,
recording_generation: 0,
+ countdown_remaining: None,
pause_control: PauseControlState::default(),
pause_control_error: None,
#[cfg(target_os = "linux")]
@@ -514,6 +539,10 @@ impl RecordingSession {
}
}
+ pub fn countdown_remaining(&self) -> Option<u32> {
+ self.countdown_remaining
+ }
+
pub fn start(&mut self, config: StartConfig, cx: &mut Context<Self>) {
if self.phase != Phase::Idle {
return;
@@ -525,14 +554,17 @@ impl RecordingSession {
self.storage_monitor = None;
self.failure_monitor = None;
self.recording_generation = self.recording_generation.wrapping_add(1);
+ let generation = self.recording_generation;
+ let countdown = crate::store::GeneralSettings::load()
+ .recording_countdown
+ .unwrap_or(0);
self.pause_control.invalidate();
self.pause_control.uncertain = false;
self.pause_control_error = None;
self.pipeline_failed = false;
#[cfg(target_os = "linux")]
{
- self.instant_attempt = (config.mode == recording::RecordingMode::Instant)
- .then(recording::InstantAttempt::new);
+ self.instant_attempt = None;
self.clean_control.invalidate();
self.clean_control.uncertain = false;
}
@@ -543,10 +575,65 @@ impl RecordingSession {
self.stopped_for_low_storage = false;
self.stopped_elapsed = None;
self.last_config = Some(config.clone());
+ self.countdown_remaining = (countdown > 0).then_some(countdown);
cx.notify();
+ if countdown == 0 {
+ self.start_engine(config, generation, cx);
+ return;
+ }
+
+ cx.spawn(async move |this, cx| {
+ loop {
+ cx.background_executor().timer(Duration::from_secs(1)).await;
+ let keep_waiting = this
+ .update(cx, |this, cx| {
+ match countdown_advance(
+ this.phase,
+ this.recording_generation,
+ generation,
+ this.countdown_remaining,
+ ) {
+ CountdownAdvance::Ignore => false,
+ CountdownAdvance::Tick(remaining) => {
+ this.countdown_remaining = Some(remaining);
+ cx.notify();
+ true
+ }
+ CountdownAdvance::Start => {
+ this.countdown_remaining = None;
+ cx.notify();
+ this.start_engine(config.clone(), generation, cx);
+ false
+ }
+ }
+ })
+ .unwrap_or(false);
+ if !keep_waiting {
+ return;
+ }
+ }
+ })
+ .detach();
+ }
+
+ fn start_engine(&mut self, config: StartConfig, generation: u64, cx: &mut Context<Self>) {
+ if self.phase != Phase::Starting
+ || self.recording_generation != generation
+ || self.countdown_remaining.is_some()
+ {
+ return;
+ }
+ if !crate::menus::recording_start_allowed(cx) {
+ self.finish(cx);
+ return;
+ }
+
#[cfg(target_os = "linux")]
- let generation = self.recording_generation;
+ {
+ self.instant_attempt = (config.mode == recording::RecordingMode::Instant)
+ .then(recording::InstantAttempt::new);
+ }
#[cfg(target_os = "linux")]
let attempt = self.instant_attempt.clone();
#[cfg(target_os = "linux")]
@@ -758,6 +845,11 @@ impl RecordingSession {
}
pub fn stop(&mut self, cx: &mut Context<Self>) {
+ if self.phase == Phase::Starting && self.countdown_remaining.is_some() {
+ self.countdown_remaining = None;
+ self.finish(cx);
+ return;
+ }
#[cfg(target_os = "linux")]
if matches!(self.phase, Phase::Starting | Phase::Stopping)
&& let Some(attempt) = self.instant_attempt.clone()
@@ -1551,6 +1643,7 @@ impl RecordingSession {
self.pause_control_error = None;
self.pipeline_failed = false;
self.storage_monitor = None;
+ self.countdown_remaining = None;
self.phase = Phase::Idle;
self.mic_muted = false;
self.storage_warning = false;
@@ -1566,6 +1659,47 @@ fn recording_failure_is_current(phase: Phase, current: u64, completed: u64) -> b
current == completed && matches!(phase, Phase::Recording { .. })
}
+#[cfg(test)]
+mod countdown_tests {
+ use super::*;
+
+ #[test]
+ fn countdown_ticks_until_the_final_step_before_start() {
+ assert_eq!(
+ countdown_advance(Phase::Starting, 7, 7, Some(3)),
+ CountdownAdvance::Tick(2)
+ );
+ assert_eq!(
+ countdown_advance(Phase::Starting, 7, 7, Some(2)),
+ CountdownAdvance::Tick(1)
+ );
+ assert_eq!(
+ countdown_advance(Phase::Starting, 7, 7, Some(1)),
+ CountdownAdvance::Start
+ );
+ assert_eq!(
+ countdown_advance(Phase::Starting, 7, 7, None),
+ CountdownAdvance::Ignore
+ );
+ }
+
+ #[test]
+ fn cancelled_or_superseded_countdown_cannot_start_capture() {
+ assert_eq!(
+ countdown_advance(Phase::Idle, 7, 7, Some(1)),
+ CountdownAdvance::Ignore
+ );
+ assert_eq!(
+ countdown_advance(Phase::Starting, 8, 7, Some(1)),
+ CountdownAdvance::Ignore
+ );
+ assert_eq!(
+ countdown_advance(Phase::Recording { paused: false }, 7, 7, Some(1)),
+ CountdownAdvance::Ignore
+ );
+ }
+}
+
#[cfg(target_os = "linux")]
fn clean_capture_stop_must_wait(phase: Phase, transition: Option<CleanControlKind>) -> bool {
phase == Phase::Starting || transition == Some(CleanControlKind::Pause)
diff --git a/apps/desktop-gpui/src/settings_pages.rs b/apps/desktop-gpui/src/settings_pages.rs
index 820ea3188..3cbd3d9e6 100644
--- a/apps/desktop-gpui/src/settings_pages.rs
+++ b/apps/desktop-gpui/src/settings_pages.rs
@@ -2029,7 +2029,6 @@ pub(crate) fn start_update_handoff(cx: &mut gpui::App) {
}
fn quit_after_flushing_editors(cx: &mut gpui::App) {
- crate::app_windows::flush_pending_editor_saves(cx);
crate::menus::quit(cx);
}
@@ -2068,7 +2067,13 @@ fn begin_update_handoff(cx: &mut gpui::App, request_handoff: fn() -> std::io::Re
if update_handoff_blocked(cx) {
return;
}
- crate::app_windows::flush_pending_editor_saves(cx);
+ if let Err(error) = crate::app_windows::flush_pending_editor_saves(cx) {
+ cx.spawn(async move |_| {
+ crate::platform::alert_dialog("Cap is still open", &error);
+ })
+ .detach();
+ return;
+ }
if let Err(error) = request_handoff() {
tracing::error!("couldn't request the Tauri updater: {error}");
@@ -2434,7 +2439,11 @@ impl SettingsWindow {
if self.switch_back_blocked(cx) {
return;
}
- crate::app_windows::flush_pending_editor_saves(cx);
+ if let Err(error) = crate::app_windows::flush_pending_editor_saves(cx) {
+ self.pages.switch_back = Some(SwitchBack::Failed(error));
+ cx.notify();
+ return;
+ }
self.settings.enable_gpui_app = false;
self.write_bool("enableGpuiApp", false, cx);
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 96c4094d5..961127329 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -377,6 +377,7 @@ impl CameraWindowCloseGate {
pub struct AppExitState {
exiting: AtomicBool,
restarting: AtomicBool,
+ title_flush_pending: AtomicBool,
admission: std::sync::Mutex<()>,
}
@@ -385,12 +386,24 @@ impl Default for AppExitState {
Self {
exiting: AtomicBool::new(false),
restarting: AtomicBool::new(false),
+ title_flush_pending: AtomicBool::new(false),
admission: std::sync::Mutex::new(()),
}
}
}
impl AppExitState {
+ fn begin_title_flush(&self) -> Option<PendingTitleExit<'_>> {
+ self.title_flush_pending
+ .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
+ .ok()
+ .map(|_| PendingTitleExit(self))
+ }
+
+ fn exit_pending(&self) -> bool {
+ self.is_exiting() || self.title_flush_pending.load(Ordering::Acquire)
+ }
+
pub fn begin(&self) -> bool {
self.exiting
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
@@ -411,6 +424,14 @@ impl AppExitState {
}
}
+struct PendingTitleExit<'a>(&'a AppExitState);
+
+impl Drop for PendingTitleExit<'_> {
+ fn drop(&mut self) {
+ self.0.title_flush_pending.store(false, Ordering::Release);
+ }
+}
+
pub struct MainWindowReadyState(AtomicBool);
impl Default for MainWindowReadyState {
@@ -1112,7 +1133,9 @@ impl App {
target: ScreenCaptureTarget,
) -> Result<(), String> {
recording_start_allowed(
- app_is_exiting(&self.handle),
+ self.handle
+ .try_state::<AppExitState>()
+ .is_some_and(|state| state.exit_pending()),
updates::recording_start_blocked(&self.handle),
)?;
#[cfg(target_os = "linux")]
@@ -2775,6 +2798,15 @@ pub(crate) fn with_idle_app<T>(
app: &AppHandle,
include_exports: bool,
begin: impl FnOnce() -> T,
+) -> Result<T, ExitBlocked> {
+ with_idle_app_for_title_flush(app, include_exports, false, begin)
+}
+
+fn with_idle_app_for_title_flush<T>(
+ app: &AppHandle,
+ include_exports: bool,
+ owns_title_flush: bool,
+ begin: impl FnOnce() -> T,
) -> Result<T, ExitBlocked> {
let exit_state = app
.try_state::<AppExitState>()
@@ -2783,7 +2815,9 @@ pub(crate) fn with_idle_app<T>(
.admission
.try_lock()
.map_err(|_| ExitBlocked::StateUnavailable)?;
- if exit_state.is_exiting() {
+ if exit_state.is_exiting()
+ || (!owns_title_flush && exit_state.title_flush_pending.load(Ordering::Acquire))
+ {
return Err(ExitBlocked::AlreadyExiting);
}
let state = app
@@ -2865,6 +2899,96 @@ fn show_exit_blocked(app: &AppHandle, reason: ExitBlocked) {
.show(|_| {});
}
+#[derive(Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct EditorTitleSaveRequest {
+ request_id: String,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct EditorTitleSaveResponse {
+ request_id: String,
+ window_label: String,
+ error: Option<String>,
+}
+
+async fn wait_for_editor_title_saves(
+ request_id: &str,
+ mut pending: HashSet<String>,
+ mut responses: tokio::sync::mpsc::UnboundedReceiver<EditorTitleSaveResponse>,
+ timeout: Duration,
+) -> Result<(), String> {
+ tokio::time::timeout(timeout, async {
+ while !pending.is_empty() {
+ let response = responses
+ .recv()
+ .await
+ .ok_or("The editor title save connection closed before saving finished.")?;
+ if response.request_id != request_id || !pending.remove(&response.window_label) {
+ continue;
+ }
+ if let Some(error) = response.error {
+ return Err(format!("Could not save the recording title: {error}"));
+ }
+ }
+ Ok(())
+ })
+ .await
+ .map_err(|_| {
+ "Could not confirm that all recording titles were saved. Try Quit again.".to_string()
+ })?
+}
+
+async fn flush_editor_titles_for_exit(
+ app: &AppHandle,
+) -> Result<Option<EditorTitleSaveRequest>, String> {
+ let labels: HashSet<_> = app
+ .webview_windows()
+ .into_keys()
+ .filter(|label| matches!(CapWindowId::from_str(label), Ok(CapWindowId::Editor { .. })))
+ .collect();
+ if labels.is_empty() {
+ return Ok(None);
+ }
+
+ let request = EditorTitleSaveRequest {
+ request_id: uuid::Uuid::new_v4().to_string(),
+ };
+ let (sender, responses) = tokio::sync::mpsc::unbounded_channel();
+ let listener = app.listen_any("editor-title-save-finished", move |event| {
+ if let Ok(response) = serde_json::from_str(event.payload()) {
+ let _ = sender.send(response);
+ }
+ });
+ let result = async {
+ for label in &labels {
+ app.emit_to(label, "editor-title-save-request", &request)
+ .map_err(|error| format!("Could not request an editor title save: {error}"))?;
+ }
+ wait_for_editor_title_saves(
+ &request.request_id,
+ labels.clone(),
+ responses,
+ Duration::from_secs(5),
+ )
+ .await?;
+ if app.webview_windows().keys().any(|label| {
+ !labels.contains(label)
+ && matches!(CapWindowId::from_str(label), Ok(CapWindowId::Editor { .. }))
+ }) {
+ return Err("Another editor opened while preparing to quit. Try Quit again.".into());
+ }
+ Ok(())
+ }
+ .await;
+ app.unlisten(listener);
+ if result.is_err() {
+ let _ = app.emit("editor-title-save-cancelled", &request);
+ }
+ result.map(|()| Some(request))
+}
+
#[tauri::command]
#[specta::specta]
fn restart_app(app: AppHandle) -> Result<(), String> {
@@ -2879,14 +3003,47 @@ fn restart_app(app: AppHandle) -> Result<(), String> {
}
pub async fn request_app_exit(app: AppHandle) {
- match begin_app_exit_if_idle(&app, false) {
- Ok(true) => {}
- Ok(false) => return,
+ let Some(exit_state) = app.try_state::<AppExitState>() else {
+ show_exit_blocked(&app, ExitBlocked::StateUnavailable);
+ return;
+ };
+ let pending = match with_idle_app(&app, false, || exit_state.begin_title_flush()) {
+ Ok(Some(pending)) => pending,
+ Ok(None) => return,
Err(ExitBlocked::AlreadyExiting) => return,
Err(reason) => {
show_exit_blocked(&app, reason);
return;
}
+ };
+ let request = match flush_editor_titles_for_exit(&app).await {
+ Ok(request) => request,
+ Err(error) => {
+ drop(pending);
+ warn!(%error, "Quit canceled because an editor title could not be saved");
+ app.dialog()
+ .message(format!(
+ "{error}\n\nCap is still open. Your title is still in the editor."
+ ))
+ .title("Title not saved")
+ .kind(tauri_plugin_dialog::MessageDialogKind::Warning)
+ .show(|_| {});
+ return;
+ }
+ };
+ let admission = with_idle_app_for_title_flush(&app, true, true, || exit_state.begin());
+ drop(pending);
+ match admission {
+ Ok(true) => {}
+ result => {
+ if let Some(request) = request {
+ let _ = app.emit("editor-title-save-cancelled", request);
+ }
+ if let Err(reason) = result {
+ show_exit_blocked(&app, reason);
+ }
+ return;
+ }
}
complete_admitted_app_exit(app).await;
}
@@ -4765,17 +4922,10 @@ fn acquire_recording_delete_lock(
cap_recording::upload_resume::UploadLock::acquire(path).map_err(|error| error.to_string())
}
-#[tauri::command]
-#[specta::specta]
-#[instrument(skip(app))]
-async fn delete_recording_directory(app: AppHandle, path: PathBuf) -> Result<(), String> {
- // The library lists recordings from every known storage folder, so
- // deletion must accept the same set — but nothing outside it.
- let recordings_dirs = recordings_locations::known_recordings_dirs(&app);
-
- // Reject `..` components up front: `Path::starts_with` compares raw components
- // and does not normalize them, so a path like `<recordings_dir>/../../etc` would
- // otherwise pass the prefix check below.
+fn recording_delete_target(
+ recordings_dirs: &[PathBuf],
+ path: &Path,
+) -> Result<Option<PathBuf>, String> {
if path
.components()
.any(|component| matches!(component, std::path::Component::ParentDir))
@@ -4783,26 +4933,53 @@ async fn delete_recording_directory(app: AppHandle, path: PathBuf) -> Result<(),
return Err("Invalid path".to_string());
}
- if !recordings_dirs.iter().any(|dir| path.starts_with(dir)) {
+ let canonical_dirs: Vec<_> = recordings_dirs
+ .iter()
+ .filter_map(|dir| dir.canonicalize().ok())
+ .collect();
+ if recordings_dirs
+ .iter()
+ .chain(&canonical_dirs)
+ .any(|dir| path == dir)
+ {
return Err("Path is not inside a recordings directory".to_string());
}
- if path.exists() {
- // Canonicalize both paths so symlinks can't be used to escape the
- // recordings directories before we recursively delete.
+ if path
+ .try_exists()
+ .map_err(|error| format!("Failed to inspect recording path: {error}"))?
+ {
let canonical_path = path
.canonicalize()
- .map_err(|e| format!("Failed to resolve recording path: {e}"))?;
-
- let inside_known_dir = recordings_dirs.iter().any(|dir| {
- dir.canonicalize()
- .map(|dir| canonical_path.starts_with(&dir))
- .unwrap_or(false)
- });
- if !inside_known_dir {
+ .map_err(|error| format!("Failed to resolve recording path: {error}"))?;
+ if canonical_dirs.iter().any(|dir| &canonical_path == dir)
+ || !canonical_dirs
+ .iter()
+ .any(|dir| canonical_path.starts_with(dir))
+ {
return Err("Path is not inside a recordings directory".to_string());
}
+ Ok(Some(canonical_path))
+ } else if recordings_dirs
+ .iter()
+ .chain(&canonical_dirs)
+ .any(|dir| path.starts_with(dir))
+ {
+ Ok(None)
+ } else {
+ Err("Path is not inside a recordings directory".to_string())
+ }
+}
+#[tauri::command]
+#[specta::specta]
+#[instrument(skip(app))]
+async fn delete_recording_directory(app: AppHandle, path: PathBuf) -> Result<(), String> {
+ // The library lists recordings from every known storage folder, so
+ // deletion must accept the same set — but nothing outside it.
+ let recordings_dirs = recordings_locations::known_recordings_dirs(&app);
+
+ if let Some(canonical_path) = recording_delete_target(&recordings_dirs, &path)? {
upload::lifecycle::cancel(&canonical_path).await;
let ownership = acquire_recording_delete_lock(&canonical_path)?;
upload::lifecycle::mark_cancelled(&canonical_path).map_err(|error| error.to_string())?;
@@ -6234,8 +6411,13 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
let camera_preview = CameraPreviewManager::new(&app);
let camera_session_id_handle = camera_preview.session_id_handle();
- let requested_settings = RecordingSettingsStore::get(&app)?
- .unwrap_or_default();
+ let requested_settings = match RecordingSettingsStore::get(&app) {
+ Ok(settings) => settings.unwrap_or_default(),
+ Err(error) => {
+ warn!(%error, "Failed to load recording settings during startup");
+ RecordingSettingsStore::default()
+ }
+ };
app.manage(linux_instant_camera::PresentationBroker::default());
app.manage(RequestedInputsState::new(
requested_settings.mic_name,
@@ -7764,6 +7946,112 @@ fn open_project_from_path(path: &Path, app: AppHandle) -> Result<(), String> {
Ok(())
}
+#[cfg(test)]
+mod editor_title_save_tests {
+ use super::{AppExitState, EditorTitleSaveResponse, wait_for_editor_title_saves};
+ use std::{collections::HashSet, time::Duration};
+ use tokio::sync::mpsc;
+
+ fn response(request: &str, window: &str, error: Option<&str>) -> EditorTitleSaveResponse {
+ EditorTitleSaveResponse {
+ request_id: request.into(),
+ window_label: window.into(),
+ error: error.map(str::to_string),
+ }
+ }
+
+ #[test]
+ fn failed_title_flush_releases_admission_without_stopping_device_watchers() {
+ let state = AppExitState::default();
+ let pending = state.begin_title_flush().unwrap();
+ assert!(state.exit_pending());
+ assert!(!state.is_exiting());
+ assert!(state.begin_title_flush().is_none());
+ drop(pending);
+ assert!(!state.exit_pending());
+ assert!(!state.is_exiting());
+ let pending = state.begin_title_flush().unwrap();
+ assert!(state.begin());
+ drop(pending);
+ assert!(state.is_exiting());
+ assert!(state.exit_pending());
+ }
+
+ #[tokio::test]
+ async fn quit_waits_for_every_editor_and_ignores_stale_or_duplicate_responses() {
+ let (sender, responses) = mpsc::unbounded_channel();
+ let pending = HashSet::from(["editor-1".into(), "editor-2".into()]);
+ sender.send(response("previous", "editor-1", None)).unwrap();
+ sender.send(response("current", "unknown", None)).unwrap();
+ sender.send(response("current", "editor-1", None)).unwrap();
+ sender.send(response("current", "editor-1", None)).unwrap();
+ let waiting =
+ wait_for_editor_title_saves("current", pending, responses, Duration::from_secs(1));
+ tokio::pin!(waiting);
+ assert!(futures::poll!(&mut waiting).is_pending());
+ sender.send(response("current", "editor-2", None)).unwrap();
+ assert_eq!(waiting.await, Ok(()));
+ }
+
+ #[tokio::test]
+ async fn one_editor_save_failure_prevents_quit() {
+ let (sender, responses) = mpsc::unbounded_channel();
+ sender
+ .send(response("current", "editor-1", Some("disk full")))
+ .unwrap();
+ let result = wait_for_editor_title_saves(
+ "current",
+ HashSet::from(["editor-1".into(), "editor-2".into()]),
+ responses,
+ Duration::from_secs(1),
+ )
+ .await;
+ assert!(result.unwrap_err().contains("disk full"));
+ }
+
+ #[tokio::test]
+ async fn missing_editor_acknowledgement_does_not_authorize_quit() {
+ let (_sender, responses) = mpsc::unbounded_channel();
+ let result = wait_for_editor_title_saves(
+ "current",
+ HashSet::from(["editor-1".into()]),
+ responses,
+ Duration::from_millis(1),
+ )
+ .await;
+ assert!(result.unwrap_err().contains("Could not confirm"));
+ }
+
+ #[tokio::test]
+ async fn closed_response_channel_does_not_authorize_quit() {
+ let (sender, responses) = mpsc::unbounded_channel();
+ drop(sender);
+ let result = wait_for_editor_title_saves(
+ "current",
+ HashSet::from(["editor-1".into()]),
+ responses,
+ Duration::from_secs(1),
+ )
+ .await;
+ assert!(result.unwrap_err().contains("connection closed"));
+ }
+
+ #[tokio::test]
+ async fn no_editor_requires_no_acknowledgement() {
+ let (_sender, responses) = mpsc::unbounded_channel();
+ assert_eq!(
+ wait_for_editor_title_saves(
+ "current",
+ HashSet::new(),
+ responses,
+ Duration::from_millis(1),
+ )
+ .await,
+ Ok(())
+ );
+ }
+}
+
#[cfg(test)]
mod studio_microphone_ownership_tests {
use super::{
@@ -8531,6 +8819,109 @@ mod screenshot_share_cache_tests {
}
}
+#[cfg(test)]
+mod recording_delete_path_tests {
+ use super::recording_delete_target;
+
+ #[test]
+ fn delete_target_rejects_an_allowed_root_nested_in_another_allowed_root() {
+ let temp = tempfile::tempdir().unwrap();
+ let recordings = temp.path().join("recordings");
+ let nested = recordings.join("nested");
+ let bundle = nested.join("keep-me.cap");
+ std::fs::create_dir_all(&bundle).unwrap();
+ let dirs = [recordings, nested.clone()];
+
+ for path in [&nested, &nested.canonicalize().unwrap()] {
+ assert_eq!(
+ recording_delete_target(&dirs, path),
+ Err("Path is not inside a recordings directory".to_string())
+ );
+ assert!(bundle.is_dir());
+ }
+ assert_eq!(
+ recording_delete_target(&dirs, &bundle),
+ Ok(Some(bundle.canonicalize().unwrap()))
+ );
+ }
+
+ #[test]
+ fn delete_target_accepts_only_strict_children_of_a_recordings_root() {
+ let temp = tempfile::tempdir().unwrap();
+ let recordings = temp.path().join("recordings");
+ let bundle = recordings.join("delete-me.cap");
+ let outside = temp.path().join("outside.cap");
+ std::fs::create_dir_all(&bundle).unwrap();
+ std::fs::create_dir_all(&outside).unwrap();
+
+ assert_eq!(
+ recording_delete_target(std::slice::from_ref(&recordings), &bundle),
+ Ok(Some(bundle.canonicalize().unwrap()))
+ );
+ assert_eq!(
+ recording_delete_target(std::slice::from_ref(&recordings), &recordings),
+ Err("Path is not inside a recordings directory".to_string())
+ );
+ assert_eq!(
+ recording_delete_target(std::slice::from_ref(&recordings), &outside),
+ Err("Path is not inside a recordings directory".to_string())
+ );
+ assert_eq!(
+ recording_delete_target(
+ std::slice::from_ref(&recordings),
+ &recordings.join("..").join("outside.cap"),
+ ),
+ Err("Invalid path".to_string())
+ );
+ assert_eq!(
+ recording_delete_target(
+ std::slice::from_ref(&recordings),
+ &recordings.join("already-gone.cap"),
+ ),
+ Ok(None)
+ );
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn delete_target_rejects_a_symlink_escape() {
+ let temp = tempfile::tempdir().unwrap();
+ let recordings = temp.path().join("recordings");
+ let victim = temp.path().join("victim");
+ let escape = recordings.join("escape.cap");
+ std::fs::create_dir_all(&recordings).unwrap();
+ std::fs::create_dir_all(&victim).unwrap();
+ std::fs::write(victim.join("keep.txt"), b"keep").unwrap();
+ std::os::unix::fs::symlink(&victim, &escape).unwrap();
+
+ assert_eq!(
+ recording_delete_target(&[recordings], &escape),
+ Err("Path is not inside a recordings directory".to_string())
+ );
+ assert!(victim.join("keep.txt").is_file());
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn delete_target_accepts_a_canonical_windows_project_under_a_raw_root() {
+ let temp = tempfile::tempdir().unwrap();
+ let recordings = temp.path().join("recordings");
+ let bundle = recordings.join("delete-me.cap");
+ std::fs::create_dir_all(&bundle).unwrap();
+ let canonical_bundle = bundle.canonicalize().unwrap();
+
+ assert_eq!(
+ recording_delete_target(std::slice::from_ref(&recordings), &canonical_bundle),
+ Ok(Some(canonical_bundle.clone()))
+ );
+ std::fs::remove_dir_all(&canonical_bundle).unwrap();
+ assert_eq!(
+ recording_delete_target(&[recordings], &canonical_bundle),
+ Ok(None)
+ );
+ }
+}
+
#[cfg(test)]
mod typescript_bindings_tests {
#[test]
diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsx
index 52c839204..217556b4d 100644
--- a/apps/desktop/src/routes/editor/Editor.tsx
+++ b/apps/desktop/src/routes/editor/Editor.tsx
@@ -7,6 +7,7 @@ import { makePersisted } from "@solid-primitives/storage";
import { createMutation, createQuery, skipToken } from "@tanstack/solid-query";
import { convertFileSrc } from "@tauri-apps/api/core";
import { LogicalPosition } from "@tauri-apps/api/dpi";
+import { emitTo } from "@tauri-apps/api/event";
import { Menu } from "@tauri-apps/api/menu";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { ask } from "@tauri-apps/plugin-dialog";
@@ -52,7 +53,7 @@ import {
useEditorInstanceContext,
} from "./context";
import { EditorErrorScreen } from "./EditorErrorScreen";
-import { Header } from "./Header";
+import { Header, type TitleSaveRegistration } from "./Header";
import { ImportProgress } from "./ImportProgress";
import { PlayerContent } from "./Player";
import { Timeline } from "./Timeline";
@@ -140,6 +141,81 @@ function getPreviewProjectConfig(
}
export function Editor() {
+ const currentWindow = getCurrentWindow();
+ let flushTitleSave: (() => Promise<void>) | undefined;
+ let setTitleReadOnly: ((readOnly: boolean) => void) | undefined;
+ let activeTitleSave: { generation: number; requestId: string } | undefined;
+ const registerTitleSave = (
+ registration: TitleSaveRegistration | undefined,
+ ) => {
+ flushTitleSave = registration?.flush;
+ setTitleReadOnly = registration?.setReadOnly;
+ setTitleReadOnly?.(activeTitleSave !== undefined);
+ };
+
+ onMount(() => {
+ let disposed = false;
+ let titleSaveGeneration = 0;
+
+ const titleSaveCancelled = currentWindow.listen<{ requestId: string }>(
+ "editor-title-save-cancelled",
+ ({ payload }) => {
+ if (activeTitleSave?.requestId !== payload.requestId) return;
+ activeTitleSave = undefined;
+ setTitleReadOnly?.(false);
+ },
+ );
+
+ const titleSaveRequest = titleSaveCancelled.then(() =>
+ currentWindow.listen<{ requestId: string }>(
+ "editor-title-save-request",
+ async ({ payload }) => {
+ if (disposed) return;
+
+ const generation = titleSaveGeneration + 1;
+ titleSaveGeneration = generation;
+ const { requestId } = payload;
+ activeTitleSave = { generation, requestId };
+ const readOnly = setTitleReadOnly;
+ readOnly?.(true);
+
+ let error: string | null = null;
+ try {
+ if (flushTitleSave) await flushTitleSave();
+ } catch (cause) {
+ error = cause instanceof Error ? cause.message : String(cause);
+ }
+
+ if (
+ disposed ||
+ activeTitleSave?.generation !== generation ||
+ activeTitleSave?.requestId !== requestId
+ )
+ return;
+
+ try {
+ await emitTo(currentWindow.label, "editor-title-save-finished", {
+ requestId,
+ windowLabel: currentWindow.label,
+ error,
+ });
+ } catch (cause) {
+ console.error("Failed to acknowledge editor title save:", cause);
+ return;
+ }
+ },
+ ),
+ );
+
+ onCleanup(() => {
+ disposed = true;
+ activeTitleSave = undefined;
+ setTitleReadOnly?.(false);
+ void titleSaveRequest.then((unlisten) => unlisten()).catch(() => {});
+ void titleSaveCancelled.then((unlisten) => unlisten()).catch(() => {});
+ });
+ });
+
const [projectPath] = createResource(() => commands.getEditorProjectPath());
const rawMetaQuery = createQuery(() => ({
@@ -240,7 +316,11 @@ export function Editor() {
)}
>
<EditorInstanceContextProvider>
- <EditorContent projectPath={path()} />
+ <EditorContent
+ projectPath={path()}
+ getTitleSave={() => flushTitleSave}
+ registerTitleSave={registerTitleSave}
+ />
</EditorInstanceContextProvider>
</ErrorBoundary>
)}
@@ -249,7 +329,11 @@ export function Editor() {
);
}
-function EditorContent(props: { projectPath: string }) {
+function EditorContent(props: {
+ projectPath: string;
+ getTitleSave: () => (() => Promise<void>) | undefined;
+ registerTitleSave: (registration: TitleSaveRegistration | undefined) => void;
+}) {
const ctx = useEditorInstanceContext();
const errorInfo = () => {
@@ -290,7 +374,10 @@ function EditorContent(props: { projectPath: string }) {
<Match when={readyData()}>
{(values) => (
<EditorContextProvider {...values()}>
- <Inner />
+ <Inner
+ getTitleSave={props.getTitleSave}
+ registerTitleSave={props.registerTitleSave}
+ />
</EditorContextProvider>
)}
</Match>
@@ -298,7 +385,10 @@ function EditorContent(props: { projectPath: string }) {
);
}
-function Inner() {
+function Inner(props: {
+ getTitleSave: () => (() => Promise<void>) | undefined;
+ registerTitleSave: (registration: TitleSaveRegistration | undefined) => void;
+}) {
const {
project,
editorInstance,
@@ -369,21 +459,27 @@ function Inner() {
let allowExportClose = false;
let closePromptOpen = false;
- onMount(async () => {
- const unlisten = await currentWindow.onCloseRequested(async (event) => {
- if (
- allowExportClose ||
- exportState.type === "idle" ||
- exportState.type === "done"
- ) {
- return;
- }
+ onMount(() => {
+ const closeRequested = currentWindow.onCloseRequested(async (event) => {
+ if (allowExportClose) return;
event.preventDefault();
if (closePromptOpen) return;
closePromptOpen = true;
try {
+ try {
+ await props.getTitleSave()?.();
+ } catch {
+ return;
+ }
+
+ if (exportState.type === "idle" || exportState.type === "done") {
+ allowExportClose = true;
+ await currentWindow.close();
+ return;
+ }
+
const resumeExport = await ask(
"An export is currently running. Keep this editor open to continue it, or quit the editor and cancel the export.",
{
@@ -403,7 +499,9 @@ function Inner() {
}
});
- onCleanup(() => unlisten());
+ onCleanup(() => {
+ void closeRequested.then((unlisten) => unlisten()).catch(() => {});
+ });
});
const [layoutRef, setLayoutRef] = createSignal<HTMLDivElement>();
@@ -671,7 +769,7 @@ function Inner() {
}
>
<div class="flex flex-col flex-1 min-h-0">
- <Header />
+ <Header registerTitleSave={props.registerTitleSave} />
<div
class="flex overflow-y-hidden flex-col flex-1 gap-2 w-full min-h-0 leading-5"
data-tauri-drag-region
diff --git a/apps/desktop/src/routes/editor/Header.tsx b/apps/desktop/src/routes/editor/Header.tsx
index 549e512af..ce4d7dd60 100644
--- a/apps/desktop/src/routes/editor/Header.tsx
+++ b/apps/desktop/src/routes/editor/Header.tsx
@@ -9,10 +9,12 @@ import {
createEffect,
createMemo,
createSignal,
+ on,
onCleanup,
onMount,
Show,
} from "solid-js";
+import toast from "solid-toast";
import Tooltip from "~/components/Tooltip";
import CaptionControlsMacOS from "~/components/titlebar/controls/CaptionControlsMacOS";
import CaptionControlsWindows11 from "~/components/titlebar/controls/CaptionControlsWindows11";
@@ -22,6 +24,7 @@ import { initializeTitlebar } from "~/utils/titlebar-state";
import { useEditorContext } from "./context";
import OrganizationDropdown from "./OrganizationDropdown";
import PresetsDropdown from "./PresetsDropdown";
+import { createRecordingTitleSave } from "./recording-title-save";
import ShareButton from "./ShareButton";
import { EditorButton } from "./ui";
@@ -44,7 +47,14 @@ export interface ExportEstimates {
estimated_size_mb: number;
}
-export function Header() {
+export type TitleSaveRegistration = {
+ flush: () => Promise<void>;
+ setReadOnly: (readOnly: boolean) => void;
+};
+
+type RegisterTitleSave = (save: TitleSaveRegistration | undefined) => void;
+
+export function Header(props: { registerTitleSave: RegisterTitleSave }) {
const {
editorInstance,
project,
@@ -86,6 +96,8 @@ export function Header() {
return "type" in d && d.type === "clips" && d.open;
});
+ const [titleReadOnly, setTitleReadOnly] = createSignal(false);
+
return (
<div
data-tauri-drag-region
@@ -121,7 +133,12 @@ export function Header() {
/>
<div class="flex flex-row items-center">
- <NameEditor name={meta().prettyName} />
+ <NameEditor
+ name={meta().prettyName}
+ registerTitleSave={props.registerTitleSave}
+ readOnly={titleReadOnly()}
+ setReadOnly={setTitleReadOnly}
+ />
<span class="text-sm text-gray-11">.cap</span>
</div>
<div data-tauri-drag-region class="flex-1 h-full" />
@@ -273,21 +290,50 @@ const UploadIcon = (props: ComponentProps<"svg">) => {
);
};
-function NameEditor(props: { name: string }) {
+function NameEditor(props: {
+ name: string;
+ registerTitleSave: RegisterTitleSave;
+ readOnly: boolean;
+ setReadOnly: (readOnly: boolean) => void;
+}) {
const { refetchMeta } = useEditorContext();
let prettyNameRef: HTMLInputElement | undefined;
let prettyNameMeasureRef: HTMLSpanElement | undefined;
const [truncated, setTruncated] = createSignal(false);
const [prettyName, setPrettyName] = createSignal(props.name);
-
- createEffect(() => {
- if (!prettyNameRef || !prettyNameMeasureRef) return;
- prettyNameMeasureRef.textContent = prettyName();
- const inputWidth = prettyNameRef.offsetWidth;
- const textWidth = prettyNameMeasureRef.offsetWidth;
- setTruncated(inputWidth < textWidth);
+ const flushPrettyName = createRecordingTitleSave({
+ initialName: props.name,
+ getDraft: prettyName,
+ resetDraft: setPrettyName,
+ save: async (trimmed) => {
+ try {
+ await commands.setPrettyName(trimmed);
+ void refetchMeta();
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ toast.error(`Failed to save recording title: ${message}`);
+ throw error;
+ }
+ },
+ });
+ props.registerTitleSave({
+ flush: flushPrettyName,
+ setReadOnly: props.setReadOnly,
});
+ onCleanup(() => props.registerTitleSave(undefined));
+
+ createEffect(
+ on(prettyName, () => {
+ const frame = requestAnimationFrame(() => {
+ if (!prettyNameMeasureRef) return;
+ setTruncated(
+ prettyNameMeasureRef.scrollWidth > prettyNameMeasureRef.clientWidth,
+ );
+ });
+ onCleanup(() => cancelAnimationFrame(frame));
+ }),
+ );
return (
<Tooltip disabled={!truncated()} content={props.name}>
@@ -295,23 +341,16 @@ function NameEditor(props: { name: string }) {
<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",
+ "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",
truncated() && "truncate",
(prettyName().length < 5 || prettyName().length > 100) &&
"focus:border-red-500",
)}
value={prettyName()}
+ readOnly={props.readOnly}
onInput={(e) => setPrettyName(e.currentTarget.value)}
- onBlur={async () => {
- const trimmed = prettyName().trim();
- if (trimmed.length < 5 || trimmed.length > 100) {
- setPrettyName(props.name);
- return;
- }
- if (trimmed && trimmed !== props.name) {
- await commands.setPrettyName(trimmed);
- refetchMeta();
- }
+ onBlur={() => {
+ void flushPrettyName().catch(() => {});
}}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === "Escape") {
@@ -319,11 +358,12 @@ function NameEditor(props: { name: string }) {
}
}}
/>
- {/* Hidden span for measuring text width */}
<span
ref={prettyNameMeasureRef}
class="pointer-events-none max-w-[200px] px-px m-0 peer-focus:opacity-0 border-b border-transparent truncate whitespace-pre"
- />
+ >
+ {prettyName()}
+ </span>
</div>
</Tooltip>
);
diff --git a/apps/desktop/src/routes/editor/recording-title-save.test.ts b/apps/desktop/src/routes/editor/recording-title-save.test.ts
new file mode 100644
index 000000000..9e486bb3d
--- /dev/null
+++ b/apps/desktop/src/routes/editor/recording-title-save.test.ts
@@ -0,0 +1,115 @@
+import { describe, expect, it, vi } from "vitest";
+import { createRecordingTitleSave } from "./recording-title-save";
+
+function deferred() {
+ let resolve!: () => void;
+ let reject!: (reason: Error) => void;
+ const promise = new Promise<void>((yes, no) => {
+ resolve = yes;
+ reject = no;
+ });
+ return { promise, resolve, reject };
+}
+
+function setup(save = vi.fn(async (_name: string) => {})) {
+ let draft = "Original title";
+ const flush = createRecordingTitleSave({
+ initialName: draft,
+ getDraft: () => draft,
+ resetDraft: (name) => {
+ draft = name;
+ },
+ save,
+ });
+ return {
+ save,
+ flush,
+ getDraft: () => draft,
+ setDraft: (name: string) => {
+ draft = name;
+ },
+ };
+}
+
+describe("recording title saves", () => {
+ it("does not save on keystrokes or when the persisted title is unchanged", async () => {
+ const title = setup();
+ title.setDraft("Changed title");
+ expect(title.save).not.toHaveBeenCalled();
+ title.setDraft("Original title");
+ await title.flush();
+ expect(title.save).not.toHaveBeenCalled();
+ });
+
+ it("shares a pending blur save with the close request", async () => {
+ const write = deferred();
+ const title = setup(vi.fn(() => write.promise));
+ title.setDraft("Changed title");
+ const blur = title.flush();
+ const close = title.flush();
+ expect(close).toBe(blur);
+ expect(title.save).toHaveBeenCalledTimes(1);
+ write.resolve();
+ await close;
+ });
+
+ it("waits for the newest draft if it changes during a write", async () => {
+ const first = deferred();
+ const second = deferred();
+ const save = vi
+ .fn<(_name: string) => Promise<void>>()
+ .mockReturnValueOnce(first.promise)
+ .mockReturnValueOnce(second.promise);
+ const title = setup(save);
+ title.setDraft("First title");
+ let finished = false;
+ const closing = title.flush().then(() => {
+ finished = true;
+ });
+ title.setDraft("Newest title");
+ first.resolve();
+ await Promise.resolve();
+ expect(save.mock.calls).toEqual([["First title"], ["Newest title"]]);
+ expect(finished).toBe(false);
+ second.resolve();
+ await closing;
+ expect(finished).toBe(true);
+ });
+
+ it("retains an unsaved draft after failure and allows retry", async () => {
+ const write = deferred();
+ const save = vi
+ .fn<(_name: string) => Promise<void>>()
+ .mockReturnValueOnce(write.promise)
+ .mockResolvedValueOnce();
+ const title = setup(save);
+ title.setDraft("Keep this title");
+ const closing = title.flush();
+ write.reject(new Error("disk full"));
+ await expect(closing).rejects.toThrow("disk full");
+ expect(title.getDraft()).toBe("Keep this title");
+ await title.flush();
+ expect(save.mock.calls).toEqual([["Keep this title"], ["Keep this title"]]);
+ });
+
+ it.each(["", "tiny", "a".repeat(101)])(
+ "restores the last persisted title when the draft is invalid: %s",
+ async (invalid) => {
+ const title = setup();
+ title.setDraft("Saved title");
+ await title.flush();
+ title.setDraft(invalid);
+ await title.flush();
+ expect(title.getDraft()).toBe("Saved title");
+ expect(title.save).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it("trims the saved title and does not repeat the same write", async () => {
+ const title = setup();
+ title.setDraft(" Saved title ");
+ await title.flush();
+ await title.flush();
+ expect(title.save.mock.calls).toEqual([["Saved title"]]);
+ });
+});
diff --git a/apps/desktop/src/routes/editor/recording-title-save.ts b/apps/desktop/src/routes/editor/recording-title-save.ts
new file mode 100644
index 000000000..4225c71b8
--- /dev/null
+++ b/apps/desktop/src/routes/editor/recording-title-save.ts
@@ -0,0 +1,34 @@
+export function createRecordingTitleSave(options: {
+ initialName: string;
+ getDraft: () => string;
+ resetDraft: (name: string) => void;
+ save: (name: string) => Promise<void>;
+}) {
+ let persistedName = options.initialName;
+ let saveInFlight: Promise<void> | undefined;
+
+ const saveDraft = async () => {
+ while (true) {
+ const trimmed = options.getDraft().trim();
+ if (trimmed.length < 5 || trimmed.length > 100) {
+ options.resetDraft(persistedName);
+ return;
+ }
+ if (trimmed === persistedName) return;
+
+ await options.save(trimmed);
+ persistedName = trimmed;
+ if (options.getDraft().trim() === persistedName) return;
+ }
+ };
+
+ return () => {
+ if (saveInFlight) return saveInFlight;
+ const save = saveDraft();
+ const tracked = save.finally(() => {
+ if (saveInFlight === tracked) saveInFlight = undefined;
+ });
+ saveInFlight = tracked;
+ return tracked;
+ };
+}