From ff8d83aed937ff1fd0d260ca10a79049e84b1348 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Wed, 2 Dec 2026 03:57:30 +0800 Subject: [PATCH 1/4] Add Actual Size view using physical display resolution --- crates/engine-core/src/shell_commands.rs | 1 + crates/ui-egui/Cargo.toml | 9 +- crates/ui-egui/src/menu_catalog.rs | 1 + crates/ui-egui/src/menus/invoke.rs | 1 + crates/ui-egui/src/menus/view_cmds.rs | 5 + .../src/menus/view_cmds/actual_size.rs | 146 ++++++++++++++++++ .../src/menus/view_cmds/actual_size_tests.rs | 77 +++++++++ .../ui-egui/src/menus/view_cmds/dispatch.rs | 13 +- 8 files changed, 250 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/menus/view_cmds/actual_size.rs create mode 100644 crates/ui-egui/src/menus/view_cmds/actual_size_tests.rs diff --git a/crates/engine-core/src/shell_commands.rs b/crates/engine-core/src/shell_commands.rs index 718454fba3..08dc7b21df 100644 --- a/crates/engine-core/src/shell_commands.rs +++ b/crates/engine-core/src/shell_commands.rs @@ -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+.")), diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 647e7decb9..ea1b797f30 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -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"] } diff --git a/crates/ui-egui/src/menu_catalog.rs b/crates/ui-egui/src/menu_catalog.rs index 479e8e0368..731634301e 100644 --- a/crates/ui-egui/src/menu_catalog.rs +++ b/crates/ui-egui/src/menu_catalog.rs @@ -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"), diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 8515d08a01..5d2165aff6 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -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", diff --git a/crates/ui-egui/src/menus/view_cmds.rs b/crates/ui-egui/src/menus/view_cmds.rs index 7aed10a946..053535a089 100644 --- a/crates/ui-egui/src/menus/view_cmds.rs +++ b/crates/ui-egui/src/menus/view_cmds.rs @@ -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; diff --git a/crates/ui-egui/src/menus/view_cmds/actual_size.rs b/crates/ui-egui/src/menus/view_cmds/actual_size.rs new file mode 100644 index 0000000000..6da565197d --- /dev/null +++ b/crates/ui-egui/src/menus/view_cmds/actual_size.rs @@ -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 { + let physical_ppi = display_ppi(ctx); + apply(app, physical_ppi, params) +} + +pub(super) fn apply(app: &mut PhotocraftApp, physical_ppi: Option, params: &Value) -> Result { + 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 { + 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 { + 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 { + 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 { + 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 { + None +} diff --git a/crates/ui-egui/src/menus/view_cmds/actual_size_tests.rs b/crates/ui-egui/src/menus/view_cmds/actual_size_tests.rs new file mode 100644 index 0000000000..3c68653acf --- /dev/null +++ b/crates/ui-egui/src/menus/view_cmds/actual_size_tests.rs @@ -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); + } +} diff --git a/crates/ui-egui/src/menus/view_cmds/dispatch.rs b/crates/ui-egui/src/menus/view_cmds/dispatch.rs index 62a94a1277..b8d19a2877 100644 --- a/crates/ui-egui/src/menus/view_cmds/dispatch.rs +++ b/crates/ui-egui/src/menus/view_cmds/dispatch.rs @@ -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> { + 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); } From 7a022d34bd7d67196478be7699e317a7bc865366 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Wed, 2 Dec 2026 04:48:47 +0800 Subject: [PATCH 2/4] Read Actual Size display dimensions from validated monitor EDID --- Cargo.lock | 2 + crates/ui-egui/Cargo.toml | 2 +- crates/ui-egui/src/menus/view_cmds.rs | 2 +- .../src/menus/view_cmds/actual_size.rs | 97 +++++++++++++++++-- .../src/menus/view_cmds/actual_size_tests.rs | 60 +++++++++++- 5 files changed, 152 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 980c2438d5..3f47ef1ed5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7103,6 +7103,7 @@ version = "0.23.1" dependencies = [ "base64 0.23.1", "chrono", + "core-graphics", "craft", "craft-file-formats", "craft-i18n", @@ -7141,6 +7142,7 @@ dependencies = [ "toml", "web-time", "winsafe", + "x11rb", ] [[package]] diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index ea1b797f30..68e4fb0815 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -69,7 +69,7 @@ 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", "gdi", "user"] } +winsafe = { version = "=0.0.29", default-features = false, features = ["kernel", "dxgi", "advapi", "user"] } # Safe physical display dimensions for View > Actual Size. Both are already in the lockfile. [target.'cfg(target_os = "macos")'.dependencies] diff --git a/crates/ui-egui/src/menus/view_cmds.rs b/crates/ui-egui/src/menus/view_cmds.rs index 053535a089..c166082763 100644 --- a/crates/ui-egui/src/menus/view_cmds.rs +++ b/crates/ui-egui/src/menus/view_cmds.rs @@ -13,8 +13,8 @@ use serde_json::{Map, Value, json}; use crate::PhotocraftApp; -mod arrange; mod actual_size; +mod arrange; pub(crate) mod dialogs; mod dispatch; mod options; diff --git a/crates/ui-egui/src/menus/view_cmds/actual_size.rs b/crates/ui-egui/src/menus/view_cmds/actual_size.rs index 6da565197d..976202e48c 100644 --- a/crates/ui-egui/src/menus/view_cmds/actual_size.rs +++ b/crates/ui-egui/src/menus/view_cmds/actual_size.rs @@ -59,7 +59,7 @@ pub(super) fn physical_ppi(pixels: f64, millimeters: f64) -> Option { #[cfg(target_os = "windows")] fn display_ppi(ctx: &egui::Context) -> Option { - use winsafe::{HWND, prelude::*}; + use winsafe::{HDC, prelude::*}; let rect = ctx.input(|input| input.viewport().outer_rect)?; let scale = f64::from(ctx.pixels_per_point()); @@ -67,18 +67,19 @@ fn display_ppi(ctx: &egui::Context) -> Option { 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| { + HDC::NULL + .EnumDisplayMonitors(None, |monitor, _, 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))), - ); + let ppi = monitor + .GetMonitorInfo() + .ok() + .and_then(|info| windows_monitor_width(&info.szDevice())) + .and_then(|millimeters| physical_ppi(f64::from(rect.right) - f64::from(rect.left), millimeters)); + best = (area, ppi); } true }) @@ -86,6 +87,86 @@ fn display_ppi(ctx: &egui::Context) -> Option { best.1 } +/// GDI's HORZSIZE can be synthesized from 96 DPI on WDDM. Read the monitor's EDID instead. +#[cfg(target_os = "windows")] +fn windows_monitor_width(device: &str) -> Option { + use winsafe::{HKEY, RegistryValue, co}; + + let mut result = None; + for monitor in winsafe::EnumDisplayDevices(Some(device), Some(co::EDD::GET_DEVICE_INTERFACE_NAME)).take(64) { + let monitor = monitor.ok()?; + let path = monitor_registry_path(&monitor.DeviceID())?; + let key = HKEY::LOCAL_MACHINE.RegOpenKeyEx(Some(&path), co::REG_OPTION::default(), co::KEY::READ).ok()?; + let override_key = key.RegOpenKeyEx(Some("EDID_OVERRIDE"), co::REG_OPTION::default(), co::KEY::READ).ok(); + let value = match override_key.as_ref().map(|override_key| windows_edid_value(override_key, "0")) { + Some(Ok(value)) => value, + Some(Err(error)) if error != co::ERROR::FILE_NOT_FOUND => return None, + _ => windows_edid_value(&key, "EDID").ok()?, + }; + let RegistryValue::Binary(edid) = value else { return None }; + let width = edid_width(&edid)?; + // Mirrored outputs must agree on physical size before one scale can describe both. + if result.is_some_and(|previous: f64| (previous - width).abs() > 0.5) { + return None; + } + result = Some(width); + } + result +} + +#[cfg(target_os = "windows")] +fn windows_edid_value(key: &winsafe::HKEY, value: &str) -> Result { + // Registry EDIDs are small. Bound the safe binding's allocation before asking for the value. + let mut maximum = 0; + key.RegQueryInfoKey(None, None, None, None, None, None, Some(&mut maximum), None, None)?; + if maximum > 32768 { + return Err(winsafe::co::ERROR::INVALID_DATA); + } + key.RegQueryValueEx(Some(value)) +} + +#[cfg(any(test, target_os = "windows"))] +pub(super) fn monitor_registry_path(interface: &str) -> Option { + let mut parts = interface.strip_prefix(r"\\?\")?.split('#'); + if !parts.next()?.eq_ignore_ascii_case("DISPLAY") { + return None; + } + let model = parts.next()?; + let instance = parts.next()?; + let class = parts.next()?; + if parts.next().is_some() || !class.eq_ignore_ascii_case("{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}") { + return None; + } + let safe_component = + |value: &str| !value.is_empty() && value.len() <= 256 && value.bytes().all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'&' | b'_' | b'-')); + if !safe_component(model) || !safe_component(instance) { + return None; + } + Some(format!(r"SYSTEM\CurrentControlSet\Enum\DISPLAY\{model}\{instance}\Device Parameters")) +} + +#[cfg(any(test, target_os = "windows"))] +pub(super) fn edid_width(edid: &[u8]) -> Option { + let base = edid.get(..128)?; + if base.get(..8)? != [0, 255, 255, 255, 255, 255, 255, 0] || base.iter().fold(0u8, |sum, value| sum.wrapping_add(*value)) != 0 { + return None; + } + // EDID detailed timing descriptors carry millimetres, with the high bits shared at byte 14. + for timing in base.get(54..126)?.chunks_exact(18) { + if timing.get(..2)? == [0, 0] { + continue; + } + let width = u16::from(*timing.get(12)?) | (u16::from(*timing.get(14)? & 0xf0) << 4); + let height = u16::from(*timing.get(13)?) | (u16::from(*timing.get(14)? & 0x0f) << 8); + if width > 0 && height > 0 { + return Some(f64::from(width)); + } + } + let width = *base.get(21)?; + let height = *base.get(22)?; + (width > 0 && height > 0).then_some(f64::from(width) * 10.0) +} + #[cfg(target_os = "macos")] fn display_ppi(ctx: &egui::Context) -> Option { use core_graphics::display::CGDisplay; diff --git a/crates/ui-egui/src/menus/view_cmds/actual_size_tests.rs b/crates/ui-egui/src/menus/view_cmds/actual_size_tests.rs index 3c68653acf..e874c7bcac 100644 --- a/crates/ui-egui/src/menus/view_cmds/actual_size_tests.rs +++ b/crates/ui-egui/src/menus/view_cmds/actual_size_tests.rs @@ -1,4 +1,4 @@ -use super::actual_size::{apply, physical_ppi}; +use super::actual_size::{apply, edid_width, monitor_registry_path, physical_ppi}; use crate::{PhotocraftApp, Services}; use photocraft_engine::Session; use serde_json::json; @@ -75,3 +75,61 @@ fn actual_size_rejects_bad_parameters_and_unusable_metrics() { assert_eq!(apply(&mut app, ppi, &json!({})).unwrap()["fallback"], true); } } + +#[test] +fn actual_size_remains_unsnapped_on_the_canvas_then_uses_the_next_zoom_rung() { + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 3000, "height": 2000})).unwrap(); + crate::canvas::testing::frame(&mut app); + app.ui.views[0].center = [1500.0, 1000.0]; + apply(&mut app, Some(95.8), &json!({})).unwrap(); + crate::canvas::testing::frame(&mut app); + assert!((app.ui.views[0].zoom - 95.0 / 72.0).abs() < 1e-6); + assert_eq!(app.ui.views[0].center, [1500.0, 1000.0]); + let ctx = app.ctx().clone(); + crate::menus::invoke(&mut app, &ctx, "view.zoomIn", json!({})).unwrap(); + crate::canvas::testing::frame(&mut app); + assert_eq!(app.ui.views[0].zoom, 2.0); +} + +#[test] +fn actual_size_reads_validated_edid_physical_dimensions() { + let mut edid = [0u8; 128]; + edid[..8].copy_from_slice(&[0, 255, 255, 255, 255, 255, 255, 0]); + edid[21] = 51; + edid[22] = 29; + edid[54] = 1; + edid[66] = 253; + edid[67] = 30; + edid[68] = 0x11; + edid[127] = 0u8.wrapping_sub(edid.iter().copied().fold(0u8, u8::wrapping_add)); + assert_eq!(edid_width(&edid), Some(509.0)); + assert_eq!(physical_ppi(1920.0, edid_width(&edid).unwrap()), Some(95.0)); + for length in 0..128 { + assert_eq!(edid_width(&edid[..length]), None); + } + edid[54] = 0; + edid[127] = edid[127].wrapping_add(1); + assert_eq!(edid_width(&edid), Some(510.0), "centimetres when detailed dimensions are absent"); + edid[21] = 0; + edid[127] = edid[127].wrapping_add(51); + assert_eq!(edid_width(&edid), None, "an aspect ratio has no physical width"); + edid[1] = 0; + assert_eq!(edid_width(&edid), None, "corrupt headers are unavailable"); +} + +#[test] +fn actual_size_maps_only_recognized_monitor_interfaces_to_edid_keys() { + assert_eq!( + monitor_registry_path(r"\\?\DISPLAY#MODEL01#5&0000&0&UID1#{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}"), + Some(r"SYSTEM\CurrentControlSet\Enum\DISPLAY\MODEL01\5&0000&0&UID1\Device Parameters".into()) + ); + for interface in [ + "", + r"\\?\DISPLAY#MODEL01", + r"\\?\OTHER#MODEL01#INSTANCE#{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}", + r"\\?\DISPLAY#..\MODEL01#INSTANCE#{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}", + ] { + assert_eq!(monitor_registry_path(interface), None); + } +} From 91855750a9bc12d2aed518cfad636ae731f918da Mon Sep 17 00:00:00 2001 From: Terra854 Date: Wed, 2 Dec 2026 05:32:01 +0800 Subject: [PATCH 3/4] fix(view): use array chunks for EDID timing descriptors --- crates/ui-egui/src/menus/view_cmds/actual_size.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/menus/view_cmds/actual_size.rs b/crates/ui-egui/src/menus/view_cmds/actual_size.rs index 976202e48c..1e863fb60d 100644 --- a/crates/ui-egui/src/menus/view_cmds/actual_size.rs +++ b/crates/ui-egui/src/menus/view_cmds/actual_size.rs @@ -152,7 +152,7 @@ pub(super) fn edid_width(edid: &[u8]) -> Option { return None; } // EDID detailed timing descriptors carry millimetres, with the high bits shared at byte 14. - for timing in base.get(54..126)?.chunks_exact(18) { + for timing in base.get(54..126)?.as_chunks::<18>().0.iter() { if timing.get(..2)? == [0, 0] { continue; } From 40ea294a22ca0b1faf56962c1c74beab0c4442e4 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Wed, 2 Dec 2026 07:11:51 +0800 Subject: [PATCH 4/4] fix(view): match actual size metrics to display axes and backing pixels --- .../src/menus/view_cmds/actual_size.rs | 36 ++++++++++++--- .../src/menus/view_cmds/actual_size_tests.rs | 45 ++++++++++++++++--- 2 files changed, 69 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/menus/view_cmds/actual_size.rs b/crates/ui-egui/src/menus/view_cmds/actual_size.rs index 1e863fb60d..191c16a003 100644 --- a/crates/ui-egui/src/menus/view_cmds/actual_size.rs +++ b/crates/ui-egui/src/menus/view_cmds/actual_size.rs @@ -92,6 +92,13 @@ fn display_ppi(ctx: &egui::Context) -> Option { fn windows_monitor_width(device: &str) -> Option { use winsafe::{HKEY, RegistryValue, co}; + // Without a current orientation, a rotated desktop width cannot be paired with an EDID axis safely. + let mut mode = winsafe::DEVMODE::default(); + if !winsafe::EnumDisplaySettingsEx(Some(device), winsafe::GmidxEnum::Enum(co::ENUM_SETTINGS::CURRENT), &mut mode, co::EDS::default()).ok()? + || !mode.dmFields.has(co::DM::DISPLAYORIENTATION) + { + return None; + } let mut result = None; for monitor in winsafe::EnumDisplayDevices(Some(device), Some(co::EDD::GET_DEVICE_INTERFACE_NAME)).take(64) { let monitor = monitor.ok()?; @@ -104,7 +111,7 @@ fn windows_monitor_width(device: &str) -> Option { _ => windows_edid_value(&key, "EDID").ok()?, }; let RegistryValue::Binary(edid) = value else { return None }; - let width = edid_width(&edid)?; + let width = oriented_width(edid_size(&edid)?, mode.dmDisplayOrientation().raw())?; // Mirrored outputs must agree on physical size before one scale can describe both. if result.is_some_and(|previous: f64| (previous - width).abs() > 0.5) { return None; @@ -146,7 +153,7 @@ pub(super) fn monitor_registry_path(interface: &str) -> Option { } #[cfg(any(test, target_os = "windows"))] -pub(super) fn edid_width(edid: &[u8]) -> Option { +pub(super) fn edid_size(edid: &[u8]) -> Option<[f64; 2]> { let base = edid.get(..128)?; if base.get(..8)? != [0, 255, 255, 255, 255, 255, 255, 0] || base.iter().fold(0u8, |sum, value| sum.wrapping_add(*value)) != 0 { return None; @@ -159,12 +166,31 @@ pub(super) fn edid_width(edid: &[u8]) -> Option { let width = u16::from(*timing.get(12)?) | (u16::from(*timing.get(14)? & 0xf0) << 4); let height = u16::from(*timing.get(13)?) | (u16::from(*timing.get(14)? & 0x0f) << 8); if width > 0 && height > 0 { - return Some(f64::from(width)); + return Some([f64::from(width), f64::from(height)]); } } let width = *base.get(21)?; let height = *base.get(22)?; - (width > 0 && height > 0).then_some(f64::from(width) * 10.0) + (width > 0 && height > 0).then_some([f64::from(width) * 10.0, f64::from(height) * 10.0]) +} + +/// EDID describes the unrotated panel; desktop horizontal pixels follow the current display orientation. +#[cfg(any(test, target_os = "windows"))] +pub(super) fn oriented_width(size: [f64; 2], quarter_turns: u32) -> Option { + if !size.iter().all(|value| value.is_finite() && *value > 0.0) { + return None; + } + match quarter_turns { + 0 | 2 => Some(size[0]), + 1 | 3 => Some(size[1]), + _ => None, + } +} + +/// Missing backing-mode metrics must fall back, rather than substitute a logical display width. +#[cfg(any(test, target_os = "macos"))] +pub(super) fn backing_mode_ppi(width: Option, millimeters: f64) -> Option { + physical_ppi(width? as f64, millimeters) } #[cfg(target_os = "macos")] @@ -182,7 +208,7 @@ fn display_ppi(ctx: &egui::Context) -> Option { 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 = (area, backing_mode_ppi(display.display_mode().map(|mode| mode.pixel_width()), display.screen_size().width)); } } best.1 diff --git a/crates/ui-egui/src/menus/view_cmds/actual_size_tests.rs b/crates/ui-egui/src/menus/view_cmds/actual_size_tests.rs index e874c7bcac..eff9979c72 100644 --- a/crates/ui-egui/src/menus/view_cmds/actual_size_tests.rs +++ b/crates/ui-egui/src/menus/view_cmds/actual_size_tests.rs @@ -1,4 +1,4 @@ -use super::actual_size::{apply, edid_width, monitor_registry_path, physical_ppi}; +use super::actual_size::{apply, backing_mode_ppi, edid_size, monitor_registry_path, oriented_width, physical_ppi}; use crate::{PhotocraftApp, Services}; use photocraft_engine::Session; use serde_json::json; @@ -103,19 +103,50 @@ fn actual_size_reads_validated_edid_physical_dimensions() { edid[67] = 30; edid[68] = 0x11; edid[127] = 0u8.wrapping_sub(edid.iter().copied().fold(0u8, u8::wrapping_add)); - assert_eq!(edid_width(&edid), Some(509.0)); - assert_eq!(physical_ppi(1920.0, edid_width(&edid).unwrap()), Some(95.0)); + assert_eq!(edid_size(&edid), Some([509.0, 286.0])); + assert_eq!(physical_ppi(1920.0, oriented_width(edid_size(&edid).unwrap(), 0).unwrap()), Some(95.0)); for length in 0..128 { - assert_eq!(edid_width(&edid[..length]), None); + assert_eq!(edid_size(&edid[..length]), None); } edid[54] = 0; edid[127] = edid[127].wrapping_add(1); - assert_eq!(edid_width(&edid), Some(510.0), "centimetres when detailed dimensions are absent"); + assert_eq!(edid_size(&edid), Some([510.0, 290.0]), "centimetres when detailed dimensions are absent"); edid[21] = 0; edid[127] = edid[127].wrapping_add(51); - assert_eq!(edid_width(&edid), None, "an aspect ratio has no physical width"); + assert_eq!(edid_size(&edid), None, "an aspect ratio has no physical width"); edid[1] = 0; - assert_eq!(edid_width(&edid), None, "corrupt headers are unavailable"); + assert_eq!(edid_size(&edid), None, "corrupt headers are unavailable"); +} + +#[test] +fn actual_size_matches_the_edid_axis_to_all_four_windows_orientations() { + let size = [600.0, 337.0]; + for (orientation, pixels, millimeters) in [(0, 1920.0, 600.0), (1, 1080.0, 337.0), (2, 1920.0, 600.0), (3, 1080.0, 337.0)] { + let width = oriented_width(size, orientation).unwrap(); + assert_eq!(width, millimeters); + assert_eq!(physical_ppi(pixels, width), Some(81.0)); + } + assert_eq!(oriented_width(size, 4), None); + for invalid in [[0.0, 337.0], [600.0, f64::NAN], [f64::INFINITY, 337.0]] { + assert_eq!(oriented_width(invalid, 1), None); + } +} + +#[test] +fn actual_size_uses_backing_mode_pixels_and_falls_back_without_a_usable_mode() { + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 640, "height": 480})).unwrap(); + let physical = backing_mode_ppi(Some(3024), 344.0); + assert_eq!(physical, Some(223.0), "backing width rather than a 1512-point logical mode"); + assert_eq!(physical_ppi(1512.0, 344.0), Some(111.0)); + assert_eq!(apply(&mut app, physical, &json!({})).unwrap()["fallback"], false); + for mode in [None, Some(0)] { + let missing = backing_mode_ppi(mode, 344.0); + assert_eq!(missing, None); + let fallback = apply(&mut app, missing, &json!({})).unwrap(); + assert_eq!(fallback["fallback"], true); + assert!(fallback["status"].as_str().unwrap().contains("Screen Resolution")); + } } #[test]