diff --git a/src-tauri/src/editor.rs b/src-tauri/src/editor.rs index a41eaa8..f03913c 100644 --- a/src-tauri/src/editor.rs +++ b/src-tauri/src/editor.rs @@ -1,5 +1,5 @@ use std::path::Path; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use base64::{engine::general_purpose::STANDARD, Engine as _}; use image::{GenericImageView, Rgba, RgbaImage}; @@ -69,6 +69,18 @@ pub fn open_in_editor(app: AppHandle, path: String) -> Result, current: Option) -> bool { matches!((requested, current), (Some(requested), Some(current)) if requested == current) } +/// The window size in logical pixels that shows a `preview`-sized image, keeping +/// its aspect ratio. +/// +/// Small is the freshly pinned reference: never larger than the picture itself, +/// never longer than 520 px on its longest edge. Enlarged fills up to +/// `PIN_FIT_FRACTION` of the monitor's work area and is allowed to grow past the +/// picture's own pixels, because "放大" means making it bigger to read, not +/// resampling it losslessly. `work_area` of `None` means the monitor could not be +/// read; that answers with the small size rather than a guess, since a pin sized +/// off a phantom screen is one the user cannot reach. +fn pin_window_size( + preview: (u32, u32), + work_area: Option<(f64, f64)>, + enlarged: bool, +) -> (f64, f64) { + let width = f64::from(preview.0.max(1)); + let height = f64::from(preview.1.max(1)); + let scale = match (enlarged, work_area) { + (true, Some((area_width, area_height))) => (area_width * PIN_FIT_FRACTION / width) + .min(area_height * PIN_FIT_FRACTION / height) + .min(PIN_MAX_GROWTH), + // A pin is never shrunk below the picture's own pixels at either size. + _ => (PIN_SMALL_EDGE / width.max(height)).min(1.0), + }; + ((width * scale).max(160.0), (height * scale).max(100.0)) +} + +/// The part of a monitor a window may be placed on: the screen minus the menu bar +/// and any dock, in the physical pixels the platform positions windows in. +#[derive(Clone, Copy, Debug)] +struct PinArea { + left: f64, + top: f64, + width: f64, + height: f64, +} + +impl PinArea { + fn of(monitor: &tauri::Monitor) -> PinArea { + let area = monitor.work_area(); + PinArea { + left: f64::from(area.position.x), + top: f64::from(area.position.y), + width: f64::from(area.size.width), + height: f64::from(area.size.height), + } + } + + /// How much of it a window may be sized to, in the logical pixels `set_size` + /// is told in. Only the extent converts this way: the origin is asked in + /// physical pixels and is left alone. + fn logical_size(self, scale: f64) -> (f64, f64) { + (self.width / scale, self.height / scale) + } +} + +/// The monitor a pin is on, with its usable area in both units and the scale factor +/// between them. `current_monitor` is preferred, with the primary monitor as the +/// answer for a window the platform cannot place; `None` when there is no monitor. +struct PinScreen { + /// Usable extent, in the logical pixels `set_size` is told in. + size: (f64, f64), + /// The same rectangle, in the physical pixels `set_position` is told in. + physical: PinArea, + scale: f64, +} + +fn pin_screen(window: &tauri::WebviewWindow) -> Option { + let monitor = window + .current_monitor() + .ok() + .flatten() + .or_else(|| window.primary_monitor().ok().flatten())?; + let scale = monitor.scale_factor().max(f64::MIN_POSITIVE); + let physical = PinArea::of(&monitor); + Some(PinScreen { + size: physical.logical_size(scale), + physical, + scale, + }) +} + +/// Where to put an enlarged pin so it stays centred on the window it replaces. All +/// three arguments are physical: growing from the centre is what makes the button +/// read as zooming the picture rather than moving a window, and clamping to the work +/// area is what stops a pin parked against a screen edge from growing away off it. +fn pin_placement(size: (f64, f64), scale: f64, centre: (f64, f64), area: PinArea) -> (i32, i32) { + let width = size.0 * scale; + let height = size.1 * scale; + let edge = |start: f64, length: f64, start_of_area: f64, span: f64| { + // An oversized window sits on the near edge instead of hanging off the far one. + if length >= span { + start_of_area + } else { + start.clamp(start_of_area, start_of_area + span - length) + } + }; + ( + edge(centre.0 - width / 2.0, width, area.left, area.width).round() as i32, + edge(centre.1 - height / 2.0, height, area.top, area.height).round() as i32, + ) +} + +/// The middle of the window as it stands, in physical pixels, so that changing its +/// size can hold the picture in place instead of sliding it down and right. +fn pin_centre(window: &tauri::WebviewWindow) -> Option<(f64, f64)> { + let position = window.outer_position().ok()?; + let size = window.outer_size().ok()?; + Some(( + f64::from(position.x) + f64::from(size.width) / 2.0, + f64::from(position.y) + f64::from(size.height) / 2.0, + )) +} + +/// Enlarge the pin until it fills the screen, or put it back the size it arrived at. +/// One button for both directions, because an enlarged pin has to be shrunk again to +/// be usable as a reference, and a second control would spend hover space on the less +/// common half of the gesture. Returns whether the pin is now enlarged, so the page +/// can label the button the way the window looks. +#[tauri::command] +pub fn zoom_pin(app: AppHandle) -> Result { + let window = app + .get_webview_window(PIN_LABEL) + .ok_or_else(|| "Pin window is unavailable.".to_string())?; + let state = app.state::(); + let preview = state + .pinned_image + .lock() + .map_err(|error| error.to_string())? + .clone() + .ok_or_else(|| "Nothing is pinned.".to_string())?; + let enlarged = !PIN_ENLARGED.load(Ordering::Relaxed); + let screen = + pin_screen(&window).ok_or_else(|| "No display was found for this pin.".to_string())?; + let centre = pin_centre(&window); + let size = pin_window_size( + (preview.width, preview.height), + enlarged.then_some(screen.size), + enlarged, + ); + window + .set_size(tauri::LogicalSize::new(size.0, size.1)) + .map_err(|error| error.to_string())?; + if let Some(centre) = centre { + let (x, y) = pin_placement(size, screen.scale, centre, screen.physical); + window + .set_position(tauri::PhysicalPosition::new(x, y)) + .map_err(|error| error.to_string())?; + } + PIN_ENLARGED.store(enlarged, Ordering::Relaxed); + Ok(enlarged) +} + #[tauri::command] pub async fn pin_image(app: AppHandle, path: String) -> Result<(), String> { let source = Path::new(&path).to_path_buf(); @@ -158,30 +323,35 @@ pub async fn pin_image(app: AppHandle, path: String) -> Result<(), String> { .await .map_err(|error| error.to_string())??; preview.id = PIN_SEQUENCE.fetch_add(1, Ordering::Relaxed) + 1; - let max_edge = 520.0_f64; - let scale = (max_edge / preview.width.max(preview.height) as f64).min(1.0); - let window_width = (preview.width as f64 * scale).max(160.0); - let window_height = (preview.height as f64 * scale).max(100.0); + // A fresh pin always opens as the small reference, whatever the last one was + // showing, so an enlarged pin being replaced does not come back huge. + PIN_ENLARGED.store(false, Ordering::Relaxed); let window = app .get_webview_window(PIN_LABEL) .ok_or_else(|| "Pin window is unavailable.".to_string())?; + // The small size is bounded by the picture, not the screen, so it needs no monitor. + let (window_width, window_height) = + pin_window_size((preview.width, preview.height), None, false); window .set_size(tauri::LogicalSize::new(window_width, window_height)) .map_err(|error| error.to_string())?; - if let Some((cursor, monitor_scale)) = app.cursor_position().ok().and_then(|cursor| { + if let Some((cursor, monitor_scale, work_area)) = + app.cursor_position().ok().and_then(|cursor| { + window + .monitor_from_point(cursor.x, cursor.y) + .ok() + .flatten() + .map(|monitor| (cursor, monitor.scale_factor(), PinArea::of(&monitor))) + }) + { + let (x, y) = pin_placement( + (window_width, window_height), + monitor_scale, + (cursor.x, cursor.y), + work_area, + ); window - .monitor_from_point(cursor.x, cursor.y) - .ok() - .flatten() - .map(|monitor| (cursor, monitor.scale_factor())) - }) { - let physical_width = window_width * monitor_scale; - let physical_height = window_height * monitor_scale; - window - .set_position(tauri::PhysicalPosition::new( - (cursor.x - physical_width / 2.0).round() as i32, - (cursor.y - physical_height / 2.0).round() as i32, - )) + .set_position(tauri::PhysicalPosition::new(x, y)) .map_err(|error| error.to_string())?; } let state = app.state::(); @@ -242,9 +412,88 @@ pub async fn close_pin(app: AppHandle) -> Result<(), String> { #[cfg(test)] mod tests { - use super::{flatten_for_pin, is_current_pin}; + use super::{flatten_for_pin, is_current_pin, pin_placement, pin_window_size, PinArea}; use image::{DynamicImage, Rgba, RgbaImage}; + /// The screen the tests place pins on: a 1512x982 laptop with a 2x backing + /// scale and a 37 px menu bar already taken out of the usable height. + fn retina() -> (PinArea, f64) { + ( + PinArea { + left: 0.0, + top: 37.0, + width: 3024.0, + height: 1890.0, + }, + 2.0, + ) + } + + #[test] + fn a_fresh_pin_never_exceeds_its_own_picture_or_520_px() { + // The reference size is a ceiling, not a stretch: a small screenshot pinned + // at 320 px must stay 320 px rather than arrive blown up and blurry. + let small = pin_window_size((320, 200), Some((1512.0, 945.0)), false); + assert_eq!(small, (320.0, 200.0)); + let large = pin_window_size((2400, 1200), Some((1512.0, 945.0)), false); + assert_eq!(large, (520.0, 260.0)); + // And it is the same answer with no monitor at all, which is what a hidden + // pin window on a headless or mid-sleep display has to fall back to. + assert_eq!(pin_window_size((2400, 1200), None, false), large); + } + + #[test] + fn enlarging_fills_the_screen_but_stays_inside_it() { + let (area, scale) = retina(); + let logical = area.logical_size(scale); + let size = pin_window_size((1040, 520), Some(logical), true); + assert!( + size.0 <= logical.0 && size.1 <= logical.1, + "{size:?} out of {logical:?}" + ); + // 90% of the usable width is what binds for a 2:1 screenshot, and the point + // of the button is that the picture really does grow past its preview. + assert!(size.0 > logical.0 * 0.85, "{size:?} did not grow"); + assert!((size.0 / size.1 - 2.0).abs() < 0.01, "aspect ratio lost"); + } + + #[test] + fn a_small_picture_is_not_blown_up_to_the_ceiling() { + // The preview is capped at 1040 px, so an 80 px icon enlarged threefold is + // already as much softness as this button should sell. Without the cap a + // pinned emoji would fill the display and dissolve. + let (area, scale) = retina(); + let size = pin_window_size((80, 80), Some(area.logical_size(scale)), true); + assert_eq!(size, (240.0, 240.0)); + } + + #[test] + fn an_enlarged_pin_grows_from_its_centre() { + let (area, scale) = retina(); + let centre = (800.0, 600.0); + let placed = pin_placement((600.0, 400.0), scale, centre, area); + // Centre is preserved in physical pixels: 800 - (600 x 2)/2, 600 - (400 x 2)/2. + assert_eq!(placed, (200, 200)); + } + + #[test] + fn a_pin_against_a_screen_edge_grows_inward_not_off_screen() { + let (area, scale) = retina(); + // Pinned hard against the top-left: enlarging must pull it back inside the + // work area instead of pushing half the picture under the menu bar. + let placed = pin_placement((1000.0, 800.0), scale, (100.0, 120.0), area); + assert_eq!(placed, (0, area.top as i32)); + // And the same at the far corner, where the clamp is against the right edge. + let far = pin_placement((1000.0, 800.0), scale, (2950.0, 1900.0), area); + assert_eq!( + far, + ( + (area.width - 2000.0) as i32, + (area.top + area.height - 1600.0) as i32 + ) + ); + } + #[test] fn only_the_newest_pin_can_reveal_the_window() { assert!(is_current_pin(Some(4), Some(4))); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index fe7b5eb..875b8fa 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -467,6 +467,7 @@ pub fn run() { editor::get_pinned_image, editor::pin_ready, editor::close_pin, + editor::zoom_pin, drag_bridge::get_radial_context, drag_bridge::hide_radial, drag_bridge::stand_down_radial, diff --git a/src/components/PinnedImage.tsx b/src/components/PinnedImage.tsx index b16d620..49d10e3 100644 --- a/src/components/PinnedImage.tsx +++ b/src/components/PinnedImage.tsx @@ -1,7 +1,7 @@ import { isTauri } from "@tauri-apps/api/core"; import { listen } from "@tauri-apps/api/event"; import { writeImage } from "@tauri-apps/plugin-clipboard-manager"; -import { Copy, X } from "lucide-react"; +import { Copy, Maximize2, Minimize2, X } from "lucide-react"; import { useEffect, useRef, useState } from "react"; import { useI18n } from "../i18n"; import { api } from "../lib/api"; @@ -22,6 +22,10 @@ export function PinnedImage() { ); const [src, setSrc] = useState(null); const [error, setError] = useState(null); + // Whether the window is showing the enlarged size. Rust owns the real answer and + // the button only asks it to flip, so this exists to label the button the way the + // window looks rather than to remember a size the page cannot measure. + const [enlarged, setEnlarged] = useState(false); const latestId = useRef(0); const renderedId = useRef(0); @@ -41,6 +45,8 @@ export function PinnedImage() { if (preview.id === renderedId.current) return; latestId.current = preview.id; setPath(preview.path); + // A new pin always opens small, whatever the last one was left at. + setEnlarged(false); const image = new Image(); image.onload = () => { if (disposed) return; @@ -101,6 +107,16 @@ export function PinnedImage() { await writeImage(path); } + async function zoom() { + try { + setEnlarged(await api.zoomPin()); + } catch { + // The window stayed the size it was, so the label stays true and the press is + // simply repeated. A pin that cannot be resized has nothing the user is waiting + // to read, which is not worth covering the picture with an error card. + } + } + if (error) { return
{error}
; } @@ -125,6 +141,14 @@ export function PinnedImage() { )}
+ diff --git a/src/i18n.ts b/src/i18n.ts index 5ca9624..d4716d6 100644 --- a/src/i18n.ts +++ b/src/i18n.ts @@ -69,6 +69,8 @@ const messages: Record> = { copy: "Copy", pin: "Pin", pinLoadFailed: "The pinned image could not be displayed.", + enlargePin: "Enlarge", + restorePin: "Restore size", copyText: "Copy text", saveAs: "Save As…", open: "Open", @@ -344,6 +346,8 @@ const messages: Record> = { copy: "复制", pin: "钉在屏幕上", pinLoadFailed: "无法显示钉住的图片。", + enlargePin: "放大", + restorePin: "恢复原大小", copyText: "复制文字", saveAs: "另存为…", open: "打开", diff --git a/src/lib/api.ts b/src/lib/api.ts index f950558..53af4e7 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -117,6 +117,7 @@ export const api = { ), pinReady: (id: number | null) => invoke("pin_ready", { id }), closePin: () => invoke("close_pin"), + zoomPin: () => invoke("zoom_pin"), getRadialContext: () => invoke("get_radial_context"), hideRadial: () => invoke("hide_radial"), showFilesInRadial: (files: string[], mode?: "actions" | "formats" | "tools") =>