mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Add Actual Size view using physical display resolution
This commit is contained in:
1 parent
91bf9f75d2
commit
ff8d83aed9
8 files changed
+250
-3
No files matched your search
@@ -58,6 +58,7 @@ pub const SHELL_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[
|
||||
("view.zoomOut", "Zoom Out", &["View"], Some("Cmd+-")),
|
||||
("view.fitOnScreen", "Fit on Screen", &["View"], Some("Cmd+0")),
|
||||
("view.actualPixels", "100%", &["View"], Some("Cmd+1")),
|
||||
("view.actualSize", "Actual Size", &["View"], None),
|
||||
("view.rotateView", "Rotate View", &[], None),
|
||||
("view.rotateLeft", "Rotate View Left", &["View"], Some("Alt+Shift+,")),
|
||||
("view.rotateRight", "Rotate View Right", &["View"], Some("Alt+Shift+.")),
|
||||
|
||||
@@ -69,7 +69,14 @@ sys-locale = "=0.3.2"
|
||||
# symbol (`i18n::decimal_separator`, a registry read): the safe binding the desktop app already
|
||||
# uses, pinned to the same version.
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
winsafe = { version = "=0.0.29", default-features = false, features = ["kernel", "dxgi", "advapi"] }
|
||||
winsafe = { version = "=0.0.29", default-features = false, features = ["kernel", "dxgi", "advapi", "gdi", "user"] }
|
||||
|
||||
# Safe physical display dimensions for View > Actual Size. Both are already in the lockfile.
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
core-graphics = "=0.23.2"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
x11rb = { version = "=0.13.2", features = ["randr"] }
|
||||
|
||||
[dev-dependencies]
|
||||
photocraft-io = { workspace = true, features = ["testgen"] }
|
||||
|
||||
@@ -693,6 +693,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[
|
||||
(&["View"], "100%", Some("Cmd+1"), "view.actualPixels"),
|
||||
(&["View"], "200%", None, "view.twoHundredPercent"),
|
||||
(&["View"], "Print Size", None, "view.printSize"),
|
||||
(&["View"], "Actual Size", None, "view.actualSize"),
|
||||
(&["View"], "---", None, "---"),
|
||||
(&["View"], "Flip Horizontal", None, "view.flipHorizontal"),
|
||||
(&["View", "Screen Mode"], "Standard Screen Mode", None, "view.screenMode.standard"),
|
||||
|
||||
@@ -60,6 +60,7 @@ fn keeps_box_drag(id: &str) -> bool {
|
||||
"view.zoomOut",
|
||||
"view.fitOnScreen",
|
||||
"view.actualPixels",
|
||||
"view.actualSize",
|
||||
"view.rotateView",
|
||||
"view.resetView",
|
||||
"view.darkenInterface",
|
||||
|
||||
@@ -14,6 +14,7 @@ use serde_json::{Map, Value, json};
|
||||
use crate::PhotocraftApp;
|
||||
|
||||
mod arrange;
|
||||
mod actual_size;
|
||||
pub(crate) mod dialogs;
|
||||
mod dispatch;
|
||||
mod options;
|
||||
@@ -218,3 +219,7 @@ mod save_a_copy_name_tests;
|
||||
#[cfg(test)]
|
||||
#[path = "view_cmds/file_info_title_labels_tests.rs"]
|
||||
mod file_info_title_labels_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "view_cmds/actual_size_tests.rs"]
|
||||
mod actual_size_tests;
|
||||
@@ -0,0 +1,146 @@
|
||||
//! Physical-size viewing. Logical UI scaling is deliberately absent from the PPI calculation.
|
||||
|
||||
use craft::behavior::{canvas::ZoomScheme, kurbo::Size};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
|
||||
pub(super) fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, params: &Value) -> Result<Value, String> {
|
||||
let physical_ppi = display_ppi(ctx);
|
||||
apply(app, physical_ppi, params)
|
||||
}
|
||||
|
||||
pub(super) fn apply(app: &mut PhotocraftApp, physical_ppi: Option<f64>, params: &Value) -> Result<Value, String> {
|
||||
if !params.as_object().is_some_and(|object| object.is_empty()) {
|
||||
return Err("Actual Size takes an empty parameter object".into());
|
||||
}
|
||||
let index = app.session.active_index().ok_or("Actual Size needs an open document")?;
|
||||
let doc = &app.session.documents().get(index).ok_or("no document")?.doc;
|
||||
let document_ppi = f64::from(doc.resolution_dpi);
|
||||
if !document_ppi.is_finite() || document_ppi <= 0.0 {
|
||||
return Err("Actual Size needs a positive document resolution".into());
|
||||
}
|
||||
let physical_ppi = physical_ppi.filter(|ppi| ppi.is_finite() && *ppi >= 1.0).map(f64::floor);
|
||||
let fallback = physical_ppi.is_none();
|
||||
let preferred = app.session.prefs().units_and_rulers.screen_resolution;
|
||||
let screen_ppi = physical_ppi.unwrap_or(if preferred >= 1.0 { preferred.floor() } else { preferred });
|
||||
let zoom = screen_ppi / document_ppi;
|
||||
if !zoom.is_finite() || zoom <= 0.0 {
|
||||
return Err("Actual Size needs a positive screen resolution".into());
|
||||
}
|
||||
let size = Size::new(f64::from(doc.size.width), f64::from(doc.size.height));
|
||||
let zoom = ZoomScheme::PHOTOSHOP.clamp(zoom, size) as f32;
|
||||
app.sync_views();
|
||||
let animate = app.session.prefs().general.animated_zoom;
|
||||
let view = app.ui.views.get_mut(index).ok_or("no document view")?;
|
||||
view.request_zoom_animation(animate);
|
||||
view.clear_pending();
|
||||
view.zoom = zoom;
|
||||
let message = if fallback {
|
||||
tl!("Actual Size uses Screen Resolution because the display's physical size is unavailable").to_string()
|
||||
} else {
|
||||
tl!("Actual Size uses the display's physical resolution").to_string()
|
||||
};
|
||||
app.ui.status = message.clone();
|
||||
app.ui.status_error = false;
|
||||
crate::panels::actions::runner::journal_view(app, "view.actualSize", params.clone());
|
||||
Ok(json!({"zoom": zoom, "screenPpi": screen_ppi, "fallback": fallback, "status": message}))
|
||||
}
|
||||
|
||||
/// Invalid or absent device metrics must use the explicit Screen Resolution fallback.
|
||||
#[cfg(any(test, target_os = "windows", target_os = "macos", target_os = "linux"))]
|
||||
pub(super) fn physical_ppi(pixels: f64, millimeters: f64) -> Option<f64> {
|
||||
if !pixels.is_finite() || !millimeters.is_finite() || pixels <= 0.0 || millimeters <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let ppi = pixels * 25.4 / millimeters;
|
||||
(ppi.is_finite() && (1.0..=10000.0).contains(&ppi)).then_some(ppi.floor())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn display_ppi(ctx: &egui::Context) -> Option<f64> {
|
||||
use winsafe::{HWND, prelude::*};
|
||||
|
||||
let rect = ctx.input(|input| input.viewport().outer_rect)?;
|
||||
let scale = f64::from(ctx.pixels_per_point());
|
||||
let window = [f64::from(rect.left()) * scale, f64::from(rect.top()) * scale, f64::from(rect.right()) * scale, f64::from(rect.bottom()) * scale];
|
||||
if !window.iter().all(|value| value.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let desktop = HWND::NULL.GetDC().ok()?;
|
||||
let mut best = (0.0, None);
|
||||
desktop
|
||||
.EnumDisplayMonitors(None, |_, device, rect| {
|
||||
let width = (window[2].min(f64::from(rect.right)) - window[0].max(f64::from(rect.left))).max(0.0);
|
||||
let height = (window[3].min(f64::from(rect.bottom)) - window[1].max(f64::from(rect.top))).max(0.0);
|
||||
let area = width * height;
|
||||
if area > best.0 {
|
||||
best = (
|
||||
area,
|
||||
physical_ppi(f64::from(device.GetDeviceCaps(winsafe::co::GDC::HORZRES)), f64::from(device.GetDeviceCaps(winsafe::co::GDC::HORZSIZE))),
|
||||
);
|
||||
}
|
||||
true
|
||||
})
|
||||
.ok()?;
|
||||
best.1
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn display_ppi(ctx: &egui::Context) -> Option<f64> {
|
||||
use core_graphics::display::CGDisplay;
|
||||
|
||||
let window = ctx.input(|input| input.viewport().outer_rect)?;
|
||||
let native = ctx.native_pixels_per_point().filter(|scale| scale.is_finite() && *scale > 0.0)?;
|
||||
let factor = f64::from(ctx.pixels_per_point() / native);
|
||||
let mut best = (0.0, None);
|
||||
for id in CGDisplay::active_displays().ok()? {
|
||||
let display = CGDisplay::new(id);
|
||||
let bounds = display.bounds();
|
||||
let width = (f64::from(window.right()) * factor).min(bounds.origin.x + bounds.size.width) - (f64::from(window.left()) * factor).max(bounds.origin.x);
|
||||
let height = (f64::from(window.bottom()) * factor).min(bounds.origin.y + bounds.size.height) - (f64::from(window.top()) * factor).max(bounds.origin.y);
|
||||
let area = width.max(0.0) * height.max(0.0);
|
||||
if area > best.0 {
|
||||
best = (area, physical_ppi(display.pixels_wide() as f64, display.screen_size().width));
|
||||
}
|
||||
}
|
||||
best.1
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn display_ppi(ctx: &egui::Context) -> Option<f64> {
|
||||
use x11rb::{connection::Connection, protocol::randr::ConnectionExt};
|
||||
|
||||
// Xwayland's virtual outputs do not describe the native Wayland display's physical size.
|
||||
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
|
||||
return None;
|
||||
}
|
||||
let window = ctx.input(|input| input.viewport().outer_rect)?;
|
||||
let factor = f64::from(ctx.pixels_per_point());
|
||||
let (connection, screen) = x11rb::connect(None).ok()?;
|
||||
let root = connection.setup().roots.get(screen)?.root;
|
||||
let resources = connection.randr_get_screen_resources_current(root).ok()?.reply().ok()?;
|
||||
let mut best = (0.0, None);
|
||||
for output in resources.outputs {
|
||||
let output = connection.randr_get_output_info(output, resources.config_timestamp).ok()?.reply().ok()?;
|
||||
if output.crtc == 0 {
|
||||
continue;
|
||||
}
|
||||
let crtc = connection.randr_get_crtc_info(output.crtc, resources.config_timestamp).ok()?.reply().ok()?;
|
||||
let x = f64::from(crtc.x);
|
||||
let y = f64::from(crtc.y);
|
||||
let width = (f64::from(window.right()) * factor).min(x + f64::from(crtc.width)) - (f64::from(window.left()) * factor).max(x);
|
||||
let height = (f64::from(window.bottom()) * factor).min(y + f64::from(crtc.height)) - (f64::from(window.top()) * factor).max(y);
|
||||
let area = width.max(0.0) * height.max(0.0);
|
||||
if area > best.0 {
|
||||
let mode = resources.modes.iter().find(|mode| mode.id == crtc.mode)?;
|
||||
best = (area, physical_ppi(f64::from(mode.width), f64::from(output.mm_width)));
|
||||
}
|
||||
}
|
||||
best.1
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
|
||||
fn display_ppi(_ctx: &egui::Context) -> Option<f64> {
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
use super::actual_size::{apply, physical_ppi};
|
||||
use crate::{PhotocraftApp, Services};
|
||||
use photocraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn actual_size_uses_whole_physical_ppi_and_keeps_the_document() {
|
||||
let mut app = PhotocraftApp::new(Session::new(), Services::default());
|
||||
app.run("file.new", json!({"width": 3000, "height": 2000})).unwrap();
|
||||
app.sync_views();
|
||||
for (document_ppi, expected) in [(72.0, 95.0 / 72.0), (300.0, 95.0 / 300.0), (150.0, 95.0 / 150.0), (96.0, 95.0 / 96.0), (36.0, 95.0 / 36.0)] {
|
||||
app.run("image.imageSize", json!({"resolution": document_ppi, "resample": "none"})).unwrap();
|
||||
for screen_ppi in [72.0, 96.0] {
|
||||
app.run("prefs.set", json!({"path": "unitsAndRulers.screenResolution", "value": screen_ppi})).unwrap();
|
||||
app.ui.views[0].center = [126.75, 636.25];
|
||||
let before = app.session.active().unwrap().doc.clone();
|
||||
let history = app.session.active().unwrap().history.entries().len();
|
||||
let dirty = app.session.active().unwrap().is_dirty();
|
||||
let result = apply(&mut app, physical_ppi(1920.0, 509.0), &json!({})).unwrap();
|
||||
assert!((app.ui.views[0].zoom - expected).abs() < 1e-6);
|
||||
assert_eq!(app.ui.views[0].center, [126.75, 636.25]);
|
||||
assert_eq!(result["fallback"], false);
|
||||
assert_eq!(result["screenPpi"], 95.0);
|
||||
assert_eq!(app.session.active().unwrap().doc, before);
|
||||
assert_eq!(app.session.active().unwrap().history.entries().len(), history);
|
||||
assert_eq!(app.session.active().unwrap().is_dirty(), dirty);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actual_size_fallback_is_reported_by_menu_and_automation() {
|
||||
let mut app = PhotocraftApp::new(Session::new(), Services::default());
|
||||
let ctx = app.ctx().clone();
|
||||
assert!(!crate::menus::is_enabled(&app, "view.actualSize"));
|
||||
assert!(crate::menus::invoke(&mut app, &ctx, "view.actualSize", json!({})).is_err());
|
||||
app.run("file.new", json!({"width": 320, "height": 240})).unwrap();
|
||||
app.run("prefs.set", json!({"path": "unitsAndRulers.screenResolution", "value": 96.5})).unwrap();
|
||||
assert!(crate::menus::is_live("view.actualSize"));
|
||||
assert!(crate::menus::is_enabled(&app, "view.actualSize"));
|
||||
assert_eq!(super::checked(&app, "view.actualSize"), None);
|
||||
let result = crate::menus::invoke(&mut app, &ctx, "view.actualSize", json!({})).unwrap();
|
||||
assert_eq!(result["fallback"], true, "a headless context has no physical monitor");
|
||||
assert_eq!(result["screenPpi"], 96.0);
|
||||
assert!((app.ui.views[0].zoom - 96.0 / 72.0).abs() < 1e-6);
|
||||
assert_eq!(result["status"], app.ui.status);
|
||||
assert!(app.ui.status.contains("Screen Resolution"));
|
||||
let (request, _receiver) = crate::control::ControlRequest::new("engine.execute", json!({"command": "view.actualSize", "params": {}}));
|
||||
match crate::control::handle(&mut app, &ctx, &request) {
|
||||
crate::control::Reply::Done(reply) => {
|
||||
assert_eq!(reply["result"]["fallback"], true);
|
||||
assert_eq!(reply["result"]["status"], app.ui.status);
|
||||
}
|
||||
_ => panic!("Actual Size should return its fallback result immediately"),
|
||||
}
|
||||
let rows = crate::menus::menu_rows(&app);
|
||||
let positions: Vec<_> =
|
||||
["view.printSize", "view.actualSize", "view.flipHorizontal"].map(|id| rows.iter().position(|row| row.command.id == id).unwrap()).into();
|
||||
assert!(positions[0] < positions[1] && positions[1] < positions[2]);
|
||||
let registration = crate::menus::UI_COMMANDS.iter().find(|row| row.0 == "view.actualSize").unwrap();
|
||||
assert_eq!(registration.3, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actual_size_rejects_bad_parameters_and_unusable_metrics() {
|
||||
let mut app = PhotocraftApp::new(Session::new(), Services::default());
|
||||
app.run("file.new", json!({"width": 64, "height": 64})).unwrap();
|
||||
for params in [json!(null), json!([]), json!({"ppi": 95})] {
|
||||
assert!(apply(&mut app, Some(95.0), ¶ms).is_err());
|
||||
}
|
||||
for (pixels, mm) in [(0.0, 509.0), (1920.0, 0.0), (f64::NAN, 509.0), (1920.0, f64::INFINITY), (1920.0, 0.001)] {
|
||||
assert_eq!(physical_ppi(pixels, mm), None);
|
||||
}
|
||||
for ppi in [None, Some(f64::NAN), Some(-1.0)] {
|
||||
assert_eq!(apply(&mut app, ppi, &json!({})).unwrap()["fallback"], true);
|
||||
}
|
||||
}
|
||||
@@ -71,7 +71,13 @@ pub fn handles(id: &str) -> bool {
|
||||
|| is_context_task_bar(id)
|
||||
|| matches!(
|
||||
id,
|
||||
"view.extras" | "view.flipHorizontal" | "view.pixelAspectRatioCorrection" | "view.patternPreview" | "view.pixelArtPreview" | "view.rotateView"
|
||||
"view.extras"
|
||||
| "view.flipHorizontal"
|
||||
| "view.pixelAspectRatioCorrection"
|
||||
| "view.patternPreview"
|
||||
| "view.pixelArtPreview"
|
||||
| "view.rotateView"
|
||||
| "view.actualSize"
|
||||
)
|
||||
}
|
||||
|
||||
@@ -91,7 +97,7 @@ pub(super) fn is_enabled_with_engine(app: &PhotocraftApp, id: &str, engine_enabl
|
||||
// Standard again before the next pass (`leave_full_screen_without_document`).
|
||||
"view.screenMode.cycle" | "view.screenMode.cycleBack" => app.ui.text_edit.is_none() && doc,
|
||||
"view.screenMode.fullScreen" | "view.screenMode.fullScreenWithMenuBar" => doc,
|
||||
"view.rotateView" => doc,
|
||||
"view.rotateView" | "view.actualSize" => doc,
|
||||
i if i.starts_with("window.arrange.") => arrange_command(&i["window.arrange.".len()..]).is_some_and(|command| {
|
||||
let windows = &app.ui.document_windows;
|
||||
command.arrangement().enabled(app.session.documents().len(), windows.docked.len(), windows.floating.len())
|
||||
@@ -264,6 +270,9 @@ pub(super) fn no_params(p: &Value) -> bool {
|
||||
/// Run a View/Window/Type shell command, or front an engine command with its dialog. `None` when
|
||||
/// `id` isn't ours.
|
||||
pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option<Result<Value, String>> {
|
||||
if id == "view.actualSize" {
|
||||
return Some(super::actual_size::invoke(app, ctx, params));
|
||||
}
|
||||
if let Some(result) = crate::panel_docking::command(app, id, params) {
|
||||
return Some(result);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user