Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: make GPUI shutdown and recording controls safe

Richie McIlroy218d3d792df9
diff --git a/apps/desktop-gpui/patches/zed-gpui.patch b/apps/desktop-gpui/patches/zed-gpui.patch
index a1e26a858..cecc831ae 100644
--- a/apps/desktop-gpui/patches/zed-gpui.patch
+++ b/apps/desktop-gpui/patches/zed-gpui.patch
@@ -1099,7 +1099,7 @@ index 97bad184dc58..e087c0dc8a54 100644
float4 hsla_to_rgba(Hsla hsla) {
diff --git a/crates/gpui_macos/src/window.rs b/crates/gpui_macos/src/window.rs
-index 8a3aa5ea067d..aacd697be58d 100644
+index 8a3aa5ea067d..f5b2c1a52a82 100644
--- a/crates/gpui_macos/src/window.rs
+++ b/crates/gpui_macos/src/window.rs
@@ -4,7 +4,6 @@
@@ -1145,7 +1145,19 @@ index 8a3aa5ea067d..aacd697be58d 100644
}
}
-@@ -3132,7 +3127,8 @@
+@@ -1178,6 +1173,10 @@
+ }
+ this.input_handler.take();
+- this.foreground_executor
++ let accesskit_adapter = this.accesskit_adapter.take();
++ let foreground_executor = this.foreground_executor.clone();
++ drop(this);
++ foreground_executor
+ .spawn(async move {
++ drop(accesskit_adapter);
+ unsafe {
+ if let Some(parent) = sheet_parent {
+@@ -3132,7 +3131,8 @@
let hit: BOOL = msg_send![description, containsString: blur_test];
if hit == YES {
let radius: id = msg_send![class!(NSNumber), numberWithDouble: 60.0f64];
diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rs
index 276e851b6..6f1a45ba8 100644
--- a/apps/desktop-gpui/src/app_windows.rs
+++ b/apps/desktop-gpui/src/app_windows.rs
@@ -604,6 +604,7 @@ pub(crate) fn show_main_window_after_capture_pause(cx: &mut App) {
view.resume_device_restore(cx);
}
if reset_target {
+ view.show_recorder(cx);
view.clear_target(cx);
}
// Every path back to the main window is a path a new capture may
@@ -1288,11 +1289,9 @@ pub fn open_teleprompter(cx: &mut App) {
appears_transparent: true,
traffic_light_position: Some(teleprompter_window::TRAFFIC_LIGHTS),
}),
- // `alwaysOnTop: true` + `visibleOnAllWorkspaces: true` are applied
- // below as level 101 + `CanJoinAllSpaces`, the same way the main
- // window gets level 100 -- a `WindowKind::PopUp` panel would be
- // non-activating, and this window has to take keystrokes for the
- // script.
+ #[cfg(target_os = "macos")]
+ kind: WindowKind::Floating,
+ #[cfg(not(target_os = "macos"))]
kind: WindowKind::Normal,
focus: true,
show: true,
@@ -1578,6 +1577,7 @@ pub fn open_editor_recording_main(editor_path: PathBuf, cx: &mut App) {
let main = cx.global::<AppWindows>().main;
main.update(cx, |view, _, cx| {
view.cancel_deep_link_start();
+ view.show_recorder(cx);
view.clear_target(cx);
cx.notify();
})
diff --git a/apps/desktop-gpui/src/controls_window.rs b/apps/desktop-gpui/src/controls_window.rs
index 50ff84910..b9b9c01de 100644
--- a/apps/desktop-gpui/src/controls_window.rs
+++ b/apps/desktop-gpui/src/controls_window.rs
@@ -118,8 +118,17 @@ impl ControlsWindow {
"Starting".into()
} else if stopping {
"Saving…".into()
+ } else if session.pause_pending() {
+ if session.is_paused() {
+ "Resuming…"
+ } else {
+ "Pausing…"
+ }
+ .into()
} else if error.is_some() {
"Error".into()
+ } else if session.is_paused() {
+ "Paused".into()
} else {
Self::format_elapsed(session.elapsed()).into()
};
@@ -267,7 +276,21 @@ impl ControlsWindow {
let theme = self.theme;
let session = self.session.read(cx);
let paused = session.is_paused();
- let busy = !matches!(session.phase, Phase::Recording { .. });
+ let busy = !matches!(session.phase, Phase::Recording { .. }) || session.pause_unavailable();
+ let pause_pending = session.pause_pending();
+ let pause_tooltip = if session.pause_uncertain() {
+ "Capture state is unconfirmed. Use Stop."
+ } else if pause_pending {
+ if paused {
+ "Resuming recording…"
+ } else {
+ "Pausing recording…"
+ }
+ } else if paused {
+ "Resume recording"
+ } else {
+ "Pause recording"
+ };
div()
.h(px(40.))
@@ -280,6 +303,7 @@ impl ControlsWindow {
.bg(theme.gray_1)
.border_1()
.border_color(theme.gray_5)
+ .when(paused, |this| this.border_color(theme.amber_6))
.shadow(vec![gpui::BoxShadow {
color: gpui::hsla(0., 0., 0., 0.1),
offset: gpui::point(px(0.), px(1.)),
@@ -313,11 +337,22 @@ impl ControlsWindow {
},
busy,
)
+ .when(paused, |this| {
+ this.bg(theme.amber_3)
+ .border_1()
+ .border_color(theme.amber_6)
+ })
+ .when(pause_pending, |this| this.opacity(0.5))
+ .tooltip(move |_, cx| {
+ ui::Tooltip::new(&theme, pause_tooltip).view(cx)
+ })
.when(!busy, |this| {
- this.on_click(cx.listener(|this, _, _, cx| {
- this.session
- .update(cx, |session, cx| session.toggle_pause(cx));
- }))
+ this.active(|style| style.bg(theme.amber_6)).on_click(
+ cx.listener(|this, _, _, cx| {
+ this.session
+ .update(cx, |session, cx| session.toggle_pause(cx));
+ }),
+ )
}),
)
.child(
diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs
index 28d0d599a..d2cf3442c 100644
--- a/apps/desktop-gpui/src/main.rs
+++ b/apps/desktop-gpui/src/main.rs
@@ -71,7 +71,7 @@ use crate::{assets::Assets, main_window::MainWindow, session::RecordingSession};
/// Matches the Tauri main window exactly (`CapWindowId::Main`).
const MAIN_WINDOW_WIDTH: f32 = 330.;
-const MAIN_WINDOW_HEIGHT: f32 = 395.;
+const MAIN_WINDOW_HEIGHT: f32 = 460.;
/// The corner radius the native material is clipped to. `radius = 16` for
/// material `"panel"` on both visual systems in
@@ -269,11 +269,9 @@ fn main() {
window_min_size: Some(size(px(MAIN_WINDOW_WIDTH), px(MAIN_WINDOW_HEIGHT))),
#[cfg(target_os = "linux")]
window_decorations: Some(gpui::WindowDecorations::Client),
- // Stays `Normal` and gets its panel treatment (level 100,
- // all Spaces) from `platform::apply_panel_behavior` below.
- // `WindowKind::Floating` is not the answer: it allocates an
- // NSPanel, and a panel hides itself when the application
- // deactivates -- exactly wrong for a recorder.
+ #[cfg(target_os = "macos")]
+ kind: gpui::WindowKind::Floating,
+ #[cfg(not(target_os = "macos"))]
kind: gpui::WindowKind::Normal,
// The header is dragged by the app via `start_window_move`
// rather than by AppKit, so mark the content view as app-owned
@@ -301,6 +299,22 @@ fn main() {
.detach();
app_windows::init(window_handle, session, cx);
+ #[cfg(target_os = "macos")]
+ match platform::install_native_quit_handler() {
+ Ok(requests) => {
+ cx.spawn(async move |cx| {
+ while requests.recv_async().await.is_ok() {
+ cx.update(menus::quit);
+ }
+ })
+ .detach();
+ }
+ Err(error) => {
+ tracing::error!(%error, "Could not install safe native Quit handling");
+ menus::quit(cx);
+ return;
+ }
+ }
#[cfg(target_os = "linux")]
single_instance::init_linux_reopen(cx);
updates::schedule_startup_check(cx);
diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rs
index 9ec95769c..314b44da3 100644
--- a/apps/desktop-gpui/src/main_window.rs
+++ b/apps/desktop-gpui/src/main_window.rs
@@ -29,7 +29,7 @@ use gpui::{Entity, Task};
/// `MAIN_WINDOW_SIZE.expanded` in index.tsx.
const EXPANDED_WIDTH: f32 = 600.;
-const EXPANDED_HEIGHT: f32 = 660.;
+const EXPANDED_HEIGHT: f32 = 700.;
/// `duration: 180` in `resizeMainWindow`.
const RESIZE_DURATION_SECS: f32 = 0.18;
@@ -396,6 +396,13 @@ impl RecordingStartPermit {
}
}
+struct MicrophoneWarning {
+ config: recording::StartConfig,
+ permit: RecordingStartPermit,
+ dont_show_again: bool,
+ error: Option<String>,
+}
+
pub struct MainWindow {
theme: Theme,
expanded: bool,
@@ -431,6 +438,7 @@ pub struct MainWindow {
session: Entity<RecordingSession>,
checking_storage: bool,
deep_link_start: Option<RecordingStartPermit>,
+ microphone_warning: Option<MicrophoneWarning>,
/// The Recents scan, or `None` while the first one is in flight -- which
/// is the query's `isLoading`, and draws the same three skeleton cards.
recents: Option<Vec<RecentEntry>>,
@@ -624,6 +632,7 @@ impl MainWindow {
session,
checking_storage: false,
deep_link_start: None,
+ microphone_warning: None,
recents: None,
recents_task: None,
library: None,
@@ -1914,6 +1923,24 @@ impl MainWindow {
let Ok(permit) = self.prepare_deep_link_start(cx) else {
return;
};
+ let microphone_available = config.microphone.as_ref().is_some_and(|name| {
+ self.devices
+ .microphones
+ .iter()
+ .any(|device| &device.name == name)
+ });
+ if !microphone_available && crate::store::GeneralSettings::load().confirm_without_microphone
+ {
+ self.microphone_warning = Some(MicrophoneWarning {
+ config,
+ permit,
+ dont_show_again: false,
+ error: None,
+ });
+ cx.defer(app_windows::show_main_window);
+ cx.notify();
+ return;
+ }
self.check_storage_before_start(config, false, permit, cx);
}
@@ -1933,6 +1960,7 @@ impl MainWindow {
}
pub(crate) fn cancel_deep_link_start(&mut self) {
+ self.microphone_warning = None;
if RecordingStartPermit::cancel_current(&mut self.deep_link_start) {
self.checking_storage = false;
}
@@ -1980,6 +2008,40 @@ impl MainWindow {
self.finish_deep_link_start(permit);
}
+ fn confirm_microphone_warning(&mut self, cx: &mut Context<Self>) {
+ let Some(mut warning) = self.microphone_warning.take() else {
+ return;
+ };
+ if !self.recording_start_is_current(&warning.permit, cx) {
+ self.finish_recording_start(&warning.permit);
+ cx.notify();
+ return;
+ }
+ if warning.dont_show_again
+ && !crate::store::set_store_setting(
+ crate::store::RECORDING_START_SAFETY,
+ "confirmBeforeRecordingWithoutMicrophone",
+ serde_json::Value::Bool(false),
+ )
+ {
+ warning.error = Some(
+ "Could not save your preference. Try again or leave the box unchecked.".into(),
+ );
+ self.microphone_warning = Some(warning);
+ cx.notify();
+ return;
+ }
+ warning.config.microphone = None;
+ warning.config.mic_feed = None;
+ self.check_storage_before_start(warning.config, false, warning.permit, cx);
+ cx.notify();
+ }
+
+ fn dismiss_microphone_warning(&mut self, cx: &mut Context<Self>) {
+ self.cancel_deep_link_start();
+ cx.notify();
+ }
+
fn check_storage_before_start(
&mut self,
mut config: recording::StartConfig,
@@ -2304,6 +2366,9 @@ impl Render for MainWindow {
.when(app_windows::clean_capture_pending(cx), |this| {
this.child(self.render_clean_capture_preflight(cx))
})
+ .when(self.microphone_warning.is_some(), |this| {
+ this.child(self.render_microphone_warning(cx))
+ })
.on_key_down(cx.listener(|this, event: &gpui::KeyDownEvent, _, cx| {
if event.keystroke.key == "escape" && this.dismiss_main(cx) {
cx.stop_propagation();
@@ -2313,6 +2378,94 @@ impl Render for MainWindow {
}
impl MainWindow {
+ fn render_microphone_warning(&self, cx: &mut Context<Self>) -> impl IntoElement {
+ let theme = self.theme;
+ let checked = self
+ .microphone_warning
+ .as_ref()
+ .is_some_and(|warning| warning.dont_show_again);
+ let error = self
+ .microphone_warning
+ .as_ref()
+ .and_then(|warning| warning.error.clone());
+ div()
+ .id("microphone-warning")
+ .absolute()
+ .inset_0()
+ .rounded(px(16.))
+ .occlude()
+ .flex()
+ .items_center()
+ .justify_center()
+ .p(px(16.))
+ .bg(theme.shell_bg())
+ .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| cx.stop_propagation())
+ .child(
+ div()
+ .w_full()
+ .max_w(px(360.))
+ .rounded(px(12.))
+ .border_1()
+ .border_color(theme.body_border(6))
+ .bg(theme.gray_1)
+ .p(px(16.))
+ .flex()
+ .flex_col()
+ .gap(px(12.))
+ .child(div().text_size(px(15.)).text_color(theme.gray_12).child("No microphone detected"))
+ .child(
+ div()
+ .text_size(px(12.))
+ .line_height(px(18.))
+ .text_color(theme.gray_11)
+ .child("This recording will not include your voice. Select a microphone, or continue without one."),
+ )
+ .child(
+ div()
+ .id("microphone-warning-dont-show-again")
+ .flex()
+ .items_center()
+ .gap(px(8.))
+ .py(px(4.))
+ .cursor_pointer()
+ .child(
+ div()
+ .size(px(16.))
+ .rounded(px(4.))
+ .border_1()
+ .border_color(if checked { theme.blue_9 } else { theme.gray_7 })
+ .bg(if checked { theme.blue_9 } else { theme.gray_2 })
+ .when(checked, |this| this.child(svg().path("icons/check.svg").size(px(14.)).text_color(rgb(0xffffff)))),
+ )
+ .child(div().text_size(px(12.)).text_color(theme.gray_11).child("Don't show again"))
+ .on_click(cx.listener(|this, _, _, cx| {
+ if let Some(warning) = &mut this.microphone_warning {
+ warning.dont_show_again = !warning.dont_show_again;
+ warning.error = None;
+ }
+ cx.notify();
+ })),
+ )
+ .when_some(error, |this, error| this.child(div().text_size(px(11.)).text_color(theme.red_9).child(error)))
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(8.))
+ .child(
+ ui::Button::plain(&theme, "confirm-without-microphone", ui::ButtonVariant::Blue, ui::ButtonSize::Lg)
+ .label("Record without microphone")
+ .on_click(cx.listener(|this, _, _, cx| this.confirm_microphone_warning(cx))),
+ )
+ .child(
+ ui::Button::plain(&theme, "cancel-without-microphone", ui::ButtonVariant::Gray, ui::ButtonSize::Lg)
+ .label("Go back")
+ .on_click(cx.listener(|this, _, _, cx| this.dismiss_microphone_warning(cx))),
+ ),
+ ),
+ )
+ }
+
fn render_clean_capture_preflight(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
div()
@@ -3127,8 +3280,16 @@ impl MainWindow {
cx.notify();
}
- fn dismiss_main(&mut self, cx: &mut Context<Self>) -> bool {
+ pub(crate) fn show_recorder(&mut self, cx: &mut Context<Self>) {
if self.panel.is_some() {
+ self.close_panel(cx);
+ }
+ }
+
+ fn dismiss_main(&mut self, cx: &mut Context<Self>) -> bool {
+ if self.microphone_warning.is_some() {
+ self.dismiss_microphone_warning(cx);
+ } else if self.panel.is_some() {
if self.search.is_empty() {
self.close_panel(cx);
} else {
@@ -4613,6 +4774,7 @@ impl MainWindow {
/// `mt-[16px] mb-[6px]`, logo `w-[92px]`, Mode pill on the right.
fn render_logo_row(&self, cx: &mut Context<Self>) -> impl IntoElement {
+ let recording_clip = self.session.read(cx).editor_recording_target().is_some();
div()
.flex()
.flex_row()
@@ -4628,10 +4790,41 @@ impl MainWindow {
.flex_row()
.items_center()
.gap(px(4.))
- .child(self.render_logo())
- .child(self.render_plan_badge()),
+ .when(!recording_clip, |this| {
+ this.child(self.render_logo())
+ .child(self.render_plan_badge())
+ })
+ .when(recording_clip, |this| {
+ this.child(
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(4.))
+ .child(div().text_size(px(13.)).child("Record a new clip"))
+ .child(
+ div()
+ .text_size(px(10.))
+ .text_color(self.theme.gray_11)
+ .child("Add to your current project"),
+ ),
+ )
+ }),
+ )
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .items_center()
+ .gap(px(5.))
+ .child(self.render_mode_pill(cx))
+ .child(
+ div()
+ .text_size(px(10.))
+ .line_height(px(12.))
+ .text_color(self.theme.gray_11)
+ .child(format!("{} Mode", self.effective_mode(cx).panel_title())),
+ ),
)
- .child(self.render_mode_pill(cx))
}
/// The plan badge: Personal is `text-[0.6rem] ml-2 rounded-lg border
@@ -4810,20 +5003,14 @@ impl MainWindow {
.gap(px(8.))
.w_full()
.flex_shrink_0()
- .when(self.expanded, |this| {
- this.child(
- // `px-1 pb-0.5` + `text-xs font-semibold text-gray-12`.
- div().px(px(4.)).pb(px(2.)).child(
- div()
- .text_size(px(12.))
- // `font-semibold` (`new-main/index.tsx:3024`)
- // renders 700: no 600 face is loaded over there.
- .font_weight(FontWeight::BOLD)
- .text_color(self.theme.gray_12)
- .child("Capture"),
- ),
- )
- })
+ .child(
+ div()
+ .px(px(4.))
+ .text_size(px(11.))
+ .line_height(px(16.))
+ .text_color(self.theme.gray_11)
+ .child("Choose a capture source"),
+ )
.child(
div()
.flex()
@@ -4874,6 +5061,7 @@ impl MainWindow {
.id(SharedString::from(format!("{}-dropdown", target.label())))
.flex()
.w(px(28.))
+ .rounded_r(px(7.))
.flex_shrink_0()
.items_center()
.justify_center()
@@ -4953,6 +5141,8 @@ impl MainWindow {
.flex()
.flex_1()
.py(px(8.))
+ .when(split, |this| this.rounded_l(px(7.)))
+ .when(!split, |this| this.rounded(px(7.)))
// `hover:bg-blue-4` / `dark:hover:bg-blue-4/40` when selected,
// `hover:bg-gray-4` otherwise.
.hover(move |style| {
@@ -5074,6 +5264,15 @@ impl MainWindow {
})),
),
)
+ .child(
+ div()
+ .px(px(4.))
+ .pt(px(2.))
+ .text_size(px(11.))
+ .line_height(px(16.))
+ .text_color(self.theme.gray_11)
+ .child("Choose your audio devices"),
+ )
.child(
self.labelled(
"Microphone",
diff --git a/apps/desktop-gpui/src/menus.rs b/apps/desktop-gpui/src/menus.rs
index e92abd8e7..fe6a404ad 100644
--- a/apps/desktop-gpui/src/menus.rs
+++ b/apps/desktop-gpui/src/menus.rs
@@ -19,7 +19,10 @@
//! `TextInput` key context, so ⌘Z is a menu key equivalent only while a field
//! is focused and falls through to the editor's own project-undo otherwise.
-use gpui::{AnyWindowHandle, App, KeyBinding, Menu, MenuItem, OsAction, SystemMenuType, actions};
+use gpui::{
+ AnyWindowHandle, App, Global, KeyBinding, Menu, MenuItem, OsAction, Subscription,
+ SystemMenuType, actions,
+};
use crate::{
app_windows::{self, AppWindows},
@@ -287,34 +290,168 @@ pub fn close_window_by_handle(handle: gpui::AnyWindowHandle, cx: &mut App) {
});
}
-/// ⌘Q, the Cap menu's Quit item, and the tray's "Quit Cap".
-///
-/// `request_app_exit` stops a live recording before tearing the app down; the
-/// closest thing here is the session's own stop, which is asynchronous, so the
-/// quit waits for the session to come back to `Idle` (bounded, so a wedged
-/// finalize cannot make the app unquittable).
+const QUIT_STOP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum QuitAction {
+ Wait,
+ Stop,
+ Exit,
+ Failed,
+ TimedOut,
+}
+
+#[derive(Default)]
+struct QuitGate {
+ generation: u64,
+ pending: Option<(u64, bool)>,
+ exit_committed: bool,
+}
+
+impl QuitGate {
+ fn recording_start_allowed(&self) -> bool {
+ !self.exit_committed && self.pending.is_none()
+ }
+
+ fn request(&mut self, phase: Phase) -> Option<(u64, QuitAction)> {
+ if self.exit_committed || self.pending.is_some() {
+ return None;
+ }
+ self.generation = self.generation.wrapping_add(1);
+ let action = match phase {
+ Phase::Idle => QuitAction::Exit,
+ Phase::Starting | Phase::Recording { .. } => QuitAction::Stop,
+ Phase::Stopping => QuitAction::Wait,
+ };
+ if action != QuitAction::Exit {
+ self.pending = Some((self.generation, phase != Phase::Starting));
+ } else {
+ self.exit_committed = true;
+ }
+ Some((self.generation, action))
+ }
+
+ fn advance(
+ &mut self,
+ generation: u64,
+ phase: Phase,
+ failed: bool,
+ timed_out: bool,
+ ) -> QuitAction {
+ let Some((current, stop_requested)) = self.pending.as_mut() else {
+ return QuitAction::Wait;
+ };
+ if *current != generation {
+ return QuitAction::Wait;
+ }
+ let action = if failed {
+ QuitAction::Failed
+ } else if phase == Phase::Idle {
+ QuitAction::Exit
+ } else if timed_out {
+ QuitAction::TimedOut
+ } else {
+ match phase {
+ Phase::Recording { .. } if *stop_requested => QuitAction::Wait,
+ Phase::Recording { .. } => {
+ *stop_requested = true;
+ QuitAction::Stop
+ }
+ Phase::Starting | Phase::Stopping => QuitAction::Wait,
+ Phase::Idle => unreachable!(),
+ }
+ };
+ if matches!(
+ action,
+ QuitAction::Exit | QuitAction::Failed | QuitAction::TimedOut
+ ) {
+ self.pending = None;
+ }
+ if action == QuitAction::Exit {
+ self.exit_committed = true;
+ }
+ action
+ }
+}
+
+#[derive(Default)]
+struct QuitCoordinator {
+ gate: QuitGate,
+ observer: Option<Subscription>,
+}
+
+impl Global for QuitCoordinator {}
+
+pub(crate) fn recording_start_allowed(cx: &App) -> bool {
+ cx.try_global::<QuitCoordinator>()
+ .is_none_or(|coordinator| coordinator.gate.recording_start_allowed())
+}
+
pub fn quit(cx: &mut App) {
let session = RecordingSession::global(cx);
- if session.read(cx).phase == Phase::Idle {
- cx.quit();
+ 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 {
+ return;
+ };
+ if action == QuitAction::Exit {
+ apply_quit_action(action, cx);
return;
}
tracing::info!("quit requested during a recording; stopping it first");
- session.update(cx, |session, cx| session.stop(cx));
+ let observer = cx.observe(&session, move |_, cx| {
+ advance_pending_quit(generation, false, cx)
+ });
+ cx.global_mut::<QuitCoordinator>().observer = Some(observer);
cx.spawn(async move |cx| {
- for _ in 0..100 {
- cx.background_executor()
- .timer(std::time::Duration::from_millis(100))
- .await;
- let idle = cx.update(|cx| session.read(cx).phase == Phase::Idle);
- if idle {
- break;
- }
- }
- cx.update(|cx| cx.quit());
+ cx.background_executor().timer(QUIT_STOP_TIMEOUT).await;
+ cx.update(|cx| advance_pending_quit(generation, true, cx));
})
.detach();
+ apply_quit_action(action, 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 failed = session.read(cx).error.is_some();
+ let action = cx
+ .global_mut::<QuitCoordinator>()
+ .gate
+ .advance(generation, phase, failed, timed_out);
+ apply_quit_action(action, cx);
+}
+
+fn apply_quit_action(action: QuitAction, cx: &mut App) {
+ match action {
+ QuitAction::Wait => {}
+ 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();
+ }
+ QuitAction::Failed | QuitAction::TimedOut => {
+ cx.global_mut::<QuitCoordinator>().observer = None;
+ let message = RecordingSession::global(cx).update(cx, |session, cx| {
+ let message = match session.error.as_deref() {
+ Some(error) => format!("Quit canceled: {error}. Cap will stay open so you can finish or recover the recording."),
+ None if action == QuitAction::TimedOut => "Quit canceled because recording shutdown is still pending. Cap will stay open. Use Stop once available, then try Quit again.".into(),
+ None => "Quit canceled because recording shutdown could not be confirmed. Cap will stay open. Use Stop, then try Quit again.".into(),
+ };
+ session.error = Some(message.clone());
+ cx.notify();
+ message
+ });
+ tracing::warn!(%message);
+ cx.spawn(async move |_| platform::alert_dialog("Cap is still open", &message))
+ .detach();
+ }
+ }
}
// -- The dock icon -----------------------------------------------------------
@@ -449,6 +586,169 @@ fn visible_window_classes(cx: &mut App) -> (bool, bool) {
mod tests {
use super::*;
+ #[test]
+ fn quit_deadline_does_not_authorize_exit_after_a_delayed_stop() {
+ let mut gate = QuitGate::default();
+ let (generation, action) = gate.request(Phase::Recording { paused: false }).unwrap();
+ assert_eq!(action, QuitAction::Stop);
+ assert_eq!(
+ gate.advance(generation, Phase::Stopping, false, false),
+ QuitAction::Wait
+ );
+ assert_eq!(
+ gate.advance(generation, Phase::Stopping, false, true),
+ QuitAction::TimedOut
+ );
+ assert_eq!(
+ gate.advance(generation, Phase::Idle, false, false),
+ QuitAction::Wait
+ );
+ assert!(gate.pending.is_none());
+ }
+
+ #[test]
+ fn failed_stop_cancels_quit_instead_of_exiting_or_retrying_stop() {
+ let mut gate = QuitGate::default();
+ let (generation, _) = gate.request(Phase::Recording { paused: false }).unwrap();
+ assert_eq!(
+ gate.advance(generation, Phase::Stopping, false, false),
+ QuitAction::Wait
+ );
+ assert_eq!(
+ gate.advance(generation, Phase::Recording { paused: false }, true, false),
+ QuitAction::Failed
+ );
+ assert_eq!(
+ gate.advance(generation, Phase::Idle, false, true),
+ QuitAction::Wait
+ );
+ }
+
+ #[test]
+ fn quit_during_startup_stops_the_recording_once_it_starts() {
+ let mut gate = QuitGate::default();
+ let (generation, action) = gate.request(Phase::Starting).unwrap();
+ assert_eq!(action, QuitAction::Stop);
+ assert_eq!(
+ gate.advance(generation, Phase::Starting, false, false),
+ QuitAction::Wait
+ );
+ assert_eq!(
+ gate.advance(generation, Phase::Recording { paused: false }, false, false),
+ QuitAction::Stop
+ );
+ assert_eq!(
+ gate.advance(generation, Phase::Stopping, false, false),
+ QuitAction::Wait
+ );
+ assert_eq!(
+ gate.advance(generation, Phase::Idle, false, false),
+ QuitAction::Exit
+ );
+ }
+
+ #[test]
+ fn quit_waits_when_stop_is_queued_behind_a_pause_acknowledgement() {
+ let mut gate = QuitGate::default();
+ let (generation, action) = gate.request(Phase::Recording { paused: false }).unwrap();
+ assert_eq!(action, QuitAction::Stop);
+ assert_eq!(
+ gate.advance(generation, Phase::Recording { paused: false }, false, false),
+ QuitAction::Wait
+ );
+ assert_eq!(
+ gate.advance(generation, Phase::Recording { paused: true }, false, false),
+ QuitAction::Wait
+ );
+ assert_eq!(
+ gate.advance(generation, Phase::Stopping, false, false),
+ QuitAction::Wait
+ );
+ assert_eq!(
+ gate.advance(generation, Phase::Idle, false, false),
+ QuitAction::Exit
+ );
+ }
+
+ #[test]
+ fn repeated_quit_does_not_replace_the_pending_request() {
+ let mut gate = QuitGate::default();
+ let (generation, _) = gate.request(Phase::Stopping).unwrap();
+ assert_eq!(gate.request(Phase::Stopping), None);
+ assert_eq!(gate.request(Phase::Idle), None);
+ assert_eq!(
+ gate.advance(generation, Phase::Idle, false, false),
+ QuitAction::Exit
+ );
+ }
+
+ #[test]
+ fn idle_quit_has_no_stop_or_deadline_wait() {
+ let mut gate = QuitGate::default();
+ let (_, action) = gate.request(Phase::Idle).unwrap();
+ assert_eq!(action, QuitAction::Exit);
+ assert!(gate.pending.is_none());
+ assert!(gate.exit_committed);
+ }
+
+ #[test]
+ fn committed_exit_closes_recording_admission_before_the_native_callback() {
+ let mut gate = QuitGate::default();
+ assert!(gate.recording_start_allowed());
+ let (generation, _) = gate.request(Phase::Stopping).unwrap();
+ assert!(!gate.recording_start_allowed());
+ assert!(!gate.exit_committed);
+ assert_eq!(
+ gate.advance(generation, Phase::Idle, false, false),
+ QuitAction::Exit
+ );
+ assert!(gate.exit_committed);
+ assert!(!gate.recording_start_allowed());
+ assert_eq!(gate.request(Phase::Idle), None);
+ assert_eq!(
+ gate.advance(generation, Phase::Idle, false, true),
+ QuitAction::Wait
+ );
+ assert!(gate.exit_committed);
+ assert!(!gate.recording_start_allowed());
+ }
+
+ #[test]
+ fn expired_quit_cannot_affect_a_new_recording_or_quit_request() {
+ let mut gate = QuitGate::default();
+ let (old, _) = gate.request(Phase::Stopping).unwrap();
+ assert_eq!(
+ gate.advance(old, Phase::Stopping, false, true),
+ QuitAction::TimedOut
+ );
+ assert!(!gate.exit_committed);
+ assert!(gate.recording_start_allowed());
+ let (current, _) = gate.request(Phase::Recording { paused: false }).unwrap();
+ assert_eq!(
+ gate.advance(old, Phase::Idle, false, true),
+ QuitAction::Wait
+ );
+ assert_eq!(
+ gate.advance(current, Phase::Stopping, false, false),
+ QuitAction::Wait
+ );
+ assert_eq!(
+ gate.advance(current, Phase::Idle, false, false),
+ QuitAction::Exit
+ );
+ }
+
+ #[test]
+ fn completed_capture_with_finalization_error_does_not_exit() {
+ let mut gate = QuitGate::default();
+ let (generation, _) = gate.request(Phase::Stopping).unwrap();
+ assert_eq!(
+ gate.advance(generation, Phase::Idle, true, false),
+ QuitAction::Failed
+ );
+ assert!(gate.pending.is_none());
+ }
+
/// The menu bar, transcribed from `build_macos_app_menu`. Separators are
/// spelled `"-"` so the ordering is checked too.
fn describe(menu: &Menu) -> (String, Vec<String>) {
diff --git a/apps/desktop-gpui/src/platform.rs b/apps/desktop-gpui/src/platform.rs
index 32d454358..0b4a0c6e3 100644
--- a/apps/desktop-gpui/src/platform.rs
+++ b/apps/desktop-gpui/src/platform.rs
@@ -7,13 +7,6 @@
//! `raw_window_handle::HasWindowHandle`, and on macOS the AppKit handle's
//! `ns_view` reaches the `NSWindow`, where the same AppKit calls apply.
//!
-//! A plain `NSWindow` with `FullScreenPrimary` stays off other apps'
-//! fullscreen Spaces. Tauri swizzles to `NSPanel` and the nspanel fullscreen
-//! sample uses `CanJoinAllSpaces | FullScreenAuxiliary`. We promote
-//! `GPUIWindow` to `GPUIPanel` (same ivar layout, already registered) and
-//! apply that collection behavior so the recorder stays above Chrome
-//! fullscreen the way the Tauri app does.
-//!
//! Everything here must run on the main thread. gpui's foreground executor is
//! the main thread, and every caller sits inside a `Window` update, so that
//! holds by construction.
@@ -54,6 +47,42 @@ pub struct WindowMaterial(pub Option<MaterialKind>);
impl gpui::Global for WindowMaterial {}
+#[cfg(any(target_os = "macos", test))]
+struct NativeQuitRequests {
+ sender: flume::Sender<()>,
+ permitted: std::sync::atomic::AtomicBool,
+}
+
+#[cfg(any(target_os = "macos", test))]
+impl NativeQuitRequests {
+ fn new() -> (Self, flume::Receiver<()>) {
+ let (sender, receiver) = flume::bounded(1);
+ (
+ Self {
+ sender,
+ permitted: std::sync::atomic::AtomicBool::new(false),
+ },
+ receiver,
+ )
+ }
+
+ fn permit_exit(&self) {
+ self.permitted
+ .store(true, std::sync::atomic::Ordering::Release);
+ }
+
+ fn request(&self) -> bool {
+ if self
+ .permitted
+ .swap(false, std::sync::atomic::Ordering::AcqRel)
+ {
+ return true;
+ }
+ let _ = self.sender.try_send(());
+ false
+ }
+}
+
pub fn active_material(cx: &gpui::App) -> Option<MaterialKind> {
cx.try_global::<WindowMaterial>()
.and_then(|material| material.0)
@@ -95,6 +124,68 @@ mod mac {
use super::{ForcedAppearance, MaterialKind, PanelBehavior};
+ static NATIVE_QUIT_REQUESTS: std::sync::OnceLock<super::NativeQuitRequests> =
+ std::sync::OnceLock::new();
+
+ unsafe extern "C-unwind" fn application_should_terminate(
+ _: &AnyObject,
+ _: Sel,
+ _: *mut AnyObject,
+ ) -> usize {
+ usize::from(
+ NATIVE_QUIT_REQUESTS
+ .get()
+ .is_some_and(|requests| requests.request()),
+ )
+ }
+
+ pub fn install_native_quit_handler() -> Result<flume::Receiver<()>, String> {
+ use objc2::{class, ffi, msg_send, runtime::Imp, sel};
+ use objc2_foundation::MainThreadMarker;
+
+ let _main_thread =
+ MainThreadMarker::new().ok_or("Native Quit must be installed on the main thread")?;
+ unsafe {
+ let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
+ let app = app.as_ref().ok_or("NSApplication is unavailable")?;
+ let delegate: *mut AnyObject = msg_send![app, delegate];
+ let delegate = delegate
+ .as_ref()
+ .ok_or("Application delegate is unavailable")?;
+ let delegate_class = delegate.class();
+ if delegate_class.name() != "GPUIApplicationDelegate" {
+ return Err("Native Quit requires the owned GPUI application delegate".into());
+ }
+ let selector = sel!(applicationShouldTerminate:);
+ if delegate_class.instance_method(selector).is_some() {
+ return Err("Application delegate already has a native Quit handler".into());
+ }
+ let (requests, receiver) = super::NativeQuitRequests::new();
+ NATIVE_QUIT_REQUESTS
+ .set(requests)
+ .map_err(|_| "Native Quit request receiver was already installed")?;
+ let implementation = std::mem::transmute::<
+ unsafe extern "C-unwind" fn(&AnyObject, Sel, *mut AnyObject) -> usize,
+ Imp,
+ >(application_should_terminate);
+ if !ffi::class_addMethod(
+ delegate_class as *const _ as *mut _,
+ selector.as_ptr(),
+ Some(implementation),
+ c"Q@:@".as_ptr(),
+ ) {
+ return Err("Could not install the native Quit handler".into());
+ }
+ Ok(receiver)
+ }
+ }
+
+ pub fn permit_native_quit() {
+ if let Some(requests) = NATIVE_QUIT_REQUESTS.get() {
+ requests.permit_exit();
+ }
+ }
+
pub fn apply_window_theme(window: &Window, appearance: ForcedAppearance) {
use objc2_app_kit::{
NSAppearance, NSAppearanceCustomization, NSAppearanceNameAqua, NSAppearanceNameDarkAqua,
@@ -194,13 +285,14 @@ mod mac {
// at the bottom, where nothing overlaps it). Radius must match what
// the window's root element draws, not what looks close.
content_view.setWantsLayer(true);
- unsafe {
+ let set_clip_radius = |radius: f64| unsafe {
let layer: *mut AnyObject = msg_send![&*content_view, layer];
if !layer.is_null() {
let _: () = msg_send![layer, setCornerRadius: radius];
let _: () = msg_send![layer, setMasksToBounds: true];
}
- }
+ };
+ set_clip_radius(16.0);
let bounds = content_view.bounds();
@@ -221,27 +313,23 @@ mod mac {
unsafe {
let glass: *mut AnyObject = msg_send![glass_class, alloc];
let glass: *mut AnyObject = msg_send![glass, initWithFrame: bounds];
- if !glass.is_null() {
+ if let Some(glass) = Id::from_raw(glass) {
+ set_clip_radius(radius);
let identifier = NSString::from_str(LIQUID_GLASS_IDENTIFIER);
- let _: () = msg_send![glass, setIdentifier: &*identifier];
+ let _: () = msg_send![&*glass, setIdentifier: &*identifier];
let responds: bool =
- msg_send![glass, respondsToSelector: sel!(setCornerRadius:)];
+ msg_send![&*glass, respondsToSelector: sel!(setCornerRadius:)];
if responds {
- let _: () = msg_send![glass, setCornerRadius: radius];
+ let _: () = msg_send![&*glass, setCornerRadius: radius];
}
- let _: () = msg_send![glass, setStyle: NS_GLASS_EFFECT_VIEW_STYLE_REGULAR];
- let _: () = msg_send![glass, setAutoresizingMask: NS_VIEW_WIDTH_HEIGHT_SIZABLE];
- // The `alloc` claim is deliberately not balanced: the view
- // lives for the life of the process (there is no teardown
- // path here, unlike the Tauri command that can be called
- // with `enabled: false`), and the superview's retain is
- // what keeps it alive. Same steady state the shipping app
- // sits in after a single apply.
+ let _: () = msg_send![&*glass, setStyle: NS_GLASS_EFFECT_VIEW_STYLE_REGULAR];
+ let _: () =
+ msg_send![&*glass, setAutoresizingMask: NS_VIEW_WIDTH_HEIGHT_SIZABLE];
let _: () = msg_send![
&*content_view,
- addSubview: glass,
+ addSubview: &*glass,
positioned: NSWindowOrderingMode::NSWindowBelow,
relativeTo: std::ptr::null_mut::<AnyObject>(),
];
@@ -637,7 +725,8 @@ mod mac {
/// documents for floating over those Spaces, and it is what
/// tauri-nspanel's fullscreen example sets after the panel swizzle.
fn apply_fullscreen_overlay_behavior(ns_window: &NSWindow) {
- promote_to_gpui_panel(ns_window);
+ // Changing an initialized NSWindow's class breaks AppKit's KVO teardown.
+ // Callers that need a panel must create it as Floating or PopUp.
unsafe {
ns_window.setCollectionBehavior(
NSWindowCollectionBehavior::CanJoinAllSpaces
@@ -654,34 +743,6 @@ mod mac {
}
}
- /// `object_setClass` from `GPUIWindow` to `GPUIPanel` -- the gpui spelling
- /// of tauri-nspanel's `to_panel()`. Both classes are built with the same
- /// ivar (`WINDOW_STATE_IVAR`); if the sizes ever diverge we leave the
- /// window as-is and rely on the collection-behavior flags alone.
- fn promote_to_gpui_panel(ns_window: &NSWindow) {
- use objc2::runtime::{AnyClass, AnyObject};
-
- let class = ns_window.class();
- if class.name() != "GPUIWindow" {
- return;
- }
- let Some(panel) = AnyClass::get("GPUIPanel") else {
- return;
- };
- if class.instance_size() != panel.instance_size() {
- tracing::warn!(
- window_size = class.instance_size(),
- panel_size = panel.instance_size(),
- "GPUIWindow/GPUIPanel instance sizes differ; not promoting to panel"
- );
- return;
- }
- unsafe {
- AnyObject::set_class(ns_window.as_ref(), panel);
- }
- tracing::info!("promoted GPUIWindow to GPUIPanel for fullscreen overlay");
- }
-
/// `NSWindow.setAlphaValue:` -- the whole of
/// `crate::platform::set_window_opacity` in the Tauri app, which is what
/// `set_teleprompter_window_opacity` calls with
@@ -1850,6 +1911,64 @@ pub use stub::*;
#[cfg(test)]
mod tests {
+ #[test]
+ fn native_quit_permission_is_consumed_by_exactly_one_callback() {
+ let (requests, receiver) = super::NativeQuitRequests::new();
+ requests.permit_exit();
+ assert!(requests.request());
+ assert!(receiver.try_recv().is_err());
+ assert!(!requests.request());
+ assert_eq!(receiver.try_recv(), Ok(()));
+ assert!(receiver.try_recv().is_err());
+ }
+
+ #[test]
+ fn concurrent_native_quit_requests_are_cancelled_and_coalesced() {
+ let (requests, receiver) = super::NativeQuitRequests::new();
+ let requests = std::sync::Arc::new(requests);
+ let threads: Vec<_> = (0..8)
+ .map(|_| {
+ let requests = requests.clone();
+ std::thread::spawn(move || requests.request())
+ })
+ .collect();
+ for thread in threads {
+ assert!(!thread.join().unwrap());
+ }
+ assert_eq!(receiver.try_recv(), Ok(()));
+ assert!(receiver.try_recv().is_err());
+ assert!(!requests.request());
+ assert_eq!(receiver.try_recv(), Ok(()));
+ }
+
+ #[test]
+ fn concurrent_native_callbacks_cannot_reuse_an_exit_permit() {
+ let (requests, receiver) = super::NativeQuitRequests::new();
+ requests.permit_exit();
+ let requests = std::sync::Arc::new(requests);
+ let threads: Vec<_> = (0..8)
+ .map(|_| {
+ let requests = requests.clone();
+ std::thread::spawn(move || requests.request())
+ })
+ .collect();
+ let permitted = threads
+ .into_iter()
+ .map(|thread| thread.join().unwrap())
+ .filter(|permitted| *permitted)
+ .count();
+ assert_eq!(permitted, 1);
+ assert_eq!(receiver.try_recv(), Ok(()));
+ assert!(receiver.try_recv().is_err());
+ }
+
+ #[test]
+ fn missing_native_quit_consumer_never_authorizes_termination() {
+ let (requests, receiver) = super::NativeQuitRequests::new();
+ drop(receiver);
+ assert!(!requests.request());
+ }
+
#[test]
fn confirmation_accepts_native_ok_and_matching_custom_label_only() {
let accept = "Install update";
diff --git a/apps/desktop-gpui/src/recording.rs b/apps/desktop-gpui/src/recording.rs
index 4b1404cb9..9a3973a92 100644
--- a/apps/desktop-gpui/src/recording.rs
+++ b/apps/desktop-gpui/src/recording.rs
@@ -596,7 +596,6 @@ impl ActiveRecording {
}
}
- #[cfg(target_os = "linux")]
pub fn is_paused_handle(
&self,
) -> std::pin::Pin<Box<dyn Future<Output = anyhow::Result<bool>> + Send>> {
diff --git a/apps/desktop-gpui/src/session.rs b/apps/desktop-gpui/src/session.rs
index 9a155787f..f4746dd24 100644
--- a/apps/desktop-gpui/src/session.rs
+++ b/apps/desktop-gpui/src/session.rs
@@ -23,6 +23,114 @@ pub enum Phase {
Stopping,
}
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct PauseControlTicket {
+ generation: u64,
+ sequence: u64,
+ paused: bool,
+}
+
+struct PendingPauseControl {
+ ticket: PauseControlTicket,
+ abort: futures_util::future::AbortHandle,
+}
+
+#[derive(Default)]
+struct PauseControlState {
+ pending: Option<PendingPauseControl>,
+ sequence: u64,
+ uncertain: bool,
+}
+
+impl PauseControlState {
+ fn begin(
+ &mut self,
+ generation: u64,
+ paused: bool,
+ ) -> Option<(PauseControlTicket, futures_util::future::AbortRegistration)> {
+ if self.pending.is_some() || self.uncertain {
+ return None;
+ }
+ self.sequence = self.sequence.wrapping_add(1);
+ let ticket = PauseControlTicket {
+ generation,
+ sequence: self.sequence,
+ paused,
+ };
+ let (abort, registration) = futures_util::future::AbortHandle::new_pair();
+ self.pending = Some(PendingPauseControl {
+ ticket: ticket.clone(),
+ abort,
+ });
+ Some((ticket, registration))
+ }
+
+ fn invalidate(&mut self) {
+ if let Some(pending) = self.pending.take() {
+ pending.abort.abort();
+ }
+ }
+
+ fn cancel_for_stop(&mut self) {
+ self.uncertain |= self.pending.is_some();
+ self.invalidate();
+ }
+
+ fn complete(
+ &mut self,
+ ticket: &PauseControlTicket,
+ generation: u64,
+ phase: Phase,
+ paused: Option<bool>,
+ ) -> bool {
+ if generation != ticket.generation
+ || !matches!(phase, Phase::Recording { .. })
+ || self
+ .pending
+ .as_ref()
+ .is_none_or(|pending| pending.ticket != *ticket)
+ {
+ return false;
+ }
+ self.pending = None;
+ self.uncertain = paused.is_none();
+ true
+ }
+}
+
+struct PauseControlOutcome {
+ paused: Option<bool>,
+ error: Option<String>,
+}
+
+async fn run_pause_control(
+ expected_paused: bool,
+ control: impl Future<Output = anyhow::Result<()>>,
+ query_paused: impl Future<Output = anyhow::Result<bool>>,
+) -> PauseControlOutcome {
+ let result = control.await;
+ let state = tokio::time::timeout(Duration::from_secs(2), query_paused).await;
+ let (paused, state_error) = match state {
+ Ok(Ok(true)) => (Some(true), None),
+ Ok(Ok(false)) if result.is_ok() => (Some(false), None),
+ Ok(Ok(false)) => (None, None),
+ Ok(Err(error)) => (
+ None,
+ Some(format!("Could not confirm capture state: {error:#}")),
+ ),
+ Err(_) => (None, Some("Timed out confirming capture state".into())),
+ };
+ let error = result
+ .err()
+ .map(|error| format!("{error:#}"))
+ .or(state_error)
+ .or_else(|| {
+ (paused != Some(expected_paused))
+ .then(|| "Capture did not acknowledge the requested pause state".into())
+ });
+ PauseControlOutcome { paused, error }
+}
+
#[cfg(target_os = "linux")]
#[derive(Clone, Debug, PartialEq, Eq)]
struct RecordingOwner {
@@ -242,6 +350,8 @@ pub struct RecordingSession {
storage_monitor: Option<Task<()>>,
failure_monitor: Option<Task<()>>,
recording_generation: u64,
+ pause_control: PauseControlState,
+ pause_control_error: Option<String>,
#[cfg(target_os = "linux")]
instant_attempt: Option<recording::InstantAttempt>,
#[cfg(target_os = "linux")]
@@ -279,6 +389,8 @@ impl RecordingSession {
storage_monitor: None,
failure_monitor: None,
recording_generation: 0,
+ pause_control: PauseControlState::default(),
+ pause_control_error: None,
#[cfg(target_os = "linux")]
instant_attempt: None,
#[cfg(target_os = "linux")]
@@ -328,6 +440,26 @@ impl RecordingSession {
matches!(self.phase, Phase::Recording { paused: true })
}
+ pub fn pause_pending(&self) -> bool {
+ #[cfg(target_os = "linux")]
+ if self.clean_control.pending.is_some() {
+ return true;
+ }
+ self.pause_control.pending.is_some()
+ }
+
+ pub fn pause_uncertain(&self) -> bool {
+ #[cfg(target_os = "linux")]
+ if self.clean_control.uncertain {
+ return true;
+ }
+ self.pause_control.uncertain
+ }
+
+ pub fn pause_unavailable(&self) -> bool {
+ self.pause_pending() || self.pause_uncertain() || self.pipeline_failed
+ }
+
/// The live (or last) recording's mode -- the bar exposes mic mute for
/// instant recordings only (studio records the mic as an editable track,
/// where muted spans would silently bake zeros in).
@@ -386,9 +518,16 @@ impl RecordingSession {
if self.phase != Phase::Idle {
return;
}
+ if !crate::menus::recording_start_allowed(cx) {
+ cx.notify();
+ return;
+ }
self.storage_monitor = None;
self.failure_monitor = None;
self.recording_generation = self.recording_generation.wrapping_add(1);
+ self.pause_control.invalidate();
+ self.pause_control.uncertain = false;
+ self.pause_control_error = None;
self.pipeline_failed = false;
#[cfg(target_os = "linux")]
{
@@ -732,6 +871,7 @@ impl RecordingSession {
self.stop_requested = false;
}
self.stopped_elapsed = Some(self.elapsed());
+ self.pause_control.cancel_for_stop();
self.phase = Phase::Stopping;
cx.notify();
@@ -842,28 +982,70 @@ impl RecordingSession {
let Some(active) = self.active.as_ref() else {
return;
};
-
- // Optimistic flip; the actor call is fire-and-logged. The Tauri app
- // does the same through its mutation -- there is no rollback UI.
- self.phase = Phase::Recording { paused: !paused };
- if paused {
- if let Some(since) = self.paused_since.take() {
- self.paused_accum += since.elapsed();
- }
- } else {
- self.paused_since = Some(Instant::now());
+ if self.pipeline_failed {
+ return;
}
- cx.notify();
-
+ let Some((ticket, registration)) =
+ self.pause_control.begin(self.recording_generation, !paused)
+ else {
+ return;
+ };
let control = if paused {
active.resume_handle()
} else {
active.pause_handle()
};
- gpui_tokio::Tokio::spawn(cx, async move {
- if let Err(error) = control.await {
- tracing::error!("pause/resume failed: {error:#}");
- }
+ let query_paused = active.is_paused_handle();
+ cx.notify();
+ let task = gpui_tokio::Tokio::spawn(
+ cx,
+ futures_util::future::Abortable::new(
+ run_pause_control(ticket.paused, control, query_paused),
+ registration,
+ ),
+ );
+ cx.spawn(async move |this, cx| {
+ let outcome = match task.await {
+ Ok(Ok(outcome)) => outcome,
+ Ok(Err(_)) => return,
+ Err(error) => PauseControlOutcome {
+ paused: None,
+ error: Some(format!("Capture control task failed: {error}")),
+ },
+ };
+ this.update(cx, |this, cx| {
+ if !this.pause_control.complete(
+ &ticket,
+ this.recording_generation,
+ this.phase,
+ outcome.paused,
+ ) {
+ return;
+ }
+ if let Some(paused) = outcome.paused {
+ let was_paused = this.is_paused();
+ this.phase = Phase::Recording { paused };
+ if was_paused && !paused {
+ if let Some(since) = this.paused_since.take() {
+ this.paused_accum += since.elapsed();
+ }
+ } else if !was_paused && paused {
+ this.paused_since = Some(Instant::now());
+ }
+ }
+ if this.pause_control_error.is_some() && this.error == this.pause_control_error {
+ this.error = None;
+ }
+ this.pause_control_error = outcome
+ .error
+ .map(|error| format!("{error}. Use Stop if recording cannot continue safely."));
+ if let Some(error) = &this.pause_control_error {
+ tracing::error!(%error, "pause/resume failed");
+ this.error = Some(error.clone());
+ }
+ cx.notify();
+ })
+ .ok();
})
.detach();
}
@@ -1028,6 +1210,9 @@ impl RecordingSession {
/// Cancel the live recording and delete its project directory (the bar's
/// trash button).
pub fn delete(&mut self, cx: &mut Context<Self>) {
+ if self.pause_unavailable() {
+ return;
+ }
#[cfg(target_os = "linux")]
if self.clean_control.pending.is_some() || self.clean_control.uncertain {
return;
@@ -1065,6 +1250,9 @@ impl RecordingSession {
/// The bar's restart button: throw away the live recording and immediately
/// start a new one with the same config.
pub fn restart(&mut self, cx: &mut Context<Self>) {
+ if !crate::menus::recording_start_allowed(cx) || self.pause_unavailable() {
+ return;
+ }
#[cfg(target_os = "linux")]
if self.clean_control.pending.is_some() || self.clean_control.uncertain {
return;
@@ -1340,6 +1528,9 @@ impl RecordingSession {
self.show_controls_after_pause = false;
}
self.failure_monitor = None;
+ self.pause_control.invalidate();
+ self.pause_control.uncertain = false;
+ self.pause_control_error = None;
self.pipeline_failed = false;
self.storage_monitor = None;
self.phase = Phase::Idle;
@@ -1814,3 +2005,114 @@ mod recording_failure_tests {
}
}
}
+
+#[cfg(test)]
+mod pause_control_tests {
+ use super::*;
+
+ #[test]
+ fn rapid_toggle_does_not_dispatch_a_second_control() {
+ let mut state = PauseControlState::default();
+ let (ticket, _) = state.begin(1, true).unwrap();
+ assert!(state.begin(1, false).is_none());
+ assert!(state.complete(&ticket, 1, Phase::Recording { paused: false }, Some(true)));
+ assert!(state.begin(1, false).is_some());
+ }
+
+ #[test]
+ fn late_pause_acknowledgments_cannot_change_a_stopped_or_new_recording() {
+ for phase in [Phase::Idle, Phase::Starting, Phase::Stopping] {
+ let mut state = PauseControlState::default();
+ let (ticket, _) = state.begin(1, true).unwrap();
+ assert!(!state.complete(&ticket, 1, phase, Some(true)));
+ }
+ let mut state = PauseControlState::default();
+ let (old, _) = state.begin(1, true).unwrap();
+ state.invalidate();
+ let (new, _) = state.begin(2, true).unwrap();
+ assert!(!state.complete(&old, 2, Phase::Recording { paused: false }, Some(true)));
+ assert!(state.complete(&new, 2, Phase::Recording { paused: false }, Some(true)));
+ }
+
+ #[test]
+ fn a_stop_retry_does_not_accept_a_late_pause_or_resume_unconfirmed_capture() {
+ let mut state = PauseControlState::default();
+ let (old, _) = state.begin(1, true).unwrap();
+ state.cancel_for_stop();
+ assert!(state.uncertain);
+ assert!(state.begin(1, false).is_none());
+ assert!(!state.complete(&old, 1, Phase::Recording { paused: false }, Some(true)));
+ }
+
+ #[tokio::test]
+ async fn pause_is_not_confirmed_before_the_actor_acknowledges_and_reports_it() {
+ let (send, receive) = tokio::sync::oneshot::channel();
+ let queried = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let observed = queried.clone();
+ let mut control = Box::pin(run_pause_control(
+ true,
+ async {
+ receive.await?;
+ Ok(())
+ },
+ async move {
+ observed.store(true, std::sync::atomic::Ordering::SeqCst);
+ Ok(true)
+ },
+ ));
+ assert!(futures_util::poll!(&mut control).is_pending());
+ assert!(!queried.load(std::sync::atomic::Ordering::SeqCst));
+ send.send(()).unwrap();
+ let outcome = control.await;
+ assert_eq!(outcome.paused, Some(true));
+ assert!(outcome.error.is_none());
+ }
+
+ #[tokio::test]
+ async fn failed_pause_does_not_claim_capture_is_paused_or_allow_an_unsafe_retry() {
+ let outcome = run_pause_control(
+ true,
+ async { anyhow::bail!("pipeline shutdown failed") },
+ async { Ok(false) },
+ )
+ .await;
+ assert_eq!(outcome.paused, None);
+ assert!(outcome.error.unwrap().contains("pipeline shutdown failed"));
+ let mut state = PauseControlState::default();
+ let (ticket, _) = state.begin(1, true).unwrap();
+ assert!(state.complete(
+ &ticket,
+ 1,
+ Phase::Recording { paused: false },
+ outcome.paused
+ ));
+ assert!(state.uncertain);
+ assert!(state.begin(1, true).is_none());
+ }
+
+ #[tokio::test]
+ async fn failed_resume_preserves_a_confirmed_pause_and_reports_the_failure() {
+ let outcome =
+ run_pause_control(false, async { anyhow::bail!("input unavailable") }, async {
+ Ok(true)
+ })
+ .await;
+ assert_eq!(outcome.paused, Some(true));
+ assert!(outcome.error.unwrap().contains("input unavailable"));
+ }
+
+ #[tokio::test]
+ async fn stop_cancels_an_unstarted_pause_request() {
+ let mut state = PauseControlState::default();
+ let (_, registration) = state.begin(1, true).unwrap();
+ let polled = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let observed = polled.clone();
+ let control = futures_util::future::Abortable::new(
+ async move { observed.store(true, std::sync::atomic::Ordering::SeqCst) },
+ registration,
+ );
+ state.invalidate();
+ assert!(control.await.is_err());
+ assert!(!polled.load(std::sync::atomic::Ordering::SeqCst));
+ }
+}
diff --git a/apps/desktop-gpui/src/teleprompter_window.rs b/apps/desktop-gpui/src/teleprompter_window.rs
index 67885e840..cd5acac6b 100644
--- a/apps/desktop-gpui/src/teleprompter_window.rs
+++ b/apps/desktop-gpui/src/teleprompter_window.rs
@@ -31,6 +31,7 @@ use gpui::{
use crate::{
platform,
+ session::{Phase, RecordingSession},
store::{self, TeleprompterState},
theme::Theme,
ui,
@@ -150,6 +151,28 @@ struct PendingSave {
keys: BTreeSet<&'static str>,
}
+#[derive(Default)]
+struct PlaybackState {
+ requested: bool,
+ recording_paused: bool,
+ recording_active: bool,
+}
+
+impl PlaybackState {
+ fn running(&self) -> bool {
+ self.requested && !self.recording_paused
+ }
+
+ fn update_recording(&mut self, phase: Phase, uncertain: bool) {
+ if phase == Phase::Stopping || (phase == Phase::Idle && self.recording_active) {
+ self.requested = false;
+ }
+ self.recording_active = phase != Phase::Idle;
+ self.recording_paused =
+ matches!(phase, Phase::Recording { paused: true } | Phase::Stopping) || uncertain;
+ }
+}
+
impl PendingSave {
fn flush(&mut self) {
if self.keys.is_empty() {
@@ -169,7 +192,7 @@ pub struct TeleprompterWindow {
theme: Theme,
state: TeleprompterState,
settings_open: bool,
- playing: bool,
+ playback_state: PlaybackState,
/// Scroll offset in pixels from the top, positive. gpui's own offset is the
/// negative of it.
position: f32,
@@ -183,6 +206,7 @@ pub struct TeleprompterWindow {
/// store write all read it from `&self`.
script_input: Entity<ui::TextInputState>,
_script_events: gpui::Subscription,
+ _recording_events: gpui::Subscription,
/// Track rects, captured in prepaint: the window is resizable, so neither
/// pill's width is known here.
speed_track: Rc<Cell<Option<Bounds<Pixels>>>>,
@@ -237,17 +261,35 @@ impl TeleprompterWindow {
},
);
+ let session = RecordingSession::global(cx);
+ let mut playback_state = PlaybackState::default();
+ playback_state.update_recording(session.read(cx).phase, session.read(cx).pause_uncertain());
+ let recording_events = cx.observe_in(&session, window, |this, session, window, cx| {
+ let session = session.read(cx);
+ let was_running = this.playback_state.running();
+ this.playback_state
+ .update_recording(session.phase, session.pause_uncertain());
+ if !this.playback_state.running() {
+ this.playback = None;
+ } else if !was_running {
+ this.start_playback(window, cx);
+ }
+ cx.notify();
+ window.refresh();
+ });
+
crate::theme::bind_window(window, cx);
Self {
theme: Theme::for_window(window, cx, true),
state,
settings_open: false,
- playing: false,
+ playback_state,
position: 0.,
scroll: ScrollHandle::new(),
focus: cx.focus_handle(),
script_input,
_script_events: script_events,
+ _recording_events: recording_events,
speed_track: Rc::new(Cell::new(None)),
opacity_track: Rc::new(Cell::new(None)),
dragging: None,
@@ -344,17 +386,17 @@ impl TeleprompterWindow {
}
fn stop_playback(&mut self) {
- self.playing = false;
+ self.playback_state.requested = false;
self.playback = None;
}
pub fn is_playing(&self) -> bool {
- self.playing
+ self.playback_state.running()
}
/// `togglePlayback`.
pub fn toggle_playback(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- if self.playing {
+ if self.playback_state.requested {
self.stop_playback();
cx.notify();
return;
@@ -371,9 +413,19 @@ impl TeleprompterWindow {
// `if (element.scrollTop >= maximumScroll - 1) element.scrollTop = 0`
if self.position >= maximum - 1. {
self.position = 0.;
+ self.apply_scroll();
}
self.settings_open = false;
- self.playing = true;
+ self.playback_state.requested = true;
+ self.start_playback(window, cx);
+ cx.notify();
+ }
+
+ fn start_playback(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ if !self.playback_state.running() {
+ return;
+ }
+ self.position = (-f32::from(self.scroll.offset().y)).clamp(0., self.maximum_scroll());
// An inactive window only repaints when asked, so the tick both
// notifies and calls `refresh` -- the same rule the recording bar's
@@ -383,7 +435,10 @@ impl TeleprompterWindow {
loop {
cx.background_executor().timer(PLAYBACK_TICK).await;
let now = Instant::now();
- let elapsed = (now - last).as_secs_f32().min(MAX_TICK_SECONDS);
+ let elapsed = now
+ .saturating_duration_since(last)
+ .as_secs_f32()
+ .min(MAX_TICK_SECONDS);
last = now;
let running = this
.update_in(cx, |this, window, cx| {
@@ -404,9 +459,12 @@ impl TeleprompterWindow {
/// One frame of `animatePlayback`. Returns false when the loop should stop
/// -- bottom reached, or nothing left to scroll.
fn advance(&mut self, elapsed: f32) -> bool {
+ if !self.playback_state.running() {
+ return false;
+ }
let maximum = self.maximum_scroll();
if maximum <= 1. {
- self.playing = false;
+ self.playback_state.requested = false;
return false;
}
@@ -419,7 +477,7 @@ impl TeleprompterWindow {
self.apply_scroll();
if self.position >= maximum - 0.5 {
- self.playing = false;
+ self.playback_state.requested = false;
return false;
}
true
@@ -563,6 +621,7 @@ impl TeleprompterWindow {
.w_full()
.h(px(HEADER_HEIGHT))
.flex_shrink_0()
+ .rounded_t(px(theme.teleprompter_window_radius()))
.bg(theme.header_bg())
.child(
// `pointer-events-none ml-auto flex items-center gap-1.5
@@ -591,7 +650,11 @@ impl TeleprompterWindow {
.flex_shrink_0()
.text_color(Hsla::from(theme.gray_9)),
)
- .child("This window is hidden from Cap recordings"),
+ .child(if self.playback_state.recording_paused {
+ "Scrolling paused with recording"
+ } else {
+ "This window is hidden from Cap recordings"
+ }),
);
#[cfg(target_os = "windows")]
@@ -724,7 +787,7 @@ impl TeleprompterWindow {
/// `flex h-11 shrink-0 items-center px-3 pb-2`.
fn render_footer(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
- let playing = self.playing;
+ let playing = self.playback_state.requested;
let enabled = self.has_script();
div()
@@ -1030,6 +1093,58 @@ impl TeleprompterWindow {
mod tests {
use super::*;
+ #[test]
+ fn recording_pause_preserves_manual_playback_intent() {
+ let mut playback = PlaybackState {
+ requested: true,
+ ..Default::default()
+ };
+ playback.update_recording(Phase::Recording { paused: false }, false);
+ assert!(playback.running());
+ playback.update_recording(Phase::Recording { paused: true }, false);
+ assert!(!playback.running());
+ assert!(playback.requested);
+ playback.update_recording(Phase::Recording { paused: false }, false);
+ assert!(playback.running());
+ }
+
+ #[test]
+ fn recording_resume_does_not_start_a_manually_paused_script() {
+ let mut playback = PlaybackState::default();
+ playback.update_recording(Phase::Recording { paused: true }, false);
+ playback.update_recording(Phase::Recording { paused: false }, false);
+ assert!(!playback.running());
+ playback.requested = true;
+ playback.update_recording(Phase::Recording { paused: true }, false);
+ playback.requested = false;
+ playback.update_recording(Phase::Recording { paused: false }, false);
+ assert!(!playback.running());
+ }
+
+ #[test]
+ fn play_cannot_override_recording_pause_or_unconfirmed_capture_state() {
+ for uncertain in [false, true] {
+ let mut playback = PlaybackState::default();
+ playback.update_recording(Phase::Recording { paused: !uncertain }, uncertain);
+ playback.requested = true;
+ assert!(!playback.running());
+ }
+ }
+
+ #[test]
+ fn recording_stop_clears_automatic_scroll_resume() {
+ for terminal in [Phase::Stopping, Phase::Idle] {
+ let mut playback = PlaybackState {
+ requested: true,
+ ..Default::default()
+ };
+ playback.update_recording(Phase::Recording { paused: true }, false);
+ playback.update_recording(terminal, false);
+ playback.update_recording(Phase::Recording { paused: false }, false);
+ assert!(!playback.running());
+ }
+ }
+
/// `teleprompter-utils.test.ts`, translated. `countWords` splits on any
/// whitespace run, so a newline counts as a separator.
#[test]