Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: align GPUI recording controls and device persistence

Richie McIlroyff722196bd32
diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rs
index bb8d2f73a..276e851b6 100644
--- a/apps/desktop-gpui/src/app_windows.rs
+++ b/apps/desktop-gpui/src/app_windows.rs
@@ -218,25 +218,54 @@ impl CleanCaptureGate {
}
}
-/// `originalCameraBounds` / `lastRepositionedWindowId` in the window variant of
-/// the target-select overlay (`target-select-overlay.tsx:478-563`).
-///
-/// The overlay parks the camera bubble 16px inside the bottom-right corner of
-/// whatever window it is highlighting, and puts it back when the picker goes
-/// away *unless* the pick was committed -- a click that locks the highlight, or
-/// a recording/screenshot start, both of which null the saved bounds over
-/// there so the bubble stays where the user will see it in the capture.
#[derive(Default)]
pub struct CameraPark {
- /// The bubble's gpui-space logical top-left before the first park. `None`
- /// while nothing has been moved, and cleared outright once the pick is
- /// committed (`setOriginalCameraBounds(null)`).
- origin: Option<(f32, f32)>,
- /// `lastRepositionedWindowId`: the park runs once per highlighted window,
- /// not once per poll tick.
+ original: Option<CameraSnapshot>,
+ mode: Option<TargetType>,
last_window: Option<scap_targets::WindowId>,
- /// The pick was committed; no further parking and no revert.
+ last_area: Option<AreaRect>,
+ area_target: Option<(DisplayId, AreaRect)>,
released: bool,
+ epoch: u64,
+ generation: u64,
+ pending: Option<CameraPlacement>,
+}
+
+#[derive(Clone, Copy)]
+struct CameraSnapshot {
+ handle: WindowHandle<CameraWindow>,
+ bounds: AreaRect,
+ picker_size: Option<(f32, f32)>,
+}
+
+#[derive(Clone, Copy)]
+enum CameraSizeOverride {
+ Preserve,
+ Set(Option<(f32, f32)>),
+}
+
+#[derive(Clone, Copy)]
+struct CameraPlacement {
+ camera: WindowHandle<CameraWindow>,
+ bounds: AreaRect,
+ size_override: CameraSizeOverride,
+}
+
+impl CameraPark {
+ fn invalidate_pending(&mut self) {
+ self.generation = self.generation.wrapping_add(1);
+ self.pending = None;
+ }
+
+ fn reset_selection(&mut self) {
+ self.epoch = self.epoch.wrapping_add(1);
+ self.original = None;
+ self.mode = None;
+ self.last_window = None;
+ self.last_area = None;
+ self.area_target = None;
+ self.released = false;
+ }
}
impl Global for AppWindows {}
@@ -357,6 +386,11 @@ pub fn init(main: WindowHandle<MainWindow>, session: Entity<RecordingSession>, c
// clean or not: the fallback at `recording.rs:3225-3237` does the
// same so a cancelled or failed recording still restores the
// editor and cannot leak its target into the next session.
+ let main = cx.global::<AppWindows>().main;
+ main.update(cx, |view, _, _| {
+ view.cancel_deep_link_start();
+ })
+ .ok();
let editor_target =
session.update(cx, |session, _| session.take_editor_recording_target());
if let Some(editor_path) = editor_target {
@@ -547,7 +581,8 @@ pub(crate) fn show_main_window_after_capture_pause(cx: &mut App) {
open_onboarding(cx);
return;
}
- if RecordingSession::global(cx).read(cx).phase == Phase::Idle {
+ let resume_inputs = RecordingSession::global(cx).read(cx).phase == Phase::Idle;
+ if resume_inputs {
crate::feeds::Feeds::global(cx).update(cx, |feeds, cx| feeds.resume_camera_preview(cx));
}
let reset_target = RecordingSession::global(cx).read(cx).phase == Phase::Idle
@@ -565,6 +600,9 @@ pub(crate) fn show_main_window_after_capture_pause(cx: &mut App) {
let main = cx.global::<AppWindows>().main;
let native = main
.update(cx, |view, window, cx| {
+ if resume_inputs {
+ view.resume_device_restore(cx);
+ }
if reset_target {
view.clear_target(cx);
}
@@ -687,6 +725,11 @@ fn hide_main_and_park_camera_preview(cx: &mut App) {
return;
}
+ let main = cx.global::<AppWindows>().main;
+ main.update(cx, |view, _, _| {
+ view.suspend_device_restore();
+ })
+ .ok();
close_camera_window(cx);
crate::feeds::Feeds::global(cx).update(cx, |feeds, cx| feeds.park_camera_preview(cx));
}
@@ -695,25 +738,29 @@ fn camera_preview_can_be_parked(phase: Phase) -> bool {
matches!(phase, Phase::Idle)
}
-/// ⌘W, the File/Window menus' Close Window, and the main window's own red
-/// traffic light.
-///
-/// `CapWindowId::Main`'s `CloseRequested` arm (`lib.rs:5644-5697`), transcribed:
-/// prevent the close and hide the window, sync the dock, and -- when nothing is
-/// recording -- hide the camera bubble, close the target-select overlays, pause
-/// the camera preview and release the mic and camera feeds.
-///
-/// Two deviations, both noted in the report: the camera bubble is *closed*
-/// rather than hidden (this app has no hide-in-place path for it, and the
-/// observable result is the same bubble-off-screen), and `camera_preview.pause()`
-/// has no counterpart because there is no preview stream server here -- the
-/// preview is the bubble, and closing it stops the pump.
pub fn request_close_main(cx: &mut App) {
#[cfg(target_os = "linux")]
if clean_capture_pending(cx) {
cancel_clean_capture(cx);
return;
}
+ if RecordingSession::global(cx).read(cx).phase == Phase::Idle
+ && RecordingSession::global(cx)
+ .read(cx)
+ .editor_recording_target()
+ .is_some()
+ {
+ abort_editor_recording_flow(cx);
+ return;
+ }
+ if RecordingSession::global(cx).read(cx).phase == Phase::Idle {
+ let main = cx.global::<AppWindows>().main;
+ main.update(cx, |view, _, _| {
+ view.cancel_deep_link_start();
+ view.suspend_device_restore();
+ })
+ .ok();
+ }
hide_main_window(cx);
// `state.is_recording_active_or_pending()`: everything but Idle.
@@ -1065,13 +1112,20 @@ fn restore_after_settings(cx: &mut App) {
/// Must be reached through `cx.defer` from inside an entity update: opening a
/// window paints it synchronously and would double-lease the caller.
pub fn open_mode_select(cx: &mut App) -> bool {
+ if RecordingSession::global(cx)
+ .read(cx)
+ .editor_recording_target()
+ .is_some()
+ {
+ return false;
+ }
#[cfg(target_os = "linux")]
if defer_window_until_capture_safe(cx) {
return false;
}
let main = cx.global::<AppWindows>().main;
let mode = main
- .update(cx, |view, _window, _cx| view.mode())
+ .update(cx, |view, _window, cx| view.effective_mode(cx))
.unwrap_or(Mode::Instant);
if let Some(handle) = cx.global::<AppWindows>().mode_select {
@@ -1503,6 +1557,33 @@ pub fn open_editor_target_overlays(editor_path: PathBuf, request: OverlayRequest
cx.global_mut::<AppWindows>().editor_hidden_for_picker = Some(key.clone());
hide_editor_window(&key, cx);
}
+ hide_main_window(cx);
+}
+
+pub fn open_editor_recording_main(editor_path: PathBuf, cx: &mut App) {
+ let session = RecordingSession::global(cx);
+ if session.read(cx).phase != Phase::Idle
+ || session.read(cx).editor_recording_target().as_ref() != Some(&editor_path)
+ {
+ return;
+ }
+ let key = editor_key(&editor_path);
+ if editor_window_handle(&key, cx).is_none() {
+ abort_editor_recording_flow(cx);
+ return;
+ }
+ close_target_overlays(cx);
+ cx.global_mut::<AppWindows>().main_hidden_for_picker = false;
+ cx.global_mut::<AppWindows>().editor_hidden_for_picker = Some(key.clone());
+ let main = cx.global::<AppWindows>().main;
+ main.update(cx, |view, _, cx| {
+ view.cancel_deep_link_start();
+ view.clear_target(cx);
+ cx.notify();
+ })
+ .ok();
+ hide_editor_window(&key, cx);
+ show_main_window(cx);
}
fn open_overlays_core(request: OverlayRequest, cx: &mut App) -> bool {
@@ -1531,11 +1612,12 @@ fn open_overlays_core(request: OverlayRequest, cx: &mut App) -> bool {
select.update(cx, |select, cx| {
select.arm(Some(request.mode), request.recording_mode, pinned, cx)
});
+ sync_camera_presentation(cx);
- // Only the window variant parks the camera bubble; the display/area/camera
- // variants have no window to park it in.
- if request.mode == TargetType::Window {
- arm_camera_park(cx);
+ if request.mode == TargetType::Window
+ || (request.mode == TargetType::Area && request.recording_mode != Mode::Screenshot)
+ {
+ arm_camera_park(request.mode, cx);
}
let displays = match &display {
@@ -1601,10 +1683,22 @@ fn open_overlays_core(request: OverlayRequest, cx: &mut App) -> bool {
/// reveals the main window again (`dismissalReveals`,
/// `new-main/index.tsx:2047-2058`).
pub fn dismiss_target_overlays(cx: &mut App) {
+ if RecordingSession::global(cx).read(cx).phase == Phase::Idle
+ && RecordingSession::global(cx)
+ .read(cx)
+ .editor_recording_target()
+ .is_some()
+ {
+ abort_editor_recording_flow(cx);
+ return;
+ }
close_target_overlays(cx);
let main = cx.global::<AppWindows>().main;
- main.update(cx, |view, _window, cx| view.clear_target(cx))
- .ok();
+ main.update(cx, |view, _window, cx| {
+ view.cancel_deep_link_start();
+ view.clear_target(cx);
+ })
+ .ok();
// An editor-owned picker cancelled: clear the editor recording target and
// reveal that editor with focus, record modal closed -- the non-
@@ -1649,6 +1743,7 @@ pub fn close_target_overlays(cx: &mut App) {
let recording_mode = select.recording_mode;
select.arm(None, recording_mode, None, cx);
});
+ sync_camera_presentation(cx);
}
/// Repaint every overlay. The cursor probe runs while none of them is the
@@ -2816,6 +2911,7 @@ fn begin_retained_capture_restore(cx: &mut App) {
Ok(()) => {
crate::hotkeys::complete_clean_capture_stop(generation, cx);
let _restored = cx.global_mut::<AppWindows>().clean_capture.take();
+ update_camera_presentation(true, cx);
RecordingSession::global(cx).update(cx, |_, cx| cx.notify());
}
Err(error) => {
@@ -2879,6 +2975,7 @@ fn restore_clean_capture_ui(cx: &mut App) -> bool {
if let Err(error) = result.and_then(|result| result) {
tracing::warn!(%error, "could not restore the main window");
}
+ update_camera_presentation(true, cx);
true
}
@@ -3164,6 +3261,7 @@ pub fn open_camera_window(cx: &mut App) {
.unwrap_or_else(scap_targets::Display::primary);
let (x, y) = camera_window::opening_position(&display);
+ let inline = camera_preview_is_inline(cx);
let handle = cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds {
@@ -3192,7 +3290,7 @@ pub fn open_camera_window(cx: &mut App) {
WindowKind::PopUp
},
focus: false,
- show: true,
+ show: !inline,
is_resizable: false,
is_minimizable: false,
window_background: gpui::WindowBackgroundAppearance::Transparent,
@@ -3218,12 +3316,17 @@ pub fn open_camera_window(cx: &mut App) {
shadow: false,
},
);
- platform::show_window_without_focus(window);
+ if !inline {
+ platform::show_window_without_focus(window);
+ }
platform::native_window(window)
})
.ok()
.flatten();
remove_popup_window_chrome(native, cx);
+ sync_camera_presentation(cx);
+ sync_opened_camera_with_picker(cx);
+ refresh_target_overlays(cx);
}
Err(error) => tracing::error!("camera window failed to open: {error:#}"),
}
@@ -3231,136 +3334,372 @@ pub fn open_camera_window(cx: &mut App) {
pub fn close_camera_window(cx: &mut App) {
if let Some(handle) = cx.global_mut::<AppWindows>().camera.take() {
+ #[cfg(not(target_os = "macos"))]
+ if let Some(previous) = handle
+ .update(cx, |view, _, cx| view.preview_image(cx))
+ .ok()
+ .flatten()
+ {
+ evict_overlay_camera_image(previous, cx);
+ }
+ let park = &mut cx.global_mut::<AppWindows>().camera_park;
+ park.invalidate_pending();
+ park.original = None;
+ park.last_window = None;
+ park.last_area = None;
handle
.update(cx, |_, window, _| window.remove_window())
.ok();
+ refresh_target_overlays(cx);
}
}
-// -- The camera bubble parked inside a picked window -------------------------
-//
-// `repositionCameraForWindow` (`target-select-overlay.tsx:125-162`) and its
-// caller (`:507-563`): while the window picker is up and nothing has been
-// committed yet, the bubble sits 16px inside the bottom-right corner of the
-// window the overlay is highlighting, so the camera is *in* the recording of
-// that window rather than floating somewhere outside it. It goes back where it
-// came from when the picker is dismissed, and stays parked when the pick is
-// committed (a click that locks the highlight, or a start).
-
-/// The 16px inset `repositionCameraForWindow` uses on both axes; a window that
-/// cannot hold the bubble plus two of these is left alone (`:147-153`).
+fn camera_preview_is_inline(cx: &App) -> bool {
+ TargetSelect::global(cx).read(cx).mode == Some(TargetType::CameraOnly)
+}
+
+pub fn camera_preview_entity(cx: &mut App) -> Option<Entity<CameraWindow>> {
+ cx.global::<AppWindows>()
+ .camera?
+ .update(cx, |_, _, cx| cx.entity())
+ .ok()
+}
+
+fn sync_camera_presentation(cx: &mut App) {
+ update_camera_presentation(false, cx);
+}
+
+fn update_camera_presentation(force: bool, cx: &mut App) {
+ #[cfg(target_os = "linux")]
+ if cx.global::<AppWindows>().clean_capture.is_some() {
+ return;
+ }
+ let Some(handle) = cx.global::<AppWindows>().camera else {
+ return;
+ };
+ let inline = camera_preview_is_inline(cx);
+ let changed = handle
+ .update(cx, |view, window, cx| {
+ let changed = view.is_inline() != inline;
+ view.set_inline(inline, window, cx);
+ changed
+ })
+ .unwrap_or(false);
+ if !changed && !force {
+ return;
+ }
+ cx.spawn(async move |cx| {
+ #[cfg(not(target_os = "linux"))]
+ let native = cx.update(|cx| {
+ if cx.global::<AppWindows>().camera != Some(handle)
+ || camera_preview_is_inline(cx) != inline
+ {
+ return None;
+ }
+ handle
+ .update(cx, |_, window, _| {
+ #[cfg(target_os = "windows")]
+ if !inline {
+ platform::show_window_without_focus(window);
+ return None;
+ }
+ platform::native_window(window)
+ })
+ .ok()
+ .flatten()
+ });
+ #[cfg(not(target_os = "linux"))]
+ if let Some(native) = native {
+ if inline {
+ platform::hide_native(&native);
+ } else {
+ platform::order_front_native(&native);
+ }
+ }
+ #[cfg(target_os = "linux")]
+ cx.update(|cx| {
+ if cx.global::<AppWindows>().camera != Some(handle)
+ || camera_preview_is_inline(cx) != inline
+ || cx.global::<AppWindows>().clean_capture.is_some()
+ {
+ return;
+ }
+ let result = handle.update(cx, |_, window, _| {
+ if cap_recording::screenshot::uses_wayland_portal() {
+ window.set_retained_visibility(!inline).map(|_| ())
+ } else {
+ platform::set_x11_window_visible(window, !inline)
+ }
+ });
+ if let Err(error) = result.and_then(|result| result) {
+ tracing::warn!(%error, "could not update camera picker visibility");
+ }
+ });
+ })
+ .detach();
+}
+
const CAMERA_PARK_PADDING: f32 = 16.;
-/// The camera bubble's geometry, in the two coordinate spaces the move needs.
struct CameraFrame {
- native: platform::NativeWindow,
- /// gpui-space logical top-left -- the space the overlay's window bounds and
- /// the persisted `cameraWindowPosition` both live in (global, y down).
- origin: (f32, f32),
- /// The AppKit frame (bottom-left origin, points), for `setFrame:`.
- frame: (f64, f64, f64, f64),
+ native: CameraNativeFrame,
+ snapshot: CameraSnapshot,
+}
+
+enum CameraNativeFrame {
+ #[cfg(target_os = "macos")]
+ Mac {
+ native: platform::NativeWindow,
+ frame: (f64, f64, f64, f64),
+ },
+ #[cfg(target_os = "windows")]
+ Windows(platform::NativeWindow),
+ #[cfg(target_os = "linux")]
+ X11 { window_id: u32, scale: f64 },
+}
+
+#[cfg(target_os = "macos")]
+fn camera_native_frame(window: &gpui::Window) -> Option<(CameraNativeFrame, AreaRect)> {
+ let native = platform::native_window(window)?;
+ let frame = platform::window_frame(&native);
+ let origin = window.bounds().origin;
+ Some((
+ CameraNativeFrame::Mac { native, frame },
+ AreaRect {
+ x: f32::from(origin.x),
+ y: f32::from(origin.y),
+ width: frame.2 as f32,
+ height: frame.3 as f32,
+ },
+ ))
+}
+
+#[cfg(target_os = "windows")]
+fn camera_native_frame(window: &gpui::Window) -> Option<(CameraNativeFrame, AreaRect)> {
+ let native = platform::native_window(window)?;
+ let (x, y, width, height) = platform::window_logical_frame(&native);
+ Some((
+ CameraNativeFrame::Windows(native),
+ AreaRect {
+ x: x as f32,
+ y: y as f32,
+ width: width as f32,
+ height: height as f32,
+ },
+ ))
+}
+
+#[cfg(target_os = "linux")]
+fn camera_native_frame(window: &gpui::Window) -> Option<(CameraNativeFrame, AreaRect)> {
+ use raw_window_handle::{HasWindowHandle, RawWindowHandle};
+
+ let window_id = match HasWindowHandle::window_handle(window).ok()?.as_raw() {
+ RawWindowHandle::Xlib(handle) => u32::try_from(handle.window).ok()?,
+ RawWindowHandle::Xcb(handle) => handle.window.get(),
+ _ => return None,
+ };
+ let bounds = window.bounds();
+ Some((
+ CameraNativeFrame::X11 {
+ window_id,
+ scale: f64::from(window.scale_factor()),
+ },
+ AreaRect {
+ x: f32::from(bounds.origin.x),
+ y: f32::from(bounds.origin.y),
+ width: f32::from(bounds.size.width),
+ height: f32::from(bounds.size.height),
+ },
+ ))
}
fn camera_frame(cx: &mut App) -> Option<CameraFrame> {
let handle = cx.global::<AppWindows>().camera?;
handle
- .update(cx, |_, window, _| {
- let native = platform::native_window(window)?;
- #[cfg(target_os = "windows")]
- let frame = platform::window_logical_frame(&native);
- #[cfg(not(target_os = "windows"))]
- let frame = platform::window_frame(&native);
- let origin = window.bounds().origin;
+ .update(cx, |view, window, _| {
+ let (native, bounds) = camera_native_frame(window)?;
Some(CameraFrame {
native,
- origin: (f32::from(origin.x), f32::from(origin.y)),
- frame,
+ snapshot: CameraSnapshot {
+ handle,
+ bounds,
+ picker_size: view.picker_size(),
+ },
})
})
.ok()
.flatten()
+ .filter(|camera| camera.snapshot.bounds.width > 0. && camera.snapshot.bounds.height > 0.)
}
-/// `win.setPosition(new LogicalPosition(x, y))` on the camera window, spelled
-/// as the delta on its AppKit frame the way `CameraWindow::apply_window_size`
-/// does -- gpui's own origin math disagrees with AppKit's, and the delta is
-/// exact in both. Runs from a task: `setFrame:` re-enters gpui's window
-/// callbacks.
-fn move_camera_window(camera: CameraFrame, to: (f32, f32), cx: &mut App) {
- let dx = f64::from(to.0 - camera.origin.0);
- let dy = f64::from(to.1 - camera.origin.1);
- if dx.abs() < 0.5 && dy.abs() < 0.5 {
- return;
+fn camera_snapshot(cx: &mut App) -> Option<CameraSnapshot> {
+ let mut snapshot = camera_frame(cx)?.snapshot;
+ if let Some(pending) = cx.global::<AppWindows>().camera_park.pending
+ && pending.camera == snapshot.handle
+ {
+ snapshot.bounds = pending.bounds;
+ if let CameraSizeOverride::Set(picker_size) = pending.size_override {
+ snapshot.picker_size = picker_size;
+ }
}
- #[cfg(not(target_os = "windows"))]
- let (frame_x, frame_y, width, height) = camera.frame;
- #[cfg(target_os = "windows")]
- let (_, _, width, height) = camera.frame;
- #[cfg(target_os = "windows")]
- let (x, y) = (f64::from(to.0), f64::from(to.1));
- // gpui +y is down, AppKit +y is up.
- #[cfg(not(target_os = "windows"))]
- let (x, y) = (frame_x + dx, frame_y - dy);
- let native = camera.native;
- cx.spawn(async move |_| {
- #[cfg(target_os = "windows")]
- platform::set_window_logical_frame(&native, x, y, width, height);
- #[cfg(not(target_os = "windows"))]
- platform::set_window_frame(&native, x, y, width, height);
+ Some(snapshot)
+}
+
+impl CameraFrame {
+ fn apply(self, bounds: AreaRect) -> anyhow::Result<()> {
+ match self.native {
+ #[cfg(target_os = "macos")]
+ CameraNativeFrame::Mac { native, frame } => {
+ let dx = f64::from(bounds.x - self.snapshot.bounds.x);
+ let dy = f64::from(bounds.y - self.snapshot.bounds.y);
+ platform::set_window_frame(
+ &native,
+ frame.0 + dx,
+ frame.1 + frame.3 - dy - f64::from(bounds.height),
+ f64::from(bounds.width),
+ f64::from(bounds.height),
+ );
+ }
+ #[cfg(target_os = "windows")]
+ CameraNativeFrame::Windows(native) => {
+ platform::set_window_logical_frame(
+ &native,
+ f64::from(bounds.x),
+ f64::from(bounds.y),
+ f64::from(bounds.width),
+ f64::from(bounds.height),
+ );
+ }
+ #[cfg(target_os = "linux")]
+ CameraNativeFrame::X11 { window_id, scale } => {
+ use x11rb::connection::Connection as _;
+ use x11rb::protocol::xproto::{ConfigureWindowAux, ConnectionExt as _};
+
+ let (connection, _) = x11rb::connect(None)?;
+ connection
+ .configure_window(
+ window_id,
+ &ConfigureWindowAux::new()
+ .x((f64::from(bounds.x) * scale).round() as i32)
+ .y((f64::from(bounds.y) * scale).round() as i32)
+ .width((f64::from(bounds.width) * scale).round().max(1.) as u32)
+ .height((f64::from(bounds.height) * scale).round().max(1.) as u32),
+ )?
+ .check()?;
+ connection.flush()?;
+ }
+ }
+ Ok(())
+ }
+}
+
+fn queue_camera_placement(placement: CameraPlacement, cx: &mut App) {
+ let park = &mut cx.global_mut::<AppWindows>().camera_park;
+ park.invalidate_pending();
+ park.pending = Some(placement);
+ let generation = park.generation;
+ cx.spawn(async move |cx| {
+ let camera = cx.update(|cx| {
+ let windows = cx.global::<AppWindows>();
+ if windows.camera_park.generation != generation
+ || windows.camera != Some(placement.camera)
+ {
+ return None;
+ }
+ let Some(frame) = camera_frame(cx) else {
+ let park = &mut cx.global_mut::<AppWindows>().camera_park;
+ park.invalidate_pending();
+ park.last_window = None;
+ park.last_area = None;
+ return None;
+ };
+ placement
+ .camera
+ .update(cx, |view, window, cx| {
+ view.invalidate_pending_resize();
+ if let CameraSizeOverride::Set(picker_size) = placement.size_override {
+ view.set_picker_size(picker_size, window, cx);
+ }
+ })
+ .ok()?;
+ cx.global_mut::<AppWindows>().camera_park.pending = None;
+ Some(frame)
+ });
+ // Native setters re-enter GPUI; no App or camera entity borrow may survive this call.
+ if let Some(camera) = camera
+ && let Err(error) = camera.apply(placement.bounds)
+ {
+ tracing::warn!(%error, "could not move the camera preview into the capture target");
+ cx.update(|cx| {
+ let park = &mut cx.global_mut::<AppWindows>().camera_park;
+ if park.generation == generation {
+ park.last_window = None;
+ park.last_area = None;
+ }
+ });
+ }
})
.detach();
}
-/// `onMount` of the window-variant overlay (`target-select-overlay.tsx:507-517`):
-/// remember where the bubble was before the picker touches it. Only for a fresh
-/// picker -- re-pointing an open picker at another window does not remount the
-/// overlay over there, so the *original* original is what a dismissal restores.
-fn arm_camera_park(cx: &mut App) {
- {
- let park = &cx.global::<AppWindows>().camera_park;
- if park.origin.is_some() || park.released || park.last_window.is_some() {
- return;
+fn arm_camera_park(mode: TargetType, cx: &mut App) {
+ if cx.global::<AppWindows>().camera_park.mode == Some(mode) {
+ return;
+ }
+ let original = (mode == TargetType::Window)
+ .then(|| camera_snapshot(cx))
+ .flatten();
+ let park = &mut cx.global_mut::<AppWindows>().camera_park;
+ let pending = park.pending;
+ park.invalidate_pending();
+ park.reset_selection();
+ park.mode = Some(mode);
+ park.original = original;
+ if let Some(pending) = pending {
+ queue_camera_placement(pending, cx);
+ }
+}
+
+fn sync_opened_camera_with_picker(cx: &mut App) {
+ let select = TargetSelect::global(cx);
+ match select.read(cx).mode {
+ Some(TargetType::Window) => {
+ let target = select.read(cx).active_window().cloned();
+ sync_camera_park(target, cx);
+ }
+ Some(TargetType::Area) => {
+ if let Some((display, crop)) = cx.global::<AppWindows>().camera_park.area_target.clone()
+ {
+ sync_camera_area(display, Some(crop), cx);
+ }
}
+ _ => {}
}
- let origin = camera_frame(cx).map(|camera| camera.origin);
- cx.global_mut::<AppWindows>().camera_park = CameraPark {
- origin,
- last_window: None,
- released: false,
- };
}
-/// The reposition effect (`target-select-overlay.tsx:518-545`), driven by the
-/// same cursor poll that feeds the highlight: park the bubble in the window the
-/// overlay is highlighting, once per window, and stop entirely once the pick is
-/// committed.
+pub fn camera_picker_epoch(cx: &App) -> u64 {
+ cx.global::<AppWindows>().camera_park.epoch
+}
+
pub fn sync_camera_park(active: Option<HoveredWindow>, cx: &mut App) {
- if !cx.has_global::<AppWindows>() {
+ if !cx.has_global::<AppWindows>()
+ || TargetSelect::global(cx).read(cx).mode != Some(TargetType::Window)
+ {
return;
}
let Some(target) = active else {
- // `lastRepositionedWindowId = null`: nothing highlighted, so the next
- // window to be highlighted parks again even if it is the same one.
cx.global_mut::<AppWindows>().camera_park.last_window = None;
return;
};
- {
- let park = &cx.global::<AppWindows>().camera_park;
- if park.released || park.last_window.as_ref() == Some(&target.id) {
- return;
- }
+ let park = &cx.global::<AppWindows>().camera_park;
+ if park.released || park.last_window.as_ref() == Some(&target.id) {
+ return;
+ }
+ if park_camera_in_window(&target, cx) {
+ cx.global_mut::<AppWindows>().camera_park.last_window = Some(target.id);
}
- cx.global_mut::<AppWindows>().camera_park.last_window = Some(target.id.clone());
- park_camera_in_window(&target, cx);
}
-/// The bubble's new top-left, in the global logical space its own position
-/// lives in -- `repositionCameraForWindow`'s arithmetic
-/// (`target-select-overlay.tsx:141-160`), verbatim: the window's
-/// display-relative bounds made absolute with the display origin, the bubble
-/// tucked into the bottom-right corner one padding in, rounded. `None` when the
-/// window cannot hold the bubble plus a padding on each side, which is that
-/// function's early return (`:147-153`) -- the bubble stays where it is.
fn camera_park_position(
display_origin: (f32, f32),
window: AreaRect,
@@ -3375,75 +3714,214 @@ fn camera_park_position(
let absolute_x = window.x + display_origin.0;
let absolute_y = window.y + display_origin.1;
Some((
- (absolute_x + window.width - camera_width - CAMERA_PARK_PADDING).round(),
- (absolute_y + window.height - camera_height - CAMERA_PARK_PADDING).round(),
+ (absolute_x + window.width - camera_width - CAMERA_PARK_PADDING + 0.5).floor(),
+ (absolute_y + window.height - camera_height - CAMERA_PARK_PADDING + 0.5).floor(),
))
}
-fn park_camera_in_window(target: &HoveredWindow, cx: &mut App) {
+fn park_camera_in_window(target: &HoveredWindow, cx: &mut App) -> bool {
let Some(display) = scap_targets::Display::from_id(&target.display_id) else {
- return;
+ return false;
};
let Some(display_bounds) = display.raw_handle().logical_bounds() else {
- return;
+ return false;
};
- let Some(camera) = camera_frame(cx) else {
- return;
+ let Some(camera) = camera_snapshot(cx) else {
+ return false;
};
- let (_, _, width, height) = camera.frame;
let display_origin = (
display_bounds.position().x() as f32,
display_bounds.position().y() as f32,
);
- let Some(to) =
- camera_park_position(display_origin, target.bounds, (width as f32, height as f32))
- else {
- tracing::debug!(
- camera_width = width,
- camera_height = height,
- window_width = target.bounds.width,
- window_height = target.bounds.height,
- "target window is too small for the camera bubble; leaving it where it is"
- );
- return;
+ let Some((x, y)) = camera_park_position(
+ display_origin,
+ target.bounds,
+ (camera.bounds.width, camera.bounds.height),
+ ) else {
+ return false;
+ };
+
+ let park = &mut cx.global_mut::<AppWindows>().camera_park;
+ if park
+ .original
+ .is_none_or(|original| original.handle != camera.handle)
+ {
+ park.original = Some(camera);
+ }
+ queue_camera_placement(
+ CameraPlacement {
+ camera: camera.handle,
+ bounds: AreaRect {
+ x,
+ y,
+ ..camera.bounds
+ },
+ size_override: CameraSizeOverride::Preserve,
+ },
+ cx,
+ );
+ true
+}
+
+fn camera_area_bounds(
+ display_origin: (f32, f32),
+ crop: AreaRect,
+ original_size: (f32, f32),
+) -> Option<AreaRect> {
+ let (original_width, original_height) = original_size;
+ let toolbar = camera_window::CAMERA_TOOLBAR_HEIGHT;
+ let content_height = (original_height - toolbar).max(0.);
+ let content_max = original_width.max(content_height);
+ let target_max = 100_f32.max(content_max.min(crop.width.min(crop.height) * 0.5 - toolbar));
+ let scale = if content_max > 0. {
+ target_max / content_max
+ } else {
+ 1.
};
+ let width = (original_width * scale).round();
+ let height = (content_height * scale).round() + toolbar;
+ if crop.width <= width + CAMERA_PARK_PADDING * 2.
+ || crop.height <= height + CAMERA_PARK_PADDING * 2.
+ {
+ return None;
+ }
+ Some(AreaRect {
+ x: (crop.x + crop.width - width - CAMERA_PARK_PADDING).round() + display_origin.0,
+ y: (crop.y + crop.height - height - CAMERA_PARK_PADDING).round() + display_origin.1,
+ width,
+ height,
+ })
+}
+
+fn camera_area_bounds_changed(previous: AreaRect, next: AreaRect) -> bool {
+ (previous.x - next.x).abs() > 1.
+ || (previous.y - next.y).abs() > 1.
+ || (previous.width - next.width).abs() > 1.
+ || (previous.height - next.height).abs() > 1.
+}
- // A camera opened *after* the picker went up has no remembered position
- // yet; the effect over there picks it up the same way (`getCameraWindow()`
- // starts returning a window and the reposition runs).
- if cx.global::<AppWindows>().camera_park.origin.is_none() {
- cx.global_mut::<AppWindows>().camera_park.origin = Some(camera.origin);
+pub fn sync_camera_area(display_id: DisplayId, crop: Option<AreaRect>, cx: &mut App) {
+ if !cx.has_global::<AppWindows>()
+ || !cx
+ .global::<AppWindows>()
+ .overlays
+ .iter()
+ .any(|(display, _)| *display == display_id)
+ {
+ return;
}
- tracing::info!(window = %target.id, x = to.0, y = to.1, "parking the camera bubble in the picked window");
- move_camera_window(camera, to, cx);
+ let select = TargetSelect::global(cx);
+ if select.read(cx).mode != Some(TargetType::Area)
+ || select.read(cx).recording_mode == Mode::Screenshot
+ || cx.global::<AppWindows>().camera_park.released
+ {
+ return;
+ }
+ let Some(crop) = crop else {
+ if cx
+ .global::<AppWindows>()
+ .camera_park
+ .area_target
+ .as_ref()
+ .is_none_or(|(display, _)| *display == display_id)
+ {
+ revert_camera_park(cx);
+ arm_camera_park(TargetType::Area, cx);
+ }
+ return;
+ };
+ cx.global_mut::<AppWindows>().camera_park.area_target = Some((display_id.clone(), crop));
+ let Some(display) = scap_targets::Display::from_id(&display_id) else {
+ return;
+ };
+ let Some(display_bounds) = display.raw_handle().logical_bounds() else {
+ return;
+ };
+ let Some(camera) = camera_snapshot(cx) else {
+ return;
+ };
+ let park = &mut cx.global_mut::<AppWindows>().camera_park;
+ let original = match park.original {
+ Some(original) if original.handle == camera.handle => original,
+ _ => {
+ park.original = Some(camera);
+ camera
+ }
+ };
+ let Some(bounds) = camera_area_bounds(
+ (
+ display_bounds.position().x() as f32,
+ display_bounds.position().y() as f32,
+ ),
+ crop,
+ (original.bounds.width, original.bounds.height),
+ ) else {
+ return;
+ };
+ if park
+ .last_area
+ .is_some_and(|last| !camera_area_bounds_changed(last, bounds))
+ {
+ return;
+ }
+ park.last_area = Some(bounds);
+ queue_camera_placement(
+ CameraPlacement {
+ camera: camera.handle,
+ bounds,
+ size_override: CameraSizeOverride::Set(Some((bounds.width, bounds.height))),
+ },
+ cx,
+ );
}
-/// `setOriginalCameraBounds(null)`: the pick was committed -- a click that
-/// locks the highlight (`:609-617`), a recording start or a screenshot start
-/// (`:687-690`) -- so the bubble stays where the picker put it and no dismissal
-/// puts it back.
pub fn release_camera_park(cx: &mut App) {
if !cx.has_global::<AppWindows>() {
return;
}
let park = &mut cx.global_mut::<AppWindows>().camera_park;
- park.origin = None;
+ park.original = None;
park.released = true;
}
-/// `onCleanup` (`:558-563`): the picker went away without a commit, so the
-/// bubble goes back to where it was.
fn revert_camera_park(cx: &mut App) {
- let park = std::mem::take(&mut cx.global_mut::<AppWindows>().camera_park);
- let Some(origin) = park.origin else {
+ let park = &mut cx.global_mut::<AppWindows>().camera_park;
+ let original = park.original;
+ let mode = park.mode;
+ if !park.released {
+ park.invalidate_pending();
+ }
+ park.reset_selection();
+ let Some(original) = original else {
return;
};
- let Some(camera) = camera_frame(cx) else {
+ let Some(camera) = camera_snapshot(cx).filter(|camera| camera.handle == original.handle) else {
return;
};
- tracing::info!(x = origin.0, y = origin.1, "restoring the camera bubble");
- move_camera_window(camera, origin, cx);
+ let (bounds, size_override) = if mode == Some(TargetType::Area) {
+ (
+ original.bounds,
+ CameraSizeOverride::Set(original.picker_size),
+ )
+ } else {
+ (
+ AreaRect {
+ x: original.bounds.x,
+ y: original.bounds.y,
+ ..camera.bounds
+ },
+ CameraSizeOverride::Preserve,
+ )
+ };
+ queue_camera_placement(
+ CameraPlacement {
+ camera: original.handle,
+ bounds,
+ size_override,
+ },
+ cx,
+ );
}
/// Hand a camera frame to the preview window. Returns false when no window is
@@ -3456,9 +3934,35 @@ pub fn deliver_camera_frame(
let Some(handle) = cx.global::<AppWindows>().camera else {
return false;
};
- handle
+ #[cfg(not(target_os = "macos"))]
+ let previous = camera_preview_is_inline(cx)
+ .then(|| {
+ handle
+ .update(cx, |view, _, cx| view.preview_image(cx))
+ .ok()
+ .flatten()
+ })
+ .flatten();
+ let delivered = handle
.update(cx, |view, window, cx| view.frame_arrived(frame, window, cx))
- .is_ok()
+ .is_ok();
+ #[cfg(not(target_os = "macos"))]
+ if let Some(previous) = previous {
+ evict_overlay_camera_image(previous, cx);
+ }
+ delivered
+}
+
+#[cfg(not(target_os = "macos"))]
+fn evict_overlay_camera_image(image: Arc<gpui::RenderImage>, cx: &mut App) {
+ let overlays = cx.global::<AppWindows>().overlays.clone();
+ for (_, overlay) in overlays {
+ overlay
+ .update(cx, |_, window, _| {
+ let _ = window.drop_image(image.clone());
+ })
+ .ok();
+ }
}
// -- Editor -----------------------------------------------------------------
@@ -4277,6 +4781,20 @@ pub fn editor_closed(project_path: &Path, cx: &mut App) {
}
}
+ let session = RecordingSession::global(cx);
+ if session.read(cx).phase == Phase::Idle
+ && session
+ .read(cx)
+ .editor_recording_target()
+ .is_some_and(|path| editor_key(&path) == key)
+ {
+ if clean_capture_owned(cx) {
+ cancel_clean_capture(cx);
+ } else {
+ abort_editor_recording_flow(cx);
+ }
+ }
+
let windows = cx.global::<AppWindows>();
let editors_left = windows.editors.len() + windows.screenshot_editors.len();
let settings_open = windows.settings.is_some();
@@ -4438,6 +4956,15 @@ fn set_editor_content_protection(project_path: &Path, hidden: bool, cx: &mut App
/// there the window merely stays minimized, here it was hidden outright and
/// leaving it hidden would leave the app with no window at all.
fn editor_recording_finished(editor_path: PathBuf, recording: Option<PathBuf>, cx: &mut App) {
+ cx.global_mut::<AppWindows>().editor_hidden_for_picker = None;
+ cx.global_mut::<AppWindows>().main_hidden_for_picker = false;
+ let main = cx.global::<AppWindows>().main;
+ main.update(cx, |view, _, cx| {
+ view.cancel_deep_link_start();
+ view.clear_target(cx);
+ cx.notify();
+ })
+ .ok();
set_editor_content_protection(&editor_path, false, cx);
let Some(handle) = editor_window_handle(&editor_path, cx) else {
@@ -4468,13 +4995,37 @@ fn editor_recording_finished(editor_path: PathBuf, recording: Option<PathBuf>, c
/// would stay hidden forever, since no phase transition is coming.
pub fn abort_editor_recording_flow(cx: &mut App) {
let session = RecordingSession::global(cx);
- let Some(editor_path) = session.update(cx, |session, _| session.take_editor_recording_target())
- else {
+ if session.read(cx).phase != Phase::Idle || session.read(cx).editor_recording_target().is_none()
+ {
+ return;
+ }
+ let main = cx.global::<AppWindows>().main;
+ main.update(cx, |view, _, _| view.cancel_deep_link_start())
+ .ok();
+ let Some(editor_path) = session.update(cx, |session, cx| {
+ let target = session.take_editor_recording_target();
+ cx.notify();
+ target
+ }) else {
return;
};
+ close_target_overlays(cx);
cx.global_mut::<AppWindows>().editor_hidden_for_picker = None;
+ cx.global_mut::<AppWindows>().main_hidden_for_picker = false;
+ let main = cx.global::<AppWindows>().main;
+ main.update(cx, |view, _, cx| {
+ view.cancel_deep_link_start();
+ view.clear_target(cx);
+ cx.notify();
+ })
+ .ok();
+ hide_main_window(cx);
tracing::info!(path = %editor_path.display(), "editor recording flow aborted before start");
- if editor_window_handle(&editor_path, cx).is_some() {
+ if let Some(handle) = editor_window_handle(&editor_path, cx) {
+ hide_main_and_park_camera_preview(cx);
+ handle
+ .update(cx, |view, _, cx| view.editor_picker_dismissed(cx))
+ .ok();
reveal_editor_window(&editor_path, cx);
} else {
show_main_window(cx);
@@ -5772,6 +6323,10 @@ mod tests {
camera_park_position((0.4, 0.), window, (320.3, 240.)),
Some((564., 394.))
);
+ assert_eq!(
+ camera_park_position((-1920.5, 0.), window, (320., 240.)),
+ Some((-1356., 394.))
+ );
// Exactly one padding on each side still fits; one point more does not.
let snug = AreaRect {
@@ -5787,4 +6342,128 @@ mod tests {
assert_eq!(camera_park_position((0., 0.), snug, (321., 240.)), None);
assert_eq!(camera_park_position((0., 0.), snug, (320., 241.)), None);
}
+
+ #[test]
+ fn area_camera_keeps_toolbar_height_and_restores_the_original_scale() {
+ let crop = AreaRect {
+ x: 100.,
+ y: 50.,
+ width: 800.,
+ height: 600.,
+ };
+ assert_eq!(
+ camera_area_bounds((0., 0.), crop, (320., 376.)),
+ Some(AreaRect {
+ x: 640.,
+ y: 334.,
+ width: 244.,
+ height: 300.,
+ })
+ );
+ assert_eq!(
+ camera_area_bounds(
+ (0., 0.),
+ AreaRect {
+ width: 1200.,
+ height: 1000.,
+ ..crop
+ },
+ (320., 376.)
+ ),
+ Some(AreaRect {
+ x: 964.,
+ y: 658.,
+ width: 320.,
+ height: 376.,
+ })
+ );
+ }
+
+ #[test]
+ fn area_camera_preserves_landscape_and_portrait_content_aspects() {
+ let crop = AreaRect {
+ x: 100.,
+ y: 50.,
+ width: 600.,
+ height: 400.,
+ };
+ assert_eq!(
+ camera_area_bounds((0., 0.), crop, (320., 236.)),
+ Some(AreaRect {
+ x: 540.,
+ y: 297.,
+ width: 144.,
+ height: 137.,
+ })
+ );
+ assert_eq!(
+ camera_area_bounds((0., 0.), crop, (180., 376.)),
+ Some(AreaRect {
+ x: 603.,
+ y: 234.,
+ width: 81.,
+ height: 200.,
+ })
+ );
+ }
+
+ #[test]
+ fn area_camera_uses_the_minimum_size_and_requires_room_beyond_both_insets() {
+ let crop = AreaRect {
+ x: 0.,
+ y: 0.,
+ width: 200.,
+ height: 200.,
+ };
+ assert_eq!(
+ camera_area_bounds((0., 0.), crop, (320., 376.)),
+ Some(AreaRect {
+ x: 84.,
+ y: 28.,
+ width: 100.,
+ height: 156.,
+ })
+ );
+ assert_eq!(
+ camera_area_bounds(
+ (0., 0.),
+ AreaRect {
+ width: 132.,
+ ..crop
+ },
+ (320., 376.)
+ ),
+ None
+ );
+ assert_eq!(
+ camera_area_bounds(
+ (0., 0.),
+ AreaRect {
+ height: 188.,
+ ..crop
+ },
+ (320., 376.)
+ ),
+ None
+ );
+ }
+
+ #[test]
+ fn area_camera_position_preserves_the_display_origin() {
+ let crop = AreaRect {
+ x: 100.,
+ y: 50.,
+ width: 800.,
+ height: 600.,
+ };
+ assert_eq!(
+ camera_area_bounds((-1920.5, -1080.25), crop, (320., 376.)),
+ Some(AreaRect {
+ x: -1280.5,
+ y: -746.25,
+ width: 244.,
+ height: 300.,
+ })
+ );
+ }
}
diff --git a/apps/desktop-gpui/src/camera_window.rs b/apps/desktop-gpui/src/camera_window.rs
index 9d5bdd249..ff10c92c7 100644
--- a/apps/desktop-gpui/src/camera_window.rs
+++ b/apps/desktop-gpui/src/camera_window.rs
@@ -99,6 +99,53 @@ pub fn window_size(state: &CameraWindowState, frame_aspect: Option<f32>) -> (f32
(width, height + CAMERA_TOOLBAR_HEIGHT)
}
+pub(crate) fn inline_preview_size(
+ state: &CameraWindowState,
+ frame_aspect: Option<f32>,
+ viewport: (f32, f32),
+) -> (f32, f32) {
+ let (width, height) = preview_dimensions(state, frame_aspect);
+ let scale = ((viewport.0 - 48.).max(160.) / width)
+ .min((viewport.1 - 320.).max(160.) / height)
+ .min(1.);
+ (
+ (width * scale).round(),
+ (height * scale).round() + CAMERA_TOOLBAR_HEIGHT,
+ )
+}
+
+#[cfg(test)]
+mod inline_preview_tests {
+ use super::*;
+
+ #[test]
+ fn camera_only_preview_preserves_size_until_viewport_requires_scaling() {
+ let state = CameraWindowState::default();
+ assert_eq!(
+ inline_preview_size(&state, Some(16. / 9.), (1920., 1080.)),
+ window_size(&state, Some(16. / 9.)),
+ );
+ assert_eq!(
+ inline_preview_size(&state, None, (100., 100.)),
+ (160., 216.),
+ );
+ }
+
+ #[test]
+ fn camera_only_wide_preview_preserves_aspect_and_toolbar_space() {
+ let state = CameraWindowState {
+ size: 600.,
+ shape: CameraShape::Full,
+ ..Default::default()
+ };
+ assert_eq!(
+ inline_preview_size(&state, Some(16. / 9.), (800., 600.)),
+ (498., 336.),
+ );
+ assert_eq!(state.size, 600.);
+ }
+}
+
/// 0..1 across the 150..600 size range -- drives the toolbar scale and the
/// issue overlay's text metrics, like `cameraToolbarScale` /
/// `cameraOverlayTextMetrics`.
@@ -114,7 +161,7 @@ fn normalized_size(state: &CameraWindowState) -> f32 {
/// (`camera.tsx:805-807`). The `cameraBorderRadius` 3rem formula styles only
/// the native page's issue overlay, and the native WGSL mask uses its own
/// smaller radii; the 24px container is what users see.
-fn preview_radius(state: &CameraWindowState) -> f32 {
+pub(crate) fn preview_radius(state: &CameraWindowState) -> f32 {
match state.shape {
CameraShape::Round => clamp_size(state.size) / 2.,
_ => 24.,
@@ -159,6 +206,7 @@ fn linux_camera_recording_snapshot(
client_rect: LinuxCameraPhysicalRect,
viewport: (f32, f32),
scale_factor: f32,
+ picker_size: Option<(f32, f32)>,
) -> anyhow::Result<LinuxCameraRecordingSnapshot> {
if !scale_factor.is_finite() || scale_factor <= 0.0 {
anyhow::bail!("Camera window has an invalid scale factor");
@@ -181,7 +229,8 @@ fn linux_camera_recording_snapshot(
if physical_viewport != (client_rect.width, client_rect.height) {
anyhow::bail!("Camera viewport and X11 client dimensions disagree; wait for resizing");
}
- let expected = window_size(&state, Some(frame_width as f32 / frame_height as f32));
+ let expected = picker_size
+ .unwrap_or_else(|| window_size(&state, Some(frame_width as f32 / frame_height as f32)));
if (
recording_physical_extent(expected.0, scale_factor)?,
recording_physical_extent(expected.1, scale_factor)?,
@@ -724,6 +773,9 @@ struct BlurBridge {
pub struct CameraWindow {
theme: Theme,
state: CameraWindowState,
+ inline: bool,
+ picker_size: Option<(f32, f32)>,
+ size_generation: Arc<AtomicU64>,
chrome_visible: bool,
resizing: Option<ResizeDrag>,
hovered_handle: Option<ResizeCorner>,
@@ -789,6 +841,7 @@ impl CameraWindow {
},
(f32::from(viewport.width), f32::from(viewport.height)),
window.scale_factor(),
+ self.picker_size,
)
}
@@ -831,6 +884,9 @@ impl CameraWindow {
Self {
theme,
state,
+ inline: false,
+ picker_size: None,
+ size_generation: Arc::new(AtomicU64::new(0)),
chrome_visible: false,
resizing: None,
hovered_handle: None,
@@ -852,6 +908,55 @@ impl CameraWindow {
}
}
+ pub fn set_inline(&mut self, inline: bool, window: &mut Window, cx: &mut Context<Self>) {
+ if self.inline == inline {
+ return;
+ }
+ self.inline = inline;
+ self.invalidate_pending_resize();
+ self.resizing = None;
+ self.chrome_visible = false;
+ self.hovered_handle = None;
+ if !inline {
+ self.apply_window_size(window, cx);
+ }
+ cx.notify();
+ }
+
+ pub fn inline_size(&self, viewport: (f32, f32)) -> (f32, f32) {
+ inline_preview_size(&self.state, self.frame_aspect(), viewport)
+ }
+
+ pub fn is_inline(&self) -> bool {
+ self.inline
+ }
+
+ pub fn picker_size(&self) -> Option<(f32, f32)> {
+ self.picker_size
+ }
+
+ pub fn invalidate_pending_resize(&self) {
+ self.size_generation.fetch_add(1, Ordering::AcqRel);
+ }
+
+ pub fn set_picker_size(
+ &mut self,
+ size: Option<(f32, f32)>,
+ _window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if self.picker_size != size {
+ self.invalidate_pending_resize();
+ self.picker_size = size;
+ cx.notify();
+ }
+ }
+
+ #[cfg(not(target_os = "macos"))]
+ pub fn preview_image(&self, cx: &gpui::App) -> Option<Arc<gpui::RenderImage>> {
+ self.preview.read(cx).latest_frame.clone()
+ }
+
/// Called by the feed pump for every camera frame. Only the preview child
/// is notified, so the cached toolbar chrome is reused; `refresh` is
/// reserved for the first frame, where an inactive window may need the
@@ -1083,6 +1188,7 @@ impl CameraWindow {
) {
#[cfg(target_os = "macos")]
let blur_before = self.state.background_blur;
+ self.picker_size = None;
mutate(&mut self.state);
self.state.size = clamp_size(self.state.size);
#[cfg(not(target_os = "macos"))]
@@ -1116,7 +1222,14 @@ impl CameraWindow {
/// *bottom*-left, so the anchor and the clamp both go through one native
/// `setFrame:` instead.
fn apply_window_size(&self, window: &mut Window, cx: &mut Context<Self>) {
- let (width, height) = window_size(&self.state, self.frame_aspect());
+ if self.inline {
+ return;
+ }
+ let (width, height) = self
+ .picker_size
+ .unwrap_or_else(|| window_size(&self.state, self.frame_aspect()));
+ let generation = self.size_generation.fetch_add(1, Ordering::AcqRel) + 1;
+ let generations = self.size_generation.clone();
let bounds = window.bounds();
let (x, y) = (f32::from(bounds.origin.x), f32::from(bounds.origin.y));
@@ -1147,6 +1260,9 @@ impl CameraWindow {
#[cfg(target_os = "windows")]
if let Some(native) = platform::native_window(window) {
cx.spawn(async move |_, _| {
+ if generations.load(Ordering::Acquire) != generation {
+ return;
+ }
platform::set_window_logical_frame(
&native,
f64::from(new_x),
@@ -1171,6 +1287,9 @@ impl CameraWindow {
// callbacks, so it runs from a fresh runloop turn (the
// `set_window_frame` rule).
cx.spawn(async move |_, _| {
+ if generations.load(Ordering::Acquire) != generation {
+ return;
+ }
platform::set_window_frame(
&native,
appkit_x,
@@ -1551,6 +1670,7 @@ impl CameraWindow {
let delta = dx.max(dy);
let next = clamp_size(drag.start_size + delta);
if (next - self.state.size).abs() > 0.5 {
+ self.picker_size = None;
self.state.size = next;
self.apply_window_size(window, cx);
self.sync_preview_chrome(cx);
@@ -1595,7 +1715,7 @@ impl Render for CameraWindow {
.on_mouse_down(
MouseButton::Left,
cx.listener(|this, _, window, _| {
- if this.resizing.is_none() {
+ if this.resizing.is_none() && !this.inline {
window.start_window_move();
}
}),
@@ -1802,9 +1922,15 @@ mod recording_snapshot_tests {
for scale in [1.0, 1.25, 1.5, 2.0] {
for origin in [(37, 91), (-1920, -1080)] {
let (client, viewport) = geometry(state, (640, 480), scale, origin);
- let snapshot =
- linux_camera_recording_snapshot(state, (640, 480), client, viewport, scale)
- .unwrap();
+ let snapshot = linux_camera_recording_snapshot(
+ state,
+ (640, 480),
+ client,
+ viewport,
+ scale,
+ None,
+ )
+ .unwrap();
let expected_side = (state.size * scale).round() as u32;
assert_eq!(
snapshot.content_rect,
@@ -1831,7 +1957,8 @@ mod recording_snapshot_tests {
};
let (client, viewport) = geometry(state, (1920, 1080), 1.5, (-1400, 20));
let snapshot =
- linux_camera_recording_snapshot(state, (1920, 1080), client, viewport, 1.5).unwrap();
+ linux_camera_recording_snapshot(state, (1920, 1080), client, viewport, 1.5, None)
+ .unwrap();
assert_eq!(snapshot.content_rect.width, 1067);
assert_eq!(snapshot.content_rect.height, 600);
assert_eq!(snapshot.content_rect.x, -1400);
@@ -1840,6 +1967,52 @@ mod recording_snapshot_tests {
assert_eq!(snapshot.state, state);
}
+ #[test]
+ fn snapshot_accepts_temporary_picker_size_without_changing_saved_size() {
+ let state = CameraWindowState::default();
+ let viewport = (150.0, 206.0);
+ let client = LinuxCameraPhysicalRect {
+ x: 80,
+ y: 120,
+ width: 150,
+ height: 206,
+ };
+ assert!(
+ linux_camera_recording_snapshot(state, (640, 480), client, viewport, 1.0, None,)
+ .is_err()
+ );
+ let snapshot = linux_camera_recording_snapshot(
+ state,
+ (640, 480),
+ client,
+ viewport,
+ 1.0,
+ Some(viewport),
+ )
+ .unwrap();
+ assert_eq!(snapshot.state, state);
+ assert_eq!(
+ snapshot.content_rect,
+ LinuxCameraPhysicalRect {
+ x: 80,
+ y: 176,
+ width: 150,
+ height: 150,
+ }
+ );
+ assert!(
+ linux_camera_recording_snapshot(
+ state,
+ (640, 480),
+ client,
+ viewport,
+ 1.0,
+ Some((151.0, 206.0)),
+ )
+ .is_err()
+ );
+ }
+
#[test]
fn snapshot_square_radius_scales_without_becoming_a_circle() {
let state = CameraWindowState {
@@ -1850,7 +2023,7 @@ mod recording_snapshot_tests {
for scale in [1.0, 1.25, 1.5, 2.0] {
let (client, viewport) = geometry(state, (1280, 720), scale, (0, 0));
let snapshot =
- linux_camera_recording_snapshot(state, (1280, 720), client, viewport, scale)
+ linux_camera_recording_snapshot(state, (1280, 720), client, viewport, scale, None)
.unwrap();
assert_eq!(snapshot.content_rect.width, snapshot.content_rect.height);
assert_eq!(snapshot.corner_radius_pixels, 24.0 * scale);
@@ -1869,6 +2042,7 @@ mod recording_snapshot_tests {
client,
(viewport.0 + 1.0, viewport.1),
1.25,
+ None,
)
.is_err()
);
@@ -1882,6 +2056,7 @@ mod recording_snapshot_tests {
client,
viewport,
1.25,
+ None,
)
.is_err()
);
@@ -1891,7 +2066,8 @@ mod recording_snapshot_tests {
};
let (client, viewport) = geometry(full, (1920, 1080), 1.0, (0, 0));
assert!(
- linux_camera_recording_snapshot(full, (2400, 1000), client, viewport, 1.0).is_err()
+ linux_camera_recording_snapshot(full, (2400, 1000), client, viewport, 1.0, None)
+ .is_err()
);
}
@@ -1901,7 +2077,7 @@ mod recording_snapshot_tests {
let (client, viewport) = geometry(state, (640, 480), 1.0, (0, 0));
for invalid in [0.0, -1.0, f32::NAN, f32::INFINITY] {
assert!(
- linux_camera_recording_snapshot(state, (640, 480), client, viewport, invalid)
+ linux_camera_recording_snapshot(state, (640, 480), client, viewport, invalid, None)
.is_err()
);
assert!(
@@ -1914,6 +2090,7 @@ mod recording_snapshot_tests {
client,
viewport,
1.0,
+ None,
)
.is_err()
);
@@ -1924,12 +2101,15 @@ mod recording_snapshot_tests {
client,
(invalid, viewport.1),
1.0,
+ None,
)
.is_err()
);
}
for frame in [(0, 480), (640, 0)] {
- assert!(linux_camera_recording_snapshot(state, frame, client, viewport, 1.0).is_err());
+ assert!(
+ linux_camera_recording_snapshot(state, frame, client, viewport, 1.0, None).is_err()
+ );
}
assert!(
linux_camera_recording_snapshot(
@@ -1938,6 +2118,7 @@ mod recording_snapshot_tests {
LinuxCameraPhysicalRect { width: 0, ..client },
viewport,
1.0,
+ None,
)
.is_err()
);
@@ -1949,7 +2130,8 @@ mod recording_snapshot_tests {
for origin in [(i32::MAX, 0), (0, i32::MAX)] {
let (client, viewport) = geometry(state, (640, 480), 1.0, origin);
assert!(
- linux_camera_recording_snapshot(state, (640, 480), client, viewport, 1.0).is_err()
+ linux_camera_recording_snapshot(state, (640, 480), client, viewport, 1.0, None)
+ .is_err()
);
}
assert!(recording_physical_extent(f32::MAX, 2.0).is_err());
@@ -1962,7 +2144,8 @@ mod recording_snapshot_tests {
let scale = 4.0 / 3.0;
let (client, viewport) = geometry(state, (640, 480), scale, (0, 0));
let snapshot =
- linux_camera_recording_snapshot(state, (640, 480), client, viewport, scale).unwrap();
+ linux_camera_recording_snapshot(state, (640, 480), client, viewport, scale, None)
+ .unwrap();
assert_eq!(snapshot.content_rect.width, 307);
assert_eq!(snapshot.content_rect.height, 306);
assert_eq!(snapshot.content_rect.x, client.x);
diff --git a/apps/desktop-gpui/src/deeplink.rs b/apps/desktop-gpui/src/deeplink.rs
index 4eb7ca684..b92aa6f5f 100644
--- a/apps/desktop-gpui/src/deeplink.rs
+++ b/apps/desktop-gpui/src/deeplink.rs
@@ -427,7 +427,13 @@ impl DeepLinkAction {
app_windows::clean_capture_owned(cx),
cx,
app_windows::cancel_clean_capture,
- |cx| session.update(cx, |session, cx| session.stop(cx)),
+ |cx| {
+ if session.read(cx).phase == crate::session::Phase::Idle {
+ app_windows::abort_editor_recording_flow(cx);
+ } else {
+ session.update(cx, |session, cx| session.stop(cx));
+ }
+ },
);
Ok(())
}
diff --git a/apps/desktop-gpui/src/devices.rs b/apps/desktop-gpui/src/devices.rs
index 6740350eb..064108127 100644
--- a/apps/desktop-gpui/src/devices.rs
+++ b/apps/desktop-gpui/src/devices.rs
@@ -13,6 +13,7 @@ use scap_targets::{Display, DisplayId, Window, WindowId};
#[derive(Debug, Clone, PartialEq)]
pub struct CameraOption {
pub device_id: String,
+ pub model_id: Option<cap_camera::ModelID>,
pub label: String,
/// Highest-resolution format the device advertises, shown as the row's
/// subtitle. `None` when the device reports no formats.
@@ -185,6 +186,7 @@ fn list_cameras() -> Vec<CameraOption> {
CameraOption {
device_id: camera.device_id().to_string(),
+ model_id: camera.model_id().cloned(),
label: camera.display_name().to_string(),
best_format,
}
diff --git a/apps/desktop-gpui/src/editor_clips.rs b/apps/desktop-gpui/src/editor_clips.rs
index 73fe939a1..dbf7e71d9 100644
--- a/apps/desktop-gpui/src/editor_clips.rs
+++ b/apps/desktop-gpui/src/editor_clips.rs
@@ -3,8 +3,6 @@
//! list, rename, reorder and delete the timeline's clip segments, plus the
//! import and record-a-new-clip entry points.
//!
-//! Three seams differ from the Tauri app, each marked where it bites:
-//!
//! * **Thumbnails** are decoded in-process off the main thread and cached in
//! memory keyed by `(recording segment, start ms)` -- `get_clip_thumbnail`
//! (`src-tauri/src/clip_thumbnails.rs`) writes a JPEG cache under the
@@ -14,20 +12,6 @@
//! copied into this bundle, the metas and the timeline extended, and the
//! editor reloaded -- `window.location.reload()`'s native spelling is
//! [`crate::app_windows::reload_editor`].
-//! * **"Record a new clip"** is the whole `setEditorRecordingTarget` flow,
-//! natively: the modal's start actions arm the session's editor recording
-//! target (`EditorRecordingTarget`, `src-tauri/src/windows.rs:3679-3697`)
-//! and open the target-select overlays with the editor hidden for the
-//! picker; the capture is forced into Studio mode; and when it stops
-//! cleanly the session observer reveals this editor and hands it the
-//! bundle, which lands through the same whole-segment-copy the import path
-//! uses, followed by the recording directory's deletion and an editor
-//! reload -- the `EditorRecordingAdded` listener (`Editor.tsx:312-335`),
-//! transcribed. The Display/Window chevron menus list the same enumeration
-//! the main window's pickers use, with the same live ScreenCaptureKit
-//! thumbnails and app icons -- `ClipsSidebar.tsx:378-385` runs the same two
-//! `*WithThumbnails` queries the main window does, through the same
-//! `TargetCard`.
use std::{
cell::RefCell,
@@ -47,33 +31,20 @@ use gpui::{
AnyElement, AppContext as _, Bounds, Context, CursorStyle, Entity, FontWeight, Hsla,
InteractiveElement, IntoElement, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
ParentElement, Pixels, Point, RenderImage, ScrollHandle, SharedString,
- StatefulInteractiveElement as _, Styled, StyledImage as _, Task, Window, div, img,
+ StatefulInteractiveElement as _, Styled, StyledImage as _, Window, div, img,
prelude::FluentBuilder, px, svg,
};
use crate::{
app_windows,
- devices::{CameraOption, DeviceSnapshot, DisplayOption, MicrophoneOption, WindowOption},
editor_edits::{self as edits, TrackSegmentOps},
editor_timeline::clip_timeline_offsets,
editor_window::EditorWindow,
- main_window::{Mode, TargetType},
session::{Phase, RecordingSession},
- target_thumbnails,
theme::Theme,
ui,
};
-/// The width one target card gets in the record modal, computed rather than
-/// flexed.
-///
-/// The modal is `w-full max-w-[460px]` and the editor's minimum window width is
-/// 1275, so 460 is always what it gets; its body is `p-5`, and the grid has an
-/// 8px gutter: `(460 - 40 - 8) / 2`. Stating the width keeps `flex_1` off a
-/// text-bearing card in a grid that can hold every window on the machine --
-/// the same reason `MainWindow::target_card_width` exists.
-const RECORD_TARGET_CARD_WIDTH: f32 = 206.;
-
// ---------------------------------------------------------------------------
// Naming (`ClipsSidebar.tsx:558-609`)
// ---------------------------------------------------------------------------
@@ -314,45 +285,12 @@ pub(crate) struct ClipDrag {
active: bool,
}
-/// Which of the record modal's device selects is unfolded --
-/// `CameraSelectBase` / `MicrophoneSelectBase`'s open dropdown
-/// (`ClipsSidebar.tsx:1084-1122`), drawn here as an in-modal list the way the
-/// chevron target menus are (a KSelect popover has no gpui counterpart).
-#[derive(Clone, Copy, PartialEq, Eq)]
-enum RecordDeviceMenu {
- Camera,
- Microphone,
-}
-
/// Everything the clips layout mode owns. Lives on [`EditorWindow`] so the
/// mode is hidden, not destroyed, while closed -- the Tauri sidebar stays
/// mounted with `class="hidden"` (`Editor.tsx:739-746`).
pub(crate) struct ClipsState {
/// `isClipsMode()` (`Editor.tsx:347-350`).
pub(crate) open: bool,
- /// `recordOpen`.
- record_open: bool,
- /// `displayMenuOpen` / `windowMenuOpen` (`:292-296`) -- which chevron
- /// target menu the modal body is showing. Only `Display` and `Window`
- /// ever land here.
- record_target_menu: Option<TargetType>,
- /// Which device select is unfolded.
- record_device_menu: Option<RecordDeviceMenu>,
- /// `targetSearch`, as the shared text-input entity (created on first use,
- /// like the rename field -- it needs a window).
- target_search_input: Option<Entity<ui::TextInputState>>,
- /// `createDevicesQuery` (`:365`): enumerated when the modal opens, `None`
- /// while the scan is in flight so the menus can say "Loading...".
- record_devices: Option<DeviceSnapshot>,
- /// Thumbnails and app icons for the record modal's target cards.
- /// `ClipsSidebar.tsx:378-385` runs the same
- /// `listDisplaysWithThumbnails`/`listWindowsWithThumbnails` queries the
- /// main window does, so the cards look the same -- but on this route's own
- /// `QueryClient`, which is why this cache is per-view too.
- record_thumbnails: target_thumbnails::ThumbnailCache,
- /// The in-flight sweep for whichever target menu is open. Dropping it
- /// stops the loop; the loop also stops itself the moment the menu closes.
- record_thumbnail_task: Option<Task<()>>,
/// The import menu's anchor, while it is up. A native `Menu.popup()` in
/// the Tauri app (`:541-556`); here the `ui::Menu` shape -- full-window
/// backdrop, panel at the click position.
@@ -378,13 +316,6 @@ impl Default for ClipsState {
fn default() -> Self {
Self {
open: false,
- record_open: false,
- record_target_menu: None,
- record_device_menu: None,
- target_search_input: None,
- record_devices: None,
- record_thumbnails: target_thumbnails::ThumbnailCache::default(),
- record_thumbnail_task: None,
import_menu: None,
importing: false,
editing: None,
@@ -468,28 +399,36 @@ impl EditorWindow {
cx.notify();
}
- /// `backToEditor` and the close half of the `createEffect(on(open))`
- /// cleanup (`ClipsSidebar.tsx:278, 343-363`), `resetRecordingTarget`
- /// included: a target armed by the modal but never recorded is cleared so
- /// it cannot redirect a later capture. Guarded on Idle -- mid-recording
- /// the target belongs to the live capture and must survive (the Tauri
- /// effect runs unguarded, but its editor window is hidden then, so the
- /// guard only closes a hole rather than changing behaviour). A live
- /// rename commits first: hiding the DOM input blurs it, and blur commits.
pub(crate) fn close_clips(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.clips.editing.is_some() {
self.commit_clip_rename(window, cx);
}
self.clips.open = false;
- self.clips.record_open = false;
- self.clips.record_target_menu = None;
- self.clips.record_device_menu = None;
self.clips.import_menu = None;
self.clips.drag = None;
self.clips.drop_index = None;
let session = RecordingSession::global(cx);
- if session.read(cx).phase == Phase::Idle {
- session.update(cx, |session, _| session.set_editor_recording_target(None));
+ if session.read(cx).phase == Phase::Idle
+ && session.read(cx).editor_recording_target().as_ref() == Some(&self.project_path)
+ {
+ let main = cx.global::<app_windows::AppWindows>().main;
+ main.update(cx, |view, _, _| view.cancel_deep_link_start())
+ .ok();
+ let editor_path = self.project_path.clone();
+ cx.defer(move |cx| {
+ if RecordingSession::global(cx)
+ .read(cx)
+ .editor_recording_target()
+ .as_ref()
+ == Some(&editor_path)
+ {
+ if app_windows::clean_capture_owned(cx) {
+ app_windows::cancel_clean_capture(cx);
+ } else {
+ app_windows::abort_editor_recording_flow(cx);
+ }
+ }
+ });
}
cx.notify();
}
@@ -502,18 +441,6 @@ impl EditorWindow {
cx.notify();
return true;
}
- if self.clips.record_open {
- // The modal's own Escape ladder (`ClipsSidebar.tsx:764-775`): an
- // open target or device menu closes first, the modal second.
- if self.clips.record_target_menu.is_some() || self.clips.record_device_menu.is_some() {
- self.clips.record_target_menu = None;
- self.clips.record_device_menu = None;
- } else {
- self.clips.record_open = false;
- }
- cx.notify();
- return true;
- }
false
}
@@ -857,8 +784,14 @@ impl EditorWindow {
.font_weight(FontWeight::MEDIUM)
.full_width()
.on_click(cx.listener(
- |this, _, window, cx| {
- this.open_record_modal(window, cx);
+ |this, _, _window, cx| {
+ if !this.begin_editor_recording(cx) {
+ return;
+ }
+ let project_path = this.project_path.clone();
+ cx.defer(move |cx| {
+ app_windows::open_editor_recording_main(project_path, cx);
+ });
},
)),
),
@@ -1237,447 +1170,39 @@ impl EditorWindow {
.into_any_element()
}
- // -- Record a new clip (`ClipsSidebar.tsx:434-501`, `Editor.tsx:312-335`) --
-
- /// The action row's blue button: open the modal and refresh the device
- /// enumeration behind it (`createDevicesQuery` is enabled by
- /// `props.open && recordOpen()`, so the lists are re-read per opening).
- fn open_record_modal(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- self.clips.record_open = true;
- self.clips.record_target_menu = None;
- self.clips.record_device_menu = None;
- // Whatever the last session cached is stale by now (and the queries
- // would refetch on mount anyway), so release the sprite-atlas tiles
- // rather than carry them for the life of the editor window.
- for image in self.clips.record_thumbnails.reset() {
- let _ = window.drop_image(image);
- }
- self.clips.record_thumbnail_task = None;
- self.refresh_record_devices(cx);
- cx.notify();
- }
-
- /// The record modal's thumbnail loop.
- ///
- /// `ClipsSidebar.tsx:378-385` enables each thumbnail query on
- /// `props.open && recordOpen() && <kind>MenuOpen()` and takes the query's
- /// own `refetchInterval` -- 10s for displays (`utils/queries.ts:75`),
- /// none for windows (`:66`). So: capture once when the menu opens, and for
- /// displays keep re-capturing every `THUMBNAIL_STALE_TIME` until it closes.
- ///
- /// Unlike the main window there is no cheap-list poll and no signature
- /// comparison, because the sidebar does not run `listScreens`/`listWindows`
- /// at all. Each sweep re-enumerates, so the target rows still refresh.
- fn start_record_thumbnails(
- &mut self,
- kind: TargetType,
- window: &mut Window,
- cx: &mut Context<Self>,
- ) {
- if matches!(kind, TargetType::Area | TargetType::CameraOnly) {
- self.clips.record_thumbnail_task = None;
- return;
- }
-
- self.clips.record_thumbnail_task = Some(cx.spawn_in(window, async move |this, cx| {
- let mut captured = false;
- loop {
- // The loop owns its own lifetime: every path that closes the
- // modal or the menu is a state change, so reading the state
- // here beats hunting down six call sites to cancel a task.
- let Ok(open) = this.update(cx, |this, _| {
- this.clips.record_open && this.clips.record_target_menu == Some(kind)
- }) else {
- return;
- };
- if !open {
- // Closing the modal releases the atlas tiles; closing just
- // the menu keeps them, the way a 60s `gcTime` would.
- this.update_in(cx, |this, window, _| {
- if !this.clips.record_open {
- for image in this.clips.record_thumbnails.reset() {
- let _ = window.drop_image(image);
- }
- }
- })
- .ok();
- return;
- }
-
- // Displays re-capture on every tick (`refetchInterval:
- // 10_000`); windows capture once and the loop stays only to
- // notice the menu closing (`refetchInterval: false`).
- if kind == TargetType::Display || !captured {
- let Ok(sweep) = this.update_in(cx, |this, window, cx| {
- this.start_record_capture(kind, window, cx)
- }) else {
- return;
- };
- if let Some(sweep) = sweep {
- sweep.await;
- captured = true;
- }
- }
-
- cx.background_executor()
- .timer(target_thumbnails::THUMBNAIL_STALE_TIME)
- .await;
- }
- }));
- }
-
- /// One sweep, the editor twin of `MainWindow::start_capture` -- same
- /// in-flight guard, same off-thread split, same reconcile-by-id install.
- fn start_record_capture(
- &mut self,
- kind: TargetType,
- window: &mut Window,
- cx: &mut Context<Self>,
- ) -> Option<Task<()>> {
- match kind {
- TargetType::Display => {
- if self.clips.record_thumbnails.display_inflight() {
- return None;
- }
- self.clips.record_thumbnails.set_display_inflight(true);
-
- let (events_tx, events) = flume::unbounded();
- let capture = gpui_tokio::Tokio::spawn(cx, async move {
- target_thumbnails::capture_displays(events_tx).await;
- });
-
- Some(cx.spawn_in(window, async move |this, cx| {
- let _capture = capture;
- while let Ok(first) = events.recv_async().await {
- let mut batch = vec![first];
- batch.extend(events.try_iter());
- if this
- .update_in(cx, |this, window, cx| {
- this.apply_record_display_events(batch, window, cx)
- })
- .is_err()
- {
- return;
- }
- }
- this.update(cx, |this, _| {
- this.clips.record_thumbnails.set_display_inflight(false)
- })
- .ok();
- }))
- }
- TargetType::Window => {
- if self.clips.record_thumbnails.window_inflight() {
- return None;
- }
- self.clips.record_thumbnails.set_window_inflight(true);
-
- let (events_tx, events) = flume::unbounded();
- let capture = gpui_tokio::Tokio::spawn(cx, async move {
- target_thumbnails::capture_windows(events_tx).await;
- });
-
- Some(cx.spawn_in(window, async move |this, cx| {
- let _capture = capture;
- while let Ok(first) = events.recv_async().await {
- let mut batch = vec![first];
- batch.extend(events.try_iter());
- if this
- .update_in(cx, |this, window, cx| {
- this.apply_record_window_events(batch, window, cx)
- })
- .is_err()
- {
- return;
- }
- }
- this.update(cx, |this, _| {
- this.clips.record_thumbnails.set_window_inflight(false)
- })
- .ok();
- }))
- }
- TargetType::Area | TargetType::CameraOnly => None,
- }
- }
-
- fn apply_record_display_events(
- &mut self,
- batch: Vec<target_thumbnails::DisplayEvent>,
- window: &mut Window,
- cx: &mut Context<Self>,
- ) {
- for event in batch {
- match event {
- target_thumbnails::DisplayEvent::Listed(list) => {
- for image in self.clips.record_thumbnails.retain_displays(&list) {
- let _ = window.drop_image(image);
- }
- if let Some(devices) = self.clips.record_devices.as_mut() {
- devices.displays = list;
- }
- }
- target_thumbnails::DisplayEvent::Captured(id, image) => {
- if let Some(old) = self.clips.record_thumbnails.insert_display(&id, image) {
- let _ = window.drop_image(old);
- }
- }
- }
- }
- cx.notify();
- // The editor is not necessarily the active window while a sweep lands,
- // and an inactive window only repaints when asked.
- window.refresh();
- }
-
- fn apply_record_window_events(
- &mut self,
- batch: Vec<target_thumbnails::WindowEvent>,
- window: &mut Window,
- cx: &mut Context<Self>,
- ) {
- for event in batch {
- match event {
- target_thumbnails::WindowEvent::Listed(list) => {
- for image in self.clips.record_thumbnails.retain_windows(&list) {
- let _ = window.drop_image(image);
- }
- if let Some(devices) = self.clips.record_devices.as_mut() {
- devices.windows = list;
- }
- }
- target_thumbnails::WindowEvent::Captured {
- id,
- image,
- app_icon,
- } => {
- let icon = app_icon.map(|bytes| {
- Arc::new(gpui::Image::from_bytes(gpui::ImageFormat::Png, bytes))
- });
- if let Some(old) = self.clips.record_thumbnails.insert_window(&id, image, icon)
- {
- let _ = window.drop_image(old);
- }
- }
- }
- }
- cx.notify();
- window.refresh();
- }
-
- /// The enumeration hits AVFoundation and the window server, so it runs on
- /// the background executor -- the `start_enumeration` rule from the main
- /// window, which shares `DeviceSnapshot`.
- fn refresh_record_devices(&mut self, cx: &mut Context<Self>) {
- self.clips.record_devices = None;
- cx.spawn(async move |this, cx| {
- let snapshot = cx
- .background_executor()
- .spawn(async move { DeviceSnapshot::enumerate() })
- .await;
- this.update(cx, |this, cx| {
- this.clips.record_devices = Some(snapshot);
- cx.notify();
- })
- .ok();
- })
- .detach();
- }
-
- /// The chevron menus' search field, created on first use like the rename
- /// input. Escape with text clears it (the source input's own
- /// `onKeyDown`, `:1155-1161`); Escape empty falls back to closing the
- /// menu, which is what bubbling to the window handler would do.
- fn ensure_target_search_input(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- if self.clips.target_search_input.is_some() {
- return;
- }
- let input = cx.new(|cx| ui::TextInputState::single_line(window, cx));
- let subscription = cx.subscribe_in(
- &input,
- window,
- |this: &mut Self, input, event: &ui::TextInputEvent, _window, cx| match event {
- ui::TextInputEvent::Changed => cx.notify(),
- ui::TextInputEvent::Cancelled => {
- if input.read(cx).text().is_empty() {
- this.clips.record_target_menu = None;
- this.clips.record_device_menu = None;
- } else {
- input.update(cx, |input, cx| input.set_text("", cx));
- }
- cx.notify();
- }
- ui::TextInputEvent::Confirmed | ui::TextInputEvent::Blurred => {}
- },
- );
- self.push_text_subscription(subscription);
- self.clips.target_search_input = Some(input);
- }
-
- fn target_search_text(&self, cx: &Context<Self>) -> String {
- self.clips
- .target_search_input
- .as_ref()
- .map(|input| input.read(cx).text().trim().to_lowercase())
- .unwrap_or_default()
- }
-
- /// Toggle a chevron target menu open (`:1029-1035, 1062-1068`), focusing
- /// the search field the way the Tauri menu's `Input` autofocuses.
- fn toggle_record_target_menu(
- &mut self,
- kind: TargetType,
- window: &mut Window,
- cx: &mut Context<Self>,
- ) {
- if self.clips.record_target_menu == Some(kind) {
- self.clips.record_target_menu = None;
- } else {
- self.ensure_target_search_input(window, cx);
- if let Some(input) = self.clips.target_search_input.clone() {
- input.update(cx, |input, cx| {
- // `placeholder={... ? "Search windows" : "Search displays"}`
- // (`:1162-1166`).
- input.set_placeholder(if kind == TargetType::Window {
- "Search windows"
- } else {
- "Search displays"
- });
- input.set_text("", cx);
- input.focus_and_select_all(window, cx);
- });
- }
- self.clips.record_target_menu = Some(kind);
- self.clips.record_device_menu = None;
- // `enabled: props.open && recordOpen() && <kind>MenuOpen()` --
- // the thumbnail query only runs while this menu is up, and each
- // sweep re-enumerates, so the list refreshes with it.
- self.start_record_thumbnails(kind, window, cx);
- }
- cx.notify();
- }
-
- /// `beginEditorRecording` (`ClipsSidebar.tsx:434-445`): close the modal,
- /// stop playback, persist the live project config (the `setProjectConfig`
- /// call -- the finish-time append merges into what is on disk), and arm
- /// the session's editor recording target. Studio mode is forced app-side
- /// (`begin_recording`), so the persisted recording-mode setting is left
- /// alone -- the sidebar's `previousMode` save/restore dance nets out to
- /// exactly that.
- ///
- /// Returns false without arming when a recording is already live: the
- /// Tauri backend refuses the second start in `set_pending_recording`, and
- /// refusing *before* the target write means the modal cannot re-point a
- /// live recording's append at a different project.
fn begin_editor_recording(&mut self, cx: &mut Context<Self>) -> bool {
let session = RecordingSession::global(cx);
- if session.read(cx).phase != Phase::Idle {
+ if session.read(cx).phase != Phase::Idle || app_windows::clean_capture_owned(cx) {
tracing::warn!("a recording is already live; not starting another from the editor");
return false;
}
- self.clips.record_open = false;
- self.clips.record_target_menu = None;
- self.clips.record_device_menu = None;
if self.playing {
self.stop_playback(cx);
}
self.pending_save().borrow_mut().flush();
if let Err(error) = self.project.write(&self.project_path) {
tracing::error!("failed to persist the project config before recording: {error}");
+ let message = format!("Could not save the current project before recording: {error}");
+ cx.spawn(async move |_, _| show_append_error(&message))
+ .detach();
+ return false;
+ }
+ let main = cx.global::<app_windows::AppWindows>().main;
+ if let Err(error) = main.update(cx, |view, _, _| view.cancel_deep_link_start()) {
+ let message = format!("Could not prepare the recording controls: {error}");
+ cx.spawn(async move |_, _| show_append_error(&message))
+ .detach();
+ return false;
}
- session.update(cx, |session, _| {
- session.set_editor_recording_target(Some(self.project_path.clone()))
+ session.update(cx, |session, cx| {
+ session.set_editor_recording_target(Some(self.project_path.clone()));
+ cx.notify();
});
cx.notify();
true
}
- /// `openTargetMode` (`:447-463`): arm the target, then the picker
- /// overlays with the editor hidden behind them.
- fn open_editor_target_mode(&mut self, kind: TargetType, cx: &mut Context<Self>) {
- if !self.begin_editor_recording(cx) {
- return;
- }
- if kind == TargetType::CameraOnly {
- // `setOptions("captureSystemAudio", false)` (`:452-458`): a
- // camera-only capture records no system audio, and the option is
- // the shared one the main window owns.
- let main = cx.global::<app_windows::AppWindows>().main;
- cx.defer(move |cx: &mut gpui::App| {
- main.update(cx, |view, _window, cx| view.set_system_audio(false, cx))
- .ok();
- });
- }
- let project_path = self.project_path.clone();
- let request = app_windows::OverlayRequest {
- mode: kind,
- recording_mode: Mode::Studio,
- display: None,
- pinned_window: None,
- };
- cx.defer(move |cx: &mut gpui::App| {
- app_windows::open_editor_target_overlays(project_path, request, cx)
- });
- }
-
- /// `selectDisplayTarget` (`:465-479`): the overlays narrowed to the
- /// picked display, editor hidden.
- fn select_record_display(&mut self, display: DisplayOption, cx: &mut Context<Self>) {
- if !self.begin_editor_recording(cx) {
- return;
- }
- let project_path = self.project_path.clone();
- let request = app_windows::OverlayRequest {
- mode: TargetType::Display,
- recording_mode: Mode::Studio,
- display: Some(display.id),
- pinned_window: None,
- };
- cx.defer(move |cx: &mut gpui::App| {
- app_windows::open_editor_target_overlays(project_path, request, cx)
- });
- }
-
- /// `selectWindowTarget` (`:481-501`): the overlays pinned to the picked
- /// window, and then the picked window's app brought forward -- the
- /// trailing `commands.focusWindow(target.id)` (`:497`), which the main
- /// window's own window list does too. Only windows: `selectDisplayTarget`
- /// has no such call, and neither has a click on the overlay itself.
- fn select_record_window(&mut self, target: WindowOption, cx: &mut Context<Self>) {
- if !self.begin_editor_recording(cx) {
- return;
- }
- let project_path = self.project_path.clone();
- let focus = target.id.clone();
- let request = app_windows::OverlayRequest {
- mode: TargetType::Window,
- recording_mode: Mode::Studio,
- display: None,
- pinned_window: Some(target.id),
- };
- cx.defer(move |cx: &mut gpui::App| {
- app_windows::open_editor_target_overlays(project_path, request, cx);
- // After the overlays, the way the source awaits `focusWindow` last,
- // and off the main thread: the Tauri command runs on an async
- // command thread, and activating another application inside this
- // update would re-enter gpui's window callbacks.
- cx.background_executor()
- .spawn(async move {
- crate::platform::focus_capture_target_window(&focus);
- })
- .detach();
- });
- }
-
- /// The picker was cancelled while this editor was hidden for it
- /// (`rawOptions.targetMode == null && hiddenForPicker`,
- /// `ClipsSidebar.tsx:413-426`): the reveal and the target clear happen in
- /// `app_windows::dismiss_target_overlays`; this is the modal-state half
- /// (`restoreMode(); closeRecord()`).
pub(crate) fn editor_picker_dismissed(&mut self, cx: &mut Context<Self>) {
- self.clips.record_open = false;
- self.clips.record_target_menu = None;
- self.clips.record_device_menu = None;
cx.notify();
}
@@ -1758,16 +1283,11 @@ impl EditorWindow {
.detach();
}
- // -- Overlays: import menu, record modal, drag ghost -----------------------
-
pub(crate) fn render_clips_overlays(&mut self, cx: &mut Context<Self>) -> Vec<AnyElement> {
let mut overlays = Vec::new();
if let Some(menu) = self.render_clips_import_menu(cx) {
overlays.push(menu);
}
- if let Some(modal) = self.render_clips_record_modal(cx) {
- overlays.push(modal);
- }
if let Some(layer) = self.render_clips_drag_layer(cx) {
overlays.push(layer);
}
@@ -1901,844 +1421,6 @@ impl EditorWindow {
)
}
- /// The record modal (`:969-1222`), chrome 1:1 and live: the four target
- /// actions arm the session's editor recording target and open the picker
- /// overlays, the chevron menus unfold the concrete display/window lists,
- /// and the device selects read and write the shared recording options on
- /// the main window (the gpui home of `rawOptions`).
- fn render_clips_record_modal(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
- if !self.clips.record_open {
- return None;
- }
- let theme = self.theme;
-
- // `activeTargetMenu()` swaps the whole body (`:1001-1217`); the
- // device selects reuse the same swap where the Tauri KSelect floats a
- // popover, which has no gpui counterpart here.
- let body: AnyElement = if let Some(kind) = self.clips.record_target_menu {
- self.render_record_target_menu(kind, cx).into_any_element()
- } else if let Some(menu) = self.clips.record_device_menu {
- self.render_record_device_menu(menu, cx).into_any_element()
- } else {
- self.render_record_modal_home(cx).into_any_element()
- };
-
- Some(
- div()
- .absolute()
- .inset_0()
- .flex()
- .items_center()
- .justify_center()
- .p(px(24.))
- .child(
- // `backdrop-blur-sm bg-black/60` -- gpui elements cannot
- // blur what is behind them, so the wash carries it alone.
- div()
- .id("clips-record-backdrop")
- .absolute()
- .inset_0()
- .bg(gpui::hsla(0., 0., 0., 0.6))
- .on_click(cx.listener(|this, _, _window, cx| {
- this.clips.record_open = false;
- cx.notify();
- })),
- )
- .child(
- // The panel (`:977`): `max-w-[460px] h-[480px] rounded-2xl
- // border shadow-2xl bg-gray-1 dark:bg-gray-2 border-gray-3`.
- div()
- .occlude()
- .relative()
- .flex()
- .flex_col()
- .w_full()
- .max_w(px(460.))
- .h(px(480.))
- .overflow_hidden()
- .rounded(px(16.))
- .border_1()
- .border_color(Hsla::from(theme.gray_3))
- .bg(self.panel_bg())
- .shadow_lg()
- // The header (`:978-998`).
- .child(
- div()
- .flex()
- .flex_none()
- .flex_row()
- .gap(px(12.))
- .items_center()
- .px(px(20.))
- .py(px(16.))
- .border_b_1()
- .border_color(Hsla::from(theme.gray_3))
- .child(
- div()
- .flex()
- .flex_none()
- .justify_center()
- .items_center()
- .size(px(40.))
- .rounded(px(12.))
- .bg(Hsla::from(theme.blue_3))
- .child(
- svg()
- .path("icons/clapperboard.svg")
- .size(px(20.))
- .text_color(Hsla::from(theme.blue_10)),
- ),
- )
- .child(
- div()
- .flex()
- .flex_col()
- .gap(px(2.))
- .min_w_0()
- .child(
- div()
- .text_size(px(14.))
- .font_weight(FontWeight::MEDIUM)
- .text_color(Hsla::from(theme.gray_12))
- .child("Record a new clip"),
- )
- .child(
- div()
- .text_size(px(12.))
- .text_color(Hsla::from(theme.gray_10))
- .child(
- "Captured in Studio Mode and added to \
- this project.",
- ),
- ),
- )
- .child(
- div()
- .id("clips-record-close")
- .flex()
- .flex_none()
- .justify_center()
- .items_center()
- .ml_auto()
- .rounded(px(6.))
- .size(px(28.))
- .text_color(Hsla::from(theme.gray_11))
- .hover(move |style| {
- style
- .bg(Hsla::from(theme.gray_4))
- .text_color(Hsla::from(theme.gray_12))
- })
- .child(svg().path("icons/x.svg").size(px(12.)))
- .on_click(cx.listener(|this, _, _window, cx| {
- this.clips.record_open = false;
- cx.notify();
- })),
- ),
- )
- // The body container (`:1000`): `flex flex-col flex-1
- // p-5 min-h-0`.
- .child(
- div()
- .flex()
- .flex_col()
- .flex_1()
- .p(px(20.))
- .min_h_0()
- .child(body),
- ),
- )
- .into_any_element(),
- )
- }
-
- /// The modal's home body (`:1004-1125`): the target grid over the device
- /// selects.
- fn render_record_modal_home(&self, cx: &mut Context<Self>) -> gpui::Div {
- let (camera, microphone, system_audio) = record_input_snapshot(cx);
-
- div()
- .flex()
- .flex_col()
- .flex_1()
- .min_h_0()
- .gap(px(16.))
- .child(
- div()
- .flex()
- .flex_col()
- .gap(px(8.))
- .w_full()
- .child(
- div()
- .flex()
- .flex_row()
- .gap(px(8.))
- .w_full()
- .child(self.record_split_target(
- "clips-record-display",
- "icons/monitor.svg",
- "Display",
- TargetType::Display,
- cx,
- ))
- .child(self.record_split_target(
- "clips-record-window",
- "icons/app-window-mac.svg",
- "Window",
- TargetType::Window,
- cx,
- )),
- )
- .child(
- div()
- .flex()
- .flex_row()
- .gap(px(8.))
- .w_full()
- .child(self.record_type_button(
- "clips-record-area",
- "icons/area.svg",
- "Area",
- TargetType::Area,
- true,
- cx,
- ))
- .child(self.record_type_button(
- "clips-record-camera-only",
- "icons/video.svg",
- "Camera Only",
- TargetType::CameraOnly,
- true,
- cx,
- )),
- ),
- )
- .child(
- div()
- .flex()
- .flex_col()
- .gap(px(8.))
- .child(self.record_select_row(
- "clips-record-camera",
- "icons/camera.svg",
- camera.unwrap_or_else(|| "No Camera".to_string()),
- true,
- cx.listener(|this, _, _window, cx| {
- this.clips.record_device_menu = Some(RecordDeviceMenu::Camera);
- this.clips.record_target_menu = None;
- cx.notify();
- }),
- ))
- .child(self.record_select_row(
- "clips-record-mic",
- "icons/microphone.svg",
- microphone.unwrap_or_else(|| "No Microphone".to_string()),
- true,
- cx.listener(|this, _, _window, cx| {
- this.clips.record_device_menu = Some(RecordDeviceMenu::Microphone);
- this.clips.record_target_menu = None;
- cx.notify();
- }),
- ))
- .child(self.record_select_row(
- "clips-record-system-audio",
- "icons/volume-2.svg",
- if system_audio {
- "Record System Audio".to_string()
- } else {
- "No System Audio".to_string()
- },
- false,
- cx.listener(|_this, _, _window, cx| {
- // A plain toggle, like the main window's own
- // system-audio row -- on the shared option, so it
- // goes through that window's entity, deferred.
- let main = cx.global::<app_windows::AppWindows>().main;
- cx.defer(move |cx: &mut gpui::App| {
- main.update(cx, |view, _window, cx| {
- let next = !view.system_audio_enabled();
- view.set_system_audio(next, cx);
- })
- .ok();
- });
- cx.notify();
- }),
- )),
- )
- }
-
- /// `TargetTypeButton` (`new-main/TargetTypeButton.tsx:28-48`), the
- /// name-only variant: `flex flex-col items-center gap-1 rounded-lg
- /// border py-2 justify-end`, icon `size-5 text-gray-10`, text-xs.
- fn record_type_button(
- &self,
- id: &'static str,
- icon: &'static str,
- name: &'static str,
- kind: TargetType,
- bordered: bool,
- cx: &mut Context<Self>,
- ) -> gpui::Stateful<gpui::Div> {
- let theme = self.theme;
- div()
- .id(id)
- .flex()
- .flex_1()
- .flex_col()
- .items_center()
- .justify_end()
- .gap(px(4.))
- .py(px(8.))
- .when(bordered, |this| {
- this.rounded(px(8.))
- .border_1()
- .border_color(Hsla::from(theme.gray_6))
- .bg(Hsla::from(theme.gray_2))
- })
- .cursor(CursorStyle::PointingHand)
- .hover(move |style| style.bg(Hsla::from(theme.gray_4)))
- .text_color(Hsla::from(theme.gray_12))
- .child(
- svg()
- .path(icon)
- .size(px(20.))
- .flex_shrink_0()
- .text_color(Hsla::from(theme.gray_10)),
- )
- .child(div().text_size(px(12.)).child(name))
- .on_click(cx.listener(move |this, _, _window, cx| {
- this.open_editor_target_mode(kind, cx);
- }))
- }
-
- /// The Display/Window split buttons (`:1006-1072`): a shared `rounded-lg
- /// border border-gray-5 bg-gray-3` shell -- the type half opens the
- /// picker across every display, the `border-l border-gray-6` chevron
- /// unfolds the concrete list.
- fn record_split_target(
- &self,
- id: &'static str,
- icon: &'static str,
- name: &'static str,
- kind: TargetType,
- cx: &mut Context<Self>,
- ) -> gpui::Div {
- let theme = self.theme;
- div()
- .flex()
- .flex_1()
- .overflow_hidden()
- .rounded(px(8.))
- .border_1()
- .border_color(Hsla::from(theme.gray_5))
- .bg(Hsla::from(theme.gray_3))
- .child(self.record_type_button(id, icon, name, kind, false, cx))
- .child(
- div()
- .id(SharedString::from(format!("{id}-menu")))
- .flex()
- .items_center()
- .justify_center()
- .px(px(8.))
- .border_l_1()
- .border_color(Hsla::from(theme.gray_6))
- .cursor(CursorStyle::PointingHand)
- .hover(move |style| style.bg(Hsla::from(theme.gray_5)))
- .child(
- svg()
- .path("icons/chevron-down.svg")
- .size(px(14.))
- .text_color(Hsla::from(theme.gray_10)),
- )
- .on_click(cx.listener(move |this, _, window, cx| {
- this.toggle_record_target_menu(kind, window, cx);
- })),
- )
- }
-
- /// `CameraSelectBase` / `MicrophoneSelectBase`'s shell (`:1106, 1119`):
- /// `h-[42px] rounded-lg border border-gray-5 bg-gray-3 px-2 gap-2`, live.
- /// `chevron` marks the two pickers; the system-audio toggle goes without.
- fn record_select_row(
- &self,
- id: &'static str,
- icon: &'static str,
- label: String,
- chevron: bool,
- on_click: impl Fn(&gpui::ClickEvent, &mut Window, &mut gpui::App) + 'static,
- ) -> gpui::Stateful<gpui::Div> {
- let theme = self.theme;
- div()
- .id(id)
- .flex()
- .flex_row()
- .items_center()
- .gap(px(8.))
- .px(px(8.))
- .w_full()
- .h(px(42.))
- .rounded(px(8.))
- .border_1()
- .border_color(Hsla::from(theme.gray_5))
- .bg(Hsla::from(theme.gray_3))
- .cursor(CursorStyle::PointingHand)
- .hover(move |style| style.bg(Hsla::from(theme.gray_4)))
- .text_size(px(13.))
- .text_color(Hsla::from(theme.gray_12))
- .child(
- svg()
- .path(icon)
- .size(px(16.))
- .flex_shrink_0()
- .text_color(Hsla::from(theme.gray_10)),
- )
- .child(div().flex_1().min_w_0().truncate().child(label))
- .when(chevron, |this| {
- this.child(
- svg()
- .path("icons/chevron-down.svg")
- .size(px(12.))
- .flex_shrink_0()
- .text_color(Hsla::from(theme.gray_10)),
- )
- })
- .on_click(on_click)
- }
-
- /// The back row shared by the unfolded menus (`:1129-1145`).
- fn record_menu_back(&self, cx: &mut Context<Self>) -> gpui::Stateful<gpui::Div> {
- let theme = self.theme;
- div()
- .id("clips-record-menu-back")
- .flex()
- .flex_none()
- .flex_row()
- .items_center()
- .gap(px(4.))
- .h(px(36.))
- .px(px(8.))
- .rounded(px(6.))
- .text_size(px(12.))
- .text_color(Hsla::from(theme.gray_11))
- .cursor(CursorStyle::PointingHand)
- .hover(move |style| style.bg(Hsla::from(theme.gray_4)))
- .child(
- svg()
- .path("icons/move-left.svg")
- .size(px(12.))
- .flex_shrink_0()
- .text_color(Hsla::from(theme.gray_11)),
- )
- .child(
- div()
- .font_weight(FontWeight::MEDIUM)
- .text_color(Hsla::from(theme.gray_12))
- .child("Back"),
- )
- .on_click(cx.listener(|this, _, _window, cx| {
- this.clips.record_target_menu = None;
- this.clips.record_device_menu = None;
- cx.notify();
- }))
- }
-
- /// A chevron menu's body (`:1128-1216`): back, search, and the concrete
- /// targets -- `TargetMenuGrid` as two columns of cards, each leading with
- /// the live ScreenCaptureKit thumbnail `target_thumbnails` captures.
- fn render_record_target_menu(&self, kind: TargetType, cx: &mut Context<Self>) -> gpui::Div {
- let theme = self.theme;
- let query = self.target_search_text(cx);
- let matches = |value: &str| query.is_empty() || value.to_lowercase().contains(&query);
-
- let loading = self.clips.record_devices.is_none();
- let mut cards: Vec<AnyElement> = Vec::new();
- if let Some(devices) = &self.clips.record_devices {
- match kind {
- TargetType::Display => {
- for display in devices
- .displays
- .iter()
- .filter(|display| matches(&display.label))
- {
- let chosen = display.clone();
- cards.push(
- self.record_target_card(
- SharedString::from(format!("record-display-{}", display.id)),
- self.clips.record_thumbnails.display(&display.id),
- "icons/monitor.svg",
- display.label.clone(),
- None,
- display.describe_refresh_rate(),
- cx.listener(move |this, _, _window, cx| {
- this.select_record_display(chosen.clone(), cx);
- }),
- )
- .into_any_element(),
- );
- }
- }
- TargetType::Window => {
- for target in devices
- .windows
- .iter()
- .filter(|window| matches(&window.label) || matches(&window.app))
- {
- let chosen = target.clone();
- cards.push(
- self.record_target_card(
- SharedString::from(format!("record-window-{}", target.id)),
- self.clips.record_thumbnails.window(&target.id),
- "icons/app-window-mac.svg",
- target.label.clone(),
- Some(target.app.clone()),
- target.describe_metadata(),
- cx.listener(move |this, _, _window, cx| {
- this.select_record_window(chosen.clone(), cx);
- }),
- )
- .into_any_element(),
- );
- }
- }
- TargetType::Area | TargetType::CameraOnly => {}
- }
- }
-
- let empty_message = |theme: &Theme, message: &'static str| {
- div()
- .py(px(24.))
- .w_full()
- .text_size(px(13.))
- .text_color(Hsla::from(theme.gray_11))
- .child(message)
- };
-
- let content: AnyElement = if loading {
- empty_message(&theme, "Loading...").into_any_element()
- } else if cards.is_empty() {
- empty_message(
- &theme,
- match (kind, query.is_empty()) {
- (TargetType::Display, true) => "No displays found",
- (TargetType::Display, false) => "No matching displays",
- (_, true) => "No windows found",
- (_, false) => "No matching windows",
- },
- )
- .into_any_element()
- } else {
- // Two columns as rows of two, the `render_target_grid` layout. The
- // cards carry their own width, so a lone trailing card keeps half
- // the row without a spacer holding the other half open.
- let mut grid = div().flex().flex_col().gap(px(8.)).w_full();
- let mut cards = cards.into_iter();
- while let Some(first) = cards.next() {
- let mut row = div()
- .flex()
- .flex_row()
- .gap(px(8.))
- .w_full()
- .items_stretch()
- .child(first);
- if let Some(second) = cards.next() {
- row = row.child(second);
- }
- grid = grid.child(row);
- }
- grid.into_any_element()
- };
-
- div()
- .flex()
- .flex_col()
- .flex_1()
- .min_h_0()
- .child(
- div()
- .flex()
- .flex_none()
- .flex_row()
- .items_center()
- .gap(px(12.))
- .min_h(px(36.))
- .child(self.record_menu_back(cx))
- .children(self.clips.target_search_input.as_ref().map(|input| {
- div().flex_1().min_w_0().child(
- ui::TextInput::plain(&theme, "clips-record-target-search", input)
- .height(px(36.))
- .text_size(px(13.))
- .padding_x(px(8.))
- .radius(px(6.))
- .bg(Hsla::from(theme.gray_3))
- .border(Hsla::from(theme.gray_5))
- .flex(true),
- )
- })),
- )
- .child(
- div()
- .id("clips-record-menu-scroll")
- .flex_1()
- .min_h_0()
- .pt(px(16.))
- .overflow_y_scroll()
- .child(content),
- )
- }
-
- /// `TargetCard`: the live thumbnail block over three 11px lines, the same
- /// component the main window's picker renders.
- #[allow(clippy::too_many_arguments)]
- fn record_target_card(
- &self,
- id: SharedString,
- thumb: target_thumbnails::TargetThumb,
- icon: &'static str,
- label: String,
- subtitle: Option<String>,
- metadata: Option<String>,
- on_click: impl Fn(&gpui::ClickEvent, &mut Window, &mut gpui::App) + 'static,
- ) -> gpui::Stateful<gpui::Div> {
- let theme = self.theme;
- div()
- .id(id)
- .flex()
- .flex_col()
- .w(px(RECORD_TARGET_CARD_WIDTH))
- .flex_none()
- .min_w_0()
- .overflow_hidden()
- .rounded(px(8.))
- .bg(theme.body_fill(3))
- .cursor(CursorStyle::PointingHand)
- .child(target_thumbnails::render_thumbnail_slot(thumb, icon, theme))
- .child(
- div()
- .flex()
- .flex_col()
- .w_full()
- .min_w_0()
- .px(px(8.))
- .py(px(6.))
- .text_size(px(11.))
- .child(
- div()
- .w_full()
- .truncate()
- .font_weight(FontWeight::MEDIUM)
- .text_color(Hsla::from(theme.gray_12))
- .child(label),
- )
- .children(subtitle.map(|subtitle| {
- div()
- .w_full()
- .truncate()
- .text_color(Hsla::from(theme.gray_11))
- .child(subtitle)
- }))
- .children(metadata.map(|metadata| {
- div()
- .w_full()
- .truncate()
- .text_color(Hsla::from(theme.gray_10))
- .child(metadata)
- })),
- )
- .hover(move |style| style.bg(theme.body_hover_fill(4)))
- .on_click(on_click)
- }
-
- /// A device select unfolded (`:1084-1122`): the "none" row first --
- /// turning the device off is not a search result -- then the enumerated
- /// options, exactly the main window panel's ordering. The selection
- /// lands on the shared options through the same setters that window's
- /// own rows use, deferred because it is another window's entity.
- fn render_record_device_menu(
- &self,
- menu: RecordDeviceMenu,
- cx: &mut Context<Self>,
- ) -> gpui::Div {
- let theme = self.theme;
- let (camera, microphone, _) = record_input_snapshot(cx);
-
- let mut rows: Vec<AnyElement> = Vec::new();
-
- let none_selected = match menu {
- RecordDeviceMenu::Camera => camera.is_none(),
- RecordDeviceMenu::Microphone => microphone.is_none(),
- };
- rows.push(
- self.record_device_row(
- SharedString::from("clips-record-device-none"),
- "icons/circle-x.svg",
- match menu {
- RecordDeviceMenu::Camera => "No Camera",
- RecordDeviceMenu::Microphone => "No Microphone",
- }
- .to_string(),
- none_selected,
- cx.listener(move |this, _, _window, cx| match menu {
- RecordDeviceMenu::Camera => this.set_record_camera(None, cx),
- RecordDeviceMenu::Microphone => this.set_record_microphone(None, cx),
- }),
- )
- .into_any_element(),
- );
-
- match &self.clips.record_devices {
- None => rows.push(
- div()
- .py(px(16.))
- .w_full()
- .text_size(px(13.))
- .text_color(Hsla::from(theme.gray_11))
- .child("Loading...")
- .into_any_element(),
- ),
- Some(devices) => match menu {
- RecordDeviceMenu::Camera => {
- for option in &devices.cameras {
- let selected = camera.as_deref() == Some(option.label.as_str());
- let chosen = option.clone();
- rows.push(
- self.record_device_row(
- SharedString::from(format!(
- "clips-record-camera-{}",
- option.device_id
- )),
- "icons/camera.svg",
- option.label.clone(),
- selected,
- cx.listener(move |this, _, _window, cx| {
- this.set_record_camera(Some(chosen.clone()), cx);
- }),
- )
- .into_any_element(),
- );
- }
- }
- RecordDeviceMenu::Microphone => {
- for option in &devices.microphones {
- let selected = microphone.as_deref() == Some(option.name.as_str());
- let chosen = option.clone();
- rows.push(
- self.record_device_row(
- SharedString::from(format!("clips-record-mic-{}", option.name)),
- "icons/microphone.svg",
- option.name.clone(),
- selected,
- cx.listener(move |this, _, _window, cx| {
- this.set_record_microphone(Some(chosen.clone()), cx);
- }),
- )
- .into_any_element(),
- );
- }
- }
- },
- }
-
- div()
- .flex()
- .flex_col()
- .flex_1()
- .min_h_0()
- .child(
- div()
- .flex()
- .flex_none()
- .flex_row()
- .items_center()
- .min_h(px(36.))
- .child(self.record_menu_back(cx)),
- )
- .child(
- div()
- .id("clips-record-device-scroll")
- .flex_1()
- .min_h_0()
- .pt(px(16.))
- .overflow_y_scroll()
- .child(div().flex().flex_col().gap(px(8.)).children(rows)),
- )
- }
-
- /// One row of a device select.
- fn record_device_row(
- &self,
- id: SharedString,
- icon: &'static str,
- label: String,
- selected: bool,
- on_click: impl Fn(&gpui::ClickEvent, &mut Window, &mut gpui::App) + 'static,
- ) -> gpui::Stateful<gpui::Div> {
- let theme = self.theme;
- div()
- .id(id)
- .flex()
- .flex_row()
- .items_center()
- .gap(px(8.))
- .px(px(8.))
- .w_full()
- .h(px(42.))
- .rounded(px(8.))
- .border_1()
- .border_color(if selected {
- Hsla::from(theme.blue_9)
- } else {
- Hsla::from(theme.gray_5)
- })
- .bg(Hsla::from(theme.gray_3))
- .cursor(CursorStyle::PointingHand)
- .hover(move |style| style.bg(Hsla::from(theme.gray_4)))
- .text_size(px(13.))
- .text_color(Hsla::from(theme.gray_12))
- .child(
- svg()
- .path(icon)
- .size(px(16.))
- .flex_shrink_0()
- .text_color(Hsla::from(theme.gray_10)),
- )
- .child(div().flex_1().min_w_0().truncate().child(label))
- .on_click(on_click)
- }
-
- /// `createCameraMutation` from the modal (`:1089-1103`), routed through
- /// the main window's setter (state plus the app-scoped feed, preview
- /// bubble included). The `skipCameraWindow: isCameraOnly` refinement has
- /// no seam here -- the bubble opens either way, as it does for every
- /// other selection path in this app.
- fn set_record_camera(&mut self, camera: Option<CameraOption>, cx: &mut Context<Self>) {
- self.clips.record_device_menu = None;
- let main = cx.global::<app_windows::AppWindows>().main;
- cx.defer(move |cx: &mut gpui::App| {
- main.update(cx, |view, _window, cx| {
- view.set_camera_selection(camera, cx)
- })
- .ok();
- });
- cx.notify();
- }
-
- /// `setOptions("micName", ...) + commands.setMicInput` (`:1113-1116`).
- fn set_record_microphone(
- &mut self,
- microphone: Option<MicrophoneOption>,
- cx: &mut Context<Self>,
- ) {
- self.clips.record_device_menu = None;
- let main = cx.global::<app_windows::AppWindows>().main;
- cx.defer(move |cx: &mut gpui::App| {
- main.update(cx, |view, _window, cx| {
- view.set_microphone_selection(microphone, cx)
- })
- .ok();
- });
- cx.notify();
- }
-
// -- Import (`ClipsSidebar.tsx:503-539`) -----------------------------------
/// `pickCapRecording` (`:533-539`): the `.cap` picker, rooted at the
@@ -2855,22 +1537,6 @@ fn show_append_error(message: &str) {
.show();
}
-/// The shared recording options, read off the main window -- the gpui home of
-/// `rawOptions`: the selected camera's label, the microphone name, and the
-/// system-audio flag, in that order.
-fn record_input_snapshot(cx: &gpui::App) -> (Option<String>, Option<String>, bool) {
- let main = cx.global::<app_windows::AppWindows>().main;
- main.read(cx)
- .map(|view| {
- (
- view.camera_selection().map(|camera| camera.label.clone()),
- view.microphone_selection().map(|mic| mic.name.clone()),
- view.system_audio_enabled(),
- )
- })
- .unwrap_or((None, None, false))
-}
-
// ---------------------------------------------------------------------------
// Thumbnail decode -- `decode_clip_thumbnail`
// (`src-tauri/src/clip_thumbnails.rs:67-215`), minus the JPEG cache: the
diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rs
index 86a186206..9ec95769c 100644
--- a/apps/desktop-gpui/src/main_window.rs
+++ b/apps/desktop-gpui/src/main_window.rs
@@ -43,6 +43,52 @@ const RECENT_CARD_HEIGHT: f32 = 112.;
/// `h-[42px]` in deviceRowStyles.ts.
const DEVICE_ROW_HEIGHT: f32 = 42.;
+fn remembered_camera(id: &recording::DeviceOrModelID, cameras: &[CameraOption]) -> CameraOption {
+ cameras
+ .iter()
+ .find(|camera| match id {
+ recording::DeviceOrModelID::DeviceID(id) => camera.device_id == *id,
+ recording::DeviceOrModelID::ModelID(model) => camera.model_id.as_ref() == Some(model),
+ })
+ .cloned()
+ .unwrap_or_else(|| CameraOption {
+ device_id: match id {
+ recording::DeviceOrModelID::DeviceID(id) => id.clone(),
+ recording::DeviceOrModelID::ModelID(_) => String::new(),
+ },
+ model_id: match id {
+ recording::DeviceOrModelID::ModelID(model) => Some(model.clone()),
+ recording::DeviceOrModelID::DeviceID(_) => None,
+ },
+ label: "Camera".to_string(),
+ best_format: None,
+ })
+}
+
+fn remembered_microphone(name: &str, microphones: &[MicrophoneOption]) -> MicrophoneOption {
+ microphones
+ .iter()
+ .find(|microphone| microphone.name == name)
+ .cloned()
+ .unwrap_or_else(|| MicrophoneOption {
+ name: name.to_string(),
+ sample_rate: None,
+ channels: None,
+ })
+}
+
+fn take_pending_recording_inputs(
+ pending: &mut crate::store::RecordingInputSettings,
+ enumerating: bool,
+ suspended: bool,
+) -> Option<crate::store::RecordingInputSettings> {
+ if enumerating || suspended || pending.camera_id.is_none() && pending.microphone_name.is_none()
+ {
+ return None;
+ }
+ Some(std::mem::take(pending))
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
Instant,
@@ -50,6 +96,14 @@ pub enum Mode {
Screenshot,
}
+fn effective_recording_mode(preferred: Mode, editor_recording: bool) -> Mode {
+ if editor_recording {
+ Mode::Studio
+ } else {
+ preferred
+ }
+}
+
impl Mode {
/// `cap_recording::RecordingMode`'s serialized spelling -- the value the
/// store's `recording_settings.mode` holds, shared with the Tauri app.
@@ -332,6 +386,14 @@ impl RecordingStartPermit {
fn same(&self, other: &Self) -> bool {
std::rc::Rc::ptr_eq(&self.0, &other.0)
}
+
+ fn cancel_current(current: &mut Option<Self>) -> bool {
+ let Some(permit) = current.take() else {
+ return false;
+ };
+ permit.cancel();
+ true
+ }
}
pub struct MainWindow {
@@ -341,7 +403,10 @@ pub struct MainWindow {
target: Option<TargetType>,
devices: DeviceSnapshot,
camera: Option<CameraOption>,
+ camera_id: Option<recording::DeviceOrModelID>,
microphone: Option<MicrophoneOption>,
+ pending_device_restore: crate::store::RecordingInputSettings,
+ device_restore_suspended: bool,
system_audio: bool,
/// Which display/window is selected for each split target.
selected_display: Option<DisplayOption>,
@@ -488,10 +553,34 @@ impl MainWindow {
let feeds = Feeds::global(cx);
cx.observe(&feeds, |this: &mut Self, feeds, cx| {
let feeds = feeds.read(cx);
- if this.camera.is_some() && feeds.camera.is_none() {
- this.camera = None;
- cx.notify();
- } else if matches!(this.panel, Some(Panel::Device(_))) {
+ let camera_id = feeds.camera.as_ref().map(|camera| &camera.id);
+ let camera_changed = this.camera_id.as_ref() != camera_id;
+ if camera_changed {
+ this.pending_device_restore.camera_id = None;
+ this.camera_id = camera_id.cloned();
+ this.camera = feeds.camera.as_ref().map(|selected| {
+ let mut camera = remembered_camera(&selected.id, &this.devices.cameras);
+ camera.label = selected.label.clone();
+ camera
+ });
+ if !crate::store::set_recording_camera_id(this.camera_id.as_ref()) {
+ tracing::warn!("Could not save the selected camera");
+ }
+ }
+ let microphone_changed = this.microphone.as_ref().map(|microphone| &microphone.name)
+ != feeds.microphone.as_ref();
+ if microphone_changed {
+ this.pending_device_restore.microphone_name = None;
+ this.microphone = feeds
+ .microphone
+ .as_deref()
+ .map(|name| remembered_microphone(name, &this.devices.microphones));
+ if !crate::store::set_recording_microphone_name(feeds.microphone.as_deref()) {
+ tracing::warn!("Could not save the selected microphone");
+ }
+ }
+ if camera_changed || microphone_changed || matches!(this.panel, Some(Panel::Device(_)))
+ {
cx.notify();
}
})
@@ -519,7 +608,10 @@ impl MainWindow {
target: None,
devices: DeviceSnapshot::default(),
camera: None,
+ camera_id: None,
microphone: None,
+ pending_device_restore: crate::store::RecordingInputSettings::load(),
+ device_restore_suspended: false,
system_audio: false,
selected_display: None,
selected_window: None,
@@ -577,6 +669,8 @@ impl MainWindow {
this.devices = snapshot;
this.enumerating = false;
+ this.restore_recording_inputs(cx);
+
// `CAP_GPUI_AUTO_CAMERA=1`: select the first camera the way a
// click would -- the automated check drives the preview window
// this way because synthetic clicks are dropped.
@@ -585,16 +679,7 @@ impl MainWindow {
&& let Some(first) = this.devices.cameras.first().cloned()
{
tracing::info!(camera = %first.label, "auto-selecting camera");
- this.camera = Some(first.clone());
- Feeds::global(cx).update(cx, |feeds, cx| {
- feeds.set_camera(
- Some(feeds::SelectedCamera {
- id: recording::DeviceOrModelID::DeviceID(first.device_id.clone()),
- label: first.label,
- }),
- cx,
- )
- });
+ this.set_camera_selection(Some(first), cx);
}
if std::env::var("CAP_GPUI_AUTO_MIC").is_ok_and(|value| value == "1")
&& this.microphone.is_none()
@@ -1341,7 +1426,8 @@ impl MainWindow {
/// `toggleTargetMode` / `selectDisplayTarget` / `selectWindowTarget` in
/// the Tauri main window, which each call `openTargetSelectOverlays` (or
/// `closeTargetSelectOverlays`) right after setting the mode.
- fn sync_overlays(&self, cx: &mut Context<Self>) {
+ fn sync_overlays(&mut self, cx: &mut Context<Self>) {
+ self.cancel_deep_link_start();
let Some(mode) = self.target else {
// Toggling the armed tile off is a dismissal ("cancelled" in the
// Tauri dismissal vocabulary), so it takes the same path Escape
@@ -1351,7 +1437,7 @@ impl MainWindow {
};
let request = app_windows::OverlayRequest {
mode,
- recording_mode: self.mode,
+ recording_mode: self.effective_mode(cx),
// A display picked from the dropdown narrows the overlays to that
// display; otherwise every display gets one.
display: match mode {
@@ -1369,7 +1455,21 @@ impl MainWindow {
_ => None,
},
};
- cx.defer(move |cx: &mut gpui::App| app_windows::open_target_overlays(request, cx));
+ let editor_target = self.session.read(cx).editor_recording_target();
+ cx.defer(move |cx: &mut gpui::App| {
+ if RecordingSession::global(cx)
+ .read(cx)
+ .editor_recording_target()
+ != editor_target
+ {
+ return;
+ }
+ if let Some(path) = editor_target {
+ app_windows::open_editor_target_overlays(path, request, cx);
+ } else {
+ app_windows::open_target_overlays(request, cx);
+ }
+ });
}
/// Called when the overlays are dismissed (Escape, their close button) so
@@ -1386,12 +1486,22 @@ impl MainWindow {
self.mode
}
+ pub(crate) fn effective_mode(&self, cx: &gpui::App) -> Mode {
+ effective_recording_mode(
+ self.mode(),
+ self.session.read(cx).editor_recording_target().is_some(),
+ )
+ }
+
/// `handleModeChange`: `setOptions({ mode })` plus
/// `commands.setRecordingMode(mode)`. The pill, the info panel and the mode
/// select window all land here, so there is one place a mode change
/// happens.
pub fn set_mode(&mut self, mode: Mode, cx: &mut Context<Self>) {
- if self.mode == mode {
+ if self.mode == mode
+ || self.is_preparing_recording()
+ || self.session.read(cx).editor_recording_target().is_some()
+ {
return;
}
self.mode = mode;
@@ -1448,8 +1558,8 @@ impl MainWindow {
/// The recording mode the Mode pill maps to, `None` for Screenshot (that
/// path does not go through the recording actors at all).
- fn recording_mode(&self) -> Option<recording::RecordingMode> {
- match self.mode {
+ fn recording_mode(&self, cx: &gpui::App) -> Option<recording::RecordingMode> {
+ match self.effective_mode(cx) {
Mode::Instant => Some(recording::RecordingMode::Instant),
Mode::Studio => Some(recording::RecordingMode::Studio),
Mode::Screenshot => None,
@@ -1488,6 +1598,9 @@ impl MainWindow {
let skip_mic = std::env::var("CAP_GPUI_AUTO_NO_MIC").is_ok_and(|v| v == "1")
|| mode == Mode::Screenshot;
+ if skip_mic {
+ self.set_microphone_selection(None, cx);
+ }
let required_window = auto_window_title();
cx.spawn_in(window, async move |this, cx| {
@@ -1511,7 +1624,7 @@ impl MainWindow {
.await;
if this
.update_in(cx, |this, _window, cx| {
- this.microphone = default_mic
+ let microphone = default_mic
.and_then(|name| {
this.devices
.microphones
@@ -1520,14 +1633,10 @@ impl MainWindow {
.cloned()
})
.or_else(|| this.devices.microphones.first().cloned());
- if let Some(mic) = &this.microphone {
+ if let Some(mic) = &microphone {
tracing::info!(mic = %mic.name, "auto-record microphone");
- // Through the app-scoped feed, so the automated run
- // exercises the same lock path a clicked selection uses.
- let name = mic.name.clone();
- Feeds::global(cx)
- .update(cx, |feeds, cx| feeds.set_microphone(Some(name), cx));
}
+ this.set_microphone_selection(microphone, cx);
})
.is_err()
{
@@ -1709,7 +1818,7 @@ impl MainWindow {
let Some(target) = self.armed_target() else {
return;
};
- if self.mode == Mode::Screenshot {
+ if self.effective_mode(cx) == Mode::Screenshot {
// Screenshot mode never reaches the recording actors -- the
// target goes straight to the capture path (`take_screenshot`).
cx.defer(move |cx: &mut gpui::App| crate::screenshot::take_screenshot(target, cx));
@@ -1745,7 +1854,7 @@ impl MainWindow {
let mode = if editor_flow {
recording::RecordingMode::Studio
} else {
- match self.recording_mode() {
+ match self.recording_mode(cx) {
Some(mode) => mode,
None => return,
}
@@ -1773,10 +1882,7 @@ impl MainWindow {
mode,
target,
microphone: self.microphone.as_ref().map(|mic| mic.name.clone()),
- camera: self
- .camera
- .as_ref()
- .map(|camera| recording::DeviceOrModelID::DeviceID(camera.device_id.clone())),
+ camera: self.camera_id.clone(),
system_audio: self.system_audio,
excluded_windows,
camera_feed,
@@ -1793,7 +1899,22 @@ impl MainWindow {
config: recording::StartConfig,
cx: &mut Context<Self>,
) {
- self.check_storage_before_start(config, false, None, cx);
+ if self.enumerating
+ || self.pending_device_restore.camera_id.is_some()
+ || self.pending_device_restore.microphone_name.is_some()
+ {
+ self.session.update(cx, |session, cx| {
+ session.error = Some(
+ "Recording devices are not ready. Open the recorder and try again.".into(),
+ );
+ cx.notify();
+ });
+ return;
+ }
+ let Ok(permit) = self.prepare_deep_link_start(cx) else {
+ return;
+ };
+ self.check_storage_before_start(config, false, permit, cx);
}
pub(crate) fn prepare_deep_link_start(
@@ -1805,18 +1926,28 @@ impl MainWindow {
app_windows::clean_capture_owned(cx),
self.checking_storage,
)?;
+ self.pending_device_restore = crate::store::RecordingInputSettings::default();
self.checking_storage = true;
self.deep_link_start = Some(permit.clone());
Ok(permit)
}
pub(crate) fn cancel_deep_link_start(&mut self) {
- if let Some(permit) = self.deep_link_start.take() {
- permit.cancel();
+ if RecordingStartPermit::cancel_current(&mut self.deep_link_start) {
self.checking_storage = false;
}
}
+ pub(crate) fn is_preparing_recording(&self) -> bool {
+ self.checking_storage || self.deep_link_start.is_some()
+ }
+
+ fn device_changes_allowed(&self, cx: &gpui::App) -> bool {
+ self.session.read(cx).phase == Phase::Idle
+ && !self.is_preparing_recording()
+ && !app_windows::clean_capture_owned(cx)
+ }
+
pub(crate) fn finish_deep_link_start(&mut self, permit: &RecordingStartPermit) {
if self
.deep_link_start
@@ -1833,46 +1964,36 @@ impl MainWindow {
permit: RecordingStartPermit,
cx: &mut Context<Self>,
) {
- self.check_storage_before_start(config, false, Some(permit), cx);
+ self.check_storage_before_start(config, false, permit, cx);
}
- fn recording_start_is_current(
- &self,
- permit: Option<&RecordingStartPermit>,
- cx: &gpui::App,
- ) -> bool {
+ fn recording_start_is_current(&self, permit: &RecordingStartPermit, cx: &gpui::App) -> bool {
self.session.read(cx).phase == Phase::Idle
- && permit.is_none_or(|permit| {
- self.deep_link_start
- .as_ref()
- .is_some_and(|current| current.same(permit))
- && permit.is_current(cx)
- })
+ && self
+ .deep_link_start
+ .as_ref()
+ .is_some_and(|current| current.same(permit))
+ && permit.is_current(cx)
}
- fn finish_recording_start(&mut self, permit: Option<&RecordingStartPermit>) {
- if let Some(permit) = permit {
- self.finish_deep_link_start(permit);
- } else {
- self.checking_storage = false;
- }
+ fn finish_recording_start(&mut self, permit: &RecordingStartPermit) {
+ self.finish_deep_link_start(permit);
}
fn check_storage_before_start(
&mut self,
- config: recording::StartConfig,
+ mut config: recording::StartConfig,
acknowledged: bool,
- permit: Option<RecordingStartPermit>,
+ permit: RecordingStartPermit,
cx: &mut Context<Self>,
) {
- if (permit.is_none() && self.checking_storage)
- || !self.recording_start_is_current(permit.as_ref(), cx)
- {
- if permit.is_some() {
- self.finish_recording_start(permit.as_ref());
- }
+ if !self.recording_start_is_current(&permit, cx) {
+ self.finish_recording_start(&permit);
return;
}
+ if matches!(config.target, ScreenCaptureTarget::CameraOnly) {
+ config.system_audio = false;
+ }
self.checking_storage = true;
let main = cx.global::<app_windows::AppWindows>().main;
cx.spawn(async move |this, cx| {
@@ -1880,8 +2001,8 @@ impl MainWindow {
recording::available_recording_storage()
}).await;
if !this.update(cx, |this, cx| {
- if !this.recording_start_is_current(permit.as_ref(), cx) {
- this.finish_recording_start(permit.as_ref());
+ if !this.recording_start_is_current(&permit, cx) {
+ this.finish_recording_start(&permit);
return false;
}
true
@@ -1892,11 +2013,11 @@ impl MainWindow {
Ok(storage) => storage,
Err(error) => {
this.update(cx, |this, cx| {
- if !this.recording_start_is_current(permit.as_ref(), cx) {
- this.finish_recording_start(permit.as_ref());
+ if !this.recording_start_is_current(&permit, cx) {
+ this.finish_recording_start(&permit);
return;
}
- this.finish_recording_start(permit.as_ref());
+ this.finish_recording_start(&permit);
this.session.update(cx, |session, cx| {
session.error = Some(format!("Could not check recording storage: {error}"));
cx.notify();
@@ -1912,23 +2033,18 @@ impl MainWindow {
let can_start = storage.status() != cap_utils::disk_space::DiskSpaceStatus::Exhausted;
if storage.status() == cap_utils::disk_space::DiskSpaceStatus::Ok || acknowledged && can_start {
this.update(cx, |this, cx| {
- if !this.recording_start_is_current(permit.as_ref(), cx) {
- this.finish_recording_start(permit.as_ref());
+ if !this.recording_start_is_current(&permit, cx) {
+ this.finish_recording_start(&permit);
return;
}
- if permit.is_none() {
- this.checking_storage = false;
- }
cx.defer(move |cx| {
- if let Some(permit) = permit {
- let allowed = main.update(cx, |this, _, cx| {
- let allowed = this.recording_start_is_current(Some(&permit), cx);
- this.finish_deep_link_start(&permit);
- allowed
- }).unwrap_or(false);
- if !allowed {
- return;
- }
+ let allowed = main.update(cx, |this, _, cx| {
+ let allowed = this.recording_start_is_current(&permit, cx);
+ this.finish_deep_link_start(&permit);
+ allowed
+ }).unwrap_or(false);
+ if !allowed {
+ return;
}
app_windows::begin_recording(config, cx);
});
@@ -1948,7 +2064,7 @@ impl MainWindow {
};
let receiver = cx.update(|cx| {
if RecordingSession::global(cx).read(cx).phase != Phase::Idle
- || permit.as_ref().is_some_and(|permit| !permit.is_current(cx))
+ || !permit.is_current(cx)
{
return Err(anyhow::anyhow!("Recording preparation is no longer current."));
}
@@ -1963,17 +2079,14 @@ impl MainWindow {
Err(_) => false,
};
this.update(cx, |this, cx| {
- if !this.recording_start_is_current(permit.as_ref(), cx) {
- this.finish_recording_start(permit.as_ref());
+ if !this.recording_start_is_current(&permit, cx) {
+ this.finish_recording_start(&permit);
return;
}
- if permit.is_none() {
- this.checking_storage = false;
- }
if confirmed {
this.check_storage_before_start(config, true, permit, cx);
} else {
- this.finish_recording_start(permit.as_ref());
+ this.finish_recording_start(&permit);
if this.session.read(cx).editor_recording_target().is_some() {
cx.defer(app_windows::abort_editor_recording_flow);
}
@@ -2025,19 +2138,74 @@ impl MainWindow {
self.microphone.as_ref()
}
- /// Whether the next recording captures system audio.
- pub fn system_audio_enabled(&self) -> bool {
- self.system_audio
+ pub(crate) fn device_snapshot(&self) -> &DeviceSnapshot {
+ &self.devices
+ }
+
+ pub(crate) fn is_enumerating_devices(&self) -> bool {
+ self.enumerating
+ }
+
+ pub(crate) fn suspend_device_restore(&mut self) {
+ self.device_restore_suspended = true;
+ }
+
+ pub(crate) fn resume_device_restore(&mut self, cx: &mut Context<Self>) {
+ self.device_restore_suspended = false;
+ self.restore_recording_inputs(cx);
+ }
+
+ fn restore_recording_inputs(&mut self, cx: &mut Context<Self>) {
+ let Some(settings) = take_pending_recording_inputs(
+ &mut self.pending_device_restore,
+ self.enumerating,
+ self.device_restore_suspended,
+ ) else {
+ return;
+ };
+ if let Some(id) = settings.camera_id {
+ let camera = remembered_camera(&id, &self.devices.cameras);
+ self.apply_camera_selection(Some(camera), Some(id), cx);
+ }
+ if let Some(name) = settings.microphone_name {
+ let microphone = remembered_microphone(&name, &self.devices.microphones);
+ self.apply_microphone_selection(Some(microphone), cx);
+ }
}
/// Select (or clear) the camera -- the same wiring as the camera panel's
/// rows: this window's state plus the app-scoped feed, which opens or
/// closes the preview bubble.
pub fn set_camera_selection(&mut self, camera: Option<CameraOption>, cx: &mut Context<Self>) {
- let selection = camera.as_ref().map(|camera| feeds::SelectedCamera {
- id: recording::DeviceOrModelID::DeviceID(camera.device_id.clone()),
- label: camera.label.clone(),
+ let id = camera.as_ref().map(|camera| {
+ camera
+ .model_id
+ .clone()
+ .map(recording::DeviceOrModelID::ModelID)
+ .unwrap_or_else(|| recording::DeviceOrModelID::DeviceID(camera.device_id.clone()))
});
+ self.pending_device_restore.camera_id = None;
+ if !crate::store::set_recording_camera_id(id.as_ref()) {
+ tracing::warn!("Could not save the selected camera");
+ }
+ self.apply_camera_selection(camera, id, cx);
+ }
+
+ fn apply_camera_selection(
+ &mut self,
+ camera: Option<CameraOption>,
+ id: Option<recording::DeviceOrModelID>,
+ cx: &mut Context<Self>,
+ ) {
+ let selection =
+ camera
+ .as_ref()
+ .zip(id.as_ref())
+ .map(|(camera, id)| feeds::SelectedCamera {
+ id: id.clone(),
+ label: camera.label.clone(),
+ });
+ self.camera_id = id;
self.camera = camera;
Feeds::global(cx).update(cx, |feeds, cx| {
let selected = selection.is_some();
@@ -2055,6 +2223,20 @@ impl MainWindow {
&mut self,
microphone: Option<MicrophoneOption>,
cx: &mut Context<Self>,
+ ) {
+ self.pending_device_restore.microphone_name = None;
+ if !crate::store::set_recording_microphone_name(
+ microphone.as_ref().map(|mic| mic.name.as_str()),
+ ) {
+ tracing::warn!("Could not save the selected microphone");
+ }
+ self.apply_microphone_selection(microphone, cx);
+ }
+
+ fn apply_microphone_selection(
+ &mut self,
+ microphone: Option<MicrophoneOption>,
+ cx: &mut Context<Self>,
) {
let label = microphone.as_ref().map(|mic| mic.name.clone());
self.microphone = microphone;
@@ -2122,6 +2304,11 @@ impl Render for MainWindow {
.when(app_windows::clean_capture_pending(cx), |this| {
this.child(self.render_clean_capture_preflight(cx))
})
+ .on_key_down(cx.listener(|this, event: &gpui::KeyDownEvent, _, cx| {
+ if event.keystroke.key == "escape" && this.dismiss_main(cx) {
+ cx.stop_propagation();
+ }
+ }))
}
}
@@ -2940,6 +3127,22 @@ impl MainWindow {
cx.notify();
}
+ fn dismiss_main(&mut self, cx: &mut Context<Self>) -> bool {
+ if self.panel.is_some() {
+ if self.search.is_empty() {
+ self.close_panel(cx);
+ } else {
+ self.clear_search(cx);
+ }
+ } else if self.session.read(cx).editor_recording_target().is_some() {
+ self.cancel_deep_link_start();
+ cx.defer(app_windows::abort_editor_recording_flow);
+ } else {
+ return false;
+ }
+ true
+ }
+
pub fn open_panel(&mut self, panel: Panel, window: &mut Window, cx: &mut Context<Self>) {
self.panel = Some(panel);
self.search.clear();
@@ -3864,11 +4067,7 @@ impl MainWindow {
cx.notify();
}
ui::TextInputEvent::Cancelled => {
- if self.search.is_empty() {
- self.close_panel(cx);
- } else {
- self.clear_search(cx);
- }
+ self.dismiss_main(cx);
}
_ => {}
}
@@ -3910,15 +4109,15 @@ impl MainWindow {
},
None,
cx.listener(move |this, _, _window, cx| {
+ if !this.device_changes_allowed(cx) {
+ return;
+ }
match menu {
DeviceMenu::Camera => {
- this.camera = None;
- Feeds::global(cx).update(cx, |feeds, cx| feeds.set_camera(None, cx));
+ this.set_camera_selection(None, cx);
}
DeviceMenu::Microphone => {
- this.microphone = None;
- Feeds::global(cx)
- .update(cx, |feeds, cx| feeds.set_microphone(None, cx));
+ this.set_microphone_selection(None, cx);
}
}
this.close_panel(cx);
@@ -3952,18 +4151,10 @@ impl MainWindow {
selected,
None,
cx.listener(move |this, _, _window, cx| {
- this.camera = Some(chosen.clone());
- Feeds::global(cx).update(cx, |feeds, cx| {
- feeds.set_camera(
- Some(feeds::SelectedCamera {
- id: recording::DeviceOrModelID::DeviceID(
- chosen.device_id.clone(),
- ),
- label: chosen.label.clone(),
- }),
- cx,
- )
- });
+ if !this.device_changes_allowed(cx) {
+ return;
+ }
+ this.set_camera_selection(Some(chosen.clone()), cx);
this.close_panel(cx);
}),
)
@@ -3996,10 +4187,10 @@ impl MainWindow {
feeds::picker_level(Feeds::global(cx).read(cx).mic_level_db)
}),
cx.listener(move |this, _, _window, cx| {
- this.microphone = Some(chosen.clone());
- Feeds::global(cx).update(cx, |feeds, cx| {
- feeds.set_microphone(Some(chosen.name.clone()), cx)
- });
+ if !this.device_changes_allowed(cx) {
+ return;
+ }
+ this.set_microphone_selection(Some(chosen.clone()), cx);
this.close_panel(cx);
}),
)
@@ -4227,13 +4418,16 @@ impl MainWindow {
/// both sets of strings are carried.
fn render_mode_info(&self, cx: &mut Context<Self>) -> gpui::Div {
let theme = self.theme;
+ let effective_mode = self.effective_mode(cx);
+ let locked = self.session.read(cx).editor_recording_target().is_some();
div().flex().flex_col().gap(px(8.)).w_full().children(
[Mode::Instant, Mode::Studio, Mode::Screenshot].map(|mode| {
- let selected = mode == self.mode;
+ let selected = mode == effective_mode;
div()
.id(SharedString::from(mode.panel_title()))
+ .when(locked && !selected, |this| this.opacity(0.5))
.flex()
.flex_row()
.items_center()
@@ -4515,12 +4709,14 @@ impl MainWindow {
/// `blue-500` ring offset 1px against `gray-1`.
fn render_mode_pill(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
- let selected_mode = self.mode;
+ let selected_mode = self.effective_mode(cx);
+ let locked = self.session.read(cx).editor_recording_target().is_some();
let button = |mode: Mode, id: &'static str| {
let selected = mode == selected_mode;
div()
.id(SharedString::from(id))
+ .when(locked && !selected, |this| this.opacity(0.5))
.flex()
.items_center()
.justify_center()
@@ -4551,6 +4747,9 @@ impl MainWindow {
)
.hover(|style| style.bg(theme.body_hover_fill(7)))
.on_click(cx.listener(move |this, _, _window, cx| {
+ if this.session.read(cx).editor_recording_target().is_some() {
+ return;
+ }
this.set_mode(mode, cx);
cx.defer(app_windows::refresh_target_overlays);
}))
@@ -4850,17 +5049,28 @@ impl MainWindow {
.map(|camera| camera.label.clone())
.unwrap_or_else(|| "No Camera".into()),
if self.camera.is_some() {
- PillState::On
+ if self.devices.cameras.iter().any(|camera| {
+ Some(&camera.device_id)
+ == self.camera.as_ref().map(|selected| &selected.device_id)
+ }) {
+ PillState::On
+ } else {
+ PillState::Disconnected
+ }
} else {
PillState::Off
},
+ Some(DeviceMenu::Camera),
+ cx,
)
.on_click(cx.listener(|this, _, window, cx| {
// Through `open_panel`, so the filter field takes focus
// the way it already does for the display and window
// panels -- before the field was real there was nothing
// to focus into.
- this.open_panel(Panel::Device(DeviceMenu::Camera), window, cx);
+ if !this.enumerating && this.device_changes_allowed(cx) {
+ this.open_panel(Panel::Device(DeviceMenu::Camera), window, cx);
+ }
})),
),
)
@@ -4875,17 +5085,28 @@ impl MainWindow {
.map(|mic| mic.name.clone())
.unwrap_or_else(|| "No Microphone".into()),
if self.microphone.is_some() {
- PillState::On
+ if self.devices.microphones.iter().any(|microphone| {
+ Some(&microphone.name)
+ == self.microphone.as_ref().map(|selected| &selected.name)
+ }) {
+ PillState::On
+ } else {
+ PillState::Disconnected
+ }
} else {
PillState::Off
},
+ Some(DeviceMenu::Microphone),
+ cx,
)
.on_click(cx.listener(|this, _, window, cx| {
// Through `open_panel`, so the filter field takes focus
// the way it already does for the display and window
// panels -- before the field was real there was nothing
// to focus into.
- this.open_panel(Panel::Device(DeviceMenu::Microphone), window, cx);
+ if !this.enumerating && this.device_changes_allowed(cx) {
+ this.open_panel(Panel::Device(DeviceMenu::Microphone), window, cx);
+ }
})),
),
)
@@ -4905,12 +5126,15 @@ impl MainWindow {
} else {
PillState::Off
},
+ None,
+ cx,
)
// System audio has no device to choose, so the row is a
// plain toggle rather than a picker.
.on_click(cx.listener(|this, _, _window, cx| {
- this.system_audio = !this.system_audio;
- cx.notify();
+ if this.device_changes_allowed(cx) {
+ this.set_system_audio(!this.system_audio, cx);
+ }
})),
),
)
@@ -5223,6 +5447,8 @@ impl MainWindow {
icon: &'static str,
label: String,
pill: PillState,
+ menu: Option<DeviceMenu>,
+ cx: &mut Context<Self>,
) -> gpui::Stateful<gpui::Div> {
let theme = self.theme;
@@ -5259,7 +5485,31 @@ impl MainWindow {
.truncate()
.child(label),
)
- .child(pill.render(theme))
+ .child(
+ div()
+ .id(SharedString::from(format!("{id}-toggle")))
+ .child(pill.render(theme))
+ .on_click(cx.listener(move |this, _, _window, cx| {
+ let Some(menu) = menu else {
+ return;
+ };
+ if this.enumerating || !this.device_changes_allowed(cx) {
+ cx.stop_propagation();
+ return;
+ }
+ match menu {
+ DeviceMenu::Camera if this.camera.is_some() => {
+ cx.stop_propagation();
+ this.set_camera_selection(None, cx);
+ }
+ DeviceMenu::Microphone if this.microphone.is_some() => {
+ cx.stop_propagation();
+ this.set_microphone_selection(None, cx);
+ }
+ _ => {}
+ }
+ })),
+ )
// `hover:border-gray-8` is not one of the classes theme.css remaps, so
// the border keeps its Radix step under the material.
.hover(|style| {
@@ -5346,6 +5596,7 @@ fn auto_area_rect() -> Option<crate::target_overlay::AreaRect> {
enum PillState {
On,
Off,
+ Disconnected,
}
impl PillState {
@@ -5353,6 +5604,11 @@ impl PillState {
let (bg, fg, text) = match self {
Self::On => (Hsla::from(theme.blue_9), gpui::white(), "On"),
Self::Off => (theme.body_fill(5), Hsla::from(theme.gray_11), "Off"),
+ Self::Disconnected => (
+ theme.body_fill(5),
+ Hsla::from(theme.gray_11),
+ "Not connected",
+ ),
};
div()
@@ -5399,6 +5655,95 @@ fn clear_shown_idle_error(phase: Phase, current: &mut Option<String>, shown: &st
true
}
+#[cfg(test)]
+mod remembered_device_tests {
+ use super::*;
+
+ fn camera(device: &str, model: Option<&str>) -> CameraOption {
+ CameraOption {
+ device_id: device.to_string(),
+ model_id: model.map(|model| cap_camera::ModelID::try_from(model.to_string()).unwrap()),
+ label: format!("Camera {device}"),
+ best_format: None,
+ }
+ }
+
+ #[test]
+ fn restores_model_identity_after_device_id_changes() {
+ let candidates = [
+ camera("other", Some("other:model")),
+ camera("new-id", Some("same:model")),
+ ];
+ let model = cap_camera::ModelID::try_from("same:model".to_string()).unwrap();
+ let restored = remembered_camera(&recording::DeviceOrModelID::ModelID(model), &candidates);
+ assert_eq!(restored, candidates[1]);
+ assert_eq!(
+ remembered_camera(
+ &recording::DeviceOrModelID::DeviceID("other".into()),
+ &candidates
+ ),
+ candidates[0]
+ );
+ }
+
+ #[test]
+ fn missing_camera_and_microphone_never_select_another_device() {
+ let cameras = [camera("unrequested", None)];
+ let missing = recording::DeviceOrModelID::DeviceID("remembered".into());
+ let restored = remembered_camera(&missing, &cameras);
+ assert_eq!(restored.device_id, "remembered");
+ assert_ne!(restored, cameras[0]);
+
+ let microphones = [MicrophoneOption {
+ name: "Unrequested microphone".into(),
+ sample_rate: Some(48000),
+ channels: Some(2),
+ }];
+ let restored = remembered_microphone("Remembered microphone", &microphones);
+ assert_eq!(restored.name, "Remembered microphone");
+ assert_eq!(restored.sample_rate, None);
+ assert_eq!(
+ remembered_microphone("Unrequested microphone", &microphones),
+ microphones[0]
+ );
+ }
+
+ #[test]
+ fn closing_before_enumeration_defers_saved_inputs_until_reopen_once() {
+ let saved = crate::store::RecordingInputSettings {
+ camera_id: Some(recording::DeviceOrModelID::DeviceID(
+ "remembered-camera".into(),
+ )),
+ microphone_name: Some("Remembered microphone".into()),
+ };
+ let mut pending = saved.clone();
+ assert!(take_pending_recording_inputs(&mut pending, true, false).is_none());
+ assert!(take_pending_recording_inputs(&mut pending, false, true).is_none());
+ assert_eq!(pending, saved);
+ let reopened = take_pending_recording_inputs(&mut pending, false, false).unwrap();
+ assert_eq!(reopened, saved);
+ assert!(take_pending_recording_inputs(&mut pending, false, false).is_none());
+ }
+
+ #[test]
+ fn explicit_off_during_suspended_restore_is_not_reversed_on_reopen() {
+ let mut pending = crate::store::RecordingInputSettings {
+ camera_id: Some(recording::DeviceOrModelID::DeviceID("old-camera".into())),
+ microphone_name: Some("Remembered microphone".into()),
+ };
+ assert!(take_pending_recording_inputs(&mut pending, false, true).is_none());
+ pending.camera_id = None;
+ assert!(take_pending_recording_inputs(&mut pending, true, false).is_none());
+ let reopened = take_pending_recording_inputs(&mut pending, false, false).unwrap();
+ assert!(reopened.camera_id.is_none());
+ assert_eq!(
+ reopened.microphone_name.as_deref(),
+ Some("Remembered microphone")
+ );
+ assert!(take_pending_recording_inputs(&mut pending, false, false).is_none());
+ }
+}
+
#[cfg(test)]
mod recording_start_permit_tests {
use super::*;
@@ -5486,6 +5831,33 @@ mod recording_start_permit_tests {
completion.cancel();
assert!(current.allows(Phase::Idle, false));
}
+
+ #[test]
+ fn cancel_current_rejects_queued_callbacks_after_rearm() {
+ let first = RecordingStartPermit::prepare(Phase::Idle, false, false).unwrap();
+ let callbacks: [_; 3] = std::array::from_fn(|_| first.clone());
+ let mut retained = Some(first);
+ assert!(RecordingStartPermit::cancel_current(&mut retained));
+ assert!(retained.is_none());
+ retained = Some(RecordingStartPermit::prepare(Phase::Idle, false, false).unwrap());
+
+ for callback in callbacks {
+ assert!(!callback.allows(Phase::Idle, false));
+ assert!(!retained.as_ref().unwrap().same(&callback));
+ callback.cancel();
+ assert!(retained.as_ref().unwrap().allows(Phase::Idle, false));
+ }
+ assert!(RecordingStartPermit::cancel_current(&mut retained));
+ assert!(!RecordingStartPermit::cancel_current(&mut retained));
+ }
+
+ #[test]
+ fn editor_recording_mode_does_not_change_the_normal_preference() {
+ for preferred in [Mode::Instant, Mode::Studio, Mode::Screenshot] {
+ assert_eq!(effective_recording_mode(preferred, true), Mode::Studio);
+ assert_eq!(effective_recording_mode(preferred, false), preferred);
+ }
+ }
}
#[cfg(test)]
diff --git a/apps/desktop-gpui/src/store.rs b/apps/desktop-gpui/src/store.rs
index 8e5543d04..ee2d47afc 100644
--- a/apps/desktop-gpui/src/store.rs
+++ b/apps/desktop-gpui/src/store.rs
@@ -935,6 +935,57 @@ pub const RECORDING_START_SAFETY: &str = "recording_start_safety";
/// the section the tray's Select Mode submenu reads and writes.
pub const RECORDING_SETTINGS: &str = "recording_settings";
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct RecordingInputSettings {
+ pub camera_id: Option<cap_recording::feeds::camera::DeviceOrModelID>,
+ pub microphone_name: Option<String>,
+}
+
+impl RecordingInputSettings {
+ pub fn load() -> Self {
+ let settings = store_section(RECORDING_SETTINGS);
+ Self {
+ camera_id: settings.get("cameraId").and_then(recording_camera_id),
+ microphone_name: settings
+ .get("micName")
+ .and_then(Value::as_str)
+ .filter(|name| !name.is_empty())
+ .map(str::to_string),
+ }
+ }
+}
+
+fn recording_camera_id(value: &Value) -> Option<cap_recording::feeds::camera::DeviceOrModelID> {
+ use cap_recording::feeds::camera::DeviceOrModelID;
+
+ let object = value.as_object()?;
+ if object.len() != 1 {
+ return None;
+ }
+ if let Some(id) = object.get("DeviceID").and_then(Value::as_str) {
+ return (!id.is_empty()).then(|| DeviceOrModelID::DeviceID(id.to_string()));
+ }
+ let model = object.get("ModelID")?.as_str()?.to_string();
+ cap_camera::ModelID::try_from(model)
+ .ok()
+ .map(DeviceOrModelID::ModelID)
+}
+
+pub fn set_recording_camera_id(id: Option<&cap_recording::feeds::camera::DeviceOrModelID>) -> bool {
+ let Ok(value) = serde_json::to_value(id) else {
+ return false;
+ };
+ set_store_setting(RECORDING_SETTINGS, "cameraId", value)
+}
+
+pub fn set_recording_microphone_name(name: Option<&str>) -> bool {
+ set_store_setting(
+ RECORDING_SETTINGS,
+ "micName",
+ name.map_or(Value::Null, |name| Value::String(name.to_string())),
+ )
+}
+
/// `RecordingSettingsStore.mode`, i.e. `cap_recording::RecordingMode` under
/// `#[serde(rename_all = "camelCase")]` -- one lowercase word per variant
/// (`studio`, `instant`, `screenshot`). `None` when the key is absent, which
@@ -1712,6 +1763,99 @@ mod tests {
}
}
+ #[test]
+ fn recording_inputs_round_trip_without_replacing_unknown_settings() {
+ use cap_recording::feeds::camera::DeviceOrModelID;
+
+ let store = TempStore::new(
+ "recording-inputs-round-trip",
+ Some(
+ r#"{"recording_settings":{"mode":"studio","cameraId":{"ModelID":"vendor:product"},"micName":"Desk microphone","cameraDeviceSettings":{"model:vendor:product":{"frameRate":30}},"unknown":{"keep":true}},"other":{"keep":[1,2]}}"#,
+ ),
+ );
+ let original = store.read();
+ let model = cap_camera::ModelID::try_from("vendor:product".to_string()).unwrap();
+ assert_eq!(
+ RecordingInputSettings::load(),
+ RecordingInputSettings {
+ camera_id: Some(DeviceOrModelID::ModelID(model)),
+ microphone_name: Some("Desk microphone".to_string()),
+ }
+ );
+
+ let camera = DeviceOrModelID::DeviceID("replacement-camera".to_string());
+ assert!(set_recording_camera_id(Some(&camera)));
+ assert!(set_recording_microphone_name(Some(
+ "Replacement microphone"
+ )));
+ assert_eq!(
+ RecordingInputSettings::load(),
+ RecordingInputSettings {
+ camera_id: Some(camera),
+ microphone_name: Some("Replacement microphone".to_string()),
+ }
+ );
+
+ assert!(set_recording_camera_id(None));
+ assert!(set_recording_microphone_name(None));
+ assert_eq!(
+ RecordingInputSettings::load(),
+ RecordingInputSettings::default()
+ );
+ let mut expected = original;
+ expected[RECORDING_SETTINGS]["cameraId"] = Value::Null;
+ expected[RECORDING_SETTINGS]["micName"] = Value::Null;
+ assert_eq!(store.read(), expected);
+ }
+
+ #[test]
+ fn recording_inputs_keep_saved_identity_without_device_enumeration() {
+ let store = TempStore::new(
+ "recording-inputs-absent-device",
+ Some(
+ r#"{"recording_settings":{"cameraId":{"DeviceID":"unplugged-camera"},"micName":"Unplugged microphone"}}"#,
+ ),
+ );
+ let before = std::fs::read(&store.path).unwrap();
+ let first = RecordingInputSettings::load();
+ assert_eq!(
+ first.microphone_name.as_deref(),
+ Some("Unplugged microphone")
+ );
+ assert_eq!(
+ first.camera_id,
+ Some(cap_recording::feeds::camera::DeviceOrModelID::DeviceID(
+ "unplugged-camera".into()
+ ))
+ );
+ assert_eq!(RecordingInputSettings::load(), first);
+ assert_eq!(std::fs::read(&store.path).unwrap(), before);
+ }
+
+ #[test]
+ fn recording_inputs_malformed_camera_does_not_panic_or_clear_other_settings() {
+ let store = TempStore::new(
+ "recording-inputs-malformed-model",
+ Some(
+ r#"{"recording_settings":{"cameraId":{"ModelID":"missing-separator"},"micName":"Valid microphone","future":42}}"#,
+ ),
+ );
+ let before = store.read();
+ let settings = RecordingInputSettings::load();
+ assert!(settings.camera_id.is_none());
+ assert_eq!(
+ settings.microphone_name.as_deref(),
+ Some("Valid microphone")
+ );
+ assert!(set_recording_microphone_name(None));
+ let after = store.read();
+ assert_eq!(
+ after[RECORDING_SETTINGS]["cameraId"],
+ before[RECORDING_SETTINGS]["cameraId"]
+ );
+ assert_eq!(after[RECORDING_SETTINGS]["future"], 42);
+ }
+
#[test]
fn temporary_stores_are_thread_local_without_mutating_process_environment() {
let original = std::env::var_os("CAP_GPUI_TAURI_STORE");
diff --git a/apps/desktop-gpui/src/target_overlay.rs b/apps/desktop-gpui/src/target_overlay.rs
index 131c15017..2d4ab4e37 100644
--- a/apps/desktop-gpui/src/target_overlay.rs
+++ b/apps/desktop-gpui/src/target_overlay.rs
@@ -67,6 +67,16 @@ fn required_window_title_matches(required: Option<&str>, actual: Option<&str>) -
required.is_none_or(|required| actual == Some(required))
}
+fn recording_devices_available(cx: &App) -> bool {
+ crate::session::RecordingSession::global(cx).read(cx).phase == crate::session::Phase::Idle
+ && !app_windows::clean_capture_owned(cx)
+ && cx
+ .global::<app_windows::AppWindows>()
+ .main
+ .read(cx)
+ .is_ok_and(|view| !view.is_preparing_recording())
+}
+
/// How close to an edge or corner counts as grabbing that handle. The TSX's
/// corner buttons are 30px boxes hung 12px outside the crop and its edge
/// buttons are 10px strips straddling the border; this is the same reach
@@ -454,6 +464,23 @@ pub struct OverlayWindow {
/// popped up at the event location (`target-select-overlay.tsx:2064-2090,
/// 2206-2210`). `Some` while it is open.
mode_menu: Option<crate::ui::MenuState>,
+ inline_camera: Option<Entity<crate::camera_window::CameraWindow>>,
+ inline_camera_subscription: Option<gpui::Subscription>,
+ empty_camera_state: crate::store::CameraWindowState,
+ device_menu: Option<OverlayDeviceMenu>,
+ _main_subscription: Option<gpui::Subscription>,
+}
+
+#[derive(Clone)]
+enum OverlayDeviceChoice {
+ Camera(Option<crate::devices::CameraOption>),
+ Microphone(Option<crate::devices::MicrophoneOption>),
+}
+
+struct OverlayDeviceMenu {
+ state: crate::ui::MenuState,
+ items: Vec<crate::ui::MenuItem>,
+ choices: Vec<OverlayDeviceChoice>,
}
/// `menuModes` (`target-select-overlay.tsx:2064-2090`): three check items, in
@@ -482,6 +509,11 @@ impl OverlayWindow {
crate::theme::bind_window(window, cx);
let theme = Theme::for_window(window, cx, false);
cx.observe(&select, |_, _, cx| cx.notify()).detach();
+ let main = cx.global::<app_windows::AppWindows>().main;
+ let main_subscription = main
+ .update(cx, |_, _, cx| cx.entity())
+ .ok()
+ .map(|main| cx.observe(&main, |_, _, cx| cx.notify()));
let logical = display
.logical_size()
@@ -504,6 +536,11 @@ impl OverlayWindow {
crop: None,
drag: None,
mode_menu: None,
+ inline_camera: None,
+ inline_camera_subscription: None,
+ empty_camera_state: crate::store::load().camera_window.unwrap_or_default(),
+ device_menu: None,
+ _main_subscription: main_subscription,
}
}
@@ -515,6 +552,7 @@ impl OverlayWindow {
/// (`CAP_GPUI_AUTO_AREA`), since unprivileged synthetic drags are dropped.
pub fn set_crop(&mut self, crop: AreaRect, cx: &mut Context<Self>) {
self.crop = Some(crop.clamped(self.display_size));
+ self.sync_area_camera(cx);
cx.notify();
}
@@ -593,6 +631,35 @@ impl OverlayWindow {
self.theme.refresh(window, cx, false);
}
+ fn sync_inline_camera(&mut self, cx: &mut Context<Self>) {
+ let camera = (self.select.read(cx).mode == Some(TargetType::CameraOnly))
+ .then(|| app_windows::camera_preview_entity(cx))
+ .flatten();
+ if self.inline_camera.as_ref().map(Entity::entity_id)
+ == camera.as_ref().map(Entity::entity_id)
+ {
+ return;
+ }
+ self.inline_camera_subscription = camera
+ .as_ref()
+ .map(|camera| cx.observe(camera, |_, _, cx| cx.notify()));
+ self.inline_camera = camera;
+ }
+
+ fn sync_area_camera(&self, cx: &mut Context<Self>) {
+ if self.select.read(cx).recording_mode == Mode::Screenshot {
+ return;
+ }
+ let display = self.display_id.clone();
+ let crop = self.crop;
+ let epoch = app_windows::camera_picker_epoch(cx);
+ cx.defer(move |cx| {
+ if app_windows::camera_picker_epoch(cx) == epoch {
+ app_windows::sync_camera_area(display, crop, cx);
+ }
+ });
+ }
+
/// True when the cursor is on this overlay's display -- `data-over` in the
/// display variant, `isActiveDisplay` in the area variant.
fn is_active_display(&self, cx: &App) -> bool {
@@ -603,6 +670,7 @@ impl OverlayWindow {
impl Render for OverlayWindow {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.sync_appearance(window, cx);
+ self.sync_inline_camera(cx);
let mode = self.select.read(cx).mode;
let root = div()
@@ -611,6 +679,19 @@ impl Render for OverlayWindow {
.key_context("TargetSelectOverlay")
.on_key_down(
cx.listener(|this, event: &gpui::KeyDownEvent, _window, cx| {
+ if let Some(menu) = &mut this.device_menu {
+ match menu.state.on_key(&event.keystroke.key) {
+ crate::ui::MenuKey::Commit(index) => this.choose_device(index, cx),
+ crate::ui::MenuKey::Dismiss => {
+ this.device_menu = None;
+ cx.notify();
+ }
+ crate::ui::MenuKey::Moved => cx.notify(),
+ crate::ui::MenuKey::Ignored => return,
+ }
+ cx.stop_propagation();
+ return;
+ }
// The Tauri app registers Escape as a *global* shortcut while
// the overlays are up; here it is a plain key handler on the
// overlay that has focus (see the README deviation).
@@ -644,11 +725,214 @@ impl Render for OverlayWindow {
};
// Painted after the variant so the dropdown sits above the start
// cluster it drops from.
- root.children(self.render_mode_menu(cx)).into_any_element()
+ root.children(self.render_mode_menu(cx))
+ .children(self.render_device_menu(cx))
+ .into_any_element()
}
}
impl OverlayWindow {
+ fn render_device_menu(&self, cx: &mut Context<Self>) -> Option<gpui::AnyElement> {
+ let menu = self.device_menu.as_ref()?;
+ Some(
+ crate::ui::Menu::plain(
+ &self.theme,
+ "overlay-device-menu",
+ menu.items.clone(),
+ &menu.state,
+ )
+ .on_select(cx.listener(|this, index: &usize, _, cx| {
+ this.choose_device(*index, cx);
+ }))
+ .on_dismiss(cx.listener(|this, _, _, cx| {
+ this.device_menu = None;
+ cx.notify();
+ }))
+ .into_any_element(),
+ )
+ }
+
+ fn choose_device(&mut self, index: usize, cx: &mut Context<Self>) {
+ let choice = self
+ .device_menu
+ .take()
+ .and_then(|menu| menu.choices.get(index).cloned());
+ if let Some(choice) = choice {
+ self.apply_device_choice(choice, cx);
+ }
+ cx.notify();
+ }
+
+ fn apply_device_choice(&mut self, choice: OverlayDeviceChoice, cx: &mut Context<Self>) {
+ self.device_menu = None;
+ let main = cx.global::<app_windows::AppWindows>().main;
+ cx.defer(move |cx| {
+ if !recording_devices_available(cx) {
+ return;
+ }
+ if let Err(error) = main.update(cx, |view, _, cx| match choice {
+ OverlayDeviceChoice::Camera(camera) => view.set_camera_selection(camera, cx),
+ OverlayDeviceChoice::Microphone(mic) => view.set_microphone_selection(mic, cx),
+ }) {
+ tracing::warn!(%error, "could not update the recording device");
+ }
+ });
+ cx.notify();
+ }
+
+ fn open_device_menu(&mut self, camera: bool, position: Point<Pixels>, cx: &mut Context<Self>) {
+ if !recording_devices_available(cx) {
+ return;
+ }
+ let main = cx.global::<app_windows::AppWindows>().main;
+ let Ok(view) = main.read(cx) else { return };
+ if view.is_enumerating_devices() {
+ return;
+ }
+ let (items, choices) = if camera {
+ let mut items = vec![crate::ui::MenuItem::new(
+ "No Camera",
+ view.camera_selection().is_none(),
+ )];
+ let mut choices = vec![OverlayDeviceChoice::Camera(None)];
+ for camera in &view.device_snapshot().cameras {
+ items.push(crate::ui::MenuItem::new(
+ camera.label.clone(),
+ view.camera_selection()
+ .is_some_and(|selected| selected.device_id == camera.device_id),
+ ));
+ choices.push(OverlayDeviceChoice::Camera(Some(camera.clone())));
+ }
+ (items, choices)
+ } else {
+ let mut items = vec![crate::ui::MenuItem::new(
+ "No Microphone",
+ view.microphone_selection().is_none(),
+ )];
+ let mut choices = vec![OverlayDeviceChoice::Microphone(None)];
+ for mic in &view.device_snapshot().microphones {
+ items.push(crate::ui::MenuItem::new(
+ mic.name.clone(),
+ view.microphone_selection()
+ .is_some_and(|selected| selected.name == mic.name),
+ ));
+ choices.push(OverlayDeviceChoice::Microphone(Some(mic.clone())));
+ }
+ (items, choices)
+ };
+ self.mode_menu = None;
+ self.device_menu = Some(OverlayDeviceMenu {
+ state: crate::ui::MenuState::new(position, &items),
+ items,
+ choices,
+ });
+ cx.notify();
+ }
+
+ fn render_device_control(&self, camera: bool, cx: &mut Context<Self>) -> gpui::AnyElement {
+ let main = cx.global::<app_windows::AppWindows>().main;
+ let Ok(view) = main.read(cx) else {
+ return div().into_any_element();
+ };
+ let selected = if camera {
+ view.camera_selection().map(|camera| camera.label.clone())
+ } else {
+ view.microphone_selection().map(|mic| mic.name.clone())
+ };
+ let enabled = selected.is_some();
+ let disabled = view.is_enumerating_devices() || !recording_devices_available(cx);
+ let theme = self.theme;
+ div()
+ .id(if camera {
+ "overlay-camera"
+ } else {
+ "overlay-microphone"
+ })
+ .flex()
+ .items_center()
+ .gap(px(8.))
+ .px(px(8.))
+ .h(px(42.))
+ .flex_1()
+ .min_w_0()
+ .rounded(px(8.))
+ .border_1()
+ .border_color(theme.gray_5)
+ .bg(theme.gray_3)
+ .text_color(theme.gray_12)
+ .when(disabled, |row| row.opacity(0.7))
+ .child(
+ svg()
+ .path(if camera {
+ "icons/camera.svg"
+ } else {
+ "icons/microphone.svg"
+ })
+ .size(px(16.))
+ .flex_shrink_0(),
+ )
+ .child(
+ div()
+ .flex_1()
+ .min_w_0()
+ .truncate()
+ .text_size(px(14.))
+ .child(selected.unwrap_or_else(|| {
+ if camera { "No Camera" } else { "No Microphone" }.into()
+ })),
+ )
+ .child(
+ div()
+ .id(if camera {
+ "overlay-camera-toggle"
+ } else {
+ "overlay-microphone-toggle"
+ })
+ .px(px(10.))
+ .h(px(24.))
+ .min_w(px(40.))
+ .flex()
+ .items_center()
+ .justify_center()
+ .rounded_full()
+ .text_size(px(11.))
+ .bg(if enabled {
+ Hsla::from(theme.blue_9)
+ } else {
+ Hsla::from(theme.gray_5)
+ })
+ .text_color(if enabled {
+ gpui::white()
+ } else {
+ Hsla::from(theme.gray_11)
+ })
+ .child(if enabled { "On" } else { "Off" })
+ .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
+ .on_click(cx.listener(move |this, event: &gpui::ClickEvent, _, cx| {
+ cx.stop_propagation();
+ if disabled {
+ return;
+ }
+ if enabled {
+ this.apply_device_choice(
+ if camera {
+ OverlayDeviceChoice::Camera(None)
+ } else {
+ OverlayDeviceChoice::Microphone(None)
+ },
+ cx,
+ );
+ } else {
+ this.open_device_menu(camera, event.position(), cx);
+ }
+ })),
+ )
+ .on_click(cx.listener(move |this, event: &gpui::ClickEvent, _, cx| {
+ this.open_device_menu(camera, event.position(), cx);
+ }))
+ .into_any_element()
+ }
+
/// The caret's dropdown while it is open -- `Menu.popup` in the source,
/// rendered with the app's own menu component here (the closest thing to
/// a native context menu this side of AppKit; check state, outside-click
@@ -676,6 +960,14 @@ impl OverlayWindow {
/// `TargetSelect::set_recording_mode`, and refreshes the tray.
fn choose_mode(&mut self, index: usize, cx: &mut Context<Self>) {
self.mode_menu = None;
+ if crate::session::RecordingSession::global(cx)
+ .read(cx)
+ .editor_recording_target()
+ .is_some()
+ {
+ cx.notify();
+ return;
+ }
if let Some((_, mode)) = MODE_MENU.get(index).copied() {
app_windows::set_recording_mode(mode, cx);
}
@@ -827,10 +1119,46 @@ impl OverlayWindow {
.into_any_element()
}
- /// The camera-only variant: no capture target to pick, just the start
- /// cluster over a dim screen. The TSX also inlines a camera preview here;
- /// ours keeps the preview bubble window it already has (README deviation).
fn render_camera_variant(&self, cx: &mut Context<Self>) -> impl IntoElement {
+ let preview = if let Some(camera) = &self.inline_camera {
+ let (width, height) = camera.read(cx).inline_size(self.display_size);
+ div()
+ .w(px(width))
+ .h(px(height))
+ .flex_none()
+ .child(camera.clone())
+ .into_any_element()
+ } else {
+ let (width, height) = crate::camera_window::inline_preview_size(
+ &self.empty_camera_state,
+ None,
+ self.display_size,
+ );
+ div()
+ .w(px(width))
+ .h(px(height))
+ .pt(px(crate::camera_window::CAMERA_TOOLBAR_HEIGHT))
+ .child(
+ div()
+ .size_full()
+ .flex()
+ .flex_col()
+ .items_center()
+ .justify_center()
+ .gap(px(8.))
+ .rounded(px(crate::camera_window::preview_radius(
+ &self.empty_camera_state,
+ )))
+ .border_1()
+ .border_color(self.theme.gray_6)
+ .bg(gpui::black())
+ .text_size(px(14.))
+ .text_color(self.theme.gray_11)
+ .child(svg().path("icons/camera.svg").size(px(32.)))
+ .child("Please select a camera"),
+ )
+ .into_any_element()
+ };
div()
.size_full()
.relative()
@@ -863,6 +1191,15 @@ impl OverlayWindow {
.child("Record using only your camera and microphone"),
),
)
+ .child(
+ div()
+ .flex()
+ .justify_center()
+ .w_full()
+ .px(px(24.))
+ .mb(px(16.))
+ .child(preview),
+ )
.child(self.render_controls_cluster(self.target(cx), false, cx))
}
@@ -1119,10 +1456,16 @@ impl OverlayWindow {
let (screen_width, screen_height) = self.display_size;
let below = crop.bottom() + MARGIN_BELOW;
- let y = if below + CLUSTER_HEIGHT <= screen_height {
+ let cluster_height = CLUSTER_HEIGHT
+ + if self.select.read(cx).recording_mode == Mode::Screenshot {
+ 0.
+ } else {
+ 78.
+ };
+ let y = if below + cluster_height <= screen_height {
below
} else {
- let above = crop.y - CLUSTER_HEIGHT - MARGIN_TOP_OUTSIDE;
+ let above = crop.y - cluster_height - MARGIN_TOP_OUTSIDE;
if above >= TOP_SAFE_MARGIN {
above
} else {
@@ -1202,10 +1545,6 @@ impl OverlayWindow {
/// `RecordingControls`: the close button, the gradient start pill with its
/// mode line and caret, and the pre-recording settings button.
- ///
- /// The device row (a second glass card with camera and microphone selects)
- /// and the "What is X Mode?" link below it are deferred -- the device
- /// pickers live in the main window here (README).
fn render_controls_cluster(
&self,
target: Option<ScreenCaptureTarget>,
@@ -1260,6 +1599,18 @@ impl OverlayWindow {
),
),
)
+ .when(mode != Mode::Screenshot, |cluster| {
+ cluster.child(
+ self.glass_surface().p(px(12.)).child(
+ div()
+ .flex()
+ .gap(px(8.))
+ .w_full()
+ .child(self.render_device_control(true, cx))
+ .child(self.render_device_control(false, cx)),
+ ),
+ )
+ })
}
/// `size-9 rounded-full bg-gray-12` with the inverted X glyph.
@@ -1413,7 +1764,15 @@ impl OverlayWindow {
MouseButton::Left,
cx.listener(|this, event: &gpui::MouseDownEvent, _window, cx| {
cx.stop_propagation();
+ if crate::session::RecordingSession::global(cx)
+ .read(cx)
+ .editor_recording_target()
+ .is_some()
+ {
+ return;
+ }
let current = this.select.read(cx).recording_mode;
+ this.device_menu = None;
this.mode_menu = Some(crate::ui::MenuState::new(
event.position,
&mode_menu_items(current),
@@ -1515,6 +1874,7 @@ impl OverlayWindow {
Some(AreaDrag::Draw { anchor: point })
}
};
+ self.sync_area_camera(cx);
cx.notify();
}
@@ -1563,6 +1923,7 @@ impl OverlayWindow {
};
self.crop = Some(next);
+ self.sync_area_camera(cx);
cx.notify();
}
@@ -1578,6 +1939,7 @@ impl OverlayWindow {
self.crop = Some(crop.clamped(self.display_size));
}
}
+ self.sync_area_camera(cx);
// Releasing a fresh draw in screenshot mode captures immediately --
// the screenshot area picker has no confirm step
// (`target-select-overlay.tsx`'s area mouse-up). Move/resize grabs
diff --git a/apps/desktop-gpui/src/target_thumbnails.rs b/apps/desktop-gpui/src/target_thumbnails.rs
index dcd90e0bf..c553c37df 100644
--- a/apps/desktop-gpui/src/target_thumbnails.rs
+++ b/apps/desktop-gpui/src/target_thumbnails.rs
@@ -208,25 +208,6 @@ impl ThumbnailCache {
dropped
}
- /// Empty the cache, handing back every image for atlas eviction.
- ///
- /// Clears the in-flight flags as well, because the only caller that resets
- /// is one that is also dropping the tasks those flags belong to (the record
- /// modal reopening). Leaving a flag set behind a dropped task would wedge
- /// that kind's refresh permanently. A sweep whose `flume` receiver went
- /// with the task stops at its next `send`, so at worst one extra screenshot
- /// overlaps the new sweep.
- #[must_use = "the images have to be dropped from the window's atlas"]
- pub fn reset(&mut self) -> Vec<Arc<RenderImage>> {
- let mut images: Vec<_> = self.displays.drain().map(|(_, image)| image).collect();
- images.extend(self.windows.drain().filter_map(|(_, thumb)| thumb.image));
- self.display_signature = None;
- self.window_signature = None;
- self.display_inflight = false;
- self.window_inflight = false;
- images
- }
-
pub fn display_inflight(&self) -> bool {
self.display_inflight
}
@@ -1627,33 +1608,4 @@ mod tests {
}));
assert_eq!(rx.try_iter().collect::<Vec<_>>(), vec!["captured"]);
}
-
- #[test]
- fn reset_returns_every_image_and_clears_the_inflight_flags() {
- let mut cache = ThumbnailCache::default();
- let _ = cache.insert_display(
- &DisplayId::from_str("1").unwrap(),
- crate::library::rgba_to_render_image(solid(2, 2, [1; 4])),
- );
- let _ = cache.insert_window(
- &WindowId::from_str("2").unwrap(),
- Some(crate::library::rgba_to_render_image(solid(2, 2, [2; 4]))),
- None,
- );
- cache.set_display_inflight(true);
- cache.set_window_inflight(true);
- cache.set_display_signature("stale".into());
-
- let images = cache.reset();
- assert_eq!(images.len(), 2);
- assert!(!cache.display_inflight());
- assert!(!cache.window_inflight());
- assert!(cache.displays_stale(&[]));
- assert!(
- cache
- .display(&DisplayId::from_str("1").unwrap())
- .image
- .is_none()
- );
- }
}