mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Read Actual Size display dimensions from validated monitor EDID
This commit is contained in:
1 parent
ff8d83aed9
commit
7a022d34bd
5 files changed
+152
-11
No files matched your search
Generated
+2
@@ -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]]
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -59,7 +59,7 @@ pub(super) fn physical_ppi(pixels: f64, millimeters: f64) -> Option<f64> {
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn display_ppi(ctx: &egui::Context) -> Option<f64> {
|
||||
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<f64> {
|
||||
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<f64> {
|
||||
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<f64> {
|
||||
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<winsafe::RegistryValue, winsafe::co::ERROR> {
|
||||
// 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<String> {
|
||||
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<f64> {
|
||||
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<f64> {
|
||||
use core_graphics::display::CGDisplay;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user