mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge pull request #18807
Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com>
This commit is contained in:
commit
ea1ee03841
9 files changed
+448
-3
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]]
|
||||
|
||||
@@ -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", "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",
|
||||
|
||||
@@ -13,6 +13,7 @@ use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
|
||||
mod actual_size;
|
||||
mod arrange;
|
||||
pub(crate) mod dialogs;
|
||||
mod dispatch;
|
||||
@@ -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,253 @@
|
||||
//! 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::{HDC, 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 mut best = (0.0, None);
|
||||
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 {
|
||||
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
|
||||
})
|
||||
.ok()?;
|
||||
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};
|
||||
|
||||
// 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()?;
|
||||
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 = 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;
|
||||
}
|
||||
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_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;
|
||||
}
|
||||
// EDID detailed timing descriptors carry millimetres, with the high bits shared at byte 14.
|
||||
for timing in base.get(54..126)?.as_chunks::<18>().0.iter() {
|
||||
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), f64::from(height)]);
|
||||
}
|
||||
}
|
||||
let width = *base.get(21)?;
|
||||
let height = *base.get(22)?;
|
||||
(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<f64> {
|
||||
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<u64>, millimeters: f64) -> Option<f64> {
|
||||
physical_ppi(width? as f64, millimeters)
|
||||
}
|
||||
|
||||
#[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, backing_mode_ppi(display.display_mode().map(|mode| mode.pixel_width()), 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,166 @@
|
||||
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;
|
||||
|
||||
#[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);
|
||||
}
|
||||
}
|
||||
|
||||
#[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_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_size(&edid[..length]), None);
|
||||
}
|
||||
edid[54] = 0;
|
||||
edid[127] = edid[127].wrapping_add(1);
|
||||
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_size(&edid), None, "an aspect ratio has no physical width");
|
||||
edid[1] = 0;
|
||||
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]
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -78,7 +78,13 @@ pub fn handles(id: &str) -> bool {
|
||||
|| is_options_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"
|
||||
)
|
||||
}
|
||||
|
||||
@@ -98,7 +104,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())
|
||||
@@ -274,6 +280,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