Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: restore GPUI recorder interaction parity

Richie McIlroyc9059c3f4090
diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rs
index 8cd3bf0b0..43ac6766d 100644
--- a/apps/desktop-gpui/src/app_windows.rs
+++ b/apps/desktop-gpui/src/app_windows.rs
@@ -357,7 +357,11 @@ pub fn init(main: WindowHandle<MainWindow>, session: Entity<RecordingSession>, c
let escape = platform::escape_hotkey_events();
cx.spawn(async move |cx| {
while escape.recv_async().await.is_ok() {
- cx.update(dismiss_target_overlays);
+ cx.update(|cx| {
+ if TargetSelect::global(cx).read(cx).mode.is_some() {
+ dismiss_target_overlays(cx);
+ }
+ });
}
})
.detach();
@@ -377,6 +381,7 @@ pub fn init(main: WindowHandle<MainWindow>, session: Entity<RecordingSession>, c
return;
}
close_controls(&session, cx);
+ close_target_overlays(cx);
#[cfg(target_os = "linux")]
if !restore_clean_capture_ui(cx) {
return;
@@ -873,6 +878,24 @@ fn first_registered_reopen_target(
.find(|candidate| live.contains(&candidate.window_id()))
}
+pub fn open_quality_settings(mode: Mode, cx: &mut App) {
+ if mode == Mode::Screenshot {
+ return;
+ }
+ #[cfg(target_os = "linux")]
+ if defer_window_until_capture_safe(cx) {
+ return;
+ }
+ open_settings(Page::General, cx);
+ if let Some(handle) = cx.global::<AppWindows>().settings {
+ handle
+ .update(cx, |view, window, cx| {
+ view.show_quality_settings(mode, window, cx);
+ })
+ .ok();
+ }
+}
+
/// Open the settings window on a page, and hide the main window.
///
/// The header gear in `new-main/index.tsx` is
@@ -1823,6 +1846,10 @@ pub fn dismiss_target_overlays(cx: &mut App) {
/// selection alone.
pub fn close_target_overlays(cx: &mut App) {
close_overlay_windows(cx);
+ disarm_target_selection(cx);
+}
+
+fn disarm_target_selection(cx: &mut App) {
let select = TargetSelect::global(cx);
select.update(cx, |select, cx| {
let recording_mode = select.recording_mode;
@@ -1831,6 +1858,133 @@ pub fn close_target_overlays(cx: &mut App) {
sync_camera_presentation(cx);
}
+fn area_overlay_matches(
+ target: &ScreenCaptureTarget,
+ candidate: &ScreenCaptureTarget,
+ capture_excluded: bool,
+) -> bool {
+ let (
+ ScreenCaptureTarget::Area { screen, bounds },
+ ScreenCaptureTarget::Area {
+ screen: candidate_screen,
+ bounds: candidate_bounds,
+ },
+ ) = (target, candidate)
+ else {
+ return false;
+ };
+ capture_excluded
+ && screen == candidate_screen
+ && bounds.position() == candidate_bounds.position()
+ && bounds.size() == candidate_bounds.size()
+}
+
+fn area_overlay_for_recording(
+ target: &ScreenCaptureTarget,
+ cx: &mut App,
+) -> Option<WindowHandle<OverlayWindow>> {
+ let ScreenCaptureTarget::Area { screen, .. } = target else {
+ return None;
+ };
+ let handle = overlay_handle(Some(screen.clone()), cx)?;
+ handle
+ .update(cx, |view, window, cx| {
+ let candidate = view.target(cx)?;
+ #[cfg(target_os = "macos")]
+ let capture_excluded = platform::window_is_visible(window)
+ && platform::window_number(window).is_some_and(|number| number > 0);
+ #[cfg(not(target_os = "macos"))]
+ let capture_excluded = {
+ let _ = window;
+ false
+ };
+ area_overlay_matches(target, &candidate, capture_excluded).then_some(handle)
+ })
+ .ok()
+ .flatten()
+}
+
+fn close_other_overlays(retained: WindowHandle<OverlayWindow>, cx: &mut App) {
+ let closing: Vec<_> = cx
+ .global::<AppWindows>()
+ .overlays
+ .iter()
+ .filter(|(_, handle)| *handle != retained)
+ .map(|(display, _)| display.clone())
+ .collect();
+ for display in closing {
+ close_overlay(&display, cx);
+ }
+}
+
+fn retain_recording_area(
+ target: &ScreenCaptureTarget,
+ cx: &mut App,
+) -> Option<WindowHandle<OverlayWindow>> {
+ let Some(handle) = area_overlay_for_recording(target, cx) else {
+ close_target_overlays(cx);
+ return None;
+ };
+ let committed = handle
+ .update(cx, |view, _, cx| {
+ view.is_recording_area() || view.commit_area_for_recording(cx)
+ })
+ .unwrap_or(false);
+ if !committed {
+ close_target_overlays(cx);
+ return None;
+ }
+ release_camera_park(cx);
+ close_other_overlays(handle, cx);
+ platform::unregister_escape_hotkey();
+ disarm_target_selection(cx);
+ Some(handle)
+}
+
+fn make_recording_area_passive(handle: WindowHandle<OverlayWindow>, cx: &mut App) {
+ cx.spawn(async move |cx| {
+ let native = cx.update(|cx| {
+ if RecordingSession::global(cx).read(cx).phase == Phase::Idle
+ || !cx
+ .global::<AppWindows>()
+ .overlays
+ .iter()
+ .any(|(_, current)| *current == handle)
+ {
+ return None;
+ }
+ Some(
+ handle
+ .update(cx, |view, window, _| {
+ view.is_recording_area()
+ .then(|| platform::native_window(window))
+ .flatten()
+ })
+ .ok()
+ .flatten(),
+ )
+ });
+ let Some(native) = native else {
+ return;
+ };
+ if !native.is_some_and(|native| platform::set_window_click_through(&native, true)) {
+ tracing::warn!("recording area click-through failed; removing the outline");
+ cx.update(|cx| {
+ let display = cx
+ .global::<AppWindows>()
+ .overlays
+ .iter()
+ .find(|(_, current)| *current == handle)
+ .map(|(display, _)| display.clone());
+ if let Some(display) = display {
+ close_overlay(&display, cx);
+ }
+ });
+ }
+ })
+ .detach();
+}
+
/// Repaint every overlay. The cursor probe runs while none of them is the
/// active window, and an inactive window only repaints when told to.
pub fn refresh_target_overlays(cx: &mut App) {
@@ -1870,33 +2024,54 @@ fn overlay_window_ids(cx: &mut App) -> Vec<scap_targets::WindowId> {
.collect()
}
-/// The overlay's Start button: overlays down, then the main window's start
-/// path with the target the overlay resolved.
pub fn start_recording_from_overlay(target: ScreenCaptureTarget, cx: &mut App) {
+ let main = cx.global::<AppWindows>().main;
+ if RecordingSession::global(cx).read(cx).phase != Phase::Idle
+ || main
+ .update(cx, |view, _, _| view.is_preparing_recording())
+ .unwrap_or(true)
+ {
+ return;
+ }
// Collected before the windows go away: the capture starts a beat after
// this, and an overlay that has not finished closing must not end up in
// the recording.
let excluded = overlay_window_ids(cx);
- // `onRecordingStart` nulls the saved camera bounds before the dismissal
- // (`target-select-overlay.tsx:687-690`): a bubble parked inside the picked
- // window stays there for the recording.
- release_camera_park(cx);
- close_target_overlays(cx);
- // A "recordingStudio" dismissal does not reveal the main window -- the bar
- // owns the foreground now, and the stop flow's reshow brings it back.
- cx.global_mut::<AppWindows>().main_hidden_for_picker = false;
- // Same for an editor-owned picker (`targetModeSource === "editorRecording"`
- // in the `ClipsSidebar` effect, `:416-419`): the editor stays hidden for
- // the whole recording, and the session observer's finish path reveals it.
- // The session's editor recording target survives -- that is what routes
- // the finished capture back into the project.
- cx.global_mut::<AppWindows>().editor_hidden_for_picker = None;
+ let retained_area =
+ cfg!(target_os = "macos") && matches!(&target, ScreenCaptureTarget::Area { .. });
+ if retained_area {
+ let handle = area_overlay_for_recording(&target, cx).filter(|handle| {
+ handle
+ .update(cx, |view, _, cx| view.commit_area_for_recording(cx))
+ .unwrap_or(false)
+ });
+ let Some(handle) = handle else {
+ dismiss_target_overlays(cx);
+ RecordingSession::global(cx).update(cx, |session, cx| {
+ session.error = Some(
+ "The selected area changed or is no longer available. Select it again.".into(),
+ );
+ cx.notify();
+ });
+ return;
+ };
+ close_other_overlays(handle, cx);
+ } else {
+ release_camera_park(cx);
+ close_target_overlays(cx);
+ cx.global_mut::<AppWindows>().main_hidden_for_picker = false;
+ cx.global_mut::<AppWindows>().editor_hidden_for_picker = None;
+ }
- let main = cx.global::<AppWindows>().main;
- main.update(cx, |view, window, cx| {
- view.start_recording_with_target(target, excluded, window, cx)
- })
- .ok();
+ let preparing = main
+ .update(cx, |view, window, cx| {
+ view.start_recording_with_target(target, excluded, window, cx);
+ view.is_preparing_recording()
+ })
+ .unwrap_or(false);
+ if retained_area && !preparing && RecordingSession::global(cx).read(cx).phase == Phase::Idle {
+ dismiss_target_overlays(cx);
+ }
}
/// Seed an area selection on the overlay for a display (harness path -- the
@@ -1990,6 +2165,14 @@ fn open_overlay(
.flatten();
let (x, y) = (bounds.position().x(), bounds.position().y());
cx.spawn(async move |cx| {
+ if !cx.update(|cx| {
+ cx.global::<AppWindows>()
+ .overlays
+ .iter()
+ .any(|(_, current)| *current == handle)
+ }) {
+ return;
+ }
if let Some(native) = &native {
platform::place_overlay_panel(
native,
@@ -2017,6 +2200,11 @@ fn open_overlay(
window.refresh();
})
.ok();
+ if let Some(camera) = cx.update(visible_camera_frame)
+ && let Err(error) = camera.raise()
+ {
+ tracing::warn!(%error, "could not raise the camera above the target picker");
+ }
})
.detach();
}
@@ -3256,18 +3444,14 @@ fn begin_recording_after_preflight(config: StartConfig, cx: &mut App) {
}
set_teleprompter_content_protection(true, cx);
- // `crate::target_select_overlay::close_target_select_overlay_windows(&app)`
- // at `recording.rs:1758`: the pickers come down at *every* recording start,
- // not just the ones the overlay's own Start button drove. The overlay path
- // hands its ids in already (`start_recording_from_overlay`), but the
- // hotkey, deeplink and tile paths pass an empty list, and an overlay that
- // has not finished closing is still on screen when the capture opens.
for id in overlay_window_ids(cx) {
if !excluded.contains(&id) {
excluded.push(id);
}
}
- close_target_overlays(cx);
+ let recording_area = retain_recording_area(&config.target, cx);
+ cx.global_mut::<AppWindows>().main_hidden_for_picker = false;
+ cx.global_mut::<AppWindows>().editor_hidden_for_picker = None;
// The user-configurable half. `resolve_excluded_window_ids` (in
// `recording::start`) walks `CGWindowList` for *other* processes' windows;
@@ -3292,6 +3476,7 @@ fn begin_recording_after_preflight(config: StartConfig, cx: &mut App) {
own,
move |kind| match kind {
OwnWindow::Camera => camera_hidden,
+ OwnWindow::TargetSelect => true,
kind => protected.contains(&kind),
},
cx,
@@ -3313,6 +3498,13 @@ fn begin_recording_after_preflight(config: StartConfig, cx: &mut App) {
..config
};
session.update(cx, |session, cx| session.start(config, cx));
+ if let Some(handle) = recording_area {
+ if session.read(cx).phase == Phase::Idle {
+ close_target_overlays(cx);
+ } else {
+ make_recording_area_passive(handle, cx);
+ }
+ }
}
/// Open the camera preview bubble (idempotent). Placement is the Tauri
@@ -3530,6 +3722,7 @@ const CAMERA_PARK_PADDING: f32 = 16.;
struct CameraFrame {
native: CameraNativeFrame,
snapshot: CameraSnapshot,
+ visible: bool,
}
enum CameraNativeFrame {
@@ -3606,6 +3799,7 @@ fn camera_frame(cx: &mut App) -> Option<CameraFrame> {
let (native, bounds) = camera_native_frame(window)?;
Some(CameraFrame {
native,
+ visible: platform::window_is_visible(window),
snapshot: CameraSnapshot {
handle,
bounds,
@@ -3618,6 +3812,17 @@ fn camera_frame(cx: &mut App) -> Option<CameraFrame> {
.filter(|camera| camera.snapshot.bounds.width > 0. && camera.snapshot.bounds.height > 0.)
}
+fn visible_camera_frame(cx: &mut App) -> Option<CameraFrame> {
+ if camera_preview_is_inline(cx) {
+ return None;
+ }
+ #[cfg(target_os = "linux")]
+ if clean_capture_active(cx) {
+ return None;
+ }
+ camera_frame(cx).filter(|camera| camera.visible)
+}
+
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
@@ -3632,6 +3837,39 @@ fn camera_snapshot(cx: &mut App) -> Option<CameraSnapshot> {
}
impl CameraFrame {
+ fn raise(&self) -> anyhow::Result<()> {
+ match &self.native {
+ #[cfg(target_os = "macos")]
+ CameraNativeFrame::Mac { native, .. } => platform::order_front_native(native),
+ #[cfg(target_os = "windows")]
+ CameraNativeFrame::Windows(native) => platform::order_front_native(native),
+ #[cfg(target_os = "linux")]
+ CameraNativeFrame::X11 { window_id, .. } => {
+ use x11rb::connection::Connection as _;
+ use x11rb::protocol::xproto::{
+ ConfigureWindowAux, ConnectionExt as _, MapState, StackMode,
+ };
+
+ let (connection, _) = x11rb::connect(None)?;
+ if connection
+ .get_window_attributes(*window_id)?
+ .reply()?
+ .map_state
+ == MapState::VIEWABLE
+ {
+ connection
+ .configure_window(
+ *window_id,
+ &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
+ )?
+ .check()?;
+ connection.flush()?;
+ }
+ }
+ }
+ Ok(())
+ }
+
fn apply(self, bounds: AreaRect) -> anyhow::Result<()> {
match self.native {
#[cfg(target_os = "macos")]
@@ -3645,6 +3883,9 @@ impl CameraFrame {
f64::from(bounds.width),
f64::from(bounds.height),
);
+ if self.visible {
+ platform::order_front_native(&native);
+ }
}
#[cfg(target_os = "windows")]
CameraNativeFrame::Windows(native) => {
@@ -3655,23 +3896,32 @@ impl CameraFrame {
f64::from(bounds.width),
f64::from(bounds.height),
);
+ if self.visible {
+ platform::order_front_native(&native);
+ }
}
#[cfg(target_os = "linux")]
CameraNativeFrame::X11 { window_id, scale } => {
use x11rb::connection::Connection as _;
- use x11rb::protocol::xproto::{ConfigureWindowAux, ConnectionExt as _};
+ use x11rb::protocol::xproto::{
+ ConfigureWindowAux, ConnectionExt as _, MapState, StackMode,
+ };
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()?;
+ let mut changes = 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);
+ if connection
+ .get_window_attributes(window_id)?
+ .reply()?
+ .map_state
+ == MapState::VIEWABLE
+ {
+ changes = changes.stack_mode(StackMode::ABOVE);
+ }
+ connection.configure_window(window_id, &changes)?.check()?;
connection.flush()?;
}
}
@@ -5662,6 +5912,50 @@ mod tests {
use super::*;
use crate::store::{DEFAULT_EXCLUDED_WINDOW_TITLES, WindowExclusion, default_excluded_windows};
+ fn area_target(display: &str, x: f64, y: f64, width: f64, height: f64) -> ScreenCaptureTarget {
+ ScreenCaptureTarget::Area {
+ screen: display.parse().unwrap(),
+ bounds: scap_targets::bounds::LogicalBounds::new(
+ scap_targets::bounds::LogicalPosition::new(x, y),
+ scap_targets::bounds::LogicalSize::new(width, height),
+ ),
+ }
+ }
+
+ #[test]
+ fn recording_outline_rejects_a_crop_changed_during_start_preflight() {
+ let admitted = area_target("1", -120., 80., 640., 480.);
+ let same = area_target("1", -120., 80., 640., 480.);
+ assert!(area_overlay_matches(&admitted, &same, true));
+ for changed in [
+ area_target("1", -119., 80., 640., 480.),
+ area_target("1", -120., 81., 640., 480.),
+ area_target("1", -120., 80., 641., 480.),
+ area_target("1", -120., 80., 640., 481.),
+ area_target("2", -120., 80., 640., 480.),
+ ] {
+ assert!(!area_overlay_matches(&admitted, &changed, true));
+ }
+ }
+
+ #[test]
+ fn recording_outline_requires_an_area_and_confirmed_capture_exclusion() {
+ let area = area_target("1", 0., 0., 640., 480.);
+ assert!(!area_overlay_matches(&area, &area, false));
+ for other in [
+ ScreenCaptureTarget::Display {
+ id: "1".parse().unwrap(),
+ },
+ ScreenCaptureTarget::Window {
+ id: "1".parse().unwrap(),
+ },
+ ScreenCaptureTarget::CameraOnly,
+ ] {
+ assert!(!area_overlay_matches(&area, &other, true));
+ assert!(!area_overlay_matches(&other, &area, true));
+ }
+ }
+
#[test]
fn dock_reopen_uses_registered_windows_and_falls_back_after_delete() {
let editor = WindowHandle::<EditorWindow>::new(1_u64.into());
diff --git a/apps/desktop-gpui/src/camera_window.rs b/apps/desktop-gpui/src/camera_window.rs
index ff10c92c7..6c871b3b0 100644
--- a/apps/desktop-gpui/src/camera_window.rs
+++ b/apps/desktop-gpui/src/camera_window.rs
@@ -470,9 +470,101 @@ impl ResizeCorner {
struct ResizeDrag {
corner: ResizeCorner,
start_size: f32,
+ start_picker_size: Option<(f32, f32)>,
start_position: gpui::Point<gpui::Pixels>,
}
+#[derive(Debug, Clone, Copy, PartialEq)]
+enum ResizeTarget {
+ Picker((f32, f32)),
+ State(f32),
+}
+
+fn resize_start(state_size: f32, picker_size: Option<(f32, f32)>) -> (f32, Option<(f32, f32)>) {
+ let picker_size = picker_size.filter(|(width, height)| {
+ width.is_finite() && *width > 0. && height.is_finite() && *height > CAMERA_TOOLBAR_HEIGHT
+ });
+ let start_size = picker_size
+ .map(|(_, height)| height - CAMERA_TOOLBAR_HEIGHT)
+ .unwrap_or(clamp_size(state_size));
+ (start_size, picker_size)
+}
+
+fn resize_target(
+ start_size: f32,
+ start_picker_size: Option<(f32, f32)>,
+ delta: f32,
+) -> ResizeTarget {
+ let minimum = start_picker_size.map_or(CAMERA_MIN_SIZE, |_| start_size.min(CAMERA_MIN_SIZE));
+ let next = (start_size + delta).clamp(minimum, CAMERA_MAX_SIZE);
+ if next < CAMERA_MIN_SIZE
+ && let Some((start_width, _)) = start_picker_size
+ {
+ return ResizeTarget::Picker((
+ start_width * next / start_size,
+ next + CAMERA_TOOLBAR_HEIGHT,
+ ));
+ }
+ ResizeTarget::State(next)
+}
+
+#[cfg(test)]
+mod resize_tests {
+ use super::*;
+
+ fn close(left: f32, right: f32) {
+ assert!((left - right).abs() < 0.001, "{left} != {right}");
+ }
+
+ #[test]
+ fn parked_square_resizes_from_its_visible_size() {
+ let (start, picker) = resize_start(230., Some((100., 156.)));
+ assert_eq!(start, 100.);
+ assert_eq!(
+ resize_target(start, picker, 1.),
+ ResizeTarget::Picker((101., 157.))
+ );
+ }
+
+ #[test]
+ fn parked_landscape_preserves_aspect_below_the_saved_size_floor() {
+ let (start, picker) = resize_start(180., Some((144., 137.)));
+ let ResizeTarget::Picker((width, height)) = resize_target(start, picker, 1.) else {
+ panic!("expected temporary picker geometry");
+ };
+ close(start, 81.);
+ close(height, 138.);
+ close(width / (height - CAMERA_TOOLBAR_HEIGHT), 16. / 9.);
+ }
+
+ #[test]
+ fn parked_resize_hands_off_continuously_at_the_saved_size_floor() {
+ let (start, picker) = resize_start(180., Some((144., 137.)));
+ assert_eq!(
+ resize_target(start, picker, CAMERA_MIN_SIZE - start),
+ ResizeTarget::State(CAMERA_MIN_SIZE)
+ );
+ let expected_width = 144. * CAMERA_MIN_SIZE / start;
+ let state = CameraWindowState {
+ size: CAMERA_MIN_SIZE,
+ shape: CameraShape::Full,
+ ..Default::default()
+ };
+ let (width, height) = window_size(&state, Some(16. / 9.));
+ close(width, expected_width);
+ close(height, CAMERA_MIN_SIZE + CAMERA_TOOLBAR_HEIGHT);
+ }
+
+ #[test]
+ fn parked_resize_does_not_shrink_below_its_visible_size() {
+ let (start, picker) = resize_start(230., Some((100., 156.)));
+ assert_eq!(
+ resize_target(start, picker, -50.),
+ ResizeTarget::Picker((100., 156.))
+ );
+ }
+}
+
/// `cameraOverlayTextMetrics` (`camera.tsx:891-909`), rem resolved at 16px.
struct OverlayMetrics {
gap: f32,
@@ -1631,9 +1723,12 @@ impl CameraWindow {
cx.listener(move |this, event: &gpui::MouseDownEvent, window, cx| {
window.prevent_default();
cx.stop_propagation();
+ let (start_size, start_picker_size) =
+ resize_start(this.state.size, this.picker_size);
this.resizing = Some(ResizeDrag {
corner,
- start_size: this.state.size,
+ start_size,
+ start_picker_size,
start_position: event.position,
});
cx.notify();
@@ -1668,13 +1763,27 @@ impl CameraWindow {
-delta_y
};
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);
- cx.notify();
+ match resize_target(drag.start_size, drag.start_picker_size, delta) {
+ ResizeTarget::Picker(next) => {
+ if self.picker_size.is_some_and(|current| {
+ (current.0 - next.0).abs() <= 0.5 && (current.1 - next.1).abs() <= 0.5
+ }) {
+ return;
+ }
+ self.picker_size = Some(next);
+ self.apply_window_size(window, cx);
+ cx.notify();
+ }
+ ResizeTarget::State(next) => {
+ if self.picker_size.is_none() && (next - self.state.size).abs() <= 0.5 {
+ return;
+ }
+ self.picker_size = None;
+ self.state.size = next;
+ self.apply_window_size(window, cx);
+ self.sync_preview_chrome(cx);
+ cx.notify();
+ }
}
}
@@ -1721,21 +1830,37 @@ impl Render for CameraWindow {
}),
)
.when(resizing, |this| {
- this.on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, window, cx| {
- if event.dragging() {
- this.handle_resize_move(event, window, cx);
- } else {
- this.end_resize(cx);
- }
- }))
- .on_mouse_up(
- MouseButton::Left,
- cx.listener(|this, _: &MouseUpEvent, _, cx| this.end_resize(cx)),
- )
- .on_mouse_up_out(
- MouseButton::Left,
- cx.listener(|this, _: &MouseUpEvent, _, cx| this.end_resize(cx)),
- )
+ let move_camera = cx.entity().downgrade();
+ let up_camera = cx.entity().downgrade();
+ this.child(gpui::canvas(
+ |_bounds, _window, _cx| (),
+ move |_bounds, (), window, _cx| {
+ let camera = move_camera.clone();
+ window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| {
+ if phase != gpui::DispatchPhase::Bubble {
+ return;
+ }
+ camera
+ .update(cx, |this, cx| {
+ if event.dragging() {
+ this.handle_resize_move(event, window, cx);
+ } else {
+ this.end_resize(cx);
+ }
+ })
+ .ok();
+ });
+ let camera = up_camera.clone();
+ window.on_mouse_event(move |event: &MouseUpEvent, phase, _window, cx| {
+ if phase != gpui::DispatchPhase::Bubble
+ || event.button != MouseButton::Left
+ {
+ return;
+ }
+ camera.update(cx, |this, cx| this.end_resize(cx)).ok();
+ });
+ },
+ ))
})
.child(
self.toolbar.clone().cached(
diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs
index 27dfe3046..46391b8c8 100644
--- a/apps/desktop-gpui/src/main.rs
+++ b/apps/desktop-gpui/src/main.rs
@@ -71,7 +71,7 @@ use gpui::{App, AppContext as _, Bounds, WindowBounds, WindowOptions, px, size};
use crate::{assets::Assets, main_window::MainWindow, session::RecordingSession};
const MAIN_WINDOW_WIDTH: f32 = 330.;
-const MAIN_WINDOW_HEIGHT: f32 = 440.;
+const MAIN_WINDOW_HEIGHT: f32 = 432.;
/// The corner radius the native material is clipped to. `radius = 16` for
/// material `"panel"` on both visual systems in
diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rs
index 95be70044..4b2936588 100644
--- a/apps/desktop-gpui/src/main_window.rs
+++ b/apps/desktop-gpui/src/main_window.rs
@@ -28,7 +28,7 @@ use crate::{
use gpui::{Entity, Task};
const EXPANDED_WIDTH: f32 = 600.;
-const EXPANDED_HEIGHT: f32 = 680.;
+const EXPANDED_HEIGHT: f32 = 672.;
/// `duration: 180` in `resizeMainWindow`.
const RESIZE_DURATION_SECS: f32 = 0.18;
@@ -178,6 +178,87 @@ impl Mode {
}
}
+fn capture_hover_fill(theme: Theme, selected: bool, chevron: bool) -> Hsla {
+ if selected {
+ if chevron {
+ Theme::with_alpha(theme.blue_9, if theme.is_dark() { 0.30 } else { 0.22 })
+ } else {
+ theme.tile_selected_hover_bg()
+ }
+ } else {
+ Theme::with_alpha(theme.blue_9, if chevron { 0.16 } else { 0.07 })
+ }
+}
+
+struct ModeHoverCard {
+ mode: Mode,
+ theme: Theme,
+}
+
+impl Render for ModeHoverCard {
+ fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
+ let theme = self.theme;
+ let mode = self.mode;
+ let description = match mode {
+ Mode::Instant => {
+ "No rendering required — uploads on the fly so you can share the link the moment you stop."
+ }
+ Mode::Studio => {
+ "Records at the highest quality for local rendering later. Opens the Cap editor when you're done."
+ }
+ Mode::Screenshot => "Capture and annotate stills.",
+ };
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(8.))
+ .w(px(240.))
+ .px(px(12.))
+ .py(px(10.))
+ .rounded(px(8.))
+ .border_1()
+ .border_color(theme.gray_3)
+ .bg(theme.gray_12)
+ .text_color(theme.gray_1)
+ .shadow_lg()
+ .child(
+ div()
+ .text_size(px(12.))
+ .child(format!("{} mode", mode.panel_title())),
+ )
+ .child(
+ div()
+ .text_size(px(10.))
+ .line_height(px(13.75))
+ .text_color(theme.gray_4)
+ .child(description),
+ )
+ .when(mode != Mode::Screenshot, |this| {
+ this.child(
+ div()
+ .id("mode-quality-settings")
+ .tab_index(0)
+ .flex()
+ .items_center()
+ .gap(px(6.))
+ .mx(px(-4.))
+ .px(px(8.))
+ .py(px(4.))
+ .rounded(px(6.))
+ .text_size(px(11.))
+ .text_color(theme.gray_4)
+ .hover(|style| style.bg(theme.gray_11).text_color(theme.gray_1))
+ .child(svg().path("icons/settings.svg").size(px(12.)))
+ .child("Quality settings")
+ .on_click(move |_, _, cx| {
+ cx.stop_propagation();
+ cx.defer(move |cx| app_windows::open_quality_settings(mode, cx));
+ }),
+ )
+ })
+ }
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TargetType {
Display,
@@ -370,13 +451,6 @@ impl LibraryKind {
}
}
- fn search_placeholder(self) -> &'static str {
- match self {
- Self::Recordings => "Search recordings",
- Self::Screenshots => "Search screenshots",
- }
- }
-
fn import_label(self) -> &'static str {
match self {
Self::Recordings => "Import",
@@ -483,6 +557,87 @@ struct MicrophoneWarning {
error: Option<String>,
}
+struct MicrophoneLevel {
+ active: bool,
+ fill: f32,
+ color: Hsla,
+}
+
+impl MicrophoneLevel {
+ fn new(feeds: &Entity<Feeds>, window: &mut Window, cx: &mut Context<Self>) -> Self {
+ cx.observe_in(feeds, window, |this, feeds, window, cx| {
+ let visible = if cfg!(any(target_os = "macos", target_os = "windows")) {
+ crate::platform::window_is_visible(window)
+ } else {
+ window.is_window_active()
+ };
+ if this.active && visible {
+ let fill = Self::fill(feeds.read(cx));
+ if this.fill != fill {
+ this.fill = fill;
+ cx.notify();
+ }
+ }
+ })
+ .detach();
+ Self {
+ active: false,
+ fill: 0.,
+ color: gpui::transparent_black(),
+ }
+ }
+
+ fn fill(feeds: &Feeds) -> f32 {
+ if feeds.microphone.is_some() && feeds.mic_level_db.is_finite() {
+ (1. - feeds::picker_level(feeds.mic_level_db)) as f32
+ } else {
+ 0.
+ }
+ }
+
+ fn configure(&mut self, active: bool, color: Hsla, cx: &mut Context<Self>) {
+ let fill = if active {
+ Self::fill(Feeds::global(cx).read(cx))
+ } else {
+ 0.
+ };
+ if self.active != active || self.color != color || self.fill != fill {
+ self.active = active;
+ self.color = color;
+ self.fill = fill;
+ cx.notify();
+ }
+ }
+}
+
+impl Render for MicrophoneLevel {
+ fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
+ let mut background = self.color;
+ background.a *= 0.1;
+ div()
+ .size_full()
+ .when(self.active && self.fill > 0., |this| {
+ this.child(
+ div()
+ .relative()
+ .h_full()
+ .w(gpui::relative(self.fill))
+ .rounded(px(7.))
+ .bg(background)
+ .child(
+ div()
+ .absolute()
+ .bottom_0()
+ .left_0()
+ .w_full()
+ .h(px(2.))
+ .bg(self.color),
+ ),
+ )
+ })
+ }
+}
+
pub struct MainWindow {
theme: Theme,
expanded: bool,
@@ -492,6 +647,7 @@ pub struct MainWindow {
camera: Option<CameraOption>,
camera_id: Option<recording::DeviceOrModelID>,
microphone: Option<MicrophoneOption>,
+ microphone_level: Entity<MicrophoneLevel>,
pending_device_restore: crate::store::RecordingInputSettings,
device_restore_suspended: bool,
device_format_target: Option<DeviceFormatTarget>,
@@ -654,6 +810,7 @@ impl MainWindow {
// meter notifies at ~20Hz and would otherwise repaint the home view
// for a level bar only the microphone picker shows.
let feeds = Feeds::global(cx);
+ let microphone_level = cx.new(|cx| MicrophoneLevel::new(&feeds, window, cx));
cx.observe(&feeds, |this: &mut Self, feeds, cx| {
let feeds = feeds.read(cx);
let camera_id = feeds.camera.as_ref().map(|camera| &camera.id);
@@ -723,6 +880,7 @@ impl MainWindow {
camera: None,
camera_id: None,
microphone: None,
+ microphone_level,
pending_device_restore: crate::store::RecordingInputSettings::load(),
device_restore_suspended: false,
device_format_target: None,
@@ -2454,6 +2612,12 @@ impl Render for MainWindow {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.sync_appearance(window, cx);
let theme = self.theme;
+ let meter_active = self.panel.is_none()
+ && self.microphone.is_some()
+ && self.session.read(cx).phase == Phase::Idle;
+ self.microphone_level.update(cx, |meter, cx| {
+ meter.configure(meter_active, theme.blue_9.into(), cx);
+ });
div()
.size_full()
@@ -2972,7 +3136,32 @@ impl MainWindow {
// `IconButton::header`: a 20px hit box with no fill, `text-gray-11`
// going to `text-gray-12` on hover.
let icon_button = |id: &'static str, path: &'static str, size: f32| {
- ui::IconButton::header(&theme, id, path).icon_size(px(size))
+ let label = match id {
+ "help" => "Help & Tour",
+ "expand" if expanded => "Collapse",
+ "expand" => "Expand",
+ "settings" => "Settings",
+ "screenshots" => "Screenshots",
+ "recordings" => "Recordings",
+ "teleprompter" => "Teleprompter",
+ "changelog" => "Changelog",
+ _ => unreachable!(),
+ };
+ div()
+ .id(id)
+ .when(cfg!(target_os = "windows"), |this| this.occlude())
+ .tab_index(0)
+ .flex()
+ .items_center()
+ .justify_center()
+ .size(px(20.))
+ .flex_shrink_0()
+ .rounded_full()
+ .text_color(theme.gray_11)
+ .hover(|style| style.text_color(theme.gray_12))
+ .tooltip(move |_, cx| ui::Tooltip::new(&theme, label).view(cx))
+ .tooltip_show_delay(ui::TOOLTIP_SHOW_DELAY)
+ .child(svg().path(path).size(px(size)))
};
let actions = div()
@@ -3339,9 +3528,7 @@ impl MainWindow {
DeviceFormatTarget::Microphone(name) => name.clone(),
})
.into_any_element(),
- Panel::Device(_) | Panel::Target(_) => {
- self.render_search_field(panel, cx).into_any_element()
- }
+ Panel::Device(_) | Panel::Target(_) => self.render_search_field(cx).into_any_element(),
};
div()
@@ -3499,17 +3686,9 @@ impl MainWindow {
/// double-click-a-word, the clipboard and undo all come from
/// `TextInputState`. What stays here is the only part the component cannot
/// know, which is that Escape clears the filter before it closes the panel.
- fn render_search_field(&self, panel: Panel, cx: &mut Context<Self>) -> gpui::Div {
- let placeholder = match panel {
- Panel::Target(TargetType::Display) => "Search displays",
- Panel::Target(TargetType::Window) => "Search windows",
- Panel::Device(DeviceMenu::Camera) => "Search cameras",
- Panel::Device(DeviceMenu::Microphone) => "Search microphones",
- Panel::Library(kind) => kind.search_placeholder(),
- _ => "Search",
- };
+ fn render_search_field(&self, cx: &mut Context<Self>) -> gpui::Div {
self.search_input
- .update(cx, |input, _| input.set_placeholder(placeholder));
+ .update(cx, |input, _| input.set_placeholder("Search"));
div().flex().flex_1().min_w_0().child(ui::TextInput::search(
&self.theme,
@@ -3526,7 +3705,7 @@ impl MainWindow {
.min_w_0()
.gap(px(8.))
.items_center()
- .child(self.render_search_field(Panel::Library(kind), cx))
+ .child(self.render_search_field(cx))
.child(
ui::Button::plain(
&theme,
@@ -3902,6 +4081,7 @@ impl MainWindow {
.relative()
.w_full()
.h(px(76.))
+ .rounded_t(px(8.))
.overflow_hidden()
.bg(theme.body_fill(4))
.flex()
@@ -4192,10 +4372,12 @@ impl MainWindow {
use gpui::StyledImage as _;
img(image)
.size_full()
+ .rounded_t(px(8.))
.object_fit(gpui::ObjectFit::Cover)
.into_any_element()
}
None => div()
+ .rounded_t(px(8.))
.flex()
.size_full()
.items_center()
@@ -4224,6 +4406,7 @@ impl MainWindow {
.relative()
.w_full()
.h(px(76.))
+ .rounded_t(px(8.))
.overflow_hidden()
.bg(theme.body_fill(4))
.child(thumb)
@@ -5259,8 +5442,7 @@ impl MainWindow {
.flex_row()
.items_center()
.justify_between()
- .mt(px(8.))
- .mb(px(4.))
+ .mt(px(4.))
.flex_shrink_0()
.child(
// `flex items-center space-x-1` around the logo and its badge.
@@ -5385,6 +5567,9 @@ impl MainWindow {
let selected = mode == selected_mode;
div()
.id(SharedString::from(id))
+ .tab_index(0)
+ .hoverable_tooltip(move |_, cx| cx.new(|_| ModeHoverCard { mode, theme }).into())
+ .tooltip_show_delay(std::time::Duration::from_millis(120))
.when(locked && !selected, |this| this.opacity(0.5))
.flex()
.items_center()
@@ -5443,6 +5628,9 @@ impl MainWindow {
.child(
div()
.id("mode-info")
+ .tab_index(0)
+ .tooltip(move |_, cx| ui::Tooltip::new(&theme, "Recording mode info").view(cx))
+ .tooltip_show_delay(ui::TOOLTIP_SHOW_DELAY)
.absolute()
.left(px(-6.))
.top(px(-8.))
@@ -5514,11 +5702,7 @@ impl MainWindow {
fn render_split_target(&self, target: TargetType, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
let selected = self.target == Some(target);
- let hover_fill = if selected {
- theme.tile_selected_hover_bg()
- } else {
- theme.body_hover_fill(4)
- };
+ let hover_fill = capture_hover_fill(theme, selected, false);
div()
.group(target.label())
@@ -5549,14 +5733,32 @@ impl MainWindow {
.justify_center()
.border_l_1()
.border_color(theme.body_border(6))
- .bg(theme.body_fill(4))
- .child(
- svg()
- .path("icons/chevron-down.svg")
- .size(px(16.))
- .text_color(theme.gray_11),
- )
+ .bg(if selected {
+ theme.tile_selected_bg()
+ } else {
+ theme.body_fill(2)
+ })
+ .text_color(theme.gray_11)
+ .child(svg().path("icons/chevron-down.svg").size(px(16.)))
.group_hover(target.label(), move |style| style.bg(hover_fill))
+ .hover(move |style| {
+ style
+ .bg(capture_hover_fill(theme, selected, true))
+ .text_color(theme.blue_11)
+ })
+ .active(move |style| style.bg(theme.tile_selected_hover_bg()))
+ .tooltip(move |_, cx| {
+ ui::Tooltip::new(
+ &theme,
+ match target {
+ TargetType::Display => "Choose a display",
+ TargetType::Window => "Choose a window",
+ _ => unreachable!(),
+ },
+ )
+ .view(cx)
+ })
+ .tooltip_show_delay(ui::TOOLTIP_SHOW_DELAY)
.on_click(cx.listener(move |this, _, window, cx| {
this.open_panel(Panel::Target(target), window, cx);
})),
@@ -5599,11 +5801,7 @@ impl MainWindow {
let theme = self.theme;
let selected = self.target == Some(target);
let expanded = self.expanded;
- let hover_fill = if selected {
- theme.tile_selected_hover_bg()
- } else {
- theme.body_hover_fill(4)
- };
+ let hover_fill = capture_hover_fill(theme, selected, false);
let icon_color = if selected {
theme.blue_10
@@ -5634,6 +5832,7 @@ impl MainWindow {
this.group_hover(target.label(), move |style| style.bg(hover_fill))
})
.when(!split, |this| this.hover(move |style| style.bg(hover_fill)))
+ .active(move |style| style.bg(theme.tile_selected_hover_bg()))
.on_click(cx.listener(move |this, _, _window, cx| {
// `toggleTargetMode`: clicking the armed tile again is a
// cancel, which takes the overlays down with it.
@@ -6130,6 +6329,7 @@ impl MainWindow {
div()
.id(SharedString::from(id))
+ .relative()
.flex()
.flex_row()
.items_center()
@@ -6144,6 +6344,17 @@ impl MainWindow {
.bg(theme.body_fill(2))
.cursor_default()
.overflow_hidden()
+ .when(menu == Some(DeviceMenu::Microphone), |this| {
+ this.child(
+ self.microphone_level.clone().cached(
+ gpui::StyleRefinement::default()
+ .absolute()
+ .top_0()
+ .left_0()
+ .size_full(),
+ ),
+ )
+ })
.child(
svg()
.path(icon)
diff --git a/apps/desktop-gpui/src/platform.rs b/apps/desktop-gpui/src/platform.rs
index fd8510b77..133af9ae5 100644
--- a/apps/desktop-gpui/src/platform.rs
+++ b/apps/desktop-gpui/src/platform.rs
@@ -792,6 +792,11 @@ mod mac {
}
}
+ pub fn set_window_click_through(native: &NativeWindow, click_through: bool) -> bool {
+ native.0.setIgnoresMouseEvents(click_through);
+ unsafe { native.0.ignoresMouseEvents() == click_through }
+ }
+
/// `orderOut:` -- hide without closing, the way the Tauri main window
/// hides while the recording controls bar is up. Takes the retained
/// handle for the same reason [`place_overlay_panel`] does: ordering a
@@ -1641,6 +1646,9 @@ mod stub {
pub fn set_window_capture_hidden(_native: &NativeWindow, _hidden: bool) -> usize {
0
}
+ pub fn set_window_click_through(_native: &NativeWindow, _click_through: bool) -> bool {
+ false
+ }
pub fn native_window(_window: &Window) -> Option<NativeWindow> {
None
}
diff --git a/apps/desktop-gpui/src/platform/windows.rs b/apps/desktop-gpui/src/platform/windows.rs
index 5b4a8e1ee..96dffdc6a 100644
--- a/apps/desktop-gpui/src/platform/windows.rs
+++ b/apps/desktop-gpui/src/platform/windows.rs
@@ -161,6 +161,10 @@ pub fn set_window_capture_hidden(native: &NativeWindow, hidden: bool) -> usize {
}
}
+pub fn set_window_click_through(_native: &NativeWindow, _click_through: bool) -> bool {
+ false
+}
+
pub fn restore_borderless_style(_native: &NativeWindow) {}
pub fn remove_popup_window_chrome(_native: &NativeWindow) {}
diff --git a/apps/desktop-gpui/src/settings_pages.rs b/apps/desktop-gpui/src/settings_pages.rs
index 70ff5a6e7..820ea3188 100644
--- a/apps/desktop-gpui/src/settings_pages.rs
+++ b/apps/desktop-gpui/src/settings_pages.rs
@@ -10,7 +10,7 @@
//! runtime (reqwest needs tokio); persistence goes through [`crate::store`].
use std::{
- collections::HashMap,
+ collections::{HashMap, HashSet},
path::PathBuf,
str::FromStr as _,
sync::{
@@ -356,10 +356,10 @@ pub(crate) struct PagesState {
// Automations (automations.tsx)
automations: AutomationsStore,
automations_loaded: bool,
+ automations_save_failed: bool,
expanded_rule: Option<String>,
rule_editor: Option<RuleEditor>,
- /// `testReports`, reduced to per-action `supported` flags.
- test_reports: HashMap<String, Vec<bool>>,
+ compatibility_checks: HashSet<String>,
_subscriptions: Vec<gpui::Subscription>,
}
@@ -470,9 +470,10 @@ impl PagesState {
switch_back_ticker: None,
automations: AutomationsStore::default(),
automations_loaded: false,
+ automations_save_failed: false,
expanded_rule: None,
rule_editor: None,
- test_reports: HashMap::new(),
+ compatibility_checks: HashSet::new(),
_subscriptions: subscriptions,
}
}
@@ -524,9 +525,10 @@ impl SettingsWindow {
Page::Automations => {
self.pages.automations = store::automations();
self.pages.automations_loaded = true;
+ self.pages.automations_save_failed = false;
self.pages.expanded_rule = None;
self.pages.rule_editor = None;
- self.pages.test_reports.clear();
+ self.pages.compatibility_checks.clear();
}
_ => {}
}
@@ -5875,14 +5877,6 @@ fn action_is_dangerous(kind: ActionType) -> bool {
matches!(kind, ActionType::RunCommand | ActionType::Webhook)
}
-/// The desktop host's capability set (`DesktopAutomationHost::capabilities`):
-/// everything, with OCR only where Vision/Windows-OCR exists. `skipEditor`
-/// requires no capability at all (`required_capability` returns `None`).
-fn action_supported_here(action: &Action) -> bool {
- !matches!(action, Action::RecognizeTextToClipboard)
- || cfg!(any(target_os = "macos", target_os = "windows"))
-}
-
/// `ruleSummary`.
fn rule_summary(rule: &AutomationRule) -> String {
let trigger = trigger_phrase(rule.trigger);
@@ -6106,8 +6100,10 @@ impl SettingsWindow {
cx.notify();
}
- fn automations_persist(&self) {
- if !store::set_automations(&self.pages.automations) {
+ fn automations_persist(&mut self) {
+ self.pages.compatibility_checks.clear();
+ self.pages.automations_save_failed = !store::set_automations(&self.pages.automations);
+ if self.pages.automations_save_failed {
tracing::warn!("saving the automations store failed");
}
}
@@ -6145,14 +6141,11 @@ impl SettingsWindow {
cx.notify();
}
- /// `runTest`, evaluated locally against the same capability table the
- /// desktop host reports.
fn automation_test(&mut self, index: usize, cx: &mut Context<Self>) {
let Some(rule) = self.pages.automations.rules.get(index) else {
return;
};
- let checks: Vec<bool> = rule.actions.iter().map(action_supported_here).collect();
- self.pages.test_reports.insert(rule.id.clone(), checks);
+ self.pages.compatibility_checks.insert(rule.id.clone());
cx.notify();
}
@@ -6507,6 +6500,36 @@ impl SettingsWindow {
.into_any_element()
};
+ let mut rule_content = Vec::new();
+ if self.pages.automations_save_failed {
+ rule_content.push(
+ div()
+ .flex()
+ .flex_col()
+ .items_start()
+ .gap(px(8.))
+ .text_size(px(12.))
+ .line_height(px(18.))
+ .text_color(Hsla::from(theme.amber_11))
+ .child("Failed to save automations. Your changes have not been saved.")
+ .child(
+ ui::Button::settings(
+ &theme,
+ "automations-retry-save",
+ ui::ButtonVariant::Gray,
+ ui::ButtonSize::Xs,
+ )
+ .label("Retry save")
+ .on_click(cx.listener(|this, _, _, cx| {
+ this.automations_persist();
+ cx.notify();
+ })),
+ )
+ .into_any_element(),
+ );
+ }
+ rule_content.push(rules_body);
+
// `grid grid-cols-2 gap-2.5`, as rows of two.
let mut template_rows: Vec<gpui::AnyElement> = Vec::new();
for pair in TEMPLATES.chunks(2) {
@@ -6528,11 +6551,11 @@ impl SettingsWindow {
self.section(
"Automations",
Some(
- "Run actions automatically when something happens in Cap. Rules are shared \
- with the Cap CLI.",
+ "Rules are shared with classic Cap and the Cap CLI. Experimental GPUI \
+ saves these rules but does not run automations.",
),
None,
- vec![rules_body],
+ rule_content,
)
.into_any_element(),
self.section(
@@ -6775,13 +6798,31 @@ impl SettingsWindow {
})),
)
.child(
- self.toggle(("rule-enabled", index), enabled, cx, move |this, cx| {
- if let Some(rule) = this.pages.automations.rules.get_mut(index) {
- rule.enabled = !rule.enabled;
- this.automations_persist();
- cx.notify();
- }
- }),
+ div()
+ .flex()
+ .flex_col()
+ .items_end()
+ .gap(px(4.))
+ .child(
+ div()
+ .text_size(px(11.))
+ .text_color(theme.settings_muted())
+ .child(match (enabled, self.pages.automations_save_failed) {
+ (true, false) => "Enabled · Saved",
+ (false, false) => "Disabled · Saved",
+ (true, true) => "Enabled · Not saved",
+ (false, true) => "Disabled · Not saved",
+ }),
+ )
+ .child(
+ self.toggle(("rule-enabled", index), enabled, cx, move |this, cx| {
+ if let Some(rule) = this.pages.automations.rules.get_mut(index) {
+ rule.enabled = !rule.enabled;
+ this.automations_persist();
+ cx.notify();
+ }
+ }),
+ ),
)
.child(
div()
@@ -6890,7 +6931,7 @@ impl SettingsWindow {
.actions
.iter()
.any(|action| action_is_dangerous(action_type_of(action)));
- let report = self.pages.test_reports.get(&rule.id).cloned();
+ let compatibility_checked = self.pages.compatibility_checks.contains(&rule.id);
let name_field = self.editor_field("Name", self.render_editor_input(AutoField::Name));
@@ -7017,8 +7058,7 @@ impl SettingsWindow {
.flex_col()
.gap(px(8.))
.children(rule.actions.iter().enumerate().map(|(ai, action)| {
- let support = report.as_ref().and_then(|checks| checks.get(ai)).copied();
- self.render_action_row(index, ai, action, trigger, action_count, support, cx)
+ self.render_action_row(index, ai, action, trigger, action_count, cx)
}));
let footer = div()
@@ -7100,8 +7140,22 @@ impl SettingsWindow {
.line_height(px(18.))
.text_color(Hsla::from(theme.amber_11))
.child(
- "This automation runs commands or sends network requests. Only use \
- values you trust — they execute automatically with your permissions.",
+ "In classic Cap or the Cap CLI, this automation runs commands or sends \
+ network requests with your permissions. Only use values you trust.",
+ ),
+ )
+ })
+ .when(compatibility_checked, |this| {
+ this.child(
+ div()
+ .id(("rule-compatibility-result", index))
+ .text_size(px(12.))
+ .line_height(px(18.))
+ .text_color(Hsla::from(theme.amber_11))
+ .child(
+ "Compatibility checked: this automation cannot run in Experimental \
+ GPUI. Saved rules remain available to classic Cap and the Cap CLI. \
+ No actions were run.",
),
)
})
@@ -7264,7 +7318,6 @@ impl SettingsWindow {
}
/// `<ActionRow>`.
- #[allow(clippy::too_many_arguments)]
fn render_action_row(
&self,
rule: usize,
@@ -7272,14 +7325,13 @@ impl SettingsWindow {
action: &Action,
trigger: Trigger,
action_count: usize,
- support: Option<bool>,
cx: &mut Context<Self>,
) -> gpui::AnyElement {
let theme = self.theme;
let kind = action_type_of(action);
let applies = action_applies_to_trigger(kind, trigger);
- let mut header = div().flex().flex_row().items_center().gap(px(8.)).child(
+ let header = div().flex().flex_row().items_center().gap(px(8.)).child(
div().flex_1().min_w_0().child(
self.pages_select(
SharedString::from(format!("action-type-{rule}-{index}")),
@@ -7290,19 +7342,7 @@ impl SettingsWindow {
.stretch_label(),
),
);
- if support == Some(false) {
- header = header.child(
- div()
- .px(px(6.))
- .py(px(2.))
- .rounded(px(6.))
- .bg(Theme::with_alpha(theme.amber_11, 0.15))
- .text_size(px(10.))
- .text_color(Hsla::from(theme.amber_11))
- .child("SKIPPED HERE"),
- );
- }
- header = header
+ let header = header
.child(self.render_row_icon_button(
SharedString::from(format!("action-up-{rule}-{index}")),
"icons/chevron-up.svg",
diff --git a/apps/desktop-gpui/src/settings_window.rs b/apps/desktop-gpui/src/settings_window.rs
index 0e178dbfd..3b801c2dc 100644
--- a/apps/desktop-gpui/src/settings_window.rs
+++ b/apps/desktop-gpui/src/settings_window.rs
@@ -16,14 +16,16 @@ use std::{cell::Cell, path::PathBuf, rc::Rc, sync::Arc, time::Duration};
use gpui::{
AppContext as _, Bounds, Context, Entity, FocusHandle, FontWeight, Hsla, InteractiveElement,
- IntoElement, MouseButton, ParentElement, Pixels, Point, Render, RenderImage, SharedString,
- StatefulInteractiveElement, Styled, Window, div, img, prelude::FluentBuilder, px, rgb, svg,
+ IntoElement, MouseButton, ParentElement, Pixels, Point, Render, RenderImage, ScrollAnchor,
+ ScrollHandle, SharedString, StatefulInteractiveElement, Styled, Window, div, img,
+ prelude::FluentBuilder, px, rgb, svg,
};
use serde_json::Value;
use crate::{
devices::WindowOption,
library::{self, RecordingItem, RecordingMode, ScreenshotItem},
+ main_window::Mode,
store::{
self, AppTheme, DEFAULT_PROJECT_NAME_TEMPLATE, DEFAULT_SERVER_URL, GENERAL_SETTINGS,
GeneralSettings, MainWindowStartBehaviour, PostDeletionBehaviour, RECORDING_START_SAFETY,
@@ -259,6 +261,12 @@ const INSTANT_RESOLUTION_TIERS: &[(u32, &str, &str)] = &[
/// `FREE_INSTANT_MODE_MAX_RESOLUTION`.
const FREE_INSTANT_MODE_MAX_RESOLUTION: u32 = 1280;
+#[derive(Clone, Copy)]
+enum InstantQualityNotice {
+ UpgradeRequired,
+ SaveFailed,
+}
+
/// `UPDATE_CHANNEL_OPTIONS`.
const UPDATE_CHANNEL_DESCRIPTIONS: &[(UpdateChannel, &str)] = &[
(UpdateChannel::Stable, "Versioned releases (recommended)"),
@@ -602,6 +610,12 @@ pub struct SettingsWindow {
pub(crate) page: Page,
pub(crate) settings: GeneralSettings,
menu: Option<OpenMenu>,
+ page_scroll: ScrollHandle,
+ instant_quality_anchor: ScrollAnchor,
+ studio_quality_anchor: ScrollAnchor,
+ quality_scroll_request: Option<Mode>,
+ has_cap_pro: bool,
+ instant_quality_notice: Option<InstantQualityNotice>,
/// Everything the pages in `settings_pages.rs` own -- their fetch state,
/// drafts and text-input entities.
pub(crate) pages: crate::settings_pages::PagesState,
@@ -704,6 +718,7 @@ impl SettingsWindow {
];
let pages = crate::settings_pages::PagesState::new(window, cx);
+ let page_scroll = ScrollHandle::new();
Self {
theme,
@@ -716,6 +731,12 @@ impl SettingsWindow {
server_url: settings.server_url.clone(),
settings,
menu: None,
+ instant_quality_anchor: ScrollAnchor::for_handle(page_scroll.clone()),
+ studio_quality_anchor: ScrollAnchor::for_handle(page_scroll.clone()),
+ page_scroll,
+ quality_scroll_request: None,
+ has_cap_pro: store::auth_snapshot().is_upgraded(),
+ instant_quality_notice: None,
project_name_input,
server_url_input,
_field_events: field_events,
@@ -763,6 +784,14 @@ impl SettingsWindow {
/// Re-target an already-open window, the way `showWindow({ Settings: {
/// page } })` navigates a live one.
pub fn set_page(&mut self, page: Page, window: &mut Window, cx: &mut Context<Self>) {
+ if self.page != page {
+ self.page_scroll = ScrollHandle::new();
+ self.instant_quality_anchor = ScrollAnchor::for_handle(self.page_scroll.clone());
+ self.studio_quality_anchor = ScrollAnchor::for_handle(self.page_scroll.clone());
+ }
+ self.quality_scroll_request = None;
+ self.instant_quality_notice = None;
+ self.has_cap_pro = store::auth_snapshot().is_upgraded();
self.page = page;
self.menu = None;
// The store may have changed under us while the window was in the
@@ -773,6 +802,22 @@ impl SettingsWindow {
cx.notify();
}
+ pub fn show_quality_settings(
+ &mut self,
+ mode: Mode,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if mode == Mode::Screenshot {
+ return;
+ }
+ if self.page != Page::General {
+ self.set_page(Page::General, window, cx);
+ }
+ self.quality_scroll_request = Some(mode);
+ cx.notify();
+ }
+
/// Whatever the newly shown page has to fetch.
///
/// The Recordings page's `createQuery` runs on mount and again on every
@@ -1454,6 +1499,16 @@ impl Render for SettingsWindow {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.sync_appearance(window, cx);
let theme = self.theme;
+ if self.page == Page::General
+ && let Some(mode) = self.quality_scroll_request.take()
+ {
+ match mode {
+ Mode::Instant => self.instant_quality_anchor.scroll_to(window, cx),
+ Mode::Studio => self.studio_quality_anchor.scroll_to(window, cx),
+ Mode::Screenshot => {}
+ }
+ window.request_animation_frame();
+ }
let shell = div()
.track_focus(&self.focus)
@@ -1732,7 +1787,10 @@ impl SettingsWindow {
.px(px(4.))
.py(px(2.))
.rounded(px(4.))
- .child(format!("v{}", env!("CARGO_PKG_VERSION"))),
+ .child(format!(
+ "v{} (Experimental GPUI)",
+ env!("CARGO_PKG_VERSION")
+ )),
)
.child(
div()
@@ -1840,6 +1898,8 @@ impl SettingsWindow {
if !crate::auth::sign_out() {
tracing::error!("failed to clear the auth session");
}
+ self.has_cap_pro = store::auth_snapshot().is_upgraded();
+ self.instant_quality_notice = None;
if !store::set_store_value("user_profile", Value::Null) {
tracing::error!("failed to clear the cached user profile");
}
@@ -1852,6 +1912,8 @@ impl SettingsWindow {
}
fn refresh_user_profile(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ self.has_cap_pro = store::auth_snapshot().is_upgraded();
+ self.instant_quality_notice = None;
let Some(user_id) = signed_in_user_id() else {
return;
};
@@ -1976,6 +2038,7 @@ impl SettingsWindow {
.flex_1()
.min_h_0()
.overflow_y_scroll()
+ .track_scroll(&self.page_scroll)
// `.cap-settings-page > .px-6 { max-width: none; padding:
// 18px var(--macos-settings-content-padding-x) 28px }`,
// and `space-y-7` between sections.
@@ -2964,15 +3027,33 @@ impl SettingsWindow {
)
}
- /// `CapProSection` -- `instantModeMaxResolution`, `disableAutoOpenLinks`.
- ///
- /// `hasCapPro` comes from the auth store's plan, which this app does not
- /// read, so the section renders its free-plan variant: the resolution is
- /// pinned to 720p and the other tiers are inert (the Tauri app answers a
- /// click on them with an upgrade toast).
+ fn select_instant_resolution(&mut self, index: usize, cx: &mut Context<Self>) {
+ let Some((resolution, _, _)) = INSTANT_RESOLUTION_TIERS.get(index).copied() else {
+ return;
+ };
+ self.has_cap_pro = store::auth_snapshot().is_upgraded();
+ if !self.has_cap_pro && resolution != FREE_INSTANT_MODE_MAX_RESOLUTION {
+ self.instant_quality_notice = Some(InstantQualityNotice::UpgradeRequired);
+ } else if store::set_store_setting(
+ GENERAL_SETTINGS,
+ "instantModeMaxResolution",
+ Value::from(resolution),
+ ) {
+ self.settings.instant_mode_max_resolution = resolution;
+ self.instant_quality_notice = None;
+ } else {
+ self.instant_quality_notice = Some(InstantQualityNotice::SaveFailed);
+ }
+ cx.notify();
+ }
+
fn render_cap_pro(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
- let effective = FREE_INSTANT_MODE_MAX_RESOLUTION;
+ let effective = if self.has_cap_pro {
+ self.settings.instant_mode_max_resolution
+ } else {
+ FREE_INSTANT_MODE_MAX_RESOLUTION
+ };
let summary = INSTANT_RESOLUTION_TIERS
.iter()
.find(|(value, _, _)| *value == effective)
@@ -2994,7 +3075,7 @@ impl SettingsWindow {
})
.collect(),
cx,
- |_, _, _| {},
+ |this, index, cx| this.select_instant_resolution(index, cx),
),
)
.child(
@@ -3011,14 +3092,55 @@ impl SettingsWindow {
None,
vec![
self.rows(vec![
- self.setting_row(
- "Instant Mode quality",
- Some(
- "Instant recordings are locked to 720p. Cap Pro unlocks higher \
- resolutions.",
- ),
- resolution.into_any_element(),
- ),
+ div()
+ .id("settings-instant-quality")
+ .anchor_scroll(Some(self.instant_quality_anchor.clone()))
+ .child(self.setting_row(
+ "Instant Mode quality",
+ Some(if self.has_cap_pro {
+ "Choose the maximum upload resolution for Instant recordings."
+ } else {
+ "Instant recordings are locked to 720p. Cap Pro unlocks higher resolutions."
+ }),
+ resolution.into_any_element(),
+ ))
+ .when_some(self.instant_quality_notice, |this, notice| {
+ this.child(
+ div()
+ .flex()
+ .flex_col()
+ .items_start()
+ .gap(px(8.))
+ .px(px(12.))
+ .pb(px(12.))
+ .text_size(px(12.))
+ .line_height(px(18.))
+ .text_color(Hsla::from(theme.amber_11))
+ .child(match notice {
+ InstantQualityNotice::UpgradeRequired => {
+ "Upgrade to Cap Pro to record Instant Mode videos above 720p."
+ }
+ InstantQualityNotice::SaveFailed => {
+ "Failed to save Instant Mode quality. Please try again."
+ }
+ })
+ .when(matches!(notice, InstantQualityNotice::UpgradeRequired), |this| {
+ this.child(
+ ui::Button::settings(
+ &theme,
+ "instant-quality-upgrade",
+ ui::ButtonVariant::Gray,
+ ui::ButtonSize::Xs,
+ )
+ .label("Upgrade")
+ .on_click(|_, _, cx| {
+ cx.open_url(&format!("{}/pricing", crate::auth::server_url()));
+ }),
+ )
+ }),
+ )
+ })
+ .into_any_element(),
self.setting_row(
"Auto-open shareable links",
Some("Open the share link in your browser as soon as the upload finishes."),
@@ -3053,6 +3175,8 @@ impl SettingsWindow {
.unwrap_or(STUDIO_QUALITY_TIERS[1]);
let body = div()
+ .id("settings-studio-quality")
+ .anchor_scroll(Some(self.studio_quality_anchor.clone()))
// `flex flex-col gap-3 px-4 py-4`
.flex()
.flex_col()
diff --git a/apps/desktop-gpui/src/target_overlay.rs b/apps/desktop-gpui/src/target_overlay.rs
index 2d4ab4e37..34494e55e 100644
--- a/apps/desktop-gpui/src/target_overlay.rs
+++ b/apps/desktop-gpui/src/target_overlay.rs
@@ -25,8 +25,8 @@ use std::time::Duration;
use cap_recording::sources::screen_capture::ScreenCaptureTarget;
use gpui::{
- App, AppContext as _, Context, Entity, FontWeight, Global, Hsla, ImageFormat,
- InteractiveElement as _, IntoElement, MouseButton, MouseMoveEvent, MouseUpEvent,
+ Animation, AnimationExt as _, App, AppContext as _, Context, Entity, FontWeight, Global, Hsla,
+ ImageFormat, InteractiveElement as _, IntoElement, MouseButton, MouseMoveEvent, MouseUpEvent,
ParentElement as _, Pixels, Point, Render, SharedString, StatefulInteractiveElement as _,
Styled, Window, div, img, linear_color_stop, linear_gradient, prelude::FluentBuilder as _, px,
rgb, svg,
@@ -38,6 +38,9 @@ use scap_targets::{
use crate::{
app_windows,
+ editor_canvas::{
+ GuideAxis, NormRect, SNAP_PX, SnapGuide, build_snap_targets, snap_moving_rect,
+ },
main_window::{Mode, TargetType},
theme::Theme,
};
@@ -91,6 +94,91 @@ const AREA_HANDLE_GRAB: f32 = 12.;
const CLUSTER_WIDTH: f32 = 416.;
const CLUSTER_HEIGHT: f32 = 88.;
+const COUNTDOWN_OPTIONS: &[(u32, &str)] = &[
+ (0, "Off"),
+ (3, "3 seconds"),
+ (5, "5 seconds"),
+ (10, "10 seconds"),
+];
+
+const SELECTION_HINT_CYCLE: Duration = Duration::from_millis(2800);
+
+fn material_ease(progress: f32) -> f32 {
+ let progress = progress.clamp(0., 1.);
+ if progress <= 0. {
+ return 0.;
+ }
+ if progress >= 1. {
+ return 1.;
+ }
+ let mut low = 0.;
+ let mut high = 1.;
+ for _ in 0..10 {
+ let t = (low + high) / 2.;
+ let inverse = 1. - t;
+ let x = 3. * inverse * inverse * t * 0.4 + 3. * inverse * t * t * 0.2 + t * t * t;
+ if x < progress {
+ low = t;
+ } else {
+ high = t;
+ }
+ }
+ let t = (low + high) / 2.;
+ let inverse = 1. - t;
+ 3. * inverse * t * t + t * t * t
+}
+
+fn selection_drag_progress(progress: f32) -> f32 {
+ if progress <= 0.5 {
+ material_ease(progress * 2.)
+ } else {
+ 1. - material_ease((progress - 0.5) * 2.)
+ }
+}
+
+fn norm_area_rect(rect: AreaRect, display_size: (f32, f32)) -> NormRect {
+ let width = f64::from(display_size.0.max(1.));
+ let height = f64::from(display_size.1.max(1.));
+ NormRect {
+ x: f64::from(rect.x) / width,
+ y: f64::from(rect.y) / height,
+ w: f64::from(rect.width) / width,
+ h: f64::from(rect.height) / height,
+ }
+}
+
+fn snap_area_rect(rect: AreaRect, display_size: (f32, f32)) -> (AreaRect, Vec<SnapGuide>) {
+ let rect = rect.clamped(display_size);
+ let targets = build_snap_targets(&[], None);
+ let normalized = norm_area_rect(rect, display_size);
+ let (dx, dy, guides) = snap_moving_rect(
+ normalized,
+ &targets,
+ SNAP_PX / f64::from(display_size.0.max(1.)),
+ SNAP_PX / f64::from(display_size.1.max(1.)),
+ );
+ (
+ AreaRect {
+ x: rect.x + (dx * f64::from(display_size.0)) as f32,
+ y: rect.y + (dy * f64::from(display_size.1)) as f32,
+ ..rect
+ }
+ .clamped(display_size),
+ guides,
+ )
+}
+
+fn snap_area_point(point: (f32, f32), display_size: (f32, f32)) -> ((f32, f32), Vec<SnapGuide>) {
+ let rect = AreaRect {
+ x: point.0,
+ y: point.1,
+ width: 0.,
+ height: 0.,
+ };
+ let (snapped, guides) = snap_area_rect(rect, display_size);
+ ((snapped.x, snapped.y), guides)
+}
+
/// The window under the cursor, as the overlays need it.
#[derive(Clone, Debug, PartialEq)]
pub struct HoveredWindow {
@@ -460,10 +548,13 @@ pub struct OverlayWindow {
focus: gpui::FocusHandle,
crop: Option<AreaRect>,
drag: Option<AreaDrag>,
+ snap_guides: Vec<SnapGuide>,
+ recording_area: bool,
/// The mode menu the start pill's caret drops down -- `menuModes()`
/// 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>,
+ countdown_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,
@@ -535,7 +626,10 @@ impl OverlayWindow {
focus: cx.focus_handle(),
crop: None,
drag: None,
+ snap_guides: Vec::new(),
+ recording_area: false,
mode_menu: None,
+ countdown_menu: None,
inline_camera: None,
inline_camera_subscription: None,
empty_camera_state: crate::store::load().camera_window.unwrap_or_default(),
@@ -551,14 +645,41 @@ impl OverlayWindow {
/// Seed an area selection without drawing one -- the harness path
/// (`CAP_GPUI_AUTO_AREA`), since unprivileged synthetic drags are dropped.
pub fn set_crop(&mut self, crop: AreaRect, cx: &mut Context<Self>) {
+ if self.recording_area {
+ return;
+ }
self.crop = Some(crop.clamped(self.display_size));
self.sync_area_camera(cx);
cx.notify();
}
+ pub fn commit_area_for_recording(&mut self, cx: &mut Context<Self>) -> bool {
+ if self.select.read(cx).mode != Some(TargetType::Area) || self.target(cx).is_none() {
+ return false;
+ }
+ self.recording_area = true;
+ self.drag = None;
+ self.snap_guides.clear();
+ self.mode_menu = None;
+ self.countdown_menu = None;
+ self.device_menu = None;
+ cx.notify();
+ true
+ }
+
+ pub fn is_recording_area(&self) -> bool {
+ self.recording_area
+ }
+
/// The target this overlay would record, or `None` when it has nothing to
/// record yet (no window under the cursor, no valid area drawn).
pub fn target(&self, cx: &App) -> Option<ScreenCaptureTarget> {
+ if self.recording_area {
+ return self.crop.map(|crop| ScreenCaptureTarget::Area {
+ screen: self.display_id.clone(),
+ bounds: crop.to_bounds(),
+ });
+ }
let select = self.select.read(cx);
let min = area_min_size(select.recording_mode);
match select.mode? {
@@ -679,6 +800,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.countdown_menu {
+ match menu.on_key(&event.keystroke.key) {
+ crate::ui::MenuKey::Commit(index) => this.choose_countdown(index, cx),
+ crate::ui::MenuKey::Dismiss => {
+ this.countdown_menu = None;
+ cx.notify();
+ }
+ crate::ui::MenuKey::Moved => cx.notify(),
+ crate::ui::MenuKey::Ignored => return,
+ }
+ cx.stop_propagation();
+ return;
+ }
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),
@@ -716,16 +850,21 @@ impl Render for OverlayWindow {
.font_weight(FontWeight::MEDIUM)
.text_color(gpui::white());
- let root = match mode {
- Some(TargetType::Display) => root.child(self.render_display_variant(cx)),
- Some(TargetType::Window) => root.child(self.render_window_variant(cx)),
- Some(TargetType::Area) => root.child(self.render_area_variant(cx)),
- Some(TargetType::CameraOnly) => root.child(self.render_camera_variant(cx)),
- None => root,
+ let root = if self.recording_area {
+ root.child(self.render_area_variant(cx))
+ } else {
+ match mode {
+ Some(TargetType::Display) => root.child(self.render_display_variant(cx)),
+ Some(TargetType::Window) => root.child(self.render_window_variant(cx)),
+ Some(TargetType::Area) => root.child(self.render_area_variant(cx)),
+ Some(TargetType::CameraOnly) => root.child(self.render_camera_variant(cx)),
+ None => root,
+ }
};
// Painted after the variant so the dropdown sits above the start
// cluster it drops from.
root.children(self.render_mode_menu(cx))
+ .children(self.render_countdown_menu(cx))
.children(self.render_device_menu(cx))
.into_any_element()
}
@@ -821,6 +960,7 @@ impl OverlayWindow {
(items, choices)
};
self.mode_menu = None;
+ self.countdown_menu = None;
self.device_menu = Some(OverlayDeviceMenu {
state: crate::ui::MenuState::new(position, &items),
items,
@@ -953,6 +1093,42 @@ impl OverlayWindow {
)
}
+ fn render_countdown_menu(&self, cx: &mut Context<Self>) -> Option<gpui::AnyElement> {
+ let state = self.countdown_menu.as_ref()?;
+ let current = crate::store::GeneralSettings::load()
+ .recording_countdown
+ .unwrap_or(0);
+ let items = COUNTDOWN_OPTIONS
+ .iter()
+ .map(|(value, label)| crate::ui::MenuItem::new(*label, *value == current))
+ .collect();
+ Some(
+ crate::ui::Menu::plain(&self.theme, "overlay-countdown-menu", items, state)
+ .on_select(cx.listener(|this, index: &usize, _, cx| {
+ this.choose_countdown(*index, cx);
+ }))
+ .on_dismiss(cx.listener(|this, _, _, cx| {
+ this.countdown_menu = None;
+ cx.notify();
+ }))
+ .into_any_element(),
+ )
+ }
+
+ fn choose_countdown(&mut self, index: usize, cx: &mut Context<Self>) {
+ self.countdown_menu = None;
+ if let Some((value, _)) = COUNTDOWN_OPTIONS.get(index)
+ && !crate::store::set_store_setting(
+ crate::store::GENERAL_SETTINGS,
+ "recordingCountdown",
+ serde_json::Value::from(*value),
+ )
+ {
+ tracing::warn!(value, "could not save the recording countdown");
+ }
+ cx.notify();
+ }
+
/// A `CheckMenuItem` action: `setOptions("mode", ..)` +
/// `commands.setRecordingMode(..)` -- the app's single mode funnel
/// (`app_windows::set_recording_mode` -> `MainWindow::set_mode`), which
@@ -1209,31 +1385,34 @@ impl OverlayWindow {
fn render_area_variant(&self, cx: &mut Context<Self>) -> gpui::Stateful<gpui::Div> {
let interacting = self.drag.is_some();
// `shouldShowOverlay = isInteracting() || isActiveDisplay()`.
- let visible = interacting || self.is_active_display(cx);
+ let visible = self.recording_area || interacting || self.is_active_display(cx);
let crop = self.crop;
let min = area_min_size(self.select.read(cx).recording_mode);
let valid = crop.is_some_and(|crop| crop.is_valid_for(min));
+ let interactive = !self.recording_area;
let mut root = div()
.id("area-root")
.size_full()
.relative()
- .cursor(gpui::CursorStyle::Crosshair)
- .on_mouse_down(
- MouseButton::Left,
- cx.listener(|this, event: &gpui::MouseDownEvent, _window, cx| {
- this.area_mouse_down(event.position, cx);
- }),
- )
- .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _window, cx| {
- this.area_mouse_move(event.position, cx);
- }))
- .on_mouse_up(
- MouseButton::Left,
- cx.listener(|this, _: &MouseUpEvent, _window, cx| {
- this.area_mouse_up(cx);
- }),
- );
+ .when(interactive, |this| {
+ this.cursor(gpui::CursorStyle::Crosshair)
+ .on_mouse_down(
+ MouseButton::Left,
+ cx.listener(|this, event: &gpui::MouseDownEvent, _window, cx| {
+ this.area_mouse_down(event.position, cx);
+ }),
+ )
+ .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _window, cx| {
+ this.area_mouse_move(event.position, cx);
+ }))
+ .on_mouse_up(
+ MouseButton::Left,
+ cx.listener(|this, _: &MouseUpEvent, _window, cx| {
+ this.area_mouse_up(cx);
+ }),
+ )
+ });
if !visible {
// `classList={{ "opacity-0 pointer-events-none": !shouldShowOverlay() }}`
@@ -1285,18 +1464,29 @@ impl OverlayWindow {
};
if let Some(crop) = crop {
- root = root.child(self.render_crop_region(crop));
+ root = root.child(self.render_crop_region(crop, interactive));
}
- root.child(self.render_area_toolbar(crop, valid))
- .child(self.render_area_controls(crop, valid, cx))
+ root = root.children(self.render_snap_guides());
+ if self.recording_area {
+ return root;
+ }
+ if crop.is_none() && !interacting {
+ root = root.child(self.render_selection_hint());
+ }
+ root = root.child(self.render_area_toolbar(crop, valid));
+ if crop.is_some() {
+ root.child(self.render_area_controls(crop, valid, cx))
+ } else {
+ root
+ }
}
/// `border border-white/50` around the selection, plus the eight resize
/// zones. The zones carry only a cursor: the drag itself is dispatched from
/// the root's mouse-down through [`Self::area_zone_at`], so a grab that
/// starts a pixel outside the handle still resizes.
- fn render_crop_region(&self, crop: AreaRect) -> impl IntoElement {
+ fn render_crop_region(&self, crop: AreaRect, interactive: bool) -> impl IntoElement {
let mut region = div()
.absolute()
.left(px(crop.x))
@@ -1305,9 +1495,9 @@ impl OverlayWindow {
.h(px(crop.height))
.border_1()
.border_color(gpui::hsla(0., 0., 1., 0.5))
- .cursor(gpui::CursorStyle::OpenHand);
+ .when(interactive, |this| this.cursor(gpui::CursorStyle::OpenHand));
- for handle in AreaHandle::ALL {
+ for handle in AreaHandle::ALL.into_iter().filter(|_| interactive) {
let mut zone = div().id(handle.id()).absolute().cursor(handle.cursor());
let reach = px(AREA_HANDLE_GRAB * 2.);
@@ -1389,6 +1579,142 @@ impl OverlayWindow {
region
}
+ fn render_snap_guides(&self) -> Vec<gpui::AnyElement> {
+ self.snap_guides
+ .iter()
+ .map(|guide| {
+ let color = gpui::rgb(0xFF3B6B);
+ match guide.axis {
+ GuideAxis::V => div()
+ .absolute()
+ .left(px(guide.pos as f32 * self.display_size.0))
+ .top(px(guide.start as f32 * self.display_size.1))
+ .w(px(1.))
+ .h(px((guide.end - guide.start) as f32 * self.display_size.1))
+ .bg(color)
+ .into_any_element(),
+ GuideAxis::H => div()
+ .absolute()
+ .top(px(guide.pos as f32 * self.display_size.1))
+ .left(px(guide.start as f32 * self.display_size.0))
+ .h(px(1.))
+ .w(px((guide.end - guide.start) as f32 * self.display_size.0))
+ .bg(color)
+ .into_any_element(),
+ }
+ })
+ .collect()
+ }
+
+ fn render_selection_hint(&self) -> impl IntoElement {
+ let cursor_path = if cfg!(target_os = "windows") {
+ "onboarding/cursor-windows.svg"
+ } else {
+ "onboarding/cursor-macos.svg"
+ };
+ let animation = || Animation::new(SELECTION_HINT_CYCLE).repeat();
+ let selection = div()
+ .absolute()
+ .left(px(41.))
+ .top(px(26.))
+ .border_1()
+ .border_color(gpui::hsla(0., 0., 1., 0.82))
+ .bg(linear_gradient(
+ 135.,
+ linear_color_stop(gpui::hsla(0.55, 1., 0.72, 0.4), 0.),
+ linear_color_stop(gpui::hsla(0.62, 1., 0.59, 0.2), 1.),
+ ))
+ .with_animation("area-selection-hint-box", animation(), |this, progress| {
+ let progress = selection_drag_progress(progress);
+ this.w(px(10. + 58. * progress)).h(px(8. + 44. * progress))
+ });
+ let cursor = img(cursor_path)
+ .absolute()
+ .left(px(41.))
+ .top(px(26.))
+ .w(px(18.))
+ .h(px(26.))
+ .with_animation(
+ "area-selection-hint-cursor",
+ animation(),
+ |this, progress| {
+ let progress = selection_drag_progress(progress);
+ this.left(px(41. + 68. * progress))
+ .top(px(26. + 52. * progress))
+ },
+ );
+ let click = div()
+ .absolute()
+ .rounded_full()
+ .border_2()
+ .border_color(gpui::hsla(0., 0., 1., 0.85))
+ .with_animation(
+ "area-selection-hint-click",
+ animation(),
+ |this, progress| {
+ let (scale, opacity) = if (0.1..0.12).contains(&progress) {
+ (
+ (progress - 0.1) / 0.02 * 0.2,
+ (progress - 0.1) / 0.02 * 0.95,
+ )
+ } else if (0.12..0.18).contains(&progress) {
+ (
+ 0.2 + (progress - 0.12) / 0.06 * 0.65,
+ 0.95 * (1. - (progress - 0.12) / 0.06),
+ )
+ } else {
+ (0., 0.)
+ };
+ let drag = selection_drag_progress(progress);
+ let size = 20. * scale;
+ this.left(px(41. + 68. * drag + 9. - size / 2.))
+ .top(px(26. + 52. * drag + 14.3 - size / 2.))
+ .size(px(size))
+ .opacity(opacity)
+ },
+ );
+
+ div()
+ .absolute()
+ .inset_0()
+ .flex()
+ .items_center()
+ .justify_center()
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .items_center()
+ .gap(px(20.))
+ .child(
+ div()
+ .relative()
+ .w(px(152.))
+ .h(px(104.))
+ .mb(px(24.))
+ .child(img("icons/monitor.svg").size_full())
+ .child(
+ div()
+ .absolute()
+ .left(px(4.5))
+ .top(px(4.5))
+ .w(px(143.))
+ .h(px(94.5))
+ .overflow_hidden()
+ .child(selection)
+ .child(click)
+ .child(cursor),
+ ),
+ )
+ .child(
+ div()
+ .text_size(px(16.))
+ .font_weight(FontWeight::MEDIUM)
+ .child("Click and drag to select an area"),
+ ),
+ )
+ }
+
/// The floating readout: `top-12 left-1/2 -translate-x-1/2` over the
/// liquid-glass surface, `min-w-28 px-2 text-base tabular-nums`. The
/// aspect-ratio, reset, fill and lock controls that share this bar in the
@@ -1454,6 +1780,7 @@ impl OverlayWindow {
height: 0.,
});
let (screen_width, screen_height) = self.display_size;
+ let min = area_min_size(self.select.read(cx).recording_mode);
let below = crop.bottom() + MARGIN_BELOW;
let cluster_height = CLUSTER_HEIGHT
@@ -1485,7 +1812,9 @@ impl OverlayWindow {
.flex()
.flex_col()
.items_center()
- .child(self.render_controls_cluster(self.target(cx), !valid, cx))
+ .when(valid, |this| {
+ this.child(self.render_controls_cluster(self.target(cx), false, cx))
+ })
.when(!valid, |this| {
// `Minimum size is 150 x 150` / `W x H is too small`.
this.child(
@@ -1502,10 +1831,7 @@ impl OverlayWindow {
.bg(self.theme.red_2)
.text_size(px(14.))
.text_color(self.theme.gray_12)
- .child(format!(
- "Minimum size is {} x {}",
- AREA_MIN_SIZE as u32, AREA_MIN_SIZE as u32
- ))
+ .child(format!("Minimum size is {} x {}", min as u32, min as u32))
.child(div().text_size(px(11.)).child(format!(
"{} x {} is too small",
crop.width.round(),
@@ -1576,11 +1902,8 @@ impl OverlayWindow {
.child(self.render_close_button(cx))
.child(self.render_start_button(target, disabled, mode, cx))
.child(
- // `size-9 rounded-full border bg-gray-6 text-gray-12`.
- // Inert: the countdown menu it opens needs the
- // settings store (same gap as the bar's settings
- // button).
div()
+ .id("overlay-countdown")
.flex()
.justify_center()
.items_center()
@@ -1595,7 +1918,31 @@ impl OverlayWindow {
.path("icons/gear.svg")
.size(px(20.))
.text_color(theme.gray_12),
- ),
+ )
+ .hover(|style| style.opacity(0.8))
+ .tooltip(move |_, cx| {
+ crate::ui::Tooltip::new(&theme, "Recording countdown").view(cx)
+ })
+ .on_mouse_down(MouseButton::Left, |_, _, cx| {
+ cx.stop_propagation();
+ })
+ .on_click(cx.listener(|this, event: &gpui::ClickEvent, _, cx| {
+ cx.stop_propagation();
+ let current = crate::store::GeneralSettings::load()
+ .recording_countdown
+ .unwrap_or(0);
+ let items = COUNTDOWN_OPTIONS
+ .iter()
+ .map(|(value, label)| {
+ crate::ui::MenuItem::new(*label, *value == current)
+ })
+ .collect::<Vec<_>>();
+ this.mode_menu = None;
+ this.device_menu = None;
+ this.countdown_menu =
+ Some(crate::ui::MenuState::new(event.position(), &items));
+ cx.notify();
+ })),
),
),
)
@@ -1668,8 +2015,8 @@ impl OverlayWindow {
Mode::Screenshot => "icons/camera.svg",
};
let mode_label = match mode {
- Mode::Instant => "Instant Mode",
- Mode::Studio => "Studio Mode",
+ Mode::Instant => "Instant Mode — Record shareable link",
+ Mode::Studio => "Studio Mode — Record and edit locally",
Mode::Screenshot => "Screenshot Mode",
};
let _ = target;
@@ -1695,6 +2042,7 @@ impl OverlayWindow {
))
.child(
div()
+ .id("overlay-start-action")
.flex()
.flex_1()
.items_center()
@@ -1712,6 +2060,7 @@ impl OverlayWindow {
.when(!disabled, |this| {
this.hover(|style| style.bg(gpui::hsla(0., 0., 1., 0.1)))
})
+ .tooltip(move |_, cx| crate::ui::Tooltip::new(&theme, label).view(cx))
.child(
svg()
.path(icon)
@@ -1737,6 +2086,8 @@ impl OverlayWindow {
div()
.mt(px(-2.))
.text_size(px(11.))
+ .whitespace_nowrap()
+ .truncate()
// `text-[11px] ... text-white/90
// font-light` (`t-s-overlay.tsx:2200`).
// `font-light` is 300 and no 300 face is
@@ -1760,6 +2111,7 @@ impl OverlayWindow {
// handler. Active even while start is disabled, same as the
// source (the disabled styling only wraps the leading half).
div()
+ .id("overlay-mode-picker")
.on_mouse_down(
MouseButton::Left,
cx.listener(|this, event: &gpui::MouseDownEvent, _window, cx| {
@@ -1773,6 +2125,7 @@ impl OverlayWindow {
}
let current = this.select.read(cx).recording_mode;
this.device_menu = None;
+ this.countdown_menu = None;
this.mode_menu = Some(crate::ui::MenuState::new(
event.position,
&mode_menu_items(current),
@@ -1792,6 +2145,9 @@ impl OverlayWindow {
.border_l_1()
.border_color(gpui::hsla(0., 0., 1., 0.2))
.bg(gpui::hsla(0., 0., 1., 0.05))
+ .tooltip(move |_, cx| {
+ crate::ui::Tooltip::new(&theme, "Choose recording mode").view(cx)
+ })
.child(
svg()
.path("icons/caret-down.svg")
@@ -1846,7 +2202,11 @@ impl OverlayWindow {
}
fn area_mouse_down(&mut self, position: Point<Pixels>, cx: &mut Context<Self>) {
+ if self.recording_area {
+ return;
+ }
let point = (f32::from(position.x), f32::from(position.y));
+ self.snap_guides.clear();
self.drag = match self.area_zone_at(point) {
Some(AreaZone::Handle(handle)) => Some(AreaDrag::Resize {
@@ -1879,23 +2239,34 @@ impl OverlayWindow {
}
fn area_mouse_move(&mut self, position: Point<Pixels>, cx: &mut Context<Self>) {
+ if self.recording_area {
+ return;
+ }
let Some(drag) = &self.drag else { return };
let x = f32::from(position.x).clamp(0., self.display_size.0);
let y = f32::from(position.y).clamp(0., self.display_size.1);
- let next = match drag {
- AreaDrag::Draw { anchor } => AreaRect {
- x: anchor.0.min(x),
- y: anchor.1.min(y),
- width: (x - anchor.0).abs(),
- height: (y - anchor.1).abs(),
- },
- AreaDrag::Move { grab, start } => AreaRect {
- x: start.x + (x - grab.0),
- y: start.y + (y - grab.1),
- ..*start
+ let (next, guides) = match drag {
+ AreaDrag::Draw { anchor } => {
+ let ((x, y), guides) = snap_area_point((x, y), self.display_size);
+ (
+ AreaRect {
+ x: anchor.0.min(x),
+ y: anchor.1.min(y),
+ width: (x - anchor.0).abs(),
+ height: (y - anchor.1).abs(),
+ },
+ guides,
+ )
}
- .clamped(self.display_size),
+ AreaDrag::Move { grab, start } => snap_area_rect(
+ AreaRect {
+ x: start.x + (x - grab.0),
+ y: start.y + (y - grab.1),
+ ..*start
+ },
+ self.display_size,
+ ),
AreaDrag::Resize { handle, start } => {
let mut left = start.x;
let mut top = start.y;
@@ -1913,24 +2284,32 @@ impl OverlayWindow {
if handle.south() {
bottom = y;
}
- AreaRect {
- x: left.min(right),
- y: top.min(bottom),
- width: (right - left).abs(),
- height: (bottom - top).abs(),
- }
+ (
+ AreaRect {
+ x: left.min(right),
+ y: top.min(bottom),
+ width: (right - left).abs(),
+ height: (bottom - top).abs(),
+ },
+ Vec::new(),
+ )
}
};
self.crop = Some(next);
+ self.snap_guides = guides;
self.sync_area_camera(cx);
cx.notify();
}
fn area_mouse_up(&mut self, cx: &mut Context<Self>) {
+ if self.recording_area {
+ return;
+ }
let Some(drag) = self.drag.take() else {
return;
};
+ self.snap_guides.clear();
if let Some(crop) = self.crop {
// A click with no drag is not a selection.
if crop.width < 2. || crop.height < 2. {
@@ -2045,4 +2424,52 @@ mod tests {
assert_eq!(bounds.size().width(), 800.);
assert_eq!(bounds.size().height(), 600.);
}
+
+ #[test]
+ fn moving_area_snaps_to_display_centres_and_edges() {
+ let display = (1000., 800.);
+ let (centered, center_guides) = snap_area_rect(rect(446., 180., 100., 120.), display);
+ assert_eq!(centered, rect(450., 180., 100., 120.));
+ assert!(
+ center_guides
+ .iter()
+ .any(|guide| guide.axis == GuideAxis::V && guide.pos == 0.5)
+ );
+
+ let (edge, edge_guides) = snap_area_rect(rect(894., 180., 100., 120.), display);
+ assert_eq!(edge, rect(900., 180., 100., 120.));
+ assert!(
+ edge_guides
+ .iter()
+ .any(|guide| guide.axis == GuideAxis::V && guide.pos == 1.)
+ );
+ }
+
+ #[test]
+ fn drawing_endpoint_snaps_per_axis_within_seven_pixels() {
+ let display = (1000., 800.);
+ let (snapped, guides) = snap_area_point((496., 404.), display);
+ assert_eq!(snapped, (500., 400.));
+ assert!(
+ guides
+ .iter()
+ .any(|guide| guide.axis == GuideAxis::V && guide.pos == 0.5)
+ );
+ assert!(
+ guides
+ .iter()
+ .any(|guide| guide.axis == GuideAxis::H && guide.pos == 0.5)
+ );
+
+ let (unsnapped, guides) = snap_area_point((490., 390.), display);
+ assert_eq!(unsnapped, (490., 390.));
+ assert!(guides.is_empty());
+ }
+
+ #[test]
+ fn selection_hint_curve_reaches_both_drag_extents() {
+ assert_eq!(selection_drag_progress(0.), 0.);
+ assert!((selection_drag_progress(0.5) - 1.).abs() < 0.001);
+ assert_eq!(selection_drag_progress(1.), 0.);
+ }
}
diff --git a/apps/desktop-gpui/src/ui/menu.rs b/apps/desktop-gpui/src/ui/menu.rs
index a5df3786d..9423283e4 100644
--- a/apps/desktop-gpui/src/ui/menu.rs
+++ b/apps/desktop-gpui/src/ui/menu.rs
@@ -268,6 +268,7 @@ impl RenderOnce for Menu {
.border_1()
.border_color(border)
.bg(bg)
+ .text_color(text)
.text_size(px(12.))
.children(items.into_iter().enumerate().map(|(index, item)| {
let handler = handler.clone();
diff --git a/apps/desktop-gpui/src/ui/mod.rs b/apps/desktop-gpui/src/ui/mod.rs
index 8035936d7..6afa1dd70 100644
--- a/apps/desktop-gpui/src/ui/mod.rs
+++ b/apps/desktop-gpui/src/ui/mod.rs
@@ -121,6 +121,6 @@ pub use text_input::{
#[allow(unused_imports)]
pub use toggle::{Toggle, ToggleSize};
#[allow(unused_imports)]
-pub use tooltip::{Tooltip, TooltipStyle};
+pub use tooltip::{TOOLTIP_SHOW_DELAY, Tooltip, TooltipStyle};
#[cfg(target_os = "windows")]
pub use windows_caption::windows_caption_controls;