Display and edit layer aspect ratios beside sizing controls

This commit is contained in:
Dandaedre 2026-11-14 12:21:07 +01:00
parent 7cdf3a054f
commit 310caa15d3
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
8 changed files with 365 additions and 30 deletions

View File

@ -18,6 +18,7 @@ pub(super) struct FormatDraft {
input_size: [f64; 2],
size: [f64; 2],
layer_aspect: Aspect,
ratio_edit: ratio_ui::RatioEdit,
framing: Framing,
error: String,
closing: bool,
@ -31,6 +32,7 @@ impl FormatDraft {
self.size,
self.framing,
) != self.baseline
|| self.ratio_edit.dirty
}
fn apply_framing(&mut self, layout: &mut Layout, dragging: bool) -> Result<(), String> {
if dragging && self.crop_before.is_none() {
@ -46,7 +48,26 @@ impl FormatDraft {
self.baseline.4 = self.framing;
Ok(())
}
fn apply(&mut self, layout: &mut Layout, corner: PositionPoint) -> Result<(), String> {
fn commit_ratio(&mut self, locked: bool) -> Result<(), String> {
self.ratio_edit.commit()?;
if locked && let Some(ratio) = self.ratio_edit.target {
let size = [self.size[0], self.size[0] / ratio];
if let Err(error) = midra_layout::formats::validate_size(size) {
self.ratio_edit.dirty = true;
return Err(error);
}
self.size = size;
self.ratio_edit = Default::default();
}
Ok(())
}
fn apply(
&mut self,
layout: &mut Layout,
corner: PositionPoint,
locked: bool,
) -> Result<(), String> {
self.commit_ratio(locked)?;
let input = self.source.input()?;
if input
.iter()
@ -91,6 +112,7 @@ impl FormatDraft {
input_size: source.input().unwrap(),
size: [g.width, g.height],
layer_aspect: Aspect::Custom,
ratio_edit: Default::default(),
framing: layout.formats().mapping(i, g).unwrap().framing,
error: String::new(),
closing: false,
@ -143,7 +165,7 @@ fn nonnegative_number(text: &str) -> Option<f64> {
.filter(|value| value.is_finite() && *value >= 0.0)
}
fn dimensions(ui: &mut egui::Ui, size: &mut [f64; 2], prefix: &str) {
ui.horizontal(|ui| {
ui.horizontal_wrapped(|ui| {
ui.label(prefix);
ui.add(
egui::DragValue::new(&mut size[0])
@ -157,10 +179,13 @@ fn dimensions(ui: &mut egui::Ui, size: &mut [f64; 2], prefix: &str) {
.custom_formatter(|v, _| number(v))
.prefix("H "),
);
if size[0] > 0.0 && size[1] > 0.0 {
ui.label(format!("Ratio {}", ratio_ui::label(size[0] / size[1])));
}
});
}
fn resolution(ui: &mut egui::Ui, size: &mut [u32; 2], prefix: &str, ratio: Option<f64>) {
ui.horizontal(|ui| {
ui.horizontal_wrapped(|ui| {
ui.label(prefix);
if ui
.add(egui::DragValue::new(&mut size[0]).speed(1).prefix("W "))
@ -176,6 +201,12 @@ fn resolution(ui: &mut egui::Ui, size: &mut [u32; 2], prefix: &str, ratio: Optio
{
size[0] = (size[1] as f64 * r).round() as u32;
}
if size[0] > 0 && size[1] > 0 {
ui.label(format!(
"Ratio {}",
ratio_ui::label(size[0] as f64 / size[1] as f64)
));
}
});
}
fn presets(ui: &mut egui::Ui, size: &mut [u32; 2], aspect: &mut Aspect) {
@ -318,12 +349,23 @@ impl Editor {
ui.label("Resizing automatically adjusts the layer crop to fit the new dimensions.");
ui.horizontal(|ui| {
ui.label("Format");
if aspect_combo(ui,"layer-aspect",&mut d.layer_aspect) && let Some(r)=d.layer_aspect.ratio() { d.size[1]=d.size[0]/r; }
if aspect_combo(ui,"layer-aspect",&mut d.layer_aspect) && let Some(r)=d.layer_aspect.ratio() {
d.ratio_edit.text=ratio_ui::label(r);d.ratio_edit.target=Some(r);d.ratio_edit.dirty=false;
if let Err(error)=d.commit_ratio(self.keep_aspect_ratio) {d.error=error;}
}
});
let lock_changed=ui.checkbox(&mut self.keep_aspect_ratio,"Keep aspect ratio when resizing").changed();
let ratio_changed=d.ratio_edit.show(ui,d.size[0]/d.size[1]);
if ratio_changed {d.layer_aspect=Aspect::Custom;}
if ratio_changed || (lock_changed && self.keep_aspect_ratio) {
match d.commit_ratio(self.keep_aspect_ratio) {Ok(())=>d.error.clear(),Err(error)=>d.error=error}
}
if !self.keep_aspect_ratio && d.ratio_edit.target.is_some() {ui.small("Ratio ready; enable the lock to resize.");}
if lock_changed {self.settings.save(&self.application_settings(ui.ctx()));}
let old=d.size;
dimensions(ui,&mut d.size,"Visible pixels");
if self.keep_aspect_ratio {
let ratio=d.layer_aspect.ratio().unwrap_or(old[0]/old[1]);
let ratio=old[0]/old[1];
if d.size[0]!=old[0] { d.size[1]=d.size[0]/ratio; } else if d.size[1]!=old[1] { d.size[0]=d.size[1]*ratio; }
}
}
@ -341,7 +383,7 @@ impl Editor {
}
let pending = d.pending(&self.layout);
if apply_button(ui,"Apply source / input / layer formats", pending).clicked() {
match d.apply(&mut self.layout, self.corner) { Ok(())=>{self.sync();d=FormatDraft::new(&self.layout,i);},Err(e)=>d.error=e }
match d.apply(&mut self.layout, self.corner, self.keep_aspect_ratio) { Ok(())=>{self.sync();d=FormatDraft::new(&self.layout,i);},Err(e)=>d.error=e }
}
ui.small("Apply commits pending Source and Layer changes together. Switching tabs keeps your edits.");
}
@ -394,17 +436,19 @@ impl Editor {
}
if d.closing {
match pending_close(ctx, "formats-close", &d.error) {
Some(true) => match d.apply(&mut self.layout, self.corner) {
Ok(()) => {
self.sync();
return;
Some(true) => {
match d.apply(&mut self.layout, self.corner, self.keep_aspect_ratio) {
Ok(()) => {
self.sync();
return;
}
Err(e) => {
d.error = e;
d.closing = false;
open = true;
}
}
Err(e) => {
d.error = e;
d.closing = false;
open = true;
}
},
}
Some(false) => return,
None => {}
}
@ -551,6 +595,36 @@ mod tests {
frame(app, ctx, vec![]);
}
#[test]
fn draft_ratio_changes_only_apply_to_document_on_apply() {
let mut layout = Layout::default();
let before = layout.layers().clone();
let mut draft = FormatDraft::new(&layout, 1);
draft.ratio_edit.text = "4:3".into();
draft.ratio_edit.dirty = true;
draft.commit_ratio(false).unwrap();
assert_eq!(draft.size, [before[1].width, before[1].height]);
draft.commit_ratio(true).unwrap();
assert_eq!(draft.size, [before[1].width, before[1].width * 0.75]);
assert_eq!(layout.layers(), &before);
assert!(draft.pending(&layout));
draft
.apply(&mut layout, PositionPoint::Center, true)
.unwrap();
assert_eq!(layout.layers()[1].center(), before[1].center());
assert_eq!(layout.layers()[1].height, before[1].width * 0.75);
layout.undo();
assert_eq!(layout.layers(), &before);
draft.ratio_edit.text = "0:9".into();
draft.ratio_edit.dirty = true;
assert!(
draft
.apply(&mut layout, PositionPoint::Center, true)
.is_err()
);
assert_eq!(layout.layers(), &before);
}
#[test]
fn input_crop_controls_reject_negative_paste_and_keep_fractional_values() {
let ctx = egui::Context::default();

View File

@ -11,6 +11,8 @@ mod menu_ui;
mod preferences_ui;
#[path = "project_ui.rs"]
mod project_ui;
#[path = "ratio_ui.rs"]
mod ratio_ui;
#[path = "viewport_guides.rs"]
mod viewport_guides;
use format_ui::{FormatDraft, OutputDraft, PropertyTab};
@ -45,6 +47,8 @@ pub struct Editor {
align_target: AlignTarget,
layer_order: Vec<usize>,
keep_aspect_ratio: bool,
ratio_edit: ratio_ui::RatioEdit,
ratio_layer: Option<usize>,
resize_mode: ResizeMode,
grid_tool: Option<u32>,
pivot_tool: bool,
@ -250,6 +254,8 @@ impl Default for Editor {
align_target: AlignTarget::Selection,
layer_order: Vec::new(),
keep_aspect_ratio: true,
ratio_edit: Default::default(),
ratio_layer: None,
resize_mode: ResizeMode::Individual,
grid_tool: None,
pivot_tool: false,
@ -484,6 +490,11 @@ impl Editor {
self.pivot_drag = None;
self.pivot_selection = selection;
}
let ratio_layer = self.layout.selected().map(|i| self.layout.layer_info(i).id);
if self.ratio_layer != ratio_layer {
self.ratio_layer = ratio_layer;
self.ratio_edit = Default::default();
}
let order: Vec<_> = (0..self.layout.layers().len())
.map(|i| self.layout.layer_info(i).id)
.collect();
@ -903,7 +914,7 @@ impl Editor {
let (r, _) = ui.allocate_exact_size(
Vec2::new(
ui.available_width(),
1084.0 + (self.layout.layers().len() as f32 - 2.0) * 44.0,
1136.0 + (self.layout.layers().len() as f32 - 2.0) * 44.0,
),
egui::Sense::hover(),
);
@ -1070,10 +1081,10 @@ impl Editor {
12.0,
223.0,
&format!(
"{} × {} px / {:.1}:1",
"{} × {} px / {}",
number(g.width),
number(g.height),
g.width / g.height
ratio_ui::label(g.width / g.height)
),
13.0,
palette.text,
@ -1229,10 +1240,11 @@ impl Editor {
ui.scope_builder(
egui::UiBuilder::new().max_rect(Rect::from_min_size(
ink.point(0.0, 530.0),
Vec2::new(w, 24.0),
Vec2::new(w, 76.0),
)),
|ui| self.resize_ratio_option(ui),
);
let ink = Ink::new(ui, r.translate(Vec2::new(0.0, 160.0)));
let pending = self.fields_pending();
let apply = ui
.scope_builder(
@ -1261,7 +1273,7 @@ impl Editor {
.wrap(),
);
}
let ink = Ink::new(ui, r.translate(Vec2::new(0.0, 132.0)));
let ink = Ink::new(ui, r.translate(Vec2::new(0.0, 184.0)));
ink.line([0.0, 640.0], [w, 640.0], palette.line);
ink.text(
0.0,
@ -1401,8 +1413,36 @@ impl Editor {
ui.colored_label(palette.amber, &self.error);
}
}
fn apply_ratio_target(&mut self) -> Result<(), String> {
self.ratio_edit.commit()?;
let Some(ratio) = self.ratio_edit.target else {
return Ok(());
};
if !self.keep_aspect_ratio {
return Ok(());
}
if self.fields_pending() {
self.apply_fields();
if self.fields_pending() {
return Err(self.error.clone());
}
}
let Some(i) = self.layout.selected() else {
return Ok(());
};
let g = self.layout.layers()[i];
let output = self.layout.formats().output;
let [x, y] = self.corner.offsets_on(g, output);
let next = self
.corner
.geometry_on(x, y, g.width, g.width / ratio, output)?;
self.layout.apply(i, next)?;
self.ratio_edit = Default::default();
self.sync();
Ok(())
}
fn resize_ratio_option(&mut self, ui: &mut egui::Ui) {
if ui
let changed = ui
.checkbox(
&mut self.keep_aspect_ratio,
"Keep aspect ratio when resizing",
@ -1410,8 +1450,23 @@ impl Editor {
.on_hover_text(
"Applies to layer sizing. Crop zoom always keeps the source proportions.",
)
.changed()
.changed();
let edited = if let Some(i) = self.layout.selected() {
let g = self.layout.layers()[i];
let edited = self.ratio_edit.show(ui, g.width / g.height);
if !self.keep_aspect_ratio && self.ratio_edit.target.is_some() {
ui.small("Ratio ready; enable the lock to resize.");
}
edited
} else {
false
};
if (edited || (changed && self.keep_aspect_ratio))
&& let Err(error) = self.apply_ratio_target()
{
self.ratio_edit.error = error;
}
if changed {
let options = self.application_settings(ui.ctx());
self.settings.save(&options);
}
@ -2459,7 +2514,12 @@ impl Editor {
clipped.text(
rect.left_bottom() + Vec2::new(12.0, -20.0),
Align2::LEFT_BOTTOM,
format!("{} × {} px", number(g.width), number(g.height)),
format!(
"{} × {} px · {}",
number(g.width),
number(g.height),
ratio_ui::label(g.width / g.height)
),
FontId::proportional(12.0),
palette.text,
);
@ -3374,6 +3434,81 @@ mod tests {
);
frame(app, ctx, vec![mouse(pos, false)]);
}
#[test]
fn manual_ratio_keeps_width_and_position_reference_and_is_undoable() {
for point in [
PositionPoint::TopLeft,
PositionPoint::TopRight,
PositionPoint::BottomLeft,
PositionPoint::BottomRight,
PositionPoint::Center,
] {
let mut app = Editor {
corner: point,
..Default::default()
};
app.sync();
let before = app.layout.layers().clone();
let formats = app.layout.formats().clone();
let offsets = point.offsets_on(before[1], app.layout.formats().output);
app.ratio_edit.text = "4:3".into();
app.ratio_edit.dirty = true;
app.apply_ratio_target().unwrap();
let after = app.layout.layers()[1];
assert_eq!(after.width, before[1].width);
assert!((after.width / after.height - 4.0 / 3.0).abs() < 1e-9);
assert_eq!(
point.offsets_on(after, app.layout.formats().output),
offsets
);
assert_eq!(app.layout.layers()[0], before[0]);
app.layout.undo();
assert_eq!(app.layout.layers(), &before);
assert_eq!(app.layout.formats(), &formats);
}
}
#[test]
fn unlocked_ratio_waits_for_lock_and_invalid_input_preserves_geometry() {
let mut app = Editor {
keep_aspect_ratio: false,
..Default::default()
};
let before = app.layout.layers().clone();
app.ratio_edit.text = "1.85".into();
app.ratio_edit.dirty = true;
app.apply_ratio_target().unwrap();
assert_eq!(app.layout.layers(), &before);
assert_eq!(app.ratio_edit.target, Some(1.85));
app.keep_aspect_ratio = true;
app.apply_ratio_target().unwrap();
assert!((app.layout.layers()[1].width / app.layout.layers()[1].height - 1.85).abs() < 1e-9);
let resized = app.layout.layers().clone();
for text in ["0:3", "4:0", "-1", "NaN", "inf", "4:3:2", "1e-100", ""] {
app.ratio_edit.text = text.into();
app.ratio_edit.dirty = true;
assert!(app.apply_ratio_target().is_err(), "{text}");
assert_eq!(app.layout.layers(), &resized);
}
app.layout.select(Some(0));
app.sync();
assert!(!app.ratio_edit.dirty);
assert!(app.ratio_edit.target.is_none());
}
#[test]
fn ratio_edit_enter_commits_from_the_inspector() {
let ctx = egui::Context::default();
let mut app = Editor::default();
let before = app.layout.layers().clone();
click_text(&mut app, &ctx, "16:9");
app.ratio_edit.text = "4/3".into();
app.ratio_edit.dirty = true;
frame(&mut app, &ctx, vec![key(egui::Key::Enter)]);
assert!((app.layout.layers()[1].height - before[1].width * 0.75).abs() < 1e-8);
assert_eq!(app.layout.layers()[1].width, before[1].width);
}
#[test]
fn tool_icons_fit_above_the_canvas_with_captions_and_at_minimum_window_size() {
for size in [Vec2::new(1000.0, 720.0), Vec2::new(1440.0, 940.0)] {

View File

@ -132,10 +132,7 @@ impl Editor {
"Outline-only layers (this project)",
);
ui.checkbox(&mut self.show_toolbar_icon_names, "Show toolbar icon names");
ui.checkbox(
&mut self.keep_aspect_ratio,
"Keep aspect ratio when resizing",
);
self.resize_ratio_option(ui);
ui.checkbox(
&mut self.show_pattern,
"Show source-coordinate test pattern in viewport",

View File

@ -59,7 +59,7 @@ impl Editor {
}
Section::Editing => {
ui.heading("Editing");
ui.checkbox(&mut self.keep_aspect_ratio, "Keep aspect ratio when resizing");
self.resize_ratio_option(ui);
ui.label("Applies to layer handles and numeric width/height edits. Crop zoom always keeps the source proportions.");
ui.separator();
self.snapping_options(ui);

View File

@ -0,0 +1,111 @@
//! Editable session-only aspect ratios; geometry remains the saved source of truth.
use eframe::egui;
pub(super) fn label(ratio: f64) -> String {
for (w, h) in [(16, 9), (4, 3), (16, 10), (1, 1), (9, 16), (3, 4), (21, 9)] {
if (ratio - w as f64 / h as f64).abs() < 1e-8 {
return format!("{w}:{h}");
}
}
if !(0.0001..=1e6).contains(&ratio) {
return format!("{ratio:.6e}:1");
}
let value = format!("{ratio:.6}");
format!("{}:1", value.trim_end_matches('0').trim_end_matches('.'))
}
pub(super) fn parse(text: &str) -> Result<f64, String> {
let positive = |s: &str| {
s.trim()
.parse::<f64>()
.ok()
.filter(|v| v.is_finite() && *v > 0.0)
};
let value = if let Some((w, h)) = text.split_once([':', '/']) {
positive(w).zip(positive(h)).map(|(w, h)| w / h)
} else {
positive(text)
};
value
.filter(|v| v.is_finite() && *v > 0.0)
.ok_or_else(|| "Enter a positive ratio, e.g. 16:9, 4/3 or 1.85.".into())
}
#[derive(Default)]
pub(super) struct RatioEdit {
pub text: String,
pub dirty: bool,
pub target: Option<f64>,
pub error: String,
}
impl RatioEdit {
pub fn commit(&mut self) -> Result<Option<f64>, String> {
if !self.dirty {
return Ok(None);
}
match parse(&self.text) {
Ok(ratio) => {
self.target = Some(ratio);
self.dirty = false;
self.error.clear();
Ok(Some(ratio))
}
Err(error) => {
self.error = error.clone();
Err(error)
}
}
}
pub fn show(&mut self, ui: &mut egui::Ui, current: f64) -> bool {
if !self.dirty && self.target.is_none() {
self.text = label(current);
}
let mut committed = false;
ui.horizontal(|ui| {
ui.label(format!("Ratio {}", label(current)));
let response = ui.add(egui::TextEdit::singleline(&mut self.text).desired_width(90.0))
.on_hover_text("Enter width:height, width/height or a decimal. With aspect lock on, keeps width and adjusts height.");
self.dirty |= response.changed();
if response.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Escape)) {
*self = Self::default();
} else if response.lost_focus() && self.dirty {
committed = self.commit().is_ok();
}
});
if !self.error.is_empty() {
ui.colored_label(ui.visuals().error_fg_color, &self.error);
}
committed
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ratio_notation_and_labels() {
for (text, expected) in [
("16:9", 16.0 / 9.0),
("4 / 3", 4.0 / 3.0),
("1.85", 1.85),
(" 9 : 16 ", 9.0 / 16.0),
] {
assert_eq!(parse(text).unwrap(), expected);
}
for text in [
"0",
"-2:3",
"3:0",
"nan",
"inf:2",
"2/3/4",
"",
"1e308:1e-308",
] {
assert!(parse(text).is_err(), "{text}");
}
assert_eq!(label(16.0 / 9.0), "16:9");
assert_eq!(label(1.85), "1.85:1");
assert!(parse(&label(1e-9)).unwrap() > 0.0);
}
}

View File

@ -110,7 +110,7 @@ region. Off-screen x/y are allowed. Invalid source references, duplicate layer I
missing fields and non-finite values are rejected before replacing the document.
Projects larger than 96 MiB are rejected.
Save includes **applied values only**. Pending text/format/import drafts, open
Save includes **applied values only**. Pending text/format/import drafts, prepared aspect-ratio targets, open
dialogs, undo/redo history, crop-edit mode, resize mode, temporary resize pivots, grid/pivot tool selections, and provisional device
export calculations are not persisted. The current resize mode stays selected
when opening another project in the same session; a fresh launch starts with

View File

@ -284,6 +284,22 @@ Files are limited to 64 MiB and dimensions to 8192 pixels per side or the GPU's
texture limit, whichever is smaller. Invalid imports keep the previous image.
Reference settings are session-only and independent of layer undo/redo.
### Displaying and entering aspect ratios
Layer dimensions and resolution controls show their current width:height ratio
(e.g. **16:9**). A ratio field beside **Keep aspect ratio when resizing** accepts
`16:9`, `4/3`, or a positive decimal such as `1.85`. Press Enter or leave the field
to commit. With the lock checked, width stays fixed and height changes, preserving
the selected position reference (including center). Undo restores the geometry
and crop together. Zero, negative, non-finite and out-of-range results are rejected.
With the lock unchecked, entering a ratio does not resize: it stays ready until
the lock is enabled. The displayed current ratio still describes the actual
sizes. Selecting another layer discards that prepared value. In Layer properties,
manual ratios and presets update the size draft only when locked; **Apply** commits
the draft. Unapplied ratio text/targets are temporary UI state, not saved settings
or a separate project constraint. Source content remains proportionally scaled.
### Persistent editing tools
The toolbar has **10 px grid**, **100 px grid**, and **Pivot** icon toggles.

View File

@ -4,6 +4,8 @@
## Unreleased
- Show current aspect ratios beside dimensions and the ratio lock. Accept manual W:H, W/H or decimal ratios; locked edits keep width/reference and adjust height, unlocked edits wait for the lock. Layer properties remain Apply-based.
- Add persistent 10 px/100 px grid and Pivot toolbar icons with shortcut tooltips. Grids exclude each other; Pivot combines with either. Matching modifiers temporarily invert toggles; choices last for the session.
- Ctrl shows a movable resize pivot; Ctrl-resize keeps it fixed. Same/Mirror/Opposite modes share or reflect relative pivots. Double-click resets; Ctrl+Shift keeps the 100 px grid. Session-only, with snapping and Undo.