Add direct Midra apply actions and simplify sending
Beffroi/beffroi-tools/pipeline/head This commit looks good Details

This commit is contained in:
Dandaedre 2026-11-13 18:28:12 +01:00
parent 43cb7dec6f
commit 1c2b829899
8 changed files with 147 additions and 62 deletions

View File

@ -34,7 +34,6 @@ pub struct Plan {
pub bank: String,
pub target: Target,
pub changes: Vec<Change>,
guards: Vec<(String, Value)>,
}
fn field<'a>(raw: &'a Value, path: &str) -> Result<&'a Value, String> {
raw.pointer(path)
@ -83,18 +82,7 @@ impl Plan {
bank: bank.into(),
target,
changes: vec![],
guards: vec![],
};
for path in [
format!("{base}/canvas/status/size/pp"),
format!(
"/device/transition/screenList/items/{}/status/pp/transition",
screen.id
),
] {
plan.guards
.push((path.clone(), field(&snapshot.raw, &path)?.clone()));
}
let mut locals = BTreeSet::new();
let mut destinations = BTreeSet::new();
for (id, destination) in mappings {
@ -121,19 +109,6 @@ impl Plan {
];
let native = source.native.map(f64::from);
let layer = format!("{base}/presetList/items/{bank}/liveLayerList/items/{destination}");
for section in [
"source/pp",
"crop/pp",
"mask/pp",
"size/pp",
"position/pp",
"status/pp/contentWidth",
"status/pp/contentHeight",
] {
let path = format!("{layer}/{section}");
plan.guards
.push((path.clone(), field(&snapshot.raw, &path)?.clone()));
}
let content = [
field(&snapshot.raw, &format!("{layer}/status/pp/contentWidth"))?.as_f64(),
field(&snapshot.raw, &format!("{layer}/status/pp/contentHeight"))?.as_f64(),
@ -236,14 +211,6 @@ impl Plan {
});
Ok(plan)
}
fn check_fresh(&self, snapshot: &Snapshot) -> Result<(), String> {
for (path, expected) in &self.guards {
if field(&snapshot.raw, path)? != expected {
return Err("Device state changed since review. Refresh and review again; nothing was sent.".into());
}
}
Ok(())
}
fn verified(&self, snapshot: &Snapshot) -> bool {
self.changes
.iter()
@ -256,10 +223,8 @@ trait Transport {
fn pause(&self) {}
}
fn execute(plan: &Plan, transport: &mut impl Transport) -> Result<Snapshot, String> {
let current = transport.read()?;
plan.check_fresh(&current)?;
if plan.changes.is_empty() {
return Ok(current);
return transport.read();
}
for (i, change) in plan.changes.iter().enumerate() {
transport.write(change).map_err(|e| format!("Send stopped after {i}/{} confirmed socket writes. Device may be partially changed; refresh before retrying. {e}", plan.changes.len()))?;
@ -564,7 +529,7 @@ mod tests {
}
}
#[test]
fn stale_read_sends_nothing_and_partial_failure_never_retries() {
fn changed_device_state_does_not_block_send_and_partial_failure_is_reported() {
let state = snapshot();
let plan = Plan::prepare(
&state,
@ -581,15 +546,15 @@ mod tests {
fail_at: None,
ignore: false,
};
let path = &plan.guards[0].0;
*mock.state.raw.pointer_mut(path).unwrap() = json!(null);
assert!(
execute(&plan, &mut mock)
.unwrap_err()
.contains("nothing was sent")
);
assert_eq!(mock.writes, 0);
*mock
.state
.raw
.pointer_mut("/device/screenList/items/1/canvas/status/size/pp")
.unwrap() = json!(null);
assert!(plan.verified(&execute(&plan, &mut mock).unwrap()));
assert_eq!(mock.writes, plan.changes.len());
mock.state = state;
mock.writes = 0;
mock.fail_at = Some(2);
assert!(
execute(&plan, &mut mock)

View File

@ -41,6 +41,25 @@ impl DeviceUi {
..Self::default()
}
}
fn selected_plan(&self, layout: &midra_layout::Layout) -> Result<Plan, String> {
let snapshot = self.snapshot.as_ref().ok_or("Connect to Midra first.")?;
let mappings: Vec<_> = layout
.selected_indices()
.iter()
.map(|&i| {
let id = layout.layer_info(i).id;
(id, self.send_targets.get(&id).cloned().unwrap_or_default())
})
.collect();
Plan::prepare(
snapshot,
layout,
self.screen,
&mappings,
self.target,
self.sizing,
)
}
pub(super) fn online(&self) -> bool {
self.snapshot.is_some()
}
@ -104,6 +123,49 @@ impl DeviceUi {
}
}
impl Editor {
pub(super) fn midra_apply_button(&mut self, ui: &mut egui::Ui) {
let plan = self.device.selected_plan(&self.layout);
let enabled = self.device.online()
&& self.device.pending.is_none()
&& plan.as_ref().map_or(true, |p| !p.changes.is_empty());
let tooltip = match &plan {
Ok(p) if p.changes.is_empty() => {
"Selected layers already match the device snapshot.".into()
}
Ok(p) => format!(
"Send selected layers to {:?}, screen {}, bank {} using the configured destinations.",
p.target, p.screen, p.bank
),
Err(e) => format!("Configure layer destinations before sending. {e}"),
};
if apply_button(
ui,
if self.device.sending {
"Applying…"
} else {
"Apply to Midra"
},
enabled,
)
.on_hover_text(&tooltip)
.on_disabled_hover_text(&tooltip)
.clicked()
{
match plan {
Ok(plan) => {
self.device.send(ui.ctx(), plan);
self.device.prepare_send = true;
self.device.open = true;
}
Err(_) => {
self.device.prepare_send = true;
self.device.open = true;
}
}
ui.close_menu();
}
}
fn connection_window(&mut self, ctx: &egui::Context) {
if !self.device.connection_open {
return;
@ -168,7 +230,6 @@ impl Editor {
ui.horizontal(|ui| { ui.spinner(); ui.label(if self.device.sending { "Sending and checking readback…" } else { "Reading device… editing remains available." }); });
if !self.device.sending && ui.button("Cancel read").clicked() { self.device.pending = None; }
}
ui.weak("Only the Send button writes device settings. Local edits never send automatically.");
if !self.device.error.is_empty() { ui.colored_label(ui.visuals().error_fg_color, &self.device.error); }
if !self.device.message.is_empty() { ui.label(&self.device.message); }
if let Some(snapshot) = &self.device.snapshot {
@ -238,7 +299,6 @@ impl Editor {
}
ui.separator();
ui.weak("Layer size, position, crop and aspect only. No TAKE, source routing or shared input/output changes.");
});
self.device.open = open;
if let Some(plan) = send_plan {
@ -357,7 +417,6 @@ fn send_review(
plan.bank,
plan.changes.len()
));
ui.weak("The displayed bank stays fixed during sending, even if another controller performs a TAKE. Writes are sequential, not atomic.");
ui.collapsing("Exact device changes", |ui| {
for change in &plan.changes {
ui.label(format!(
@ -394,6 +453,47 @@ fn container_label(geometry: midra_layout::Geometry) -> String {
mod tests {
use super::*;
#[test]
fn status_apply_opens_mapping_without_writing_when_unconfigured() {
let ctx = egui::Context::default();
let mut app = Editor::default();
app.device.snapshot = Some(device::Snapshot {
identity: "Test device".into(),
raw: serde_json::Value::Null,
screens: vec![device::Screen {
id: "1".into(),
resolution: [1920, 1080],
preview_bank: "UP".into(),
layers: vec![],
}],
});
let before = app.layout.layers().clone();
super::super::tests::frame(&mut app, &ctx, vec![]);
let output = super::super::tests::frame(&mut app, &ctx, vec![]);
let pos = output
.shapes
.iter()
.find_map(|s| match &s.shape {
egui::epaint::Shape::Text(t) if t.galley.job.text == "Apply to Midra" => {
Some(t.pos + Vec2::new(8.0, 6.0))
}
_ => None,
})
.expect("status apply button");
for pressed in [true, false] {
super::super::tests::frame(
&mut app,
&ctx,
vec![
egui::Event::PointerMoved(pos),
super::super::tests::mouse(pos, pressed),
],
);
}
assert!(app.device.open && app.device.prepare_send);
assert!(app.device.pending.is_none());
assert_eq!(*app.layout.layers(), before);
}
#[test]
fn send_review_only_maps_selected_layers_and_never_mutates_layout() {
let ctx = egui::Context::default();
let mut layout = midra_layout::Layout::default();

View File

@ -2412,8 +2412,17 @@ impl Editor {
palette.muted
},
);
ui.scope_builder(
egui::UiBuilder::new().max_rect(Rect::from_min_size(
r.min + Vec2::new(104.0, 5.0),
Vec2::new(130.0, 25.0),
)),
|ui| {
self.midra_apply_button(ui);
},
);
ink.text(
116.0,
248.0,
10.0,
if !self.layout.selected_indices().is_empty() {
"Shift-click or drag a box to select layers"

View File

@ -203,6 +203,7 @@ impl Editor {
}
ui.menu_button("Project", |ui| self.project_menu(ui));
ui.menu_button("Import", |ui| self.import_menu(ui));
ui.menu_button("Export", |ui| self.export_menu(ui));
ui.menu_button("Edit", |ui| {
if ui.button("Undo").clicked() {
self.layout.undo();

View File

@ -126,7 +126,7 @@ impl Editor {
if ui
.add_enabled(
self.device.online(),
egui::Button::new("Send layers to Midra…"),
egui::Button::new("Configure Midra export…"),
)
.on_hover_text("Map editor layers, review device changes and send explicitly.")
.on_disabled_hover_text(
@ -138,6 +138,16 @@ impl Editor {
self.device.open = true;
ui.close_menu();
}
ui.menu_button("Export", |ui| self.export_menu(ui));
}
pub(super) fn export_menu(&mut self, ui: &mut egui::Ui) {
self.midra_apply_button(ui);
if ui.button("Configure Midra export…").clicked() {
self.device.prepare_send = true;
self.device.open = true;
ui.close_menu();
}
ui.separator();
ui.menu_button("Export SVG", |ui| {
self.transfer_layer_picker(ui, "Choose layers to export…");
ui.menu_button("Specific layer…", |ui| {

View File

@ -21,10 +21,7 @@ Reviewed fields under the mapped live layer are only:
- `crop.pp.aspectOverride`: `CENTERED`.
At `AT_DOWN`, Preview is UP and Program DOWN; `AT_UP` reverses those roles.
The review captures one physical bank. Preflight rejects changed transition,
canvas, mapped source, size, position, crop, mask or content dimensions. A TAKE
between checking and writing can change the bank's role; the user explicitly
permits this. Commands do not retarget halfway through. No TAKE or source routing,
The selected configuration captures one physical bank. Send writes directly without a preflight read or stale-snapshot refusal. Commands do not retarget halfway through. No TAKE or source routing,
mask, effect, opacity, shared input crop or output setting is sent.
## Conversion
@ -76,3 +73,5 @@ partial/uncertain outcomes without blind retries or automatic rollback.
Program selection is explicit. The application defaults to Preview. Mappings,
plans and raw snapshots are not saved in projects or preferences. The device address is saved in [application settings](midra-layout-settings.md), never in projects. Refresh and screen changes reset destination review. Physical display
validation remains separate from the successful device-field and import round trips.
The status-bar and Export-menu **Apply to Midra** actions prepare a fresh plan for the current editor selection using the session mappings, target and sizing mode. Valid changed plans send immediately with readback verification, without a preflight refusal. Missing or invalid mappings open the configuration window without writing; no-op plans and busy/offline actions are disabled. No persistent schema changes are involved.

View File

@ -96,10 +96,10 @@ sanitize before sharing. Its exchange contract is documented in
The user's later authorization permits Program changes and accepts the physical-bank
TAKE race. This supersedes the earlier Preview-only restriction above.
**Project → Send layers to Midra…** (or the connection window's send tab) now supports
**Export → Configure Midra export…** now supports
explicit Preview or Program targeting, per-selected-layer destination mapping,
output-sized or source-aspect containers, and exact before/after field review.
Each send checks for stale state, writes once, then reads the device back. A partial
Each send writes directly, then reads the device back; it does not reject changes made since the snapshot. A partial
or uncertain result is reported without automatically repeating or rolling back writes.
Local editing, importing, undo/redo, connection and project loading never send.

View File

@ -395,7 +395,7 @@ viewport preferences, and the embedded reference image. Apply pending edits
before saving. Opening asks before replacing current work and starts a fresh
undo history. Existing files require confirmation before replacement.
**Project → Export SVG** offers **All layers** and **Visible layers only**.
**Project → Export → Export SVG** offers **All layers** and **Visible layers only**.
These exports contain whole-pixel layer boxes. Import them with **Import → SVG
file** and map the detected rectangles to the same number of selected layers.
SVG exchanges geometry; JSON preserves the complete project, including crops
@ -524,15 +524,14 @@ Choose a destination beside each device layer: existing layer, new layer, or ski
Centered crops import visible bounds and framing; unsupported aspect/mask cases
are explained in the review. Imports are one undoable edit.
After connecting, open **Project → Send layers to Midra…**. Choose editor layers,
After connecting, open **Export → Configure Midra export…**. Choose editor layers,
map each to a Midra layer, select **Preview** or **Program**, and select a container
strategy: **Output-sized** or **Source aspect**. Expand **Exact device changes** to
review sizes, centers, crop values and aspect, then click **Send mapped layers**.
The button is disabled when the snapshot already matches or a send is in progress.
The source's native dimensions must match the destination's current content.
The target bank is fixed at review time; a concurrent TAKE may change its on-air
role. Changed state before sending requires a fresh review. Writes are sequential;
The target bank is fixed when configured. Sending starts immediately without a stale-state check. Writes are sequential;
partial failures require refreshing, not automatic retries or rollback. Success
means all changed fields matched device readback. There are no automatic sends
from edits, imports or undo. Closing the connection window does not cancel a send
@ -553,7 +552,7 @@ movement, alignment and Same-handles resizing work across the selection;
Mirror/Opposite resizing still require exactly two layers.
Project JSON is now version 4, with tested migration from versions 1–3.
**Project → Export SVG → Selected layers…** exports just the current selection,
**Project → Export → Export SVG → Selected layers…** exports just the current selection,
including a single layer. All/visible export remains available.
## Reference placement and loading
@ -605,7 +604,7 @@ You can choose layers without returning to the viewport:
layer using its destination dropdown. When using a selection, there must be at least as many chosen destinations as imported rectangles
after ignoring an SVG background. Map to any subset of them; other layers stay
unchanged. Duplicate mappings and empty imports remain invalid.
- **Project → Export SVG → Choose layers to export…** selects the group for
- **Project → Export → Export SVG → Choose layers to export…** selects the group for
**Selected layers…**. **Specific layer…** remains available for individual layers,
including hidden layers.
- Midra send preparation has **Choose editor layers to send…**, followed by a
@ -618,3 +617,5 @@ The shared pickers update the viewport selection. Hidden/locked layers are label
and disabled in these pickers; choosing layers changes no geometry. Full project
save/load and screen reference images are document-wide operations, so they have
no layer mapping.
**Apply to Midra**, beside ONLINE/OFFLINE and in **Export**, sends the selected layers using the current destination mappings, screen, Preview/Program target and sizing strategy. If mapping is incomplete, it opens the send window first. Configure these choices in **Export → Configure Midra export…**. The action is disabled offline, during transfers, or when values already match the last snapshot. Sending writes directly and verifies readback; results appear in the send window. Only applied editor values are sent.