From e991c1be348397594cbe9430ce164c245ad27e60 Mon Sep 17 00:00:00 2001 From: Michael Burr Date: Thu, 5 Nov 2026 17:19:20 +0000 Subject: [PATCH] fix: eleven bugs from review, from lost settings to recording the mic - A hotkey that can't be registered (macOS without Accessibility, no shortcuts portal, a key another app holds) no longer stops settings, first-run setup included, from being saved. The error still shows. - An error partway through a recording keeps what was recorded, if the encoder can finish the file, and says it stopped early. - Recordings check for a name clash with their own extension, so they no longer overwrite earlier ones. The naming preview puts the shared random generator back, so Secure pixelation stays unpredictable. - Scanning a QR code whose text starts with non-ASCII no longer crashes. - Ctrl+Z or Ctrl+Y mid-drag waits for the drag to end instead of corrupting the annotations or panicking. - Opening a file uses ShellExecuteW instead of cmd /C start, so an & in its name can't break it or run a command. - The corner preview stays out of the next capture: excluded from capture on Windows and macOS, and closed first on Linux, where the capture waits 500ms for it to go. - macOS: region recording works in pixels on Retina screens, and overlays use each screen's own scale. - macOS and Wayland: monitors at different scales no longer overlap, so a crop can't contain the other monitor's pixels. - Linux: "What's playing" records the default sink's monitor through pw-record (or parec), never the microphone. - Linux and macOS: launching snapr again shows the running one's window. --- src/audio.rs | 214 +++++++++++++++++++++++++++++++++++++++- src/capture.rs | 249 ++++++++++++++++++++++++++++++++++++++++++----- src/main.rs | 138 ++++++++++++++++++++++---- src/naming.rs | 54 ++++++++-- src/output.rs | 36 +++++-- src/overlay.rs | 26 ++++- src/pin.rs | 9 +- src/qr.rs | 14 ++- src/record.rs | 188 +++++++++++++++++++++++++++++++---- src/record_ui.rs | 5 +- src/session.rs | 51 ++++++++++ src/toast/mod.rs | 20 ++++ src/wayland.rs | 61 +++++++++--- 13 files changed, 966 insertions(+), 99 deletions(-) diff --git a/src/audio.rs b/src/audio.rs index 9fd0ac0..fa2eba0 100644 --- a/src/audio.rs +++ b/src/audio.rs @@ -1,6 +1,7 @@ -//! Audio for screen recordings: what's playing (WASAPI loopback on Windows) -//! and/or a microphone. Each source's samples are padded to follow the -//! recording clock and sent on to be mixed and encoded with the video. +//! Audio for screen recordings: what's playing (WASAPI loopback on Windows, +//! the default sink's monitor on Linux) and/or a microphone. Each source's +//! samples are padded to follow the recording clock and sent on to be mixed +//! and encoded with the video. use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{self, Receiver, Sender}; @@ -85,6 +86,13 @@ impl Capture { out: Sender, clock: Arc>, ) -> Result { + // cpal on Linux is ALSA, whose default device records the + // microphone, even opened as the "output": what's playing comes from + // the default sink's monitor instead, or not at all. + #[cfg(target_os = "linux")] + if *source == Source::System { + return Self::start_monitor(index, out, clock); + } let host = cpal::default_host(); let device = match source { Source::System => host @@ -155,6 +163,34 @@ impl Capture { }) } + /// `start` for what's playing on Linux: the default sink's monitor, + /// through PipeWire's or PulseAudio's own recorder. + #[cfg(target_os = "linux")] + fn start_monitor(index: usize, out: Sender, clock: Arc>) -> Result { + let (child, rx) = monitor::open()?; + let stop = Arc::new(AtomicBool::new(false)); + let stopping = stop.clone(); + let thread = thread::Builder::new() + .name("audio".into()) + .spawn(move || { + let send = |samples: Vec| { + out.send((index, samples)) + .map_err(|_| "the recording stopped taking audio".to_string()) + }; + let (rate, channels) = (monitor::RATE, monitor::CHANNELS); + let result = write_samples(rx, send, &clock, &stopping, rate, channels); + drop(child); + result + }) + .map_err(|e| format!("couldn't start audio thread: {e}"))?; + Ok(Self { + sample_rate: monitor::RATE, + channels: monitor::CHANNELS, + stop, + thread: Some(thread), + }) + } + /// Stops capturing, once the samples up to now are sent. pub fn finish(mut self) -> Result<(), String> { self.stop.store(true, Ordering::Relaxed); @@ -183,6 +219,141 @@ pub fn microphones() -> Vec { .unwrap_or_default() } +/// What's playing on Linux: the default sink's monitor, recorded by +/// `pw-record` (PipeWire, told to capture a sink) or else `parec` +/// (PulseAudio, or PipeWire's stand-in for it). Never a microphone. +#[cfg(target_os = "linux")] +mod monitor { + use std::io::Read; + use std::process::{Child, Command, Stdio}; + use std::sync::mpsc::{self, Receiver, Sender}; + use std::thread; + use std::time::{Duration, Instant}; + + pub const RATE: u32 = 48_000; + pub const CHANNELS: u16 = 2; + /// How long a recorder that's sent nothing yet is given to fail (say, + /// no sound server) before it's taken as working and just quiet. + const STARTUP: Duration = Duration::from_millis(500); + + /// The recorders to try, in order, each writing raw interleaved f32 + /// samples to stdout. + fn commands() -> [Command; 2] { + let (rate, channels) = (RATE.to_string(), CHANNELS.to_string()); + let mut pw = Command::new("pw-record"); + pw.args(["--raw", "--format", "f32", "--rate", &rate, "--channels", &channels]) + .args(["--latency", "20ms", "-P"]) + .arg("{ stream.capture.sink = true node.name = snapr node.description = \"snapr (what's playing)\" }") + .arg("-"); + let mut pa = Command::new("parec"); + pa.args(["--device=@DEFAULT_MONITOR@", "--raw", "--format=float32le"]) + .arg(format!("--rate={rate}")) + .arg(format!("--channels={channels}")) + .args(["--latency-msec=20", "--client-name=snapr"]); + [pw, pa] + } + + /// A recorder that's stopped once dropped. + pub struct Recorder(Child); + + impl Drop for Recorder { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + + /// Starts the first recorder that works, with its samples. + pub fn open() -> Result<(Recorder, Receiver>), String> { + let mut failures = Vec::new(); + for mut command in commands() { + let name = command.get_program().to_string_lossy().into_owned(); + match start(&mut command) { + Ok(started) => return Ok(started), + Err(e) => failures.push(format!("{name}: {e}")), + } + } + Err(format!( + "couldn't record what's playing (it needs PipeWire's pw-record or PulseAudio's parec): {}", + failures.join("; ") + )) + } + + fn start(command: &mut Command) -> Result<(Recorder, Receiver>), String> { + let mut child = command + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .spawn() + .map_err(|e| e.to_string())?; + let stdout = child.stdout.take().expect("piped"); + let mut recorder = Recorder(child); + let (tx, rx) = mpsc::channel(); + let (ready_tx, ready_rx) = mpsc::channel(); + thread::Builder::new() + .name("audio-monitor".into()) + .spawn(move || read_samples(stdout, tx, ready_tx)) + .map_err(|e| e.to_string())?; + let began = Instant::now(); + loop { + match ready_rx.recv_timeout(Duration::from_millis(20)) { + Ok(()) => return Ok((recorder, rx)), + // Its output closed before any sound. + Err(mpsc::RecvTimeoutError::Disconnected) => { + let status = recorder.0.wait().map_err(|e| e.to_string())?; + return Err(format!("stopped straight away ({status})")); + } + Err(mpsc::RecvTimeoutError::Timeout) => { + if let Some(status) = recorder.0.try_wait().map_err(|e| e.to_string())? { + return Err(format!("stopped straight away ({status})")); + } + if began.elapsed() >= STARTUP { + return Ok((recorder, rx)); + } + } + } + } + } + + /// Sends `from`'s samples on as whole frames until it closes, saying + /// on `ready` once the first arrive. + fn read_samples(mut from: impl Read, to: Sender>, ready: Sender<()>) { + let mut buf = vec![0u8; 16 * 1024]; + let mut pending = Vec::new(); + let mut ready = Some(ready); + loop { + let n = match from.read(&mut buf) { + Ok(0) | Err(_) => return, + Ok(n) => n, + }; + pending.extend_from_slice(&buf[..n]); + let samples = take_frames(&mut pending, CHANNELS); + if samples.is_empty() { + continue; + } + if let Some(r) = ready.take() { + let _ = r.send(()); + } + if to.send(samples).is_err() { + return; + } + } + } + + /// The whole frames of raw little-endian f32 samples at the start of + /// `bytes`, leaving any partial one there for the next read. + pub(super) fn take_frames(bytes: &mut Vec, channels: u16) -> Vec { + let frame = 4 * channels.max(1) as usize; + let whole = bytes.len() / frame * frame; + let samples = bytes[..whole] + .chunks_exact(4) + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .collect(); + bytes.drain(..whole); + samples + } +} + fn build_stream( device: &cpal::Device, supported: cpal::SupportedStreamConfig, @@ -335,4 +506,41 @@ mod tests { "{frames} frames in {elapsed} ms" ); } + + /// Raw samples split mid-frame keep the rest for the next read, so the + /// channels stay in step. + #[cfg(target_os = "linux")] + #[test] + fn monitor_samples_come_in_whole_frames() { + let bytes: Vec = [1.0f32, -1.0, 0.5, 0.25].iter().flat_map(|s| s.to_le_bytes()).collect(); + // A frame and a half of stereo, then the rest. + let mut pending = bytes[..12].to_vec(); + assert_eq!(monitor::take_frames(&mut pending, 2), [1.0, -1.0]); + assert_eq!(pending.len(), 4); + pending.extend_from_slice(&bytes[12..]); + assert_eq!(monitor::take_frames(&mut pending, 2), [0.5, 0.25]); + assert!(pending.is_empty()); + } + + /// Records two seconds of what's playing, leaving the raw samples (f32, + /// interleaved) in the temp folder to inspect: + /// `cargo test records_whats_playing -- --ignored --nocapture`. + #[test] + #[ignore] + fn records_whats_playing() { + let clock = Arc::new(Mutex::new(Clock::default())); + let (tx, rx) = mpsc::channel(); + let capture = Capture::start(&Source::System, 0, tx, clock.clone()).unwrap(); + clock.lock().unwrap().start(); + thread::sleep(Duration::from_secs(2)); + let (rate, channels) = (capture.sample_rate, capture.channels); + capture.finish().unwrap(); + let samples: Vec = rx.try_iter().flat_map(|(_, s)| s).collect(); + let peak = samples.iter().fold(0f32, |m, s| m.max(s.abs())); + let path = std::env::temp_dir().join("snapr-whats-playing.f32"); + let bytes: Vec = samples.iter().flat_map(|s| s.to_le_bytes()).collect(); + std::fs::write(&path, bytes).unwrap(); + println!("{} frames at {rate} Hz x{channels}, peak {peak}, in {}", samples.len() / channels as usize, path.display()); + assert!(samples.len() / channels as usize >= rate as usize); + } } diff --git a/src/capture.rs b/src/capture.rs index 7b699f1..9f3f751 100644 --- a/src/capture.rs +++ b/src/capture.rs @@ -90,17 +90,24 @@ fn draw_cursor(cursors: &mut crate::cursor::Cursors, image: &mut RgbaImage, orig /// Every monitor, with the mouse pointer drawn in if `cursor`. pub fn capture_all(cursor: bool) -> Result, xcap::XCapError> { + Ok(capture_placed(cursor)?.into_iter().map(|(shot, _)| shot).collect()) +} + +/// `capture_all`, with where each shot is in the global space (see +/// `untangle`). +fn capture_placed(cursor: bool) -> Result, xcap::XCapError> { // wlroots compositors copy their outputs to us themselves, pointer and // all, and place them as the overlays are placed. #[cfg(target_os = "linux")] if let Some(outputs) = crate::wayland::screenshot(cursor) { let shots = outputs .into_iter() - .filter_map(|(rect, f)| { - Some(Shot { + .filter_map(|(output, f)| { + let shot = Shot { image: RgbaImage::from_raw(f.width, f.height, f.raw)?, - pos: (rect.x, rect.y), - }) + pos: output.at, + }; + Some((shot, output.rect)) }) .collect(); return Ok(shots); @@ -108,14 +115,22 @@ pub fn capture_all(cursor: bool) -> Result, xcap::XCapError> { let mut shots = capture_monitors()?; if cursor { let mut cursors = crate::cursor::Cursors::new(); - for shot in &mut shots { + for (shot, _) in &mut shots { draw_cursor(&mut cursors, &mut shot.image, shot.pos); } } - Ok(shots) + let monitors: Vec<_> = shots + .iter() + .map(|(s, scale)| { + let (w, h) = s.image.dimensions(); + (Rect { x: s.pos.0, y: s.pos.1, w, h }, *scale) + }) + .collect(); + Ok(shots.into_iter().map(|(s, _)| s).zip(untangle(&monitors)).collect()) } -fn capture_monitors() -> Result, xcap::XCapError> { +/// Each monitor's picture, and its scale. +fn capture_monitors() -> Result, xcap::XCapError> { #[cfg(windows)] let hdr = crate::hdr::displays(); xcap::Monitor::all()? @@ -135,7 +150,7 @@ fn capture_monitors() -> Result, xcap::XCapError> { (m.x()? as f32 * scale).round() as i32, (m.y()? as f32 * scale).round() as i32, ); - Ok(Shot { image, pos }) + Ok((Shot { image, pos }, scale as f64)) }) .collect() } @@ -263,7 +278,7 @@ fn xcap_window_rects(own: &[&winit::window::Window]) -> Vec<(u32, Rect)> { /// `window_rects` from one pass over the window list. Frames are in points, /// scaled like `capture_all` places monitors: by the scale of the monitor /// under the window's centre (else one it overlaps, else the main one), as -/// xcap picks it. +/// xcap picks it, and moved with that monitor where `untangle` moves it. #[cfg(target_os = "macos")] fn macos_window_rects() -> Vec<(u32, Rect)> { let monitors: Vec<([f64; 4], f32, bool)> = xcap::Monitor::all() @@ -274,6 +289,21 @@ fn macos_window_rects() -> Vec<(u32, Rect)> { Some((frame, m.scale_factor().ok()?, m.is_primary().unwrap_or(false))) }) .collect(); + // Each monitor as `capture_monitors` places it, and how far `untangle` + // moves it from there. + let placed: Vec<(Rect, f64)> = monitors + .iter() + .map(|&([x, y, w, h], s, _)| { + let px = |v: f64| (v as f32 * s).round(); + let rect = Rect { x: px(x) as i32, y: px(y) as i32, w: px(w) as u32, h: px(h) as u32 }; + (rect, s as f64) + }) + .collect(); + let moved: Vec<(i32, i32)> = placed + .iter() + .zip(untangle(&placed)) + .map(|((from, _), to)| (to.x - from.x, to.y - from.y)) + .collect(); let contains = |[x, y, w, h]: [f64; 4], (px, py): (f64, f64)| px >= x && px < x + w && py >= y && py < y + h; let overlaps = |[x, y, w, h]: [f64; 4], [ox, oy, ow, oh]: [f64; 4]| { x < ox + ow && ox < x + w && y < oy + oh && oy < y + h @@ -283,14 +313,14 @@ fn macos_window_rects() -> Vec<(u32, Rect)> { .filter_map(|w| { let [x, y, width, height] = w.frame; let centre = (x + width / 2.0, y + height / 2.0); - let s = monitors + let i = monitors .iter() - .find(|(m, ..)| contains(*m, centre) || overlaps(*m, w.frame)) - .or_else(|| monitors.iter().find(|(.., primary)| *primary))? - .1; + .position(|(m, ..)| contains(*m, centre) || overlaps(*m, w.frame)) + .or_else(|| monitors.iter().position(|(.., primary)| *primary))?; + let (s, (dx, dy)) = (monitors[i].1, moved[i]); let rect = Rect { - x: (x as i32 as f32 * s).round() as i32, - y: (y as i32 as f32 * s).round() as i32, + x: (x as i32 as f32 * s).round() as i32 + dx, + y: (y as i32 as f32 * s).round() as i32 + dy, w: (width as u32 as f32 * s).round() as u32, h: (height as u32 as f32 * s).round() as u32, }; @@ -600,18 +630,10 @@ pub fn grab(target: &Target, cursor: bool) -> Result<(RgbaImage, Option, Target::ActiveDisplay => active_display(cursor), Target::Region(_) | Target::Everything => { let (process, title) = foreground_window(); - let shots = capture_all(cursor).map_err(failure)?; + let shots = capture_placed(cursor).map_err(failure)?; let placed: Vec<_> = shots .iter() - .map(|s| PlacedShot { - image: &s.image, - rect: Rect { - x: s.pos.0, - y: s.pos.1, - w: s.image.width(), - h: s.image.height(), - }, - }) + .map(|(s, rect)| PlacedShot { image: &s.image, rect: *rect }) .collect(); let region = match target { Target::Region(r) => *r, @@ -698,6 +720,110 @@ fn pick_display(displays: &[DisplayInfo], focused: Option, pointer: Option< .or_else(|| displays.first().map(|d| d.id)) } +/// Where each monitor is in the global space the screenshot is cut from, +/// given where the platform places it (`monitors`: its rect, from winit or +/// the compositor, and its scale). macOS and Wayland put a monitor at its +/// logical position times its own scale but give it its full size in pixels, +/// so with mixed scales they overlap, and a region on one would take the +/// other's pixels. Then each axis is laid out again from the logical layout, +/// every stretch of it as many pixels as its densest monitor needs, so +/// monitors keep their order and neighbours and no longer overlap (lower +/// scale ones may leave a gap). Where nothing overlaps, they're as given. +pub fn untangle(monitors: &[(Rect, f64)]) -> Vec { + let overlapping = monitors + .iter() + .enumerate() + .any(|(i, (a, _))| monitors[i + 1..].iter().any(|(b, _)| a.intersect(b).is_some())); + if !overlapping { + return monitors.iter().map(|(r, _)| *r).collect(); + } + let max_scale = monitors.iter().map(|(_, s)| *s).fold(1.0, f64::max); + // Each monitor's logical (start, length) along one axis, and its scale. + let axis = |get: fn(&Rect) -> (i32, u32)| -> Vec { + let spans: Vec<(f64, f64, f64)> = monitors + .iter() + .map(|(r, s)| { + let s = s.max(f64::MIN_POSITIVE); + let (at, len) = get(r); + (at as f64 / s, len as f64 / s, s) + }) + .collect(); + let mut stops: Vec = spans.iter().flat_map(|&(a, l, _)| [a, a + l]).chain([0.0]).collect(); + stops.sort_by(f64::total_cmp); + stops.dedup_by(|a, b| (*a - *b).abs() < 1e-9); + // Pixels for each stretch between stops: at the scale of the + // densest monitor across it (or of any, between monitors). + let pixels: Vec = stops + .windows(2) + .map(|w| { + let scale = spans + .iter() + .filter(|&&(a, l, _)| a <= w[0] + 1e-9 && a + l >= w[1] - 1e-9) + .map(|&(.., s)| s) + .reduce(f64::max) + .unwrap_or(max_scale); + ((w[1] - w[0]) * scale - 1e-6).ceil() as i32 + }) + .collect(); + // Logical 0 stays at pixel 0, so the main monitor doesn't move. + let zero = stops.iter().position(|s| s.abs() < 1e-9).expect("0 is a stop"); + let mut at = vec![0; stops.len()]; + for i in zero + 1..stops.len() { + at[i] = at[i - 1] + pixels[i - 1]; + } + for i in (0..zero).rev() { + at[i] = at[i + 1] - pixels[i]; + } + spans + .iter() + .map(|&(a, ..)| { + let i = stops.iter().position(|s| (s - a).abs() < 1e-9).expect("a stop"); + at[i] + }) + .collect() + }; + let xs = axis(|r| (r.x, r.w)); + let ys = axis(|r| (r.y, r.h)); + monitors + .iter() + .zip(xs.into_iter().zip(ys)) + .map(|((r, _), (x, y))| Rect { x, y, ..*r }) + .collect() +} + +/// winit's monitors as `untangle` takes them. +pub fn winit_monitors(monitors: impl IntoIterator) -> Vec<(Rect, f64)> { + monitors + .into_iter() + .map(|m| { + let (p, s) = (m.position(), m.size()); + (Rect { x: p.x, y: p.y, w: s.width, h: s.height }, m.scale_factor()) + }) + .collect() +} + +/// `rect`, in the global space `untangle` makes of `monitors`, where the +/// platform places windows: moved back as the monitor its centre is on (else +/// the nearest) was moved. Unchanged where `untangle` moves nothing. +pub fn to_platform(monitors: &[(Rect, f64)], rect: Rect) -> Rect { + let untangled = untangle(monitors); + let centre = (rect.x as f64 + rect.w as f64 / 2.0, rect.y as f64 + rect.h as f64 / 2.0); + let away = |r: &Rect| { + let dx = (r.x as f64 - centre.0).max(centre.0 - r.right() as f64).max(0.0); + let dy = (r.y as f64 - centre.1).max(centre.1 - r.bottom() as f64).max(0.0); + dx * dx + dy * dy + }; + let Some(i) = (0..untangled.len()).min_by(|&a, &b| away(&untangled[a]).total_cmp(&away(&untangled[b]))) else { + return rect; + }; + let (from, to) = (monitors[i].0, untangled[i]); + Rect { + x: rect.x + from.x - to.x, + y: rect.y + from.y - to.y, + ..rect + } +} + /// Builds the final screenshot for `region`, stitching together every monitor /// it overlaps. Areas not covered by any monitor are left transparent. pub fn crop(shots: &[PlacedShot], region: Rect) -> Option { @@ -780,6 +906,79 @@ mod tests { assert_eq!(pick_display(&[], Some(1), None), None); } + /// A 4K monitor at scale 2 with a 1080p one at scale 1 to its right, as + /// macOS and Wayland place them: the second starts at the first's + /// logical width (1920), inside the first's 3840 pixels. + #[test] + fn mixed_scales_are_untangled_side_by_side() { + let rect = |x, y, w, h| Rect { x, y, w, h }; + let placed = untangle(&[(rect(0, 0, 3840, 2160), 2.0), (rect(1920, 0, 1920, 1080), 1.0)]); + assert_eq!(placed, [rect(0, 0, 3840, 2160), rect(3840, 0, 1920, 1080)]); + assert!(placed[0].intersect(&placed[1]).is_none()); + + // A region in the right half of the 4K monitor is all its own, and + // one over the seam takes each monitor's pixels on its side. + let big = RgbaImage::from_pixel(3840, 2160, Rgba([255, 0, 0, 255])); + let small = RgbaImage::from_pixel(1920, 1080, Rgba([0, 0, 255, 255])); + let shots = [ + PlacedShot { image: &big, rect: placed[0] }, + PlacedShot { image: &small, rect: placed[1] }, + ]; + let inside = crop(&shots, rect(2000, 100, 1800, 200)).unwrap(); + assert!(inside.pixels().all(|p| *p == Rgba([255, 0, 0, 255]))); + let seam = crop(&shots, rect(3830, 0, 20, 10)).unwrap(); + assert_eq!(seam.get_pixel(9, 5), &Rgba([255, 0, 0, 255])); + assert_eq!(seam.get_pixel(10, 5), &Rgba([0, 0, 255, 255])); + } + + #[test] + fn mixed_scales_are_untangled_stacked_and_on_three_monitors() { + let rect = |x, y, w, h| Rect { x, y, w, h }; + // A scale 1 monitor below a scale 2 one (logically at y 1080). + let placed = untangle(&[(rect(0, 0, 3840, 2160), 2.0), (rect(0, 1080, 1920, 1080), 1.0)]); + assert_eq!(placed, [rect(0, 0, 3840, 2160), rect(0, 2160, 1920, 1080)]); + // Scale 1 monitors on both sides of a scale 2 one: the one on the + // left (which didn't overlap anything) stays put. + let placed = untangle(&[ + (rect(-1920, 0, 1920, 1080), 1.0), + (rect(0, 0, 2880, 1800), 2.0), + (rect(1440, 0, 1920, 1080), 1.0), + ]); + assert_eq!(placed, [rect(-1920, 0, 1920, 1080), rect(0, 0, 2880, 1800), rect(2880, 0, 1920, 1080)]); + for (i, a) in placed.iter().enumerate() { + assert!(placed[i + 1..].iter().all(|b| a.intersect(b).is_none())); + } + } + + /// Monitors that don't overlap (one scale, or Windows' and X11's own + /// pixel layout) are left exactly where the platform put them. + #[test] + fn monitors_that_dont_overlap_stay_put() { + let rect = |x, y, w, h| Rect { x, y, w, h }; + let same_scale = [(rect(0, 0, 2880, 1800), 2.0), (rect(2880, -200, 3840, 2160), 2.0)]; + assert_eq!(untangle(&same_scale), [same_scale[0].0, same_scale[1].0]); + let windows = [(rect(0, 0, 3840, 2160), 1.5), (rect(3840, 0, 1920, 1080), 1.0)]; + assert_eq!(untangle(&windows), [windows[0].0, windows[1].0]); + // Overlapping, but at one scale (mirrored displays): as they were. + let mirrored = [(rect(0, 0, 2880, 1800), 2.0), (rect(0, 0, 2880, 1800), 2.0), (rect(2880, 0, 200, 100), 2.0)]; + assert_eq!(untangle(&mirrored), mirrored.map(|(r, _)| r)); + let ones = [(rect(0, 0, 1920, 1080), 1.0), (rect(1000, 0, 1920, 1080), 1.0)]; + assert_eq!(untangle(&ones), ones.map(|(r, _)| r)); + assert_eq!(to_platform(&windows, rect(4000, 10, 50, 50)), rect(4000, 10, 50, 50)); + } + + /// A window placed at a selection goes where winit puts that spot. + #[test] + fn selections_go_back_to_the_platforms_place() { + let rect = |x, y, w, h| Rect { x, y, w, h }; + let monitors = [(rect(0, 0, 3840, 2160), 2.0), (rect(1920, 0, 1920, 1080), 1.0)]; + // On the scale 1 monitor (untangled to x 3840): back by 1920. + assert_eq!(to_platform(&monitors, rect(3900, 100, 200, 100)), rect(1980, 100, 200, 100)); + // On the scale 2 one, which didn't move. + assert_eq!(to_platform(&monitors, rect(3000, 100, 200, 100)), rect(3000, 100, 200, 100)); + assert_eq!(to_platform(&[], rect(5, 5, 5, 5)), rect(5, 5, 5, 5)); + } + #[test] fn crop_outside_monitors_is_none() { let img = RgbaImage::new(10, 10); diff --git a/src/main.rs b/src/main.rs index 0d053a9..9049f05 100644 --- a/src/main.rs +++ b/src/main.rs @@ -432,9 +432,7 @@ impl App { return self.quit_if_once_done(event_loop); } }; - let out = naming - .path_for(&ctx) - .with_extension(self.settings.record_format.extension()); + let out = naming.path_with_extension(&ctx, self.settings.record_format.extension()); static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let id = NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let proxy = Mutex::new(self.proxy.clone()); @@ -589,6 +587,10 @@ impl App { if self.main_window.as_ref().is_some_and(|w| w.form.recording) { return; // the user is recording a new hotkey } + #[cfg(target_os = "linux")] + if self.close_toast_first(Start::Pick(purpose)) { + return; + } let gpu = match &self.gpu { Ok(g) => g, Err(e) => { @@ -873,29 +875,27 @@ impl App { Ok(c) => c, Err(e) => return self.report_on(event_loop, e, true, Page::Naming), }; + // A hotkey that can't be registered (taken by another app, no + // Accessibility access, no shortcuts portal) still lets the rest be + // saved; it's reported once they are. + let mut hotkey_error = None; if let Some(hk) = &mut self.hotkeys && let Err(e) = hk.set(&new.hotkey) { - return self.report_on(event_loop, e, true, Page::Hotkeys); + hotkey_error = Some(e); } if let Some(hk) = &mut self.record_hotkeys && let Err(e) = hk.set_optional(&new.record_hotkey) { - return self.report_on( - event_loop, - format!("Record hotkey: {e}"), - true, - Page::Hotkeys, - ); + hotkey_error.get_or_insert(format!("Record hotkey: {e}")); } + // Also when one failed last time (it's missing), to try it again. if !self.once - && new.tool_hotkeys != self.settings.tool_hotkeys + && (new.tool_hotkeys != self.settings.tool_hotkeys + || self.tool_hotkeys.len() != self.settings.tool_hotkeys.len()) && let Err(e) = self.set_tool_hotkeys(&new.tool_hotkeys) { - // Put the old ones back. - let old = self.settings.tool_hotkeys.clone(); - let _ = self.set_tool_hotkeys(&old); - return self.report_on(event_loop, e, true, Page::Hotkeys); + hotkey_error.get_or_insert(e); } // Only on a change: another copy (e.g. with its own SNAPR_CONFIG_DIR) // shouldn't undo this one's. @@ -950,7 +950,10 @@ impl App { w.folder = PathBuf::from(&self.settings.folder); w.speed_unit = self.settings.speed_unit; } - self.report(event_loop, "Settings saved".into(), false); + match hotkey_error { + Some(e) => self.report_on(event_loop, e, true, Page::Hotkeys), + None => self.report(event_loop, "Settings saved".into(), false), + } } /// Replaces the tools' hotkeys. Returns the first that couldn't be @@ -974,12 +977,35 @@ impl App { w.window.set_visible(false); self.restore_main_window = true; } - self.capture_at = Some((Instant::now() + Duration::from_millis(250), start)); + let at = Instant::now() + Duration::from_millis(250); + // No sooner than one already waiting (for the corner preview to go). + let at = self.capture_at.map_or(at, |(t, _)| t.max(at)); + self.capture_at = Some((at, start)); + } + + /// X11 and Wayland can't keep the corner preview out of a capture, so it + /// closes and the capture waits until it's gone: compositors may animate + /// it closing (Wayfire's takes 400ms). Whether the capture waits, or + /// is dropped because another is already on its way. + #[cfg(target_os = "linux")] + fn close_toast_first(&mut self, start: Start) -> bool { + if self.capture_at.is_some() { + return true; + } + if self.toast.take().is_none() { + return false; + } + self.capture_at = Some((Instant::now() + Duration::from_millis(500), start)); + true } /// Captures a window, display, everything or a known region straight /// away, with no overlay to pick or annotate on. fn grab(&mut self, event_loop: &ActiveEventLoop, target: capture::Target) { + #[cfg(target_os = "linux")] + if self.close_toast_first(Start::Grab(target)) { + return; + } let time = chrono::Local::now(); match capture::grab(&target, self.settings.screenshot_cursor) { Ok((image, process, title)) => { @@ -1778,7 +1804,8 @@ impl ApplicationHandler for App { Start::Pick(purpose) => self.open_session(event_loop, purpose), Start::Grab(target) => self.grab(event_loop, target), } - if self.sessions.is_empty() { + // Not while it waits for the corner preview to go. + if self.sessions.is_empty() && self.capture_at.is_none() { self.show_main_window_again(); } } @@ -2015,6 +2042,12 @@ fn single_instance(#[cfg(windows)] uploads: &[PathBuf]) -> Option std::process::exit(1); } } + // Without a tray, the window is the only way back to it. + #[cfg(unix)] + if show_request::send() { + println!("snapr is already running; showing its window"); + std::process::exit(0); + } eprintln!("snapr is already running"); std::process::exit(0); } @@ -2022,6 +2055,67 @@ fn single_instance(#[cfg(windows)] uploads: &[PathBuf]) -> Option } } +/// Lets a second snapr ask the running one to show its window, on Linux +/// and macOS (Windows finds its tray window instead). The running one +/// listens on a socket in the config folder; a connection is the request. +#[cfg(unix)] +mod show_request { + use std::os::unix::net::{UnixListener, UnixStream}; + use std::path::{Path, PathBuf}; + + fn path() -> Option { + crate::settings::Settings::config_dir().map(|dir| dir.join("snapr.sock")) + } + + /// Asks the running snapr to show its window. Whether one was listening. + pub fn send() -> bool { + path().is_some_and(|p| UnixStream::connect(p).is_ok()) + } + + /// Calls `show` for each request. Only for the snapr holding the + /// instance lock, which can take over a socket left by one that crashed. + pub fn listen(show: impl Fn() + Send + 'static) { + if let Some(p) = path() + && let Err(e) = listen_on(&p, show) + { + eprintln!("couldn't listen for another snapr starting: {e}"); + } + } + + fn listen_on(path: &Path, show: impl Fn() + Send + 'static) -> std::io::Result<()> { + let _ = std::fs::remove_file(path); + let listener = UnixListener::bind(path)?; + std::thread::Builder::new().name("show-request".into()).spawn(move || { + for stream in listener.incoming() { + if stream.is_ok() { + show(); + } + } + })?; + Ok(()) + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn a_connection_asks_to_show() { + let dir = std::env::temp_dir().join(format!("snapr-show-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let sock = dir.join("snapr.sock"); + // One left over from a crash is taken over. + std::fs::write(&sock, b"").unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + let tx = std::sync::Mutex::new(tx); + listen_on(&sock, move || tx.lock().unwrap().send(()).unwrap()).unwrap(); + assert!(UnixStream::connect(&sock).is_ok()); + rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap(); + let _ = std::fs::remove_dir_all(dir); + } + } +} + fn main() { // Release builds have no console; reattach to the launching terminal (if // any) so --help and errors are still visible there. @@ -2194,6 +2288,14 @@ fn main() { #[cfg(target_os = "macos")] macos::ask_for_screen_recording(); let proxy = event_loop.create_proxy(); + // As Windows does for its second snapr (`tray::signal_running_instance`). + #[cfg(unix)] + if lock.is_some() { + let proxy = Mutex::new(proxy.clone()); + show_request::listen(move || { + let _ = proxy.lock().unwrap().send_event(UserEvent::Tray(TrayAction::Recent)); + }); + } // Under *System*, windows follow the desktop's style (see `theme::preference`). #[cfg(target_os = "linux")] { diff --git a/src/naming.rs b/src/naming.rs index 9acc24d..3fb3441 100644 --- a/src/naming.rs +++ b/src/naming.rs @@ -407,13 +407,18 @@ impl Naming { } /// An example path for the settings window. Uses a fixed seed so the - /// random part doesn't change on every repaint. + /// random part doesn't change on every repaint; the shared generator + /// goes back to how it was after, so later draws (say, the noise the + /// Secure pixelation adds) aren't predictable. pub fn preview(&self, ctx: &Context) -> PathBuf { + let saved = fastrand::get_seed(); fastrand::seed(0x5eed); - self.candidate(ctx, None) + let path = self.candidate(ctx, None, "png"); + fastrand::seed(saved); + path } - fn candidate(&self, ctx: &Context, suffix: Option) -> PathBuf { + fn candidate(&self, ctx: &Context, suffix: Option, ext: &str) -> PathBuf { let mut path = self.dir.clone(); path.extend(components(&self.subdir.render(ctx))); let name = self.name.render(ctx); @@ -424,20 +429,26 @@ impl Naming { if let Some(n) = suffix { let _ = write!(name, "-{n}"); } - path.join(name + ".png") + path.join(format!("{name}.{ext}")) } /// Picks a path for a new screenshot that doesn't overwrite an existing one. pub fn path_for(&self, ctx: &Context) -> PathBuf { + self.path_with_extension(ctx, "png") + } + + /// Picks a path ending `.{ext}` (say, a recording's `mp4`) that doesn't + /// overwrite an existing file. + pub fn path_with_extension(&self, ctx: &Context, ext: &str) -> PathBuf { let retries = if self.name.has_random() { 16 } else { 1 }; for _ in 0..retries { - let path = self.candidate(ctx, None); + let path = self.candidate(ctx, None, ext); if !path.exists() { return path; } } (2..) - .map(|n| self.candidate(ctx, Some(n))) + .map(|n| self.candidate(ctx, Some(n), ext)) .find(|p| !Path::exists(p)) .expect("ran out of suffixes") } @@ -469,7 +480,7 @@ mod tests { fn render(name: &str) -> String { naming("", name) - .candidate(&ctx(), None) + .candidate(&ctx(), None, "png") .file_stem() .unwrap() .to_str() @@ -511,7 +522,7 @@ mod tests { #[test] fn folders_from_process_and_date() { - let p = naming("%pn/%y/%mo", "%h-%mi-%s").candidate(&ctx(), None); + let p = naming("%pn/%y/%mo", "%h-%mi-%s").candidate(&ctx(), None, "png"); assert_eq!(p, Path::new("base/my_app/2026/10/14-30-05.png")); } @@ -519,7 +530,7 @@ mod tests { fn values_cannot_escape_base_dir() { let mut c = ctx(); c.process = Some("../../etc".into()); - let p = naming("../%pn", "x").candidate(&c, None); + let p = naming("../%pn", "x").candidate(&c, None, "png"); assert_eq!(p, Path::new("base/.._.._etc/x.png")); } @@ -534,6 +545,31 @@ mod tests { assert_eq!(t.render_key(&ctx(), ""), "2026-10/my_app/14-30-05"); } + #[test] + fn recordings_dont_overwrite_recordings() { + let dir = std::env::temp_dir().join(format!("snapr-naming-{}", fastrand::u64(..))); + std::fs::create_dir_all(&dir).unwrap(); + let n = Naming { + dir: dir.clone(), + ..naming("", "clip") + }; + std::fs::write(dir.join("clip.mp4"), "").unwrap(); + let path = n.path_with_extension(&ctx(), "mp4"); + assert_eq!(path, dir.join("clip-2.mp4")); + assert_eq!(n.path_for(&ctx()), dir.join("clip.png")); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn preview_leaves_the_shared_rng_alone() { + fastrand::seed(42); + let before = fastrand::get_seed(); + let n = naming("", "%rna{8}"); + let a = n.preview(&ctx()); + assert_eq!(fastrand::get_seed(), before); + assert_eq!(n.preview(&ctx()), a, "the same every repaint"); + } + #[test] fn rejects_bad_counts() { assert!("%ra{0}".parse::