diff --git a/src-tauri/src/capture.rs b/src-tauri/src/capture.rs index 5584dd7..2625681 100644 --- a/src-tauri/src/capture.rs +++ b/src-tauri/src/capture.rs @@ -41,9 +41,11 @@ pub fn displays() -> Result> { } let info = MonitorInfo { id: monitor.id().unwrap_or(0), + // `friendly_name()` reaches for `NSScreen`, which AppKit only allows on + // the main thread, while this runs on a `spawn_blocking` worker; + // `name()` is pure CoreGraphics and safe from any thread. name: monitor - .friendly_name() - .or_else(|_| monitor.name()) + .name() .unwrap_or_else(|_| format!("Display {}", out.len() + 1)), x: monitor.x().unwrap_or(0), y: monitor.y().unwrap_or(0), diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 3566f8f..c551716 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -98,11 +98,25 @@ pub async fn start_capture(app: &AppHandle) -> Result { crate::session::Store::prune_frames(&frame_dir, &session.id); // A boot tool (tray 长截图) applies to this session's overlays only. + // One monitor failing to host a window must not cancel the whole capture: + // the remaining screens still get a usable overlay. let boot = overlay::take_boot_tool(); + let mut shown = 0usize; for info in &monitors { - let win = overlay::create(app, info.id, info.x, info.y, info.width, info.height, &boot)?; - overlay::reveal(&win)?; + match overlay::create(app, info.id, info.x, info.y, info.width, info.height, &boot) + .and_then(|win| overlay::reveal(&win, info)) + { + Ok(()) => shown += 1, + Err(e) => log::error!("overlay for monitor {} failed: {e:#}", info.id), + } + } + if shown == 0 { + anyhow::bail!("无法创建截图遮罩窗口"); } + // AppKit only delivers `mouseMoved` to the key window, so a secondary + // display's overlay would never see hover: keep the window under the + // cursor focused as the pointer crosses screens. + overlay::follow_pointer(app, monitors.clone()); let session_id = session.id.clone(); app.emit("capture://ready", &session_id)?; @@ -333,7 +347,7 @@ async fn do_confirm( }); } - let crop_id = store.put_crop(png); + let crop_id = store.put_crop(png, monitor_id); // Window-opening side effects happen before the teardown: once the // overlays are destroyed, the webview waiting on this invoke is gone and @@ -853,28 +867,47 @@ fn open_pin_for_crop(app: &AppHandle, crop_id: &str) -> Result<()> { let store: State<'_, Arc> = app.state(); let info = store.crop_info(crop_id)?; - // Match the window to the image, capped so a full-screen crop does not - // create a window larger than the desktop. - let (sw, sh, s) = app - .primary_monitor() - .ok() - .flatten() + // The monitor the crop came from owns the pin: its scale factor converts the + // PNG pixels and its logical origin anchors the window, so a secondary-screen + // crop lands on that screen and a mixed-DPI desktop scales correctly. Only a + // session that has already been replaced falls back to the primary display. + let (ox, oy, sw, sh, s) = store + .current() + .and_then(|session| session.monitor(info.monitor_id).cloned()) .map(|m| { - let s = m.scale_factor(); ( - (m.size().width as f64 / s) as f64, - (m.size().height as f64 / s) as f64, - s, + f64::from(m.x), + f64::from(m.y), + f64::from(m.width), + f64::from(m.height), + m.scale_factor, ) }) - .unwrap_or((1440.0, 900.0, 1.0)); + .or_else(|| { + // The main display is where the global display space is anchored, so + // its logical origin is the desktop origin; only its size needs the + // physical-to-logical division its handle reports in. + app.primary_monitor().ok().flatten().map(|m| { + let s = m.scale_factor(); + ( + 0.0, + 0.0, + m.size().width as f64 / s, + m.size().height as f64 / s, + s, + ) + }) + }) + .unwrap_or((0.0, 0.0, 1440.0, 900.0, 1.0)); // `crop_info` dims are PNG pixels (physical); the window is logical, so // divide by the scale factor or a Retina pin comes out twice too large. let (iw, ih) = (info.width as f64 / s, info.height as f64 / s); let fit = (sw * 0.8 / iw).min(sh * 0.8 / ih).min(1.0); + // Centred inside the source monitor's own frame; a negative origin is a + // normal position for a display placed left of, or above, the primary one. let rect = Rect { - x: ((sw - iw * fit) / 2.0).max(0.0), - y: ((sh - ih * fit) / 2.0).max(0.0), + x: ox + (sw - iw * fit) / 2.0, + y: oy + (sh - ih * fit) / 2.0, width: iw * fit, height: ih * fit, }; diff --git a/src-tauri/src/overlay.rs b/src-tauri/src/overlay.rs index aae07fe..6c16034 100644 --- a/src-tauri/src/overlay.rs +++ b/src-tauri/src/overlay.rs @@ -78,8 +78,12 @@ pub fn create( } /// Bring an overlay to the front and confirm it landed on screen. -pub fn reveal(win: &WebviewWindow) -> Result<()> { +/// +/// `monitor` is the display the window was built for: its logical origin is the +/// only trustworthy frame reference available here. +pub fn reveal(win: &WebviewWindow, monitor: &crate::types::MonitorInfo) -> Result<()> { let label = win.label().to_string(); + let (mx, my) = (f64::from(monitor.x), f64::from(monitor.y)); win.set_always_on_top(true) .map_err(|e| anyhow::anyhow!("always-on-top {label}: {e}"))?; // set_always_on_top resets the level to floating (below the Dock); @@ -113,16 +117,31 @@ pub fn reveal(win: &WebviewWindow) -> Result<()> { win.show().ok(); // Nudge the frame: some macOS versions ignore the first show of a // window created with a non-standard level. - let pos = win.outer_position().unwrap_or_default(); - let _ = win.set_position(tauri::LogicalPosition::new(pos.x, pos.y + 1)); - let _ = win.set_position(tauri::LogicalPosition::new(pos.x, pos.y)); + // + // The nudge is written in logical points, so its reference is the + // monitor's logical origin rather than a readback of the live frame: + // `outer_position()` reports physical pixels while + // `set_position(LogicalPosition)` is consumed as Cocoa points, so on + // a scaled display whose origin is not the desktop origin, a + // readback-then-write lands the window at double that origin — off + // the desktop entirely. + let _ = win.set_position(tauri::LogicalPosition::new(mx, my + 1.0)); + let _ = win.set_position(tauri::LogicalPosition::new(mx, my)); } } + // Expected values are the monitor's logical frame; the measured pair is in + // physical pixels. They differ by exactly `scale_factor` unless the window + // server has clamped or re-parented the window. let size = win.inner_size().map(|s| (s.width, s.height)).unwrap_or((0, 0)); let pos = win.outer_position().map(|p| (p.x, p.y)).unwrap_or((0, 0)); log::info!( - "overlay {label} revealed: visible={:?} size={size:?} pos={pos:?}", - win.is_visible() + "overlay {label} revealed: visible={:?} expected_logical_origin=({mx}, {my}) \ + expected_logical_size=({}x{}) actual_physical_pos={pos:?} actual_physical_size={size:?} \ + scale_factor={}", + win.is_visible(), + monitor.width, + monitor.height, + win.scale_factor().unwrap_or(0.0), ); Ok(()) } @@ -138,3 +157,58 @@ pub fn destroy_all(app: &AppHandle) { } } } + +/// Hand key-window status to the overlay the pointer is on. +/// +/// macOS delivers `mouseMoved` to the key window only, so an overlay that is +/// not key sees no pointer movement at all — window snapping, the loupe and +/// the eyedropper then track the cursor on one display only. A click still +/// works anywhere, because the mouse-down makes its own window key first. With +/// one overlay per display, exactly one display can ever be key, so the key +/// window has to follow the pointer. +/// +/// The pointer is read from the hardware event source (the same call the +/// auto-scroller uses) and only the display *change* triggers a focus call, so +/// movement inside a display — including a selection drag — leaves the window +/// stack alone. +#[cfg(target_os = "macos")] +pub fn follow_pointer(app: &AppHandle, monitors: Vec) { + let app = app.clone(); + std::thread::spawn(move || { + let mut over: Option = None; + // The overlays are the session: once confirm/cancel has closed them + // there is nothing left to track. The bound is a safety net for a + // session that ends without the windows ever being observed closed. + for _ in 0..10_000 { + let windows = app.webview_windows(); + if !windows.keys().any(|label| label.starts_with("overlay-")) { + break; + } + let (px, py) = crate::scroll::mouse_location(); + if px.is_finite() && py.is_finite() { + let hit = monitors.iter().find(|m| { + px >= f64::from(m.x) + && px < f64::from(m.x) + f64::from(m.width) + && py >= f64::from(m.y) + && py < f64::from(m.y) + f64::from(m.height) + }); + let hit = hit.map(|m| m.id); + if hit != over { + over = hit; + if let Some(id) = hit { + let label = label_for(id); + if let Some(win) = windows.get(&label) { + log::info!("pointer moved to monitor {id}: focusing {label}"); + let _ = win.set_focus(); + } + } + } + } + std::thread::sleep(Duration::from_millis(60)); + } + }); +} + +/// No other platform restricts pointer-move delivery to the key window. +#[cfg(not(target_os = "macos"))] +pub fn follow_pointer(_app: &AppHandle, _monitors: Vec) {} diff --git a/src-tauri/src/scroll/mod.rs b/src-tauri/src/scroll/mod.rs index 7a1e294..4769b5d 100644 --- a/src-tauri/src/scroll/mod.rs +++ b/src-tauri/src/scroll/mod.rs @@ -96,7 +96,7 @@ fn preview_path(_app: &AppHandle) -> Result { /// selection" test was permanently false and the armed scroller never started, /// no matter where the mouse actually was. #[cfg(target_os = "macos")] -fn mouse_location() -> (f64, f64) { +pub(crate) fn mouse_location() -> (f64, f64) { use core_graphics::geometry::CGPoint; #[link(name = "CoreGraphics", kind = "framework")] @@ -467,6 +467,8 @@ fn open_control_bar(app: &AppHandle, monitor: &crate::types::MonitorInfo) -> Res } let w = 330.0; let h = 52.0; + // Global logical coordinates: a display placed left of, or above, the primary + // one has a negative origin, so the computed position is used verbatim. let x = monitor.x as f64 + (monitor.width as f64 - w) / 2.0; let y = monitor.y as f64 + (monitor.height as f64 - h - 48.0).max(24.0); @@ -476,8 +478,8 @@ fn open_control_bar(app: &AppHandle, monitor: &crate::types::MonitorInfo) -> Res label, "index.html?view=scrollbar", "Shutter 长截图", - x.max(0.0), - y.max(0.0), + x, + y, w, h, false, diff --git a/src-tauri/src/session.rs b/src-tauri/src/session.rs index 301757a..d63156a 100644 --- a/src-tauri/src/session.rs +++ b/src-tauri/src/session.rs @@ -47,8 +47,8 @@ impl Session { pub struct Store { /// Only the newest session is kept: the overlay always operates on it. current: Mutex>>, - /// PNG bytes for finished crops, keyed by crop id. - crops: Mutex>>, + /// PNG bytes plus the monitor the crop came from, keyed by crop id. + crops: Mutex, u32)>>, } /// A crop plus the dimensions the pin window should use. @@ -56,6 +56,10 @@ pub struct CropInfo { pub png: Vec, pub width: u32, pub height: u32, + /// Id of the monitor the crop was taken from. A pin is sized and centred in + /// that display's own logical frame, which matters when the screens have + /// different scale factors or negative origins. + pub monitor_id: u32, } impl Store { @@ -99,9 +103,12 @@ impl Store { self.crops.lock().unwrap().clear(); } - pub fn put_crop(&self, png: Vec) -> String { + /// Remember a finished crop and the monitor it came from, so a later pin + /// can be placed on that display instead of wherever the pointer happens to + /// be or the primary screen. + pub fn put_crop(&self, png: Vec, monitor_id: u32) -> String { let id = uuid::Uuid::new_v4().to_string(); - self.crops.lock().unwrap().insert(id.clone(), png); + self.crops.lock().unwrap().insert(id.clone(), (png, monitor_id)); id } @@ -110,16 +117,22 @@ impl Store { .lock() .unwrap() .get(id) - .cloned() + .map(|(png, _)| png.clone()) .ok_or_else(|| anyhow!("crop {id} not found; take a new screenshot")) } /// Crop bytes plus pixel size, so window chrome can match the image. pub fn crop_info(&self, id: &str) -> Result { - let png = self.crop(id)?; + let (png, monitor_id) = self + .crops + .lock() + .unwrap() + .get(id) + .cloned() + .ok_or_else(|| anyhow!("crop {id} not found; take a new screenshot"))?; let decoded = image::load_from_memory(&png).map_err(|e| anyhow!("decode crop: {e}"))?; let (width, height) = (decoded.width(), decoded.height()); - Ok(CropInfo { png, width, height }) + Ok(CropInfo { png, width, height, monitor_id }) } } diff --git a/src/routes/Overlay.tsx b/src/routes/Overlay.tsx index a57bc2b..efc2f08 100644 --- a/src/routes/Overlay.tsx +++ b/src/routes/Overlay.tsx @@ -186,6 +186,7 @@ export function Overlay({ monitorId }: Props) { /** Load the monitor descriptor + frozen frame for this window. */ useEffect(() => { let cancelled = false; + let failTimer: number | undefined; (async () => { try { await import("@tauri-apps/api/core") @@ -196,10 +197,22 @@ export function Overlay({ monitorId }: Props) { // a second time (a second capture would include this very overlay). const session = await api.currentSession(); if (!session) throw new Error("截图会话已结束,请重新截图"); - const info = session.monitors.find((m) => m.id === monitorId) ?? session.monitors[0]; - if (!info) throw new Error("没有可用的显示器"); + // A window may only draw the monitor it was created for. Falling back + // to another monitor would show a foreign frame at foreign size and + // turn a window-placement bug into a silent wrong-crop, so an id + // mismatch is fatal here. + const info = session.monitors.find((m) => m.id === monitorId); + if (!info) throw new Error(`显示器 ${monitorId} 不可用,请重新截图`); setMonitor(info); setSessionId(session.sessionId); + // The descriptor and the webview must agree on size: a mismatch means + // the OS gave this window different bounds than its monitor, which is + // otherwise only visible as a misaligned overlay. + void reportDebug("overlay-viewport", { + monitorId: info.id, + monitor: `${info.width}x${info.height}`, + viewport: `${window.innerWidth}x${window.innerHeight}`, + }); const path = await api.framePath(info.id, session.sessionId); if (cancelled) return; @@ -263,10 +276,17 @@ export function Overlay({ monitorId }: Props) { } } catch (e) { setToast(errorText(e)); + // Every failure here leaves this window with no usable frame, so the + // whole capture is torn down rather than parking a dead overlay on + // screen; the delay lets the toast be read before the windows close. + failTimer = window.setTimeout(() => { + void api.cancelCapture().catch(() => undefined); + }, 1500); } })(); return () => { cancelled = true; + window.clearTimeout(failTimer); }; }, [monitorId]);