Adapt layer framing when switching input resolutions

This commit is contained in:
Dandaedre 2026-11-18 18:18:29 +01:00
parent ef8fcf90e8
commit df36648397
10 changed files with 238 additions and 4 deletions

2
Cargo.lock generated
View File

@ -602,7 +602,7 @@ dependencies = [
[[package]]
name = "canvas-pilot"
version = "0.10.0-rc.4"
version = "0.10.0-rc.5"
dependencies = [
"base64 0.22.1",
"craft-dwg",

View File

@ -4,7 +4,7 @@ default-members = ["crates/canvas-pilot"]
resolver = "3"
[workspace.package]
version = "0.10.0-rc.4"
version = "0.10.0-rc.5"
edition = "2024"
license = "MIT"
repository = "https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot"

View File

@ -671,10 +671,12 @@ impl Editor {
preview.paused = false;
}
let mut capture = false;
let mut changed_input = None;
ui.add_enabled_ui(preview.enabled, |ui| {
let before = preview.input;
ui.add_enabled_ui(!following, |ui| {input_picker(ui, ("layer-preview-input", id), &mut preview.input, &inputs, &mut self.capture.show_empty_inputs);});
if before != preview.input {
changed_input = Some(preview.input);
preview.host = self.device.host.clone();
preview.paused = false;
preview.texture = None;
@ -711,6 +713,9 @@ impl Editor {
if !idle { ui.spinner(); ui.small(tr(ui.ctx(), "ui.fetching-an-input-snapshot")); }
else if cooling { ui.small(tr(ui.ctx(), "ui.capture-available-again-shortly")); ui.ctx().request_repaint_after(std::time::Duration::from_secs(1)); }
});
if let Some(input) = changed_input {
self.adapt_layer_to_input(i, input);
}
if !self.capture.error.is_empty() {
ui.colored_label(ui.visuals().error_fg_color, &self.capture.error);
}
@ -725,7 +730,20 @@ impl Editor {
.capture_on_selection = false;
let input = self.capture.layers[&id].input;
self.start_input_capture(ui.ctx(), input, false);
self.capture.pending_layer = Some((id, source, input, self.device.host.clone()));
self.capture.pending_layer = Some((
id,
self.layout.formats().source_for[i],
input,
self.device.host.clone(),
));
}
}
pub(super) fn capture_input_error(&mut self, error: String) {
self.capture.error = error;
}
pub(super) fn rebind_input_preview_source(&mut self, i: usize) {
if let Some(preview) = self.capture.layers.get_mut(&self.layout.layer_info(i).id) {
preview.source = self.layout.formats().source_for[i];
}
}
fn sync_followed_inputs(&mut self) {

View File

@ -111,6 +111,7 @@ impl Plan {
&screen.program_bank
};
let mut projected = snapshot.clone();
let mut projected_layout = layout.clone();
let mut routes = Vec::new();
for (id, destination) in mappings {
let Some(input) = inputs.get(id) else {
@ -167,6 +168,10 @@ impl Plan {
}
}
}
let index = (0..layout.layers().len())
.find(|&i| layout.layer_info(i).id == *id)
.ok_or("An editor layer was removed.")?;
projected_layout.set_layer_source_resolution(index, native)?;
let layer_path = snapshot.profile.layer_path(&screen.id, bank, destination);
let path = format!("{layer_path}{}", snapshot.profile.source_field());
let before = field(&snapshot.raw, &path)?.clone();
@ -203,7 +208,14 @@ impl Plan {
});
}
}
let mut plan = Self::prepare(&projected, layout, screen_index, mappings, target, sizing)?;
let mut plan = Self::prepare(
&projected,
&projected_layout,
screen_index,
mappings,
target,
sizing,
)?;
// Conversion uses the selected input; preflight still compares the actual device state.
for (path, before) in &mut plan.observed {
*before = field(&snapshot.raw, path)?.clone();
@ -711,6 +723,50 @@ mod tests {
l
}
#[test]
fn replacing_input_reframes_only_its_layer_and_is_undoable() {
use crate::formats::{Crop, LayerFit};
for mode in std::iter::once(None).chain(LayerFit::ALL.into_iter().map(Some)) {
let mut editor = layout();
editor.formats.source_for[1] = editor.formats.source_for[0];
if mode.is_some() {
editor
.set_layer_fit(
0,
mode,
Crop {
left: 200.,
right: 100.,
top: 50.,
bottom: 20.,
},
)
.unwrap();
}
let original = editor.formats().clone();
let boxes = editor.layers().clone();
editor.set_layer_source_resolution(0, [942, 1029]).unwrap();
assert_eq!(editor.layers(), &boxes);
assert_eq!(editor.formats().input(0).unwrap(), [942., 1029.]);
assert_eq!(editor.formats().input(1).unwrap(), [1920., 1080.]);
assert_eq!(editor.formats().advanced[1], original.advanced[1]);
assert_eq!(editor.formats().masks, original.masks);
editor.formats().mapping(0, boxes[0]).unwrap();
if mode.is_none() {
let a = original.mapping(0, boxes[0]).unwrap();
let b = editor.formats().mapping(0, boxes[0]).unwrap();
assert!((a.framing.zoom - b.framing.zoom).abs() < 1e-8);
} else {
assert!(
(editor.formats().advanced[0].left / 942. - original.advanced[0].left / 1920.)
.abs()
< 1e-8
);
}
editor.undo();
assert_eq!(editor.formats(), &original);
}
}
#[test]
fn selected_input_requires_opt_in_and_preserves_fresh_state_guards() {
let mut state = snapshot();
@ -753,6 +809,29 @@ mod tests {
assert_eq!(plan.changes[0].after, json!("INPUT_5"));
assert_eq!(plan.changes[0].before, json!("INPUT_4"));
assert!(validate_fresh(&plan, &state).is_ok());
// A selected replacement signal need not match the editor's previous
// source. Reframe a planning copy and keep the original project intact.
let mut different = editor.clone();
let i = (0..different.layers().len())
.find(|&i| different.layer_info(i).id == 2)
.unwrap();
different
.set_layer_source_resolution(i, [942, 1029])
.unwrap();
let before = different.formats().clone();
let switched = Plan::prepare_with_inputs(
&state,
&different,
0,
&mappings,
Target::Preview,
Sizing::OutputBox,
&[(2, 5)].into(),
)
.unwrap();
assert_eq!(switched.changes[0].after, json!("INPUT_5"));
assert_eq!(different.formats(), &before);
assert!(validate_fresh(&switched, &state).is_ok());
let mut changed = state.clone();
changed.raw["device"]["inputList"]["items"]["INPUT_5"]["status"]["pp"]["plug"] =
json!("OTHER");

View File

@ -694,6 +694,48 @@ impl Editor {
})
.unwrap_or(0)
}
pub(super) fn adapt_layer_to_input(&mut self, i: usize, input: u32) {
let result = (|| {
let snapshot = self
.device
.snapshot
.as_ref()
.ok_or("Refresh the connection to read input dimensions.")?;
let raw = snapshot
.raw
.pointer(&format!(
"/device/inputList/items/{}",
snapshot.profile.input_key(input)
))
.ok_or("Input unavailable")?;
let plug = raw
.pointer("/status/pp/plug")
.and_then(serde_json::Value::as_str)
.ok_or("Input plug unavailable")?;
let signal = raw
.pointer(&format!("/plugList/items/{plug}/status/signal/pp"))
.ok_or("Input signal unavailable")?;
if signal.get("isValid").and_then(serde_json::Value::as_bool) != Some(true) {
return Err("Input has no valid signal".into());
}
let native = canvas_pilot::formats::resolution_from_values(
["imageWidth", "imageHeight"].map(|key| {
signal
.get(key)
.and_then(serde_json::Value::as_f64)
.unwrap_or(0.)
}),
)?;
self.layout.set_layer_source_resolution(i, native)
})();
match result {
Ok(()) => {
self.rebind_input_preview_source(i);
self.sync();
}
Err(error) => self.capture_input_error(error),
}
}
pub(super) fn source_input_controls(&mut self, ui: &mut egui::Ui, i: usize) {
let input = self.selected_physical_input(i);
let available = self
@ -710,6 +752,7 @@ impl Editor {
input,
..Default::default()
});
let previous = (choice.input, choice.change);
ui.horizontal(|ui| {
ui.label(tr(ui.ctx(), "ui.device-input"));
egui::ComboBox::from_id_salt(("source-input",i)).selected_text(if choice.input==0 {"Choose input…".into()} else {format!("Input {}",choice.input)}).show_ui(ui,|ui| {
@ -718,6 +761,10 @@ impl Editor {
});
ui.checkbox(&mut choice.change,tr(ui.ctx(), "ui.change-input")).on_hover_text("Switch this layer's mapped device destinations to the selected input on the next Send. Nothing changes immediately.");
});
let selected = choice.input;
if selected != previous.0 || (choice.change && !previous.1) {
self.adapt_layer_to_input(i, selected);
}
ui.small("Input changes are staged for this session only. Nothing is routed until Send.");
}
pub(super) fn layer_mapping_controls(&mut self, ui: &mut egui::Ui, i: usize) {

View File

@ -527,6 +527,19 @@ impl Editor {
}
});
});
// Input selection can reframe the live layer while this window owns its
// draft. Refresh only source-dependent fields, preserving pending size edits.
let source_id = self.layout.formats().source_for[i];
let source = self.layout.formats().sources[source_id];
if d.baseline.0 != source_id || d.baseline.1 != source {
d.source_id = source_id;
d.source = source;
d.input_size = source.input().unwrap();
d.baseline.0 = source_id;
d.baseline.1 = source;
d.baseline.2 = d.input_size;
d.refresh_fit(&self.layout);
}
if !open && d.pending(&self.layout) {
d.closing = true;
}

View File

@ -836,6 +836,55 @@ impl Layout {
pub fn formats(&self) -> &Formats {
&self.formats
}
/// Reframe only this layer for a replacement signal, preserving its output box.
pub fn set_layer_source_resolution(
&mut self,
i: usize,
native: [u32; 2],
) -> Result<(), String> {
formats::validate_resolution(native)?;
let g = *self.layers.get(i).ok_or("Layer unavailable")?;
let old = self.formats.input(i)?;
if old == native.map(f64::from) {
return Ok(());
}
let input = native.map(f64::from);
let crop = self.formats.advanced[i];
let next_crop = if self.formats.layer_fit[i].is_some() {
formats::Crop {
left: crop.left * input[0] / old[0],
right: crop.right * input[0] / old[0],
top: crop.top * input[1] / old[1],
bottom: crop.bottom * input[1] / old[1],
}
} else {
formats::reframed(old, [g.width, g.height], crop, input, [g.width, g.height])?.0
};
next_crop.remaining(input)?;
self.finish_drag();
let before = self.snapshot();
let source = self.formats.source_for[i];
let replacement = Source {
native,
aspect: formats::Aspect::Custom,
};
if self
.formats
.source_for
.iter()
.filter(|&&id| id == source)
.count()
> 1
{
self.formats.source_for[i] = self.formats.sources.len();
self.formats.sources.push(replacement);
} else {
self.formats.sources[source] = replacement;
}
self.formats.advanced[i] = next_crop;
self.remember(before);
Ok(())
}
pub fn set_output(&mut self, output: [u32; 2]) -> Result<(), String> {
formats::validate_resolution(output)?;
self.finish_drag();

View File

@ -4,6 +4,14 @@
## Unreleased
### v0.10.0-rc.5
- Adapt a layer to the selected input resolution instead of requiring a manual
source-size match. Preserve its outer box and normal zoom/focus; advanced fit
retains proportional crop edges. Shared editor sources are detached per layer.
- Preview input selection uses the same undoable adaptation. Explicit input-switch
plans adapt a temporary layout too, retaining device freshness validation.
### v0.10.0-rc.4
- Fix Midra layer input switching reading the wrong input crop path. Validate

View File

@ -383,3 +383,16 @@ are not stretched back to the uncropped signal size. The layer’s crop, zoom, f
and mask then apply normally. **Centered (fit)** preserves proportions;
**Fullscreen (stretch)** still deliberately stretches. This preview does not
change source dimensions or device input settings.
### Switching to a different input size
Selecting a physical input in Source properties or a different capture input in
Preview adapts that layer’s source dimensions to the valid signal. Its position
and outer size stay fixed. Normal crop mode retains zoom and normalized focus
(clamped at the new image edges); advanced fit retains proportional crop edges.
Other layers keep their source dimensions, even if they previously shared the
same editor source. Undo restores the previous framing. Input routing remains
opt-in through **Change input**, applied only on Send.
Explicit input-switch sends also adapt framing when a saved source size differs.
Existing restrictions on shared device input crop/aspect correction still apply.

View File

@ -196,3 +196,10 @@ The input-settings editor separately places captures at their applied crop posit
This affects rendering only. Stored image bytes, source dimensions, project schema
and device transfers are unchanged. Input-settings/global fit inheritance is not
inferred from a PNG; this does not add support for those device modes.
Explicit physical input selection now adapts that layer's editor source dimensions
using signal imageWidth/imageHeight (not thumbnail dimensions). Layer geometry
stays fixed; ordinary framing is recalculated with the existing zoom and normalized
focus, while explicit fit keeps crop fractions. A shared source is copied before
replacement so other layers are unaffected. This is an undoable editor change,
persisted through the existing source/crop fields without a schema change.