diff --git a/crates/midra-layout/src/device_ui.rs b/crates/midra-layout/src/device_ui.rs index dbbad1e..f01e7ba 100644 --- a/crates/midra-layout/src/device_ui.rs +++ b/crates/midra-layout/src/device_ui.rs @@ -16,6 +16,7 @@ enum Destination { #[derive(Default)] pub(super) struct DeviceUi { pub open: bool, + import_closing: bool, pub(super) connection_open: bool, pub(super) prepare_send: bool, target: Target, @@ -380,6 +381,7 @@ impl Editor { let mut imported = false; let mut send_plan = None; egui::Window::new(if self.device.prepare_send { "Send layers to Midra" } else { "Import layers from Midra" }) + .enabled(!self.format_draft.as_ref().is_some_and(|d| d.pending(&self.layout))) .open(&mut open).default_width(660.0).collapsible(false) .max_height((ctx.screen_rect().height() - 100.0).max(200.0)).vscroll(true) .show(ctx, |ui| { @@ -462,24 +464,42 @@ impl Editor { ui.weak("Centered layers import visible bounds and crop framing. Other modes import container geometry only. Source routing, shared input settings and effects stay on the device."); let selected: Vec<_> = self.device.destinations.iter().enumerate().filter_map(|(i, dest)| (*dest != Destination::Skip).then_some(i)).collect(); ui.label(format!("{} device layers to import", selected.len())); - if ui.add_enabled(matches && !selected.is_empty(), egui::Button::new("Import layers")).clicked() { - let result = screen.import(&selected).and_then(|_| { - let values: Vec<_> = selected.iter().map(|&i| { - let target = match self.device.destinations[i] { - Destination::Existing(id) => Some(id), - _ => None, - }; - (target, screen.layers[i].geometry, screen.layers[i].framing) - }).collect(); - self.layout.import_device_layers(&values) - }); - match result { Ok(()) => imported = true, Err(e) => self.device.error = e } + if apply_button(ui, "Import layers", matches && !selected.is_empty()).clicked() { + match self.apply_device_import() { Ok(()) => imported = true, Err(e) => self.device.error = e } } ui.weak("Choose an existing destination or New layer beside each device layer. Your editor selection does not limit this import."); } ui.separator(); }); + if !open + && !self.device.prepare_send + && self + .device + .destinations + .iter() + .any(|d| *d != Destination::Skip) + { + self.device.import_closing = true; + } + if self.device.import_closing { + open = true; + match pending_close(ctx, "device-import-close", &self.device.error) { + Some(true) => { + self.device.import_closing = false; + match self.apply_device_import() { + Ok(()) => imported = true, + Err(e) => self.device.error = e, + } + } + Some(false) => { + self.device.import_closing = false; + self.device.reset_mappings(); + open = false; + } + None => {} + } + } self.device.open = open; if let Some(plan) = send_plan { self.device.send(ctx, vec![plan]); @@ -488,8 +508,39 @@ impl Editor { self.sync(); self.device.error.clear(); self.device.open = false; + self.device.reset_mappings(); } } + fn apply_device_import(&mut self) -> Result<(), String> { + let snapshot = self + .device + .snapshot + .as_ref() + .ok_or("Connect to Midra first.")?; + let screen = &snapshot.screens[self.device.screen]; + if screen.resolution != self.layout.formats().output { + return Err("Match output resolution before importing.".into()); + } + let selected: Vec<_> = self + .device + .destinations + .iter() + .enumerate() + .filter_map(|(i, d)| (*d != Destination::Skip).then_some(i)) + .collect(); + screen.import(&selected)?; + let values: Vec<_> = selected + .iter() + .map(|&i| { + let target = match self.device.destinations[i] { + Destination::Existing(id) => Some(id), + _ => None, + }; + (target, screen.layers[i].geometry, screen.layers[i].framing) + }) + .collect(); + self.layout.import_device_layers(&values) + } } #[allow(clippy::too_many_arguments)] @@ -689,6 +740,24 @@ mod tests { ) .unwrap() } + #[test] + fn closing_import_review_applies_locally_and_never_starts_a_send() { + let ctx = egui::Context::default(); + let mut app = Editor::default(); + let before = app.layout.layers().clone(); + app.device.snapshot = Some(linked_test_snapshot()); + app.device.destinations = vec![Destination::Existing(1), Destination::Skip]; + app.device.open = true; + app.device.import_closing = true; + super::super::tests::click_text(&mut app, &ctx, "Apply"); + assert!(!app.device.open); + assert!(!app.device.sending); + assert!(app.device.pending.is_none()); + assert_ne!(*app.layout.layers(), before); + app.layout.undo(); + assert_eq!(*app.layout.layers(), before); + } + #[test] fn startup_connection_requires_opt_in_and_an_address_and_never_sends() { let ctx = egui::Context::default(); diff --git a/crates/midra-layout/src/format_ui.rs b/crates/midra-layout/src/format_ui.rs index 002131d..3eebbe9 100644 --- a/crates/midra-layout/src/format_ui.rs +++ b/crates/midra-layout/src/format_ui.rs @@ -11,6 +11,8 @@ pub(super) enum PropertyTab { pub(super) struct FormatDraft { layer: usize, + baseline: (usize, Source, [f64; 2], [f64; 2], Framing), + crop_before: Option, source_id: usize, source: Source, input_size: [f64; 2], @@ -18,8 +20,55 @@ pub(super) struct FormatDraft { layer_aspect: Aspect, framing: Framing, error: String, + closing: bool, } impl FormatDraft { + pub(super) fn pending(&self, _layout: &Layout) -> bool { + ( + self.source_id, + self.source, + self.input_size, + self.size, + self.framing, + ) != self.baseline + } + fn apply_framing(&mut self, layout: &mut Layout, dragging: bool) -> Result<(), String> { + if dragging && self.crop_before.is_none() { + self.crop_before = Some(layout.clone()); + } + let mut next = self.crop_before.as_ref().unwrap_or(layout).clone(); + next.set_framing(self.layer, self.framing)?; + *layout = next; + self.framing = layout + .formats() + .mapping(self.layer, layout.layers()[self.layer])? + .framing; + self.baseline.4 = self.framing; + Ok(()) + } + fn apply(&mut self, layout: &mut Layout, corner: Corner) -> Result<(), String> { + let input = self.source.input()?; + if input + .iter() + .zip(self.input_size) + .any(|(a, b)| !b.is_finite() || (a - b).abs() > 1e-7) + { + return Err("Input resolution is invalid or does not match the crop edges.".into()); + } + let g = layout.layers()[self.layer]; + let [x, y] = corner.offsets_on(g, layout.formats().output); + let geometry = + corner.geometry_on(x, y, self.size[0], self.size[1], layout.formats().output)?; + let framing_changed = self.framing != layout.formats().mapping(self.layer, g)?.framing; + if framing_changed { + midra_layout::formats::crop_from_framing(input, self.size, self.framing)?; + } + layout.configure(self.layer, self.source_id, self.source, geometry, true)?; + if framing_changed { + layout.set_framing(self.layer, self.framing)?; + } + Ok(()) + } pub(super) fn is_for(&self, layer: usize) -> bool { self.layer == layer } @@ -29,6 +78,14 @@ impl FormatDraft { let g = layout.layers()[i]; Self { layer: i, + crop_before: None, + baseline: ( + source_id, + source, + source.input().unwrap(), + [g.width, g.height], + layout.formats().mapping(i, g).unwrap().framing, + ), source_id, source, input_size: source.input().unwrap(), @@ -36,6 +93,7 @@ impl FormatDraft { layer_aspect: Aspect::Custom, framing: layout.formats().mapping(i, g).unwrap().framing, error: String::new(), + closing: false, } } } @@ -44,8 +102,12 @@ pub(super) struct OutputDraft { aspect: Aspect, locked: bool, error: String, + closing: bool, } impl OutputDraft { + pub(super) fn pending(&self, layout: &Layout) -> bool { + self.size != layout.formats().output.map(f64::from) + } pub(super) fn new(output: [u32; 2]) -> Self { Self { size: output.map(f64::from), @@ -59,6 +121,7 @@ impl OutputDraft { .unwrap_or(Aspect::Custom), locked: false, error: String::new(), + closing: false, } } } @@ -129,6 +192,7 @@ impl Editor { return; }; let mut open = true; + let previous_size = d.size; egui::Window::new("Output format / viewport resolution").open(&mut open).default_width(470.0).show(ctx,|ui| { ui.horizontal_wrapped(|ui| {for (name,value) in [("HD",[1280.0,720.0]),("Full HD",[1920.0,1080.0]),("UHD 4K",[3840.0,2160.0])] { if ui.button(name).clicked() {d.size=value;d.aspect=Aspect::SixteenNine;} @@ -147,7 +211,7 @@ impl Editor { } ui.label(format!("Proposed output: {:.1} × {:.1} px. Linked dimensions round the other side to whole pixels.",d.size[0],d.size[1])); ui.label("Changing output preserves layer positions and sizes. Custom dimensions are planning sizes, not verified device modes."); - if apply_button(ui,"Apply output resolution", d.size != self.layout.formats().output.map(f64::from)).clicked() { + if apply_button(ui,"Apply output resolution", d.size != self.layout.formats().output.map(f64::from)).clicked() || d.size != previous_size { match midra_layout::formats::resolution_from_values(d.size).and_then(|size|self.layout.set_output(size)) { Ok(())=>{ self.zoom=1.0;self.pan=Vec2::ZERO;self.sync(); d.error.clear(); },Err(e)=>d.error=e } } if !d.error.is_empty() { ui.colored_label(theme::palette(ui.ctx()).amber,&d.error); } @@ -160,7 +224,31 @@ impl Editor { if ui.button("1:1 display pixels").clicked() {self.camera_one_to_one=true;} }); }); - if open { + if !open && d.size != self.layout.formats().output.map(f64::from) { + d.closing = true; + } + if d.closing { + match pending_close(ctx, "output-close", &d.error) { + Some(true) => match midra_layout::formats::resolution_from_values(d.size) + .and_then(|size| self.layout.set_output(size)) + { + Ok(()) => { + self.zoom = 1.0; + self.pan = Vec2::ZERO; + self.sync(); + return; + } + Err(e) => { + d.error = e; + d.closing = false; + open = true; + } + }, + Some(false) => return, + None => {} + } + } + if open || d.closing { self.output_draft = Some(d); } } @@ -245,18 +333,16 @@ impl Editor { Err(e)=>{ ui.colored_label(theme::palette(ui.ctx()).amber,e); }, _=>{} } - let pending = d.source_id != self.layout.formats().source_for[i] - || d.source != self.layout.formats().sources[d.source_id] - || d.size != [g.width, g.height]; - if apply_button(ui,"Apply source / input / layer formats", reviewed.is_ok() && pending).clicked() { - let result=self.corner.geometry_on(x,y,d.size[0],d.size[1],self.layout.formats().output).and_then(|g|self.layout.configure(i,d.source_id,d.source,g,true)); - match result { Ok(_)=>{self.sync();d=FormatDraft::new(&self.layout,i);},Err(e)=>d.error=e } + 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 } } ui.small("Apply commits pending Source and Layer changes together. Switching tabs keeps your edits."); } if self.property_tab == PropertyTab::Crop { ui.heading("Layer crop / zoom & position"); 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."); + let before_framing=d.framing; let mut percent=d.framing.zoom*100.0; ui.horizontal(|ui| { if ui.add(egui::DragValue::new(&mut percent).speed(1.0).custom_formatter(|v,_|number(v)).suffix("% content zoom")).changed() {d.framing.zoom=percent/100.0;} @@ -269,22 +355,24 @@ impl Editor { } ui.horizontal(|ui| { let current_framing=self.layout.formats().mapping(i,current).unwrap().framing; - let pending=d.framing != current_framing; - let apply=apply_button(ui,"Apply crop",pending).clicked(); + let apply=d.framing != before_framing; + let _ = current_framing; let recenter=ui.button("Recenter").clicked(); let reset=ui.button("Reset crop").clicked(); if recenter { d.framing=self.layout.formats().mapping(i,current).unwrap().framing; d.framing.offset=[0.0;2]; } if reset {d.framing=Framing::default();} if apply||recenter||reset { - match self.layout.set_framing(i,d.framing) {Ok(())=>{self.sync();d.error.clear();d.framing=self.layout.formats().mapping(i,current).unwrap().framing;},Err(e)=>d.error=e} + match d.apply_framing(&mut self.layout, ui.input(|input| input.pointer.primary_down())) {Ok(())=>{self.sync();d.error.clear();},Err(e)=>d.error=e} } }); + if !ui.input(|input| input.pointer.primary_down()) { d.crop_before = None; } if ui.add(egui::Button::new(if self.edit_content { "Done adjusting crop" } else { "Adjust layer crop" }).selected(self.edit_content)).clicked() { self.edit_content = !self.edit_content; } let (_,rect)=ui.allocate_space(Vec2::new(ui.available_width(),170.0)); let preview_rect=fit_rect(rect,[current.width,current.height]); paint_pattern(ui.painter(),preview_rect,self.layout.formats().sources[self.layout.formats().source_for[i]],self.layout.formats().advanced[i]); + ui.small("Crop zoom and offsets apply as you edit. Undo restores earlier values."); ui.label("Source test pattern only; the screen reference image is not source content."); } if !d.error.is_empty() {ui.colored_label(theme::palette(ui.ctx()).amber,&d.error);} @@ -295,7 +383,27 @@ impl Editor { } }); }); - if open { + if !open && d.pending(&self.layout) { + d.closing = true; + } + 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; + } + Err(e) => { + d.error = e; + d.closing = false; + open = true; + } + }, + Some(false) => return, + None => {} + } + } + if open || d.closing { self.format_draft = Some(d); } } @@ -418,28 +526,146 @@ fn paint_pattern_clipped( #[cfg(test)] mod tests { - use super::super::tests::{frame, mouse}; + use super::super::tests::{click_text, frame, mouse}; use super::*; - fn click_text(app: &mut Editor, ctx: &egui::Context, text: &str) { - frame(app, ctx, vec![]); - let output = frame(app, ctx, vec![]); + #[test] + fn crop_control_drag_applies_without_a_button_and_keeps_pending_source_edits() { + let ctx = egui::Context::default(); + let mut app = Editor { + property_tab: PropertyTab::Crop, + ..Default::default() + }; + let before = app.layout.formats().clone(); + let mut draft = FormatDraft::new(&app.layout, 1); + draft.size = [800.0, 450.0]; + app.format_draft = Some(draft); + frame(&mut app, &ctx, vec![]); + let output = 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 == text => { + egui::Shape::Text(t) if t.galley.text().ends_with("% content zoom") => { Some(t.pos + Vec2::new(12.0, 5.0)) } _ => None, }) - .unwrap_or_else(|| panic!("Button not rendered: {text}")); + .expect("content zoom control"); frame( - app, - ctx, + &mut app, + &ctx, vec![egui::Event::PointerMoved(pos), mouse(pos, true)], ); - frame(app, ctx, vec![mouse(pos, false)]); + for distance in [15.0, 30.0, 50.0] { + frame( + &mut app, + &ctx, + vec![egui::Event::PointerMoved(pos + Vec2::new(distance, 0.0))], + ); + } + frame( + &mut app, + &ctx, + vec![mouse(pos + Vec2::new(50.0, 0.0), false)], + ); + assert!( + app.layout + .formats() + .mapping(1, app.layout.layers()[1]) + .unwrap() + .framing + .zoom + > 1.0 + ); + assert_eq!(app.format_draft.as_ref().unwrap().size, [800.0, 450.0]); + assert_eq!(app.layout.layers()[1].width, 640.0); + app.layout.undo(); + assert_eq!(*app.layout.formats(), before); } + + #[test] + fn output_preset_applies_without_an_apply_click() { + let mut app = Editor::default(); + let ctx = egui::Context::default(); + let geometry = app.layout.layers().clone(); + app.output_draft = Some(OutputDraft::new(app.layout.formats().output)); + click_text(&mut app, &ctx, "HD"); + assert_eq!(app.layout.formats().output, [1280, 720]); + assert_eq!(*app.layout.layers(), geometry); + app.layout.undo(); + assert_eq!(app.layout.formats().output, [1920, 1080]); + } + + #[test] + fn crop_drag_updates_immediately_and_undo_restores_the_whole_gesture() { + let mut app = Editor::default(); + let before = app.layout.formats().clone(); + let mut draft = FormatDraft::new(&app.layout, 1); + for zoom in [1.2, 1.5, 2.0] { + draft.framing.zoom = zoom; + draft.apply_framing(&mut app.layout, true).unwrap(); + assert!( + (app.layout + .formats() + .mapping(1, app.layout.layers()[1]) + .unwrap() + .framing + .zoom + - zoom) + .abs() + < 1e-9 + ); + assert!(!draft.pending(&app.layout)); + } + app.layout.undo(); + assert_eq!(*app.layout.formats(), before); + } + + #[test] + fn closing_formats_applies_or_discards_and_invalid_apply_keeps_the_draft() { + let ctx = egui::Context::default(); + let mut app = Editor::default(); + let before = app.layout.layers().clone(); + let mut draft = FormatDraft::new(&app.layout, 1); + draft.size = [800.0, 450.0]; + draft.closing = true; + app.format_draft = Some(draft); + click_text(&mut app, &ctx, "Discard"); + assert!(app.format_draft.is_none()); + assert_eq!(*app.layout.layers(), before); + let mut draft = FormatDraft::new(&app.layout, 1); + draft.input_size = [99999.0, 1080.0]; + draft.closing = true; + app.format_draft = Some(draft); + click_text(&mut app, &ctx, "Apply"); + let draft = app.format_draft.as_mut().unwrap(); + assert!(!draft.closing); + assert!(!draft.error.is_empty()); + assert_eq!(*app.layout.layers(), before); + draft.input_size = [1920.0, 1080.0]; + draft.size = [800.0, 450.0]; + draft.closing = true; + click_text(&mut app, &ctx, "Apply"); + assert!(app.format_draft.is_none()); + assert_eq!(app.layout.layers()[1].width, 800.0); + app.layout.undo(); + assert_eq!(*app.layout.layers(), before); + } + + #[test] + fn unrelated_sync_preserves_source_draft_but_refreshes_clean_properties() { + let mut app = Editor::default(); + let mut draft = FormatDraft::new(&app.layout, 1); + draft.size = [800.0, 450.0]; + app.format_draft = Some(draft); + app.sync(); + assert_eq!(app.format_draft.as_ref().unwrap().size, [800.0, 450.0]); + app.format_draft = Some(FormatDraft::new(&app.layout, 1)); + app.layout.select(Some(0)); + app.sync(); + assert!(app.format_draft.as_ref().unwrap().is_for(0)); + } + #[test] fn property_tabs_keep_pending_edits_and_show_only_their_controls() { let mut app = Editor::default(); diff --git a/crates/midra-layout/src/gui.rs b/crates/midra-layout/src/gui.rs index 01b86bc..8d3f9b4 100644 --- a/crates/midra-layout/src/gui.rs +++ b/crates/midra-layout/src/gui.rs @@ -30,6 +30,9 @@ pub struct Editor { files: project_ui::FileUi, corner: Corner, fields: [String; 4], + field_rects: [Rect; 4], + fields_closing: bool, + fields_edited: bool, error: String, paste: Option, zoom: f32, @@ -74,6 +77,7 @@ struct Paste { include_position: bool, include_zoom: bool, include_outline: bool, + closing: bool, error: String, } impl Paste { @@ -225,6 +229,9 @@ impl Default for Editor { files: project_ui::FileUi::default(), corner: Corner::TopRight, fields: Default::default(), + field_rects: [Rect::NOTHING; 4], + fields_closing: false, + fields_edited: false, error: String::new(), paste: None, zoom: 1.0, @@ -450,6 +457,7 @@ impl Editor { self.reference_open = open; } fn sync(&mut self) { + self.fields_edited = false; if self.layout.selected_indices().len() < 2 { self.resize_mode = ResizeMode::Individual; } @@ -459,7 +467,11 @@ impl Editor { self.fields = [number(x), number(y), number(g.width), number(g.height)]; } self.error = self.layout.gesture_error.clone().unwrap_or_default(); - if self.format_draft.is_some() { + if self + .format_draft + .as_ref() + .is_some_and(|d| !d.pending(&self.layout)) + { self.format_draft = self .layout .selected() @@ -487,6 +499,7 @@ impl Editor { include_position: true, include_zoom: true, include_outline: false, + closing: false, error: String::new(), }; if !p.text.is_empty() { @@ -627,7 +640,11 @@ impl Editor { self.preferences_open = true; return; } - if self.paste.is_some() { + if self.paste.is_some() + || self.format_draft.is_some() + || self.output_draft.is_some() + || self.layer_ui.open + { return; } if ctx.input(|i| i.key_pressed(egui::Key::Escape)) { @@ -817,7 +834,26 @@ impl Editor { } if ui.button("Cancel").clicked() {close=true;} }); - if !close && !response.should_close() { + if response.should_close() && !close && !p.shapes.is_empty() { + p.closing = true; + } + if p.closing { + match pending_close(ctx, "paste-close", &p.error) { + Some(true) => match p.apply(&mut self.layout) { + Ok(()) => { + self.sync(); + close = true; + } + Err(e) => { + p.error = e; + p.closing = false; + } + }, + Some(false) => close = true, + None => {} + } + } + if !close && (!response.should_close() || !p.shapes.is_empty()) { self.paste = Some(p); } } @@ -1072,6 +1108,7 @@ impl Editor { ] { ink.text(x, y, title, 12.0, palette.muted); let rect = Rect::from_min_size(ink.point(x, y + 23.0), Vec2::new(half, 42.0)); + self.field_rects[index] = rect; let response = ui.put( rect, egui::TextEdit::singleline(&mut self.fields[index]) @@ -1079,6 +1116,9 @@ impl Editor { .font(egui::FontId::proportional(18.0)) .margin(Vec2::new(12.0, 10.0)), ); + if response.changed() { + self.fields_edited = true; + } if response.changed() && self.keep_aspect_ratio && index >= 2 @@ -1093,7 +1133,9 @@ impl Editor { }; self.fields[if index == 2 { 3 } else { 2 }] = number(other); } - if response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + if response.lost_focus() + && (self.fields_edited || ui.input(|i| i.key_pressed(egui::Key::Enter))) + { enter = true; } } @@ -2344,6 +2386,31 @@ fn click(ui: &egui::Ui, ink: &Ink, b: [f32; 4], id: impl std::hash::Hash) -> boo } impl Editor { fn ui(&mut self, ctx: &egui::Context) { + if self.fields_edited + && self.fields_pending() + && !self.layout.dragging() + && ctx.input(|input| { + input.pointer.any_pressed() + && input + .pointer + .interact_pos() + .is_some_and(|p| !self.field_rects.iter().any(|r| r.contains(p))) + }) + { + self.apply_fields(); + self.fields_closing = self.fields_pending(); + } + let blocked = self.fields_closing + || self + .format_draft + .as_ref() + .is_some_and(|d| d.pending(&self.layout)) + || self + .output_draft + .as_ref() + .is_some_and(|d| d.pending(&self.layout)) + || (self.layer_ui.open && self.names_pending()) + || self.layer_ui.rename.is_some(); self.poll_reference(); let palette = theme::palette(ctx); let dropped = ctx.input(|i| i.raw.dropped_files.clone()); @@ -2355,11 +2422,16 @@ impl Editor { "Drop one reference image at a time; current image kept.".into(); } } - self.shortcuts(ctx); + if !blocked { + self.shortcuts(ctx); + } egui::TopBottomPanel::top("header") .exact_height(44.0) .frame(egui::Frame::NONE.fill(palette.panel)) .show(ctx, |ui| { + if blocked { + ui.disable(); + } let r = ui.max_rect(); let ink = Ink::new(ui, r); ink.text(24.0, 11.0, "MIDRA / LAYOUT", 18.0, palette.text); @@ -2392,6 +2464,9 @@ impl Editor { .exact_height(34.0) .frame(egui::Frame::NONE.fill(palette.panel)) .show(ctx, |ui| { + if blocked { + ui.disable(); + } let r = ui.max_rect(); let ink = Ink::new(ui, r); ink.painter @@ -2455,13 +2530,21 @@ impl Editor { .resizable(false) .frame(egui::Frame::NONE.fill(palette.panel).inner_margin(24.0)) .show(ctx, |ui| { + if blocked { + ui.disable(); + } egui::ScrollArea::vertical() .drag_to_scroll(false) .show(ui, |ui| self.inspector(ui)); }); egui::CentralPanel::default() .frame(egui::Frame::NONE.fill(palette.bg)) - .show(ctx, |ui| self.workspace(ui)); + .show(ctx, |ui| { + if blocked { + ui.disable(); + } + self.workspace(ui) + }); self.paste_window(ctx); self.reference_window(ctx); self.output_window(ctx); @@ -2471,6 +2554,19 @@ impl Editor { self.device_window(ctx); self.layers_window(ctx); self.theme_window(ctx); + if self.fields_closing { + match pending_close(ctx, "fields-close", &self.error) { + Some(true) => { + self.apply_fields(); + self.fields_closing = false; + } + Some(false) => { + self.sync(); + self.fields_closing = false; + } + None => {} + } + } } } @@ -2556,6 +2652,28 @@ fn alignment_icon( response.on_hover_text(title) } +// Closing a draft is a separate decision from sending anything to a device. +fn pending_close(ctx: &egui::Context, id: &str, error: &str) -> Option { + egui::Modal::new(egui::Id::new(id)) + .show(ctx, |ui| { + ui.heading("Would you like to apply changes?"); + if !error.is_empty() { + ui.colored_label(ui.visuals().error_fg_color, error); + } + ui.horizontal(|ui| { + if apply_button(ui, "Apply", true).clicked() { + Some(true) + } else if ui.button("Discard").clicked() { + Some(false) + } else { + None + } + }) + .inner + }) + .inner +} + fn apply_button(ui: &mut egui::Ui, label: &str, pending: bool) -> egui::Response { let palette = theme::palette(ui.ctx()); let button = egui::Button::new(label) @@ -2821,6 +2939,60 @@ mod tests { modifiers: egui::Modifiers::NONE, } } + pub(super) fn click_text(app: &mut Editor, ctx: &egui::Context, text: &str) { + frame(app, ctx, vec![]); + let output = frame(app, ctx, vec![]); + let pos = output + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::epaint::Shape::Text(t) if t.galley.job.text == text => { + Some(t.pos + Vec2::new(12.0, 5.0)) + } + _ => None, + }) + .unwrap_or_else(|| panic!("Button not rendered: {text}")); + frame( + app, + ctx, + vec![egui::Event::PointerMoved(pos), mouse(pos, true)], + ); + frame(app, ctx, vec![mouse(pos, false)]); + } + #[test] + fn leaving_numeric_fields_commits_before_selection_changes_and_invalid_edits_prompt() { + let ctx = egui::Context::default(); + let mut app = Editor::default(); + frame(&mut app, &ctx, vec![]); + app.fields[0] = "200".into(); + app.fields_edited = true; + let pos = Pos2::new(20.0, 15.0); + frame( + &mut app, + &ctx, + vec![egui::Event::PointerMoved(pos), mouse(pos, true)], + ); + frame(&mut app, &ctx, vec![mouse(pos, false)]); + assert_eq!( + app.corner + .offsets_on(app.layout.layers()[1], app.layout.formats().output)[0], + 200.0 + ); + assert!(!app.fields_pending()); + app.fields[0] = "invalid".into(); + app.fields_edited = true; + let before = app.layout.layers().clone(); + frame( + &mut app, + &ctx, + vec![egui::Event::PointerMoved(pos), mouse(pos, true)], + ); + frame(&mut app, &ctx, vec![mouse(pos, false)]); + assert!(app.fields_closing); + assert_eq!(*app.layout.layers(), before); + assert_eq!(app.fields[0], "invalid"); + } + #[test] fn paste_review_rejects_replaced_layer_with_same_list_index() { let mut app = Editor::default(); @@ -3716,7 +3888,7 @@ mod tests { } } #[test] - fn paste_opens_review_without_editing_and_escape_cancels() { + fn paste_opens_review_without_editing_and_escape_asks_before_discarding() { let mut app = Editor::default(); let ctx = egui::Context::default(); frame(&mut app, &ctx, vec![]); @@ -3733,7 +3905,7 @@ mod tests { assert_eq!(p.targets, vec![1]); assert_eq!(p.shapes[0].geometry.width, 945.0); frame(&mut app, &ctx, vec![key(egui::Key::Escape)]); - assert!(app.paste.is_none()); + assert!(app.paste.as_ref().unwrap().closing); assert_eq!(*app.layout.layers(), before); } #[test] diff --git a/crates/midra-layout/src/layers_ui.rs b/crates/midra-layout/src/layers_ui.rs index 1ae0055..d35f80d 100644 --- a/crates/midra-layout/src/layers_ui.rs +++ b/crates/midra-layout/src/layers_ui.rs @@ -7,9 +7,24 @@ pub(super) struct LayerUi { pub(super) rename_focus: bool, drafts: Vec<(usize, String, String)>, error: String, + closing: bool, + rename_closing: bool, + deferred: u8, folder_filter: Option, } impl Editor { + pub(super) fn names_pending(&self) -> bool { + self.layer_ui + .drafts + .iter() + .enumerate() + .any(|(i, (id, name, folder))| { + i >= self.layout.layers().len() + || self.layout.layer_info(i).id != *id + || self.layout.layer_info(i).name != name.trim() + || self.layout.layer_info(i).folder != folder.trim() + }) + } pub(super) fn manage_layers(&mut self) { self.layer_ui.open = true; self.layer_ui.drafts = (0..self.layout.layers().len()) @@ -75,6 +90,22 @@ impl Editor { cancel |= ui.button("Cancel").clicked(); }); }); + if !open && name.trim() != self.layout.layer_info(i).name { + self.layer_ui.rename_closing = true; + } + if self.layer_ui.rename_closing { + match pending_close(ctx, "rename-close", &self.error) { + Some(true) => { + apply = true; + self.layer_ui.rename_closing = false; + } + Some(false) => { + cancel = true; + self.layer_ui.rename_closing = false; + } + None => {} + } + } if apply { let folder = self.layout.layer_info(i).folder.clone(); match self.layout.rename_layer(i, &name, &folder) { @@ -84,9 +115,12 @@ impl Editor { self.manage_layers(); } } - Err(error) => self.error = error, + Err(error) => { + self.error = error; + self.layer_ui.rename = Some((id, name)); + } } - } else if open && !cancel { + } else if (open || self.layer_ui.rename_closing) && !cancel { self.layer_ui.rename = Some((id, name)); } } @@ -100,7 +134,7 @@ impl Editor { let mut remove = false; let mut refresh = false; let mut sync = false; - egui::Window::new("Layers & folders").open(&mut open).default_width(650.0).show(ctx, |ui| { + egui::Window::new("Layers & folders").enabled(!self.format_draft.as_ref().is_some_and(|d| d.pending(&self.layout))).open(&mut open).default_width(650.0).show(ctx, |ui| { ui.horizontal(|ui| { add = ui.add_enabled(self.layout.layers().len() < 256, egui::Button::new("Add layer")).clicked(); let count = self.layout.selected_indices().len(); @@ -142,6 +176,47 @@ impl Editor { } if !self.layer_ui.error.is_empty() { ui.colored_label(ui.visuals().error_fg_color, &self.layer_ui.error); } }); + if (!open || add || remove || refresh) && self.names_pending() { + self.layer_ui.closing = true; + self.layer_ui.deferred = if add { + 1 + } else if remove { + 2 + } else if refresh { + 3 + } else { + 0 + }; + } + if self.layer_ui.closing { + add = false; + remove = false; + refresh = false; + open = true; + let choice = pending_close(ctx, "names-close", &self.layer_ui.error); + if let Some(apply) = choice { + let result = if apply { + self.layout.rename_layers(&self.layer_ui.drafts) + } else { + Ok(()) + }; + match result { + Ok(()) => { + self.layer_ui.closing = false; + open = self.layer_ui.deferred != 0; + add = self.layer_ui.deferred == 1; + remove = self.layer_ui.deferred == 2; + refresh = self.layer_ui.deferred == 3; + self.layer_ui.error.clear(); + self.sync(); + } + Err(e) => { + self.layer_ui.error = e; + self.layer_ui.closing = false; + } + } + } + } self.layer_ui.open = open; if sync { self.sync(); @@ -159,6 +234,28 @@ impl Editor { #[cfg(test)] mod tests { use super::*; + #[test] + fn closing_batch_names_applies_or_discards_without_losing_identity() { + let ctx = egui::Context::default(); + let mut app = Editor::default(); + app.manage_layers(); + let id = app.layout.layer_info(1).id; + app.layer_ui.drafts[1].1 = "Camera".into(); + app.layer_ui.closing = true; + super::super::tests::click_text(&mut app, &ctx, "Apply"); + assert!(!app.layer_ui.open); + assert_eq!(app.layout.layer_info(1).name, "Camera"); + assert_eq!(app.layout.layer_info(1).id, id); + app.layout.undo(); + assert_eq!(app.layout.layer_info(1).name, "Slides"); + app.manage_layers(); + app.layer_ui.drafts[1].1 = "Discarded".into(); + app.layer_ui.closing = true; + super::super::tests::click_text(&mut app, &ctx, "Discard"); + assert!(!app.layer_ui.open); + assert_eq!(app.layout.layer_info(1).name, "Slides"); + } + #[test] fn inspector_sections_follow_the_variable_layer_list() { let ctx = egui::Context::default(); diff --git a/docs/interfaces/midra-device-send.md b/docs/interfaces/midra-device-send.md index 0c13b8c..827def3 100644 --- a/docs/interfaces/midra-device-send.md +++ b/docs/interfaces/midra-device-send.md @@ -106,3 +106,8 @@ geometry, and hidden or locked editor destinations reject the complete import without changing the document. Unlock/show destinations before loading. Results appear in the transfer window or the load button's status tooltip. No project or settings schema changes are involved. + +Closing a device import review with chosen destinations offers Apply/Discard. +Apply imports into the local editor atomically; it never writes to the device. +Closing send configuration does not send. Local property edits that apply +immediately still require an explicit device Send action. diff --git a/docs/midra-layout.md b/docs/midra-layout.md index 381064b..f17d64d 100644 --- a/docs/midra-layout.md +++ b/docs/midra-layout.md @@ -125,11 +125,11 @@ clipboard testing against a running draw.io instance remains to be done. Drag a corner handle to resize that layer, or use the single-layer numeric fields. - Arrow keys move the selection by **1 px**; Shift-arrow moves it by **10 px**. - Choose one of the four corner markers. Switching corner changes the displayed - offsets without moving the layer. Enter offsets, width and height, then click - **Apply position / size** or press Enter in a field. Resizing preserves that + offsets without moving the layer. Position and size edits apply when you leave + a field or press Enter; **Apply position / size** is also available. Resizing preserves that corner's offsets. Invalid values leave the document unchanged. - **Escape** cancels a drag or restores uncommitted numeric fields. In the paste - dialog it closes the preview without applying it. Group drags cancel atomically. + dialog it asks whether to Apply or Discard detected values. Group drags cancel atomically. - The history toolbar icons (**Undo/Redo**) or Ctrl/Cmd-Z, Ctrl/Cmd-Shift-Z (also Ctrl/Cmd-Y) reverse edits. Each drag, alignment, applied paste or numeric edit is one step; retain 100 undo records. View changes and selection are not document edits. @@ -294,6 +294,8 @@ Open the **Output format** icon (screen with sliders), first in the toolbar, for sizes support 1–16384 pixels per side as an implementation limit, not a promise of hardware support. Layer positions/sizes remain unchanged; screen-corner coordinates, alignment, reference-image mapping and warnings use the new output. +Valid output presets and numeric resolution edits apply immediately; invalid drafts +leave the output unchanged and are retained for correction. The same window offers numeric camera zoom relative to fit-to-screen and a **1:1 display pixels** action; camera changes never modify crop geometry. @@ -309,7 +311,8 @@ Select one layer and click its **Layer resolution** card to open **Layer propert enter an independent custom width and height. Apply source/input/layer changes together; the selected screen-corner anchor stays fixed. 4. Use **Layer crop / zoom & position** for zoom (100–10000%) and X/Y offsets in output pixels. - These controls operate on the applied formats. **Apply crop** is one edit; + These controls operate on the applied formats and update immediately as edited. + A continuous zoom/offset drag is one Undo step; **Recenter** preserves zoom; **Reset crop** returns to the minimum centered cover crop. Invalid typed offsets show the permitted range and do not apply. 5. Click **Adjust layer crop** in the selected layer’s parameters, below its format @@ -363,14 +366,30 @@ to both kinds of resize handles. Apply buttons are muted and disabled when their values already match the layout. Pending changes make Apply solid purple. This applies to position/size, output -resolution, source/input/layer formats, crop framing, and mapped imports. Each +resolution drafts, source/input/layer formats, names/folders, and mapped imports. Each section tracks its own values; reverting an edit clears its pending state. Layer properties has three tabs: **Source** for native/input resolution and input crop, **Layer** for the final visible box, and **Crop** for content zoom and offset. The three right-click properties entries open their matching tab directly. Switching tabs retains pending edits. Source and Layer changes still apply together -with their shared Apply button; Crop has its own Apply button. +with their shared Apply button; Crop applies immediately without a separate button. + +Closing a window with unapplied source/layer formats, invalid output values, +layer names/folders, a rename, or mapped Midra imports asks **Would you like to +apply changes?**, with **Apply** and **Discard**. Invalid Apply returns to the +editor with the draft and error intact. Escape or clicking outside clipboard/SVG +review asks the same question; its explicit Cancel button discards the review. +Adding/removing layers while batch names are pending also resolves those names +first. Pending property/name edits temporarily disable the main workspace to +prevent a selection change from replacing the draft. Switching property tabs +keeps drafts, including when live crop controls are used. + +Reference display, camera, theme and preference controls already apply immediately. +Device destination links also save to the local document immediately. Device +sends remain explicit: closing export configuration never sends, and local +Apply/Discard prompts never write to Midra. This does not change project save or +application-exit behavior; save the project to retain applied edits across launches. While adjusting a layer crop, click empty canvas or another layer to leave crop mode and select normally. Clicking or dragging the visible image or its faded