Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(desktop-gpui): share Focus across overlays and apply it to picks, pin the size menu's window, ignore stale moves, restore maximized windows

Richie McIlroy8ebbe5162489
diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rs
index 51eb8fd69..8485df406 100644
--- a/apps/desktop-gpui/src/app_windows.rs
+++ b/apps/desktop-gpui/src/app_windows.rs
@@ -2162,7 +2162,7 @@ fn restore_arranged_windows(cx: &mut App) {
cx.background_executor()
.spawn(async move {
for window in arranged {
- crate::foreign_window::arrange(&window.id, &window.display_id, window.bounds);
+ crate::foreign_window::put_back(&window);
}
})
.detach();
diff --git a/apps/desktop-gpui/src/foreign_window.rs b/apps/desktop-gpui/src/foreign_window.rs
index 2bde061fb..45a7159ef 100644
--- a/apps/desktop-gpui/src/foreign_window.rs
+++ b/apps/desktop-gpui/src/foreign_window.rs
@@ -22,11 +22,29 @@ pub fn arrange(id: &WindowId, display: &DisplayId, frame: AreaRect) -> bool {
imp::arrange(id, &display, frame)
}
-/// Bring window `id` and its app to the front.
pub fn raise(id: &WindowId) -> bool {
imp::raise(id)
}
+/// How a window sits beyond its bounds (maximized), where bounds alone
+/// cannot put it back.
+#[derive(Clone, Copy)]
+pub struct Placement(imp::RawPlacement);
+
+pub fn placement(id: &WindowId) -> Option<Placement> {
+ imp::placement(id).map(Placement)
+}
+
+pub fn put_back(original: &crate::target_overlay::ArrangedWindow) -> bool {
+ let window = &original.window;
+ if let Some(placement) = original.placement
+ && imp::restore_placement(&window.id, &placement.0)
+ {
+ return true;
+ }
+ arrange(&window.id, &window.display_id, window.bounds)
+}
+
#[cfg(target_os = "macos")]
mod imp {
use std::ffi::c_void;
@@ -82,6 +100,16 @@ mod imp {
unsafe { AXIsProcessTrusted() }
}
+ pub type RawPlacement = std::convert::Infallible;
+
+ pub fn placement(_: &WindowId) -> Option<RawPlacement> {
+ None
+ }
+
+ pub fn restore_placement(_: &WindowId, placement: &RawPlacement) -> bool {
+ match *placement {}
+ }
+
/// The AX element of window `id`, owned by the returned `CFType`.
fn ax_window(id: &WindowId) -> Option<CFType> {
let window = scap_targets::Window::from_id(id)?;
@@ -172,8 +200,8 @@ mod imp {
Foundation::{HWND, RECT},
Graphics::Dwm::{DWMWA_EXTENDED_FRAME_BOUNDS, DwmGetWindowAttribute},
UI::WindowsAndMessaging::{
- GetWindowRect, IsZoomed, SW_RESTORE, SWP_NOACTIVATE, SWP_NOZORDER, SetWindowPos,
- ShowWindow,
+ GetWindowPlacement, GetWindowRect, IsZoomed, SW_RESTORE, SWP_NOACTIVATE, SWP_NOZORDER,
+ SetWindowPlacement, SetWindowPos, ShowWindow, WINDOWPLACEMENT,
},
};
@@ -183,6 +211,29 @@ mod imp {
true
}
+ pub type RawPlacement = WINDOWPLACEMENT;
+
+ /// Only a maximized window needs its placement: resizing restores it,
+ /// and its bounds then put it back as a large normal window.
+ pub fn placement(id: &WindowId) -> Option<RawPlacement> {
+ let hwnd = hwnd(id)?;
+ unsafe {
+ if IsZoomed(hwnd) == 0 {
+ return None;
+ }
+ let mut placement: WINDOWPLACEMENT = std::mem::zeroed();
+ placement.length = std::mem::size_of::<WINDOWPLACEMENT>() as u32;
+ (GetWindowPlacement(hwnd, &mut placement) != 0).then_some(placement)
+ }
+ }
+
+ pub fn restore_placement(id: &WindowId, placement: &RawPlacement) -> bool {
+ let Some(hwnd) = hwnd(id) else {
+ return false;
+ };
+ unsafe { SetWindowPlacement(hwnd, placement) != 0 }
+ }
+
fn hwnd(id: &WindowId) -> Option<HWND> {
let window = scap_targets::Window::from_id(id)?;
let hwnd = window.raw_handle().inner().0 as HWND;
@@ -258,6 +309,16 @@ mod imp {
!cap_recording::screenshot::uses_wayland_portal()
}
+ pub type RawPlacement = std::convert::Infallible;
+
+ pub fn placement(_: &WindowId) -> Option<RawPlacement> {
+ None
+ }
+
+ pub fn restore_placement(_: &WindowId, placement: &RawPlacement) -> bool {
+ match *placement {}
+ }
+
fn send(window: u32, message: &[u8], data: [u32; 5]) -> anyhow::Result<()> {
let (connection, screen) = x11rb::connect(None)?;
let root = connection.setup().roots[screen].root;
diff --git a/apps/desktop-gpui/src/target_overlay.rs b/apps/desktop-gpui/src/target_overlay.rs
index 9e970bdb4..3a6dfa61c 100644
--- a/apps/desktop-gpui/src/target_overlay.rs
+++ b/apps/desktop-gpui/src/target_overlay.rs
@@ -303,10 +303,31 @@ pub struct TargetSelect {
/// Windows the picker moved or resized, keyed by id, with where they
/// were: dismissing the picker puts them back, starting a recording
/// keeps them where the user shaped them.
- arranged: HashMap<String, HoveredWindow>,
+ arranged: HashMap<String, ArrangedWindow>,
+ /// Focus, shared by every display's overlay because the recording reads
+ /// the one setting it mirrors.
+ pub focus_window: bool,
_poll: Option<gpui::Task<()>>,
}
+/// A window the picker moved, as the picker found it.
+#[derive(Clone)]
+pub struct ArrangedWindow {
+ pub window: HoveredWindow,
+ /// Set when its bounds alone cannot put it back (a maximized window).
+ pub placement: Option<crate::foreign_window::Placement>,
+}
+
+enum Arrangement {
+ Frame(AreaRect),
+ PutBack(ArrangedWindow),
+}
+
+fn saved_focus() -> bool {
+ crate::store::GeneralSettings::load().window_capture_style
+ == crate::store::WindowCaptureStyle::FocusedWindow
+}
+
struct TargetSelectGlobal(Entity<TargetSelect>);
impl Global for TargetSelectGlobal {}
@@ -321,6 +342,7 @@ impl TargetSelect {
microphone_fill: 0.,
icons: HashMap::new(),
arranged: HashMap::new(),
+ focus_window: saved_focus(),
_poll: None,
});
cx.set_global(TargetSelectGlobal(select.clone()));
@@ -343,6 +365,7 @@ impl TargetSelect {
self.pinned_window = pinned_window;
if self.mode.is_none() && mode.is_some() {
self.arranged.clear();
+ self.focus_window = saved_focus();
}
if self.mode == mode {
cx.notify();
@@ -381,16 +404,19 @@ impl TargetSelect {
pub fn remember_arranged(&mut self, window: &HoveredWindow) {
self.arranged
.entry(window.id.to_string())
- .or_insert_with(|| window.clone());
+ .or_insert_with(|| ArrangedWindow {
+ window: window.clone(),
+ placement: crate::foreign_window::placement(&window.id),
+ });
}
/// Where the picker found window `id`, if it has moved it since.
- pub fn arranged_original(&self, id: &WindowId) -> Option<&HoveredWindow> {
+ pub fn arranged_original(&self, id: &WindowId) -> Option<&ArrangedWindow> {
self.arranged.get(&id.to_string())
}
/// Every window the picker moved, with where it was, forgetting them.
- pub fn take_arranged(&mut self) -> Vec<HoveredWindow> {
+ pub fn take_arranged(&mut self) -> Vec<ArrangedWindow> {
self.arranged.drain().map(|(_, window)| window).collect()
}
@@ -402,14 +428,16 @@ impl TargetSelect {
}
/// Lock the highlight onto whatever the cursor is over -- the TSX's
- /// click-anywhere-to-select behavior.
- fn pin_hovered(&mut self, cx: &mut Context<Self>) {
+ /// click-anywhere-to-select behavior. True when that picked a new window.
+ fn pin_hovered(&mut self, cx: &mut Context<Self>) -> bool {
if let Some(hovered) = self.hovered_window.clone()
&& self.pinned_window.as_ref().map(|window| &window.id) != Some(&hovered.id)
{
self.pinned_window = Some(hovered);
cx.notify();
+ return true;
}
+ false
}
fn start_polling(&mut self, cx: &mut Context<Self>) {
@@ -938,9 +966,6 @@ pub struct OverlayWindow {
window_reshape: Option<(AreaRect, Instant)>,
/// Where the window highlight was last drawn, for a move to start from.
window_drawn: Cell<Option<AreaRect>>,
- /// Focus: centre the picked window and record it by itself. Mirrors the
- /// window capture style setting, which it writes.
- focus_window: bool,
inline_camera: Option<Entity<crate::camera_window::CameraWindow>>,
inline_camera_subscription: Option<gpui::Subscription>,
empty_camera_state: crate::store::CameraWindowState,
@@ -1098,8 +1123,6 @@ impl OverlayWindow {
window_menu: None,
window_reshape: None,
window_drawn: Cell::new(None),
- focus_window: crate::store::GeneralSettings::load().window_capture_style
- == crate::store::WindowCaptureStyle::FocusedWindow,
inline_camera: None,
inline_camera_subscription: None,
empty_camera_state: crate::store::load().camera_window.unwrap_or_default(),
@@ -1898,7 +1921,10 @@ impl OverlayWindow {
// cursor, exactly as the TSX's two click handlers add up to.
.on_click(cx.listener(|this, _, _window, cx| {
this.window_menu = None;
- this.select.update(cx, |select, cx| select.pin_hovered(cx));
+ let picked = this.select.update(cx, |select, cx| select.pin_hovered(cx));
+ if picked && this.select.read(cx).focus_window {
+ this.set_focus(true, cx);
+ }
// `setOriginalCameraBounds(null)` on the first click
// (`target-select-overlay.tsx:609-617`): committing a pick
// leaves the camera bubble parked in the picked window.
@@ -2005,6 +2031,7 @@ impl OverlayWindow {
return None;
}
let theme = self.theme;
+ let focus = self.select.read(cx).focus_window;
Some(
div()
.id("window-focus")
@@ -2032,11 +2059,13 @@ impl OverlayWindow {
.child("Focus"),
)
.child(
- crate::ui::Toggle::glass(&theme, "window-focus-toggle", self.focus_window)
- .on_click(cx.listener(|this, _, _, cx| {
+ crate::ui::Toggle::glass(&theme, "window-focus-toggle", focus).on_click(
+ cx.listener(|this, _, _, cx| {
cx.stop_propagation();
- this.set_focus(!this.focus_window, cx);
- })),
+ let focus = this.select.read(cx).focus_window;
+ this.set_focus(!focus, cx);
+ }),
+ ),
),
)
}
@@ -2085,6 +2114,12 @@ impl OverlayWindow {
let Some(window) = self.active_window_logical(cx) else {
return;
};
+ // The menu acts on this window until it closes, whatever the
+ // pointer passes over on the way to a row.
+ if let Some(active) = self.select.read(cx).active_window().cloned() {
+ self.select
+ .update(cx, |select, cx| select.set_pinned(active, cx));
+ }
let items: Vec<crate::ui::MenuItem> = self
.window_menu_entries(window)
.into_iter()
@@ -2126,7 +2161,7 @@ impl OverlayWindow {
.and_then(|window| self.window_menu_entries(window).into_iter().nth(index))
.map(|(_, _, frame)| frame);
match frame {
- Some(frame) => self.arrange_active_window(frame, false, cx),
+ Some(frame) => self.arrange_active_window(Arrangement::Frame(frame), false, cx),
None => cx.notify(),
}
}
@@ -2134,7 +2169,10 @@ impl OverlayWindow {
/// Focus on: centre the window, bring it forward, record it by itself.
/// Focus off: put it back where the picker found it, record the region.
pub(crate) fn set_focus(&mut self, focus: bool, cx: &mut Context<Self>) {
- self.focus_window = focus;
+ self.select.update(cx, |select, cx| {
+ select.focus_window = focus;
+ cx.notify();
+ });
let style = if focus {
crate::store::WindowCaptureStyle::FocusedWindow
} else {
@@ -2153,24 +2191,31 @@ impl OverlayWindow {
};
if focus {
let centred = crate::window_arrange::centre(window, self.controls_work_area);
- self.arrange_active_window(centred, true, cx);
+ self.arrange_active_window(Arrangement::Frame(centred), true, cx);
} else {
- let original = self.select.read(cx).active_window().and_then(|active| {
- self.select
- .read(cx)
- .arranged_original(&active.id)
- .map(|original| original.bounds.scaled(1. / self.capture_scale))
- });
+ let original = self
+ .select
+ .read(cx)
+ .active_window()
+ .and_then(|active| self.select.read(cx).arranged_original(&active.id).cloned());
match original {
- Some(original) => self.arrange_active_window(original, false, cx),
+ Some(original) => {
+ self.arrange_active_window(Arrangement::PutBack(original), false, cx)
+ }
None => cx.notify(),
}
}
}
- /// Move the picked window to `frame` (this overlay's logical points),
- /// then follow wherever its app actually put it.
- fn arrange_active_window(&mut self, frame: AreaRect, raise: bool, cx: &mut Context<Self>) {
+ /// Move the picked window (`Frame` in this overlay's logical points, or
+ /// back where the picker found it), then follow wherever its app
+ /// actually put it.
+ fn arrange_active_window(
+ &mut self,
+ arrangement: Arrangement,
+ raise: bool,
+ cx: &mut Context<Self>,
+ ) {
let Some(window) = self.select.read(cx).active_window().cloned() else {
return;
};
@@ -2182,14 +2227,24 @@ impl OverlayWindow {
select.remember_arranged(&window);
select.set_pinned(window.clone(), cx);
});
- let frame = frame.scaled(self.capture_scale);
+ let capture_scale = self.capture_scale;
let (id, display) = (window.id.clone(), window.display_id.clone());
+ let requested = id.clone();
let select = self.select.clone();
cx.spawn(async move |this, cx| {
let moved = cx
.background_executor()
.spawn(async move {
- let arranged = crate::foreign_window::arrange(&id, &display, frame);
+ let arranged = match arrangement {
+ Arrangement::Frame(frame) => crate::foreign_window::arrange(
+ &id,
+ &display,
+ frame.scaled(capture_scale),
+ ),
+ Arrangement::PutBack(original) => {
+ crate::foreign_window::put_back(&original)
+ }
+ };
if raise {
crate::foreign_window::raise(&id);
}
@@ -2204,6 +2259,19 @@ impl OverlayWindow {
if !arranged {
tracing::warn!("the picked window could not be arranged");
}
+ // Only while this picker is still up with the same window picked:
+ // a slow move must not replace a newer choice.
+ let still_picked = this
+ .update(cx, |_, cx| {
+ select
+ .read(cx)
+ .active_window()
+ .is_some_and(|window| window.id == requested)
+ })
+ .unwrap_or(false);
+ if !still_picked {
+ return;
+ }
if let Some(fresh) = fresh {
select.update(cx, |select, cx| select.set_pinned(fresh, cx));
}
diff --git a/apps/desktop-gpui/src/window_arrange.rs b/apps/desktop-gpui/src/window_arrange.rs
index 809acec55..f79071240 100644
--- a/apps/desktop-gpui/src/window_arrange.rs
+++ b/apps/desktop-gpui/src/window_arrange.rs
@@ -6,13 +6,10 @@ use crate::target_overlay::AreaRect;
/// Kept clear between a moved window and the edge of the usable area.
pub const MARGIN: f32 = 16.;
-/// The smallest window the picker will shape, on either side.
pub const MIN_SIDE: f32 = 160.;
-/// The ratios offered for a window, widest first.
pub const RATIOS: [(u32, u32); 6] = [(21, 9), (16, 9), (16, 10), (4, 3), (1, 1), (9, 16)];
-/// Exact sizes offered, in pixels as recorded.
pub const SIZES: [(&str, u32, u32); 4] = [
("720p", 1280, 720),
("1080p", 1920, 1080),
@@ -31,7 +28,6 @@ fn inset(area: AreaRect) -> AreaRect {
}
}
-/// `size` centred on (`cx`, `cy`), then pushed back inside `area`.
fn place(width: f32, height: f32, cx: f32, cy: f32, area: AreaRect) -> AreaRect {
let x = (cx - width / 2.).clamp(area.x, (area.x + area.width - width).max(area.x));
let y = (cy - height / 2.).clamp(area.y, (area.y + area.height - height).max(area.y));
@@ -43,7 +39,6 @@ fn place(width: f32, height: f32, cx: f32, cy: f32, area: AreaRect) -> AreaRect
}
}
-/// `width` x `height` scaled down, keeping its ratio, until it fits `area`.
fn fit_inside(width: f32, height: f32, area: AreaRect) -> (f32, f32) {
let scale = (area.width / width).min(area.height / height).min(1.);
(width * scale, height * scale)
@@ -92,7 +87,6 @@ pub fn fit_to_size(
})
}
-/// The window centred in the usable area, shrunk to fit if it is larger.
pub fn centre(window: AreaRect, work_area: AreaRect) -> AreaRect {
let area = inset(work_area);
let (width, height) = fit_inside(window.width, window.height, area);