Add pixel-preserving crop handles for 1:1 layer fit

This commit is contained in:
Dandaedre 2026-11-16 09:05:46 +01:00
parent ae43dbe8b0
commit 2a90330f7a
7 changed files with 321 additions and 22 deletions

View File

@ -324,7 +324,8 @@ impl Editor {
&& self.format_draft.as_ref().is_some_and(|d| {
!d.closing
&& self.layout.selected() == Some(d.layer)
&& self.layout.formats().layer_fit[d.layer].is_none()
&& self.layout.formats().layer_fit[d.layer]
.is_none_or(|fit| fit == canvas_pilot::formats::LayerFit::OneToOne)
});
if active || self.crop_tab_editing {
self.edit_content = active;
@ -501,7 +502,12 @@ impl Editor {
let current = self.layout.layers()[i];
let (_, area) = ui.allocate_space(Vec2::new(ui.available_width(),170.0));
paint_layer_source(ui.painter(),fit_rect(area,[current.width,current.height]), &self.layout, i, self.layer_preview(i));
ui.small("Edit crop edges here; visual zoom/drag controls are for normal crop mode. Disabling advanced fit restores normal cover framing. Device subpixel rendering is approximate.");
if current_fit == canvas_pilot::formats::LayerFit::OneToOne {
ui.small("Drag the canvas helper's edges to crop without zooming. The retained picture stays centered. Corners trim two edges independently. Double-click a layer to toggle the helper; use viewport zoom to reach offscreen handles.");
} else {
ui.small("Edit crop edges here; visual zoom/drag controls are for normal crop mode.");
}
ui.small("Disabling advanced fit restores normal cover framing. Device subpixel rendering is approximate.");
} else {
ui.label("Zoom and position change the crop values inside this layer, keeping its visible box fixed. 100% is the minimum crop that fills the box.");
@ -622,6 +628,21 @@ pub(super) fn paint_content_overflow(
}
}
/// Show the usable source as a faded guide behind the actual 1:1 image.
pub(super) fn paint_one_to_one_helper(
painter: &egui::Painter,
image: Rect,
source: Source,
crop: Crop,
preview: Option<(egui::TextureId, f32)>,
) {
if let Some(full) = content_bounds(image, source, crop) {
let mut ghost = painter.clone();
ghost.multiply_opacity(0.3);
paint_source_clipped(&ghost, image, source, crop, full, preview);
}
}
pub(super) fn paint_layer_source(
painter: &egui::Painter,
rect: Rect,
@ -827,7 +848,11 @@ mod tests {
);
assert!(!app.edit_content);
click_text(&mut app, &ctx, "Centered (fit)");
click_text(&mut app, &ctx, "1:1 pixels");
assert!(app.edit_content);
click_text(&mut app, &ctx, "1:1 pixels");
click_text(&mut app, &ctx, "Fullscreen (stretch)");
assert!(!app.edit_content);
assert_eq!(
app.layout.formats().layer_fit[i],
Some(canvas_pilot::formats::LayerFit::Fullscreen)

View File

@ -372,7 +372,8 @@ fn bounds(g: Geometry) -> String {
impl Editor {
fn toggle_crop_edit(&mut self) {
if let Some(i) = self.layout.selected()
&& self.layout.formats().layer_fit[i].is_some()
&& self.layout.formats().layer_fit[i]
.is_some_and(|fit| fit != canvas_pilot::formats::LayerFit::OneToOne)
{
self.edit_content = false;
self.property_tab = PropertyTab::Crop;
@ -1016,6 +1017,11 @@ impl Editor {
let result = if self.edit_content
&& let Some(i) = self.layout.selected()
{
if self.layout.formats().layer_fit[i]
== Some(canvas_pilot::formats::LayerFit::OneToOne)
{
return; // 1:1 is centered: use crop handles/fields, never pan or zoom.
}
let g = self.layout.layers()[i];
self.layout.formats().mapping(i, g).and_then(|m| {
let offset = std::array::from_fn(|axis| {
@ -1552,7 +1558,9 @@ impl Editor {
ui.put(
Rect::from_min_size(ink.point(0.0, 317.0), Vec2::new(w, 48.0)),
egui::Label::new(egui::RichText::new(
if self.layout.formats().layer_fit[i].is_some() {
if self.layout.formats().layer_fit[i] == Some(canvas_pilot::formats::LayerFit::OneToOne) {
"Drag helper edges to crop source pixels without zooming. The retained picture stays centered; the container stays fixed."
} else if self.layout.formats().layer_fit[i].is_some() {
"Opens advanced crop edges and fit mode. The rectangle defines the container."
} else {
"Changes the crop values inside this layer. Drag content to reposition it; the visible box stays fixed."
@ -2157,9 +2165,6 @@ impl Editor {
return None;
}
let i = self.layout.selected()?;
if self.layout.formats().layer_fit[i].is_some() {
return None;
}
let to_rect = |g: &Geometry| {
Rect::from_min_size(
origin + Vec2::new(g.x as f32, g.y as f32) * scale,
@ -2178,6 +2183,15 @@ impl Editor {
{
return None;
}
if self.layout.formats().layer_fit[i] == Some(canvas_pilot::formats::LayerFit::OneToOne) {
return self
.crop_bounds(origin, scale)
.filter(|r| r.contains(pointer))
.map(|_| i);
}
if self.layout.formats().layer_fit[i].is_some() {
return None;
}
format_ui::content_bounds(
rect,
self.layout.formats().sources[self.layout.formats().source_for[i]],
@ -2191,8 +2205,18 @@ impl Editor {
return None;
}
let i = self.layout.selected()?;
if self.layout.formats().layer_fit[i].is_some() {
return None;
if let Some(fit) = self.layout.formats().layer_fit[i] {
if fit != canvas_pilot::formats::LayerFit::OneToOne {
return None;
}
let retained = self.layout.formats().advanced[i]
.remaining(self.layout.formats().input(i).ok()?)
.ok()?;
let g = fit.image(retained, self.layout.layers()[i]).ok()?;
return Some(Rect::from_min_size(
origin + Vec2::new(g.x as f32, g.y as f32) * scale,
Vec2::new(g.width as f32, g.height as f32) * scale,
));
}
let g = self.layout.layers()[i];
let rect = Rect::from_min_size(
@ -3145,20 +3169,34 @@ impl Editor {
}
if self.edit_content
&& let Some(i) = self.layout.selected()
&& self.layout.formats().layer_fit[i].is_none()
&& self.layout.formats().layer_fit[i]
.is_none_or(|fit| fit == canvas_pilot::formats::LayerFit::OneToOne)
{
let g = self.layout.layers()[i];
let rect = Rect::from_min_size(
origin + Vec2::new(g.x as f32, g.y as f32) * scale,
Vec2::new(g.width as f32, g.height as f32) * scale,
);
format_ui::paint_content_overflow(
&screen.painter,
rect,
self.layout.formats().sources[self.layout.formats().source_for[i]],
self.layout.formats().advanced[i],
self.layer_preview(i),
);
if self.layout.formats().layer_fit[i] == Some(canvas_pilot::formats::LayerFit::OneToOne)
{
if let Some(image) = self.crop_bounds(origin, scale) {
format_ui::paint_one_to_one_helper(
&screen.painter,
image,
self.layout.formats().sources[self.layout.formats().source_for[i]],
self.layout.formats().advanced[i],
self.layer_preview(i),
);
}
} else {
format_ui::paint_content_overflow(
&screen.painter,
rect,
self.layout.formats().sources[self.layout.formats().source_for[i]],
self.layout.formats().advanced[i],
self.layer_preview(i),
);
}
}
for i in self.layout.viewport_order() {
let g = &self.layout.layers()[i];
@ -3379,7 +3417,7 @@ impl Editor {
ink.text(
24.0,
r.height() - 40.0,
if move_pointer { "Move tool · Drag anywhere to move the current selection · V: Select · H: Pan" } else if self.navigation_tool == NavigationTool::Pan { "Pan tool · Drag to move the view · V: Select · Z: Zoom · Space/middle-drag pans from any tool" } else if self.navigation_tool == NavigationTool::Zoom { "Zoom tool · Click to zoom in · Alt-click to zoom out · Drag right/left to zoom · V: Select · H: Pan" } else if pivot_visible { "Pivot resize · Drag pivot to position · Double-click to center · Ctrl temporarily toggles pivot" } else if self.edit_content { "Crop mode · Drag crop handles to zoom content · Drag image to reposition · Double-click or click outside to finish" } else { match self.active_resize_mode() {
if move_pointer { "Move tool · Drag anywhere to move the current selection · V: Select · H: Pan" } else if self.navigation_tool == NavigationTool::Pan { "Pan tool · Drag to move the view · V: Select · Z: Zoom · Space/middle-drag pans from any tool" } else if self.navigation_tool == NavigationTool::Zoom { "Zoom tool · Click to zoom in · Alt-click to zoom out · Drag right/left to zoom · V: Select · H: Pan" } else if self.edit_content && self.layout.selected().is_some_and(|i| self.layout.formats().layer_fit[i] == Some(canvas_pilot::formats::LayerFit::OneToOne)) { "1:1 crop · Drag edges to trim source pixels · No zoom or pan · Double-click or click outside to finish" } else if pivot_visible { "Pivot resize · Drag pivot to position · Double-click to center · Ctrl temporarily toggles pivot" } else if self.edit_content { "Crop mode · Drag crop handles to zoom content · Drag image to reposition · Double-click or click outside to finish" } else { match self.active_resize_mode() {
ResizeMode::Individual => "Corners resize · Side handles keep opposite edge fixed · Shift-click selects",
ResizeMode::Same => "Same handles · Matching handles scale selected layers proportionally · Escape cancels drag",
ResizeMode::Mirror => "Mirror horizontally · Left/right mirrored handles · Escape cancels drag",
@ -5840,6 +5878,66 @@ mod tests {
assert_eq!(*app.layout.formats(), before);
}
#[test]
fn double_click_one_to_one_opens_crop_helper_and_handles_trim_without_zoom() {
use canvas_pilot::formats::{Crop, LayerFit};
let mut app = Editor::default();
let ctx = egui::Context::default();
let output = frame(&mut app, &ctx, vec![]);
let rect = layer_rects(&output)[1];
app.layout
.set_layer_fit(
1,
Some(LayerFit::OneToOne),
Crop {
left: 640.0,
right: 640.0,
top: 360.0,
bottom: 360.0,
},
)
.unwrap();
frame(&mut app, &ctx, vec![]);
let center = rect.center();
for _ in 0..2 {
frame(
&mut app,
&ctx,
vec![egui::Event::PointerMoved(center), mouse(center, true)],
);
frame(&mut app, &ctx, vec![mouse(center, false)]);
}
assert!(app.edit_content);
assert!(app.format_draft.is_none());
let before = app.layout.layers().clone();
let crop = app.layout.formats().advanced[1];
let start = rect.left_center();
let end = start + Vec2::new(20.0, 0.0);
frame(
&mut app,
&ctx,
vec![egui::Event::PointerMoved(start), mouse(start, true)],
);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(end)]);
frame(&mut app, &ctx, vec![mouse(end, false)]);
assert!(app.edit_content);
assert_eq!(*app.layout.layers(), before);
let changed = app.layout.formats().advanced[1];
assert!(changed.left > crop.left);
assert_eq!(
[changed.right, changed.top, changed.bottom],
[crop.right, crop.top, crop.bottom]
);
assert_eq!(
app.layout.formats().mapping(1, before[1]).unwrap().scale,
1.0
);
frame(&mut app, &ctx, vec![key(egui::Key::Escape)]);
assert!(!app.edit_content);
app.layout.undo();
assert_eq!(app.layout.formats().advanced[1], crop);
}
#[test]
fn crop_handle_gesture_zooms_content_without_resizing_layer() {
for (zoom, handle_index, pivot_tool) in [0.6, 1.0]

View File

@ -885,13 +885,14 @@ impl Layout {
self.content_drag = Some((i, self.snapshot(), point));
}
}
/// Zoom content from a corner or side, fixing the opposite anchor (or enabled pivot) and layer box.
/// Resize content in normal crop mode, or trim source pixels in centered 1:1 mode.
/// The layer container stays fixed; 1:1 ignores proportional scaling and pivots.
pub fn start_content_resize(&mut self, index: usize, handle: ResizeHandle, point: [f64; 2]) {
if self
.formats
.layer_fit
.get(index)
.is_some_and(Option::is_some)
.is_some_and(|mode| mode.is_some_and(|fit| fit != formats::LayerFit::OneToOne))
{
return;
}
@ -1616,6 +1617,53 @@ impl Layout {
let i = r.index;
let g = r.before.layers[i];
let input = r.before.formats.input(i)?;
if r.before.formats.layer_fit[i] == Some(formats::LayerFit::OneToOne) {
let mut crop = r.before.formats.advanced[i];
let remaining = crop.remaining(input)?;
// The retained image stays centered: moving a displayed edge
// by d changes retained size by 2d. Only the chosen source
// crop edge changes; pixel scale and container never change.
let delta = [2.0 * (point[0] - r.start[0]), 2.0 * (point[1] - r.start[1])];
let left = matches!(
r.handle,
ResizeHandle::Left
| ResizeHandle::Corner(Corner::TopLeft | Corner::BottomLeft)
);
let right = matches!(
r.handle,
ResizeHandle::Right
| ResizeHandle::Corner(Corner::TopRight | Corner::BottomRight)
);
let top = matches!(
r.handle,
ResizeHandle::Top
| ResizeHandle::Corner(Corner::TopLeft | Corner::TopRight)
);
let bottom = matches!(
r.handle,
ResizeHandle::Bottom
| ResizeHandle::Corner(Corner::BottomLeft | Corner::BottomRight)
);
let minimum = remaining.map(|v| v.min(0.001));
if left {
crop.left =
(crop.left + delta[0]).clamp(0.0, input[0] - crop.right - minimum[0]);
}
if right {
crop.right =
(crop.right - delta[0]).clamp(0.0, input[0] - crop.left - minimum[0]);
}
if top {
crop.top =
(crop.top + delta[1]).clamp(0.0, input[1] - crop.bottom - minimum[1]);
}
if bottom {
crop.bottom =
(crop.bottom - delta[1]).clamp(0.0, input[1] - crop.top - minimum[1]);
}
crop.remaining(input)?;
return Ok(crop);
}
let m = r.before.formats.mapping(i, g)?;
let crop = r.before.formats.advanced[i];
let full = Geometry {

View File

@ -128,3 +128,112 @@ fn current_documented_example_is_valid() {
assert_eq!(p.version, 14);
p.layout().unwrap();
}
#[test]
fn one_to_one_handles_trim_source_edges_without_zoom_and_undo_atomically() {
use canvas_pilot::{Corner, ResizeHandle};
let g = box_geometry();
for (handle, delta, changes) in [
(ResizeHandle::Left, [25.0, 99.0], [50.0, 0.0, 0.0, 0.0]),
(ResizeHandle::Right, [-25.0, 99.0], [0.0, 50.0, 0.0, 0.0]),
(ResizeHandle::Top, [99.0, 15.0], [0.0, 0.0, 30.0, 0.0]),
(ResizeHandle::Bottom, [99.0, -15.0], [0.0, 0.0, 0.0, 30.0]),
(
ResizeHandle::Corner(Corner::TopLeft),
[25.0, 15.0],
[50.0, 0.0, 30.0, 0.0],
),
(
ResizeHandle::Corner(Corner::TopRight),
[-25.0, 15.0],
[0.0, 50.0, 30.0, 0.0],
),
(
ResizeHandle::Corner(Corner::BottomLeft),
[25.0, -15.0],
[50.0, 0.0, 0.0, 30.0],
),
(
ResizeHandle::Corner(Corner::BottomRight),
[-25.0, -15.0],
[0.0, 50.0, 0.0, 30.0],
),
] {
let mut layout = Layout::default();
layout.apply(0, g).unwrap();
layout.select(Some(0));
let initial = Crop {
left: 100.0,
right: 80.0,
top: 60.0,
bottom: 40.0,
};
layout
.set_layer_fit(0, Some(LayerFit::OneToOne), initial)
.unwrap();
let before = Project::from_layout(&layout);
let input = layout.formats().input(0).unwrap();
let image = LayerFit::OneToOne
.image(initial.remaining(input).unwrap(), g)
.unwrap();
let start = ResizeHandle::positions(image)
.into_iter()
.find(|(h, _)| *h == handle)
.unwrap()
.1;
layout.start_content_resize(0, handle, start);
layout.use_resize_pivot(true); // 1:1 never scales about a pivot.
layout.drag_to([start[0] + delta[0] / 2.0, start[1] + delta[1] / 2.0]);
layout.drag_to([start[0] + delta[0], start[1] + delta[1]]);
layout.finish_drag();
let crop = layout.formats().advanced[0];
assert_eq!(
[crop.left, crop.right, crop.top, crop.bottom],
[
100.0 + changes[0],
80.0 + changes[1],
60.0 + changes[2],
40.0 + changes[3]
]
);
assert_eq!(layout.layers()[0], g);
let retained = crop.remaining(input).unwrap();
let fitted = LayerFit::OneToOne.image(retained, g).unwrap();
assert_eq!([fitted.width, fitted.height], retained);
assert_eq!(fitted.center(), g.center());
let after = Project::from_layout(&layout);
layout.undo();
assert_eq!(Project::from_layout(&layout), before);
layout.redo();
assert_eq!(Project::from_layout(&layout), after);
layout.start_content_resize(0, handle, start);
layout.drag_to([start[0] + 100.0, start[1] + 100.0]);
layout.cancel_drag();
assert_eq!(Project::from_layout(&layout), after);
}
}
#[test]
fn one_to_one_crop_stops_at_source_limits_and_never_pans() {
use canvas_pilot::ResizeHandle;
let mut layout = Layout::default();
layout.select(Some(0));
layout
.set_layer_fit(0, Some(LayerFit::OneToOne), Crop::default())
.unwrap();
let input = layout.formats().input(0).unwrap();
layout.start_content_resize(0, ResizeHandle::Left, [0.0, 0.0]);
layout.drag_to([100000.0, 0.0]);
let crop = layout.formats().advanced[0];
near(crop.remaining(input).unwrap()[0], 0.001);
layout.drag_to([-100000.0, 0.0]);
assert_eq!(layout.formats().advanced[0], Crop::default());
layout.finish_drag();
layout.start_content_drag(0, [0.0, 0.0]);
assert!(!layout.dragging());
layout
.set_layer_fit(0, Some(LayerFit::Centered), Crop::default())
.unwrap();
layout.start_content_resize(0, ResizeHandle::Left, [0.0, 0.0]);
assert!(!layout.dragging());
}

View File

@ -4,6 +4,13 @@
## Unreleased
- Add the double-click crop helper for advanced 1:1 fit: independent side/corner
handles trim or restore source pixels while preserving pixel scale and the
layer container. Show a faded source guide, synchronize crop fields, and keep
one-step Undo/Escape cancellation. Centering follows Midra's 1:1 semantics;
no project schema or device protocol changes. Regression tests cover edge
limits, every handle, double-click interaction and undo/cancel.
- Add opt-in advanced Midra layer fit: centered 1:1, Centered, Fullscreen and
Cropped, with crop-first previews/export artwork, container resizing, device
load/send and undo. Normal zoom/crop remains the default; input inheritance

View File

@ -169,8 +169,16 @@ pixels, apply first; the retained image is centered and clipped to that containe
1:1 preserves pixel scale, Centered preserves proportions with transparent
margins, Fullscreen stretches, and Cropped fills while clipping overflow.
Resize changes the container and preserves these crop edges. Visual zoom/drag
controls belong to normal crop mode; edit raw edges here instead. Unchecking
Resize changes the container and preserves these crop edges. For **1:1**, double-click
the layer or choose **Adjust layer crop** to show the crop helper. Drag a side to
trim/restore that source edge; corners adjust two edges independently. The cyan
outline shows the retained image, with the usable source faded behind it. It
never zooms, stretches or pans the image, and ignores aspect lock/pivot scaling.
The retained picture stays centered, so its outline contracts/expands symmetrically
even though only the chosen source crop edge changes. The container stays fixed.
Use viewport zoom/pan to reach handles outside the screen. Each drag is one Undo
step; Escape cancels an active drag and exits the helper. Numeric crop fields stay
in sync. Other advanced modes still use the numeric crop controls. Unchecking
resets to normal centered cover framing. Input/global inheritance is intentionally
omitted. Pending Source edits remain staged and require Apply as usual.

View File

@ -25,6 +25,10 @@ to the [engineering stretch goal](midra-fit-precision.md).
some content is cut off.
- [ ] Choose 1:1, send; resize the layer and send again: content scale stays the
same, with more/less clipping or background visible.
- [ ] In 1:1, double-click the layer; drag a helper side/corner. The picture
should crop without changing pixel scale; the retained region remains centered.
Verify the crop fields, Undo and Escape. Zoom out the viewport if handles lie
outside the screen.
- [ ] Apply a noticeable asymmetric crop; repeat modes and check that the crop
stays applied. No ruler or pixel measurements are needed.
- [ ] Load the layer: mode, container and crop should return to the editor;