diff --git a/crates/midra-layout/src/device_ui.rs b/crates/midra-layout/src/device_ui.rs index e8c6f85..b43b769 100644 --- a/crates/midra-layout/src/device_ui.rs +++ b/crates/midra-layout/src/device_ui.rs @@ -5,6 +5,30 @@ use midra_layout::{ }; use std::sync::mpsc::{self, Receiver, TryRecvError}; +#[derive(Clone, Debug, Default, PartialEq)] +pub(super) enum TransferScope { + #[default] + All, + Selected, + Folder(String), +} +impl TransferScope { + fn indices(&self, layout: &midra_layout::Layout) -> Vec { + match self { + Self::All => (0..layout.layers().len()).collect(), + Self::Selected => layout.selected_indices(), + Self::Folder(folder) => layout.folder_members(folder), + } + } + fn label(&self) -> String { + match self { + Self::All => "All layers".into(), + Self::Selected => "Only selected layers".into(), + Self::Folder(folder) => format!("Folder: {folder}"), + } + } +} + #[derive(Clone, Copy, Default, PartialEq)] enum Destination { #[default] @@ -16,6 +40,7 @@ enum Destination { #[derive(Default)] pub(super) struct DeviceUi { pub open: bool, + pub(super) scope: TransferScope, import_closing: bool, pub(super) connection_open: bool, pub(super) prepare_send: bool, @@ -31,6 +56,7 @@ pub(super) struct DeviceUi { loading: Option>, screen: usize, destinations: Vec, + mapping_scope: Option<(TransferScope, Vec, String)>, error: String, } impl DeviceUi { @@ -41,6 +67,7 @@ impl DeviceUi { } pub(super) fn reset_mappings(&mut self) { self.destinations.fill(Destination::Skip); + self.mapping_scope = None; self.loading = None; } pub(super) fn with_connection_preferences(host: String, allow_program: bool) -> Self { @@ -50,29 +77,49 @@ impl DeviceUi { ..Self::default() } } - fn linked_plans(&self, layout: &midra_layout::Layout, all: bool) -> Result, String> { + fn scoped_links(&self, layout: &midra_layout::Layout) -> Vec<(usize, midra_layout::MidraLink)> { + self.scope + .indices(layout) + .into_iter() + .filter_map(|i| { + let info = layout.layer_info(i); + info.midra_link.clone().map(|link| (info.id, link)) + }) + .collect() + } + pub(super) fn set_scope(&mut self, scope: TransferScope) { + if self.scope != scope { + self.scope = scope; + self.destinations.fill(Destination::Skip); + self.mapping_scope = None; + self.message.clear(); + self.error.clear(); + } + } + pub(super) fn follow_folder(&mut self, folder: &str) { + if matches!(self.scope, TransferScope::Folder(_)) { + self.set_scope(TransferScope::Folder(folder.into())); + } + } + fn linked_plans(&self, layout: &midra_layout::Layout) -> Result, String> { let snapshot = self.snapshot.as_ref().ok_or("Connect to Midra first.")?; - let indices = if all { - (0..layout.layers().len()) - .filter(|&i| layout.layer_info(i).midra_link.is_some()) - .collect() - } else { - layout.selected_indices() - }; - if indices.is_empty() { - return Err("Choose layers and link their Midra destinations first.".into()); + let links = self.scoped_links(layout); + if links.is_empty() { + return Err( + "No linked layers in this scope. Choose a scope and map its Midra destinations." + .into(), + ); } let mut groups = std::collections::BTreeMap::>::new(); - for i in indices { - let info = layout.layer_info(i); - let link = info - .midra_link - .as_ref() - .ok_or_else(|| format!("{} has no Midra link.", info.name))?; + let mut used = std::collections::BTreeSet::new(); + for (id, link) in links { + if !used.insert((link.screen.clone(), link.layer.clone())) { + return Err("Several layers in this scope share a Midra destination. Choose one folder, use Only selected layers, or remap the conflicting links.".into()); + } groups - .entry(link.screen.clone()) + .entry(link.screen) .or_default() - .push((info.id, link.layer.clone())); + .push((id, link.layer)); } groups .into_iter() @@ -97,6 +144,49 @@ impl DeviceUi { }) .collect() } + fn seed_import_mapping(&mut self, layout: &midra_layout::Layout) { + let Some(snapshot) = &self.snapshot else { + return; + }; + let screen = &snapshot.screens[self.screen]; + let indices = self.scope.indices(layout); + let key = ( + self.scope.clone(), + indices + .iter() + .map(|&i| layout.layer_info(i).id) + .collect::>(), + screen.id.clone(), + ); + if self.mapping_scope.as_ref() == Some(&key) { + return; + } + if self.mapping_scope.is_some() || self.destinations.len() != screen.layers.len() { + self.destinations = vec![Destination::Skip; screen.layers.len()]; + } + for (j, layer) in screen.layers.iter().enumerate() { + if self.destinations[j] != Destination::Skip || layer.unsupported.is_some() { + continue; + } + let matches = indices + .iter() + .copied() + .filter(|&i| { + layout.visible(i) + && !layout.locked(i) + && layout + .layer_info(i) + .midra_link + .as_ref() + .is_some_and(|link| link.screen == screen.id && link.layer == layer.id) + }) + .collect::>(); + if let [i] = matches.as_slice() { + self.destinations[j] = Destination::Existing(layout.layer_info(*i).id); + } + } + self.mapping_scope = Some(key); + } pub(super) fn online(&self) -> bool { self.snapshot.is_some() } @@ -161,6 +251,7 @@ impl DeviceUi { self.screen = self.screen.min(snapshot.screens.len() - 1); self.destinations = vec![Destination::Skip; snapshot.screens[self.screen].layers.len()]; + self.mapping_scope = None; self.snapshot = Some(snapshot); } Err(error) => { @@ -175,7 +266,7 @@ impl DeviceUi { } } impl Editor { - pub(super) fn midra_load_button(&mut self, ui: &mut egui::Ui, all: bool) { + pub(super) fn midra_load_button(&mut self, ui: &mut egui::Ui) { let enabled = self.device.online() && self.device.pending.is_none(); let tooltip = if self.device.message.is_empty() { "Read fresh Preview geometry and cropping from Midra into the linked editor layers. Undo restores the previous layout." @@ -187,48 +278,53 @@ impl Editor { enabled, egui::Button::new(if self.device.loading.is_some() { "Loading…" - } else if all { - "Load linked layers" } else { - "Load mapped layers" + match self.device.scope { + TransferScope::All => "Load linked layers", + TransferScope::Selected => "Load selected links", + TransferScope::Folder(_) => "Load folder links", + } }), ) .on_hover_text(tooltip) .clicked() { - let indices: Vec<_> = if all { - (0..self.layout.layers().len()) - .filter(|&i| self.layout.layer_info(i).midra_link.is_some()) - .collect() - } else { - self.layout.selected_indices() - }; - let links: Result, String> = indices - .into_iter() - .map(|i| { - let info = self.layout.layer_info(i); - info.midra_link - .clone() - .map(|link| (info.id, link)) - .ok_or_else(|| format!("{} has no Midra link.", info.name)) - }) - .collect(); - match links { - Ok(links) if !links.is_empty() => { - self.device.fetch(ui.ctx()); - self.device.loading = Some(links); - } - result => { - self.device.error = result.err().unwrap_or_else(|| { - "Choose layers and link their Midra destinations first.".into() - }); - self.device.prepare_send = true; - self.device.open = true; - } - } + self.start_scoped_load(ui.ctx()); ui.close_menu(); } } + fn start_scoped_load(&mut self, ctx: &egui::Context) { + let links = self.device.scoped_links(&self.layout); + if links.is_empty() { + self.device.error = + "No linked layers in this scope. Map their destinations first.".into(); + self.device.prepare_send = true; + self.device.open = true; + return; + } + self.device.fetch(ctx); + self.device.loading = Some(links); + } + pub(super) fn midra_scope_picker(&mut self, ui: &mut egui::Ui) { + let before = self.device.scope.clone(); + egui::ComboBox::from_id_salt("midra-transfer-scope") + .width(175.0) + .selected_text(self.device.scope.label()) + .show_ui(ui, |ui| { + ui.selectable_value(&mut self.device.scope, TransferScope::All, "All layers"); + ui.selectable_value(&mut self.device.scope, TransferScope::Selected, "Only selected layers"); + ui.separator(); + for folder in self.layout.folders() { + ui.selectable_value(&mut self.device.scope, TransferScope::Folder(folder.clone()), format!("Folder: {folder}")); + } + }).response.on_hover_text("Scope for both Midra send and load. In Folder mode, clicking a folder in the layer list switches the scope."); + if before != self.device.scope { + self.device.destinations.fill(Destination::Skip); + self.device.mapping_scope = None; + self.device.error.clear(); + self.device.message.clear(); + } + } fn finish_linked_load(&mut self) { if self.device.pending.is_some() { return; @@ -259,13 +355,18 @@ impl Editor { } pub(super) fn open_midra_export(&mut self) { if let Some(snapshot) = &self.device.snapshot - && let Some(index) = self.layout.selected_indices().iter().find_map(|&i| { - let link = self.layout.layer_info(i).midra_link.as_ref()?; - snapshot - .screens - .iter() - .position(|screen| screen.id == link.screen) - }) + && let Some(index) = self + .device + .scope + .indices(&self.layout) + .iter() + .find_map(|&i| { + let link = self.layout.layer_info(i).midra_link.as_ref()?; + snapshot + .screens + .iter() + .position(|screen| screen.id == link.screen) + }) { self.device.screen = index; } @@ -285,7 +386,7 @@ impl Editor { } } pub(super) fn midra_send_button(&mut self, ui: &mut egui::Ui) { - let plans = self.device.linked_plans(&self.layout, true); + let plans = self.device.linked_plans(&self.layout); let enabled = self.device.online() && self.device.pending.is_none(); let tooltip = if self.device.sending { "Sending and checking readback…".into() @@ -306,7 +407,11 @@ impl Editor { if self.device.sending { "Applying…" } else { - "Send all linked layers" + match self.device.scope { + TransferScope::All => "Send all linked layers", + TransferScope::Selected => "Send selected links", + TransferScope::Folder(_) => "Send folder links", + } }, enabled, ) @@ -385,9 +490,15 @@ impl Editor { .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| { - if self.device.prepare_send { - self.transfer_layer_picker(ui, "Choose editor layers to send…"); + ui.horizontal(|ui| { + ui.label("Apply to"); + self.midra_scope_picker(ui); + }); + if self.device.scope == TransferScope::Selected { + self.transfer_layer_picker(ui, "Choose selected layers…"); } + let scope_indices = self.device.scope.indices(&self.layout); + ui.weak(format!("{} editor layers in scope · {} saved links. Unlinked layers are skipped by linked send/load.", scope_indices.len(), self.device.scoped_links(&self.layout).len())); ui.horizontal(|ui| { if ui.button("Connection settings…").clicked() { self.device.connection_open = true; } if ui.add_enabled(self.device.online() && self.device.pending.is_none(), egui::Button::new("Refresh layers")).clicked() { self.device.fetch(ctx); } @@ -399,6 +510,7 @@ impl Editor { } 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 !self.device.prepare_send { self.device.seed_import_mapping(&self.layout); } if let Some(snapshot) = &self.device.snapshot { ui.separator(); ui.strong(&snapshot.identity); @@ -409,18 +521,21 @@ impl Editor { for (i, screen) in snapshot.screens.iter().enumerate() { ui.selectable_value(&mut self.device.screen, i, format!("Screen {} · {} × {}", screen.id, screen.resolution[0], screen.resolution[1])); } }); let screen = &snapshot.screens[self.device.screen]; - if previous != self.device.screen { self.device.destinations = vec![Destination::Skip; screen.layers.len()]; } + if previous != self.device.screen { + self.device.destinations = vec![Destination::Skip; screen.layers.len()]; + self.device.mapping_scope = None; + } ui.label(format!("Captured Preview bank: {}. Refresh to read subsequent changes.", screen.preview_bank)); let matches = screen.resolution == self.layout.formats().output; if !matches { ui.colored_label(ui.visuals().warn_fg_color, format!("Device canvas {} × {}; editor {} × {}. Match output resolution before importing.", screen.resolution[0], screen.resolution[1], self.layout.formats().output[0], self.layout.formats().output[1])); } if self.device.prepare_send { let screen_id = screen.id.clone(); - let mut targets: std::collections::BTreeMap<_, _> = self.layout.selected_indices().into_iter().map(|i| { + let mut targets: std::collections::BTreeMap<_, _> = scope_indices.iter().copied().map(|i| { let info = self.layout.layer_info(i); (info.id, info.midra_link.as_ref().filter(|link| link.screen == screen_id).map(|link| link.layer.clone()).unwrap_or_default()) }).collect(); let previous = targets.clone(); - send_plan = send_review(ui, &self.layout, snapshot, self.device.screen, &mut targets, + send_plan = send_review(ui, &self.layout, &scope_indices, snapshot, self.device.screen, &mut targets, &mut self.device.target, &mut self.device.sizing, self.device.pending.is_some(), self.device.allow_program); for (id, destination) in targets { if previous.get(&id) != Some(&destination) { @@ -429,10 +544,20 @@ impl Editor { if let Err(e) = self.layout.set_midra_link(i, link) { self.device.error = e; } } } - self.midra_load_button(ui, false); - self.midra_send_button(ui); + self.midra_load_button(ui); return; } + ui.horizontal(|ui| { + if ui.button("Use saved links").clicked() { + self.device.destinations.fill(Destination::Skip); + self.device.mapping_scope = None; + } + if ui.add_enabled(self.device.scope != TransferScope::Selected, egui::Button::new("Import unmapped as new layers")).clicked() { + for (i, layer) in screen.layers.iter().enumerate() { + if self.device.destinations[i] == Destination::Skip && layer.unsupported.is_none() { self.device.destinations[i] = Destination::New; } + } + } + }); egui::ScrollArea::vertical().max_height(300.0).show(ui, |ui| { for (i, layer) in screen.layers.iter().enumerate() { ui.horizontal(|ui| { @@ -448,8 +573,10 @@ impl Editor { }; egui::ComboBox::from_id_salt(("midra_destination", i)).selected_text(label).show_ui(ui, |ui| { ui.selectable_value(destination, Destination::Skip, "Do not import"); - ui.selectable_value(destination, Destination::New, "New layer"); - for j in 0..self.layout.layers().len() { + ui.add_enabled_ui(self.device.scope != TransferScope::Selected, |ui| { + ui.selectable_value(destination, Destination::New, "New layer"); + }); + for &j in &scope_indices { ui.add_enabled_ui(self.layout.visible(j) && !self.layout.locked(j), |ui| { ui.selectable_value(destination, Destination::Existing(self.layout.layer_info(j).id), self.layout.layer_label(j)); }); @@ -467,7 +594,7 @@ impl Editor { 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.weak("Choose an existing destination or New layer beside each device layer. The scope limits available destinations; each mapping can still be changed."); } ui.separator(); @@ -521,6 +648,20 @@ impl Editor { if screen.resolution != self.layout.formats().output { return Err("Match output resolution before importing.".into()); } + let allowed = self.device.scope.indices(&self.layout); + for destination in &self.device.destinations { + if *destination == Destination::New && self.device.scope == TransferScope::Selected { + return Err( + "Only selected layers cannot create new layers. Choose All layers or a folder." + .into(), + ); + } + if let Destination::Existing(id) = destination + && !allowed.iter().any(|&i| self.layout.layer_info(i).id == *id) + { + return Err("An import destination is outside the current scope. Remap it or choose All layers.".into()); + } + } let selected: Vec<_> = self .device .destinations @@ -539,7 +680,19 @@ impl Editor { (target, screen.layers[i].geometry, screen.layers[i].framing) }) .collect(); - self.layout.import_device_layers(&values) + let links = selected + .iter() + .map(|&i| midra_layout::MidraLink { + screen: screen.id.clone(), + layer: screen.layers[i].id.clone(), + }) + .collect::>(); + let folder = match &self.device.scope { + TransferScope::Folder(folder) => folder.as_str(), + _ => "", + }; + self.layout + .import_linked_device_layers(&values, &links, folder) } } @@ -547,6 +700,7 @@ impl Editor { fn send_review( ui: &mut egui::Ui, layout: &midra_layout::Layout, + indices: &[usize], snapshot: &device::Snapshot, screen_index: usize, targets: &mut std::collections::BTreeMap, @@ -571,18 +725,18 @@ fn send_review( ui.selectable_value(sizing, Sizing::OutputBox, "Output-sized"); ui.selectable_value(sizing, Sizing::SourceAspect, "Source aspect"); }); - let selected = layout.selected_indices(); + let selected = indices; targets.retain(|id, _| selected.iter().any(|&i| layout.layer_info(i).id == *id)); ui.strong(format!( - "{} selected editor layers → Screen {}", + "{} editor layers in scope → Screen {}", selected.len(), screen.id )); if selected.is_empty() { - ui.label("Select editor layers to prepare their destination mapping."); + ui.label("No layers in this scope. Choose All layers, select layers, or choose a folder."); } let mut used = std::collections::BTreeSet::new(); - for i in selected { + for &i in selected { let info = layout.layer_info(i); let id = info.id; if let Some(link) = &info.midra_link { @@ -597,12 +751,12 @@ fn send_review( ui.strong(layout.layer_label(i)); egui::ComboBox::from_id_salt(("midra_send_target", id)) .selected_text(if target.is_empty() { - "Choose Midra layer".into() + "Not linked / skip".into() } else { format!("Screen {} · Layer {target}", screen.id) }) .show_ui(ui, |ui| { - ui.selectable_value(target, String::new(), "Choose Midra layer"); + ui.selectable_value(target, String::new(), "Not linked / skip"); for layer in &screen.layers { ui.selectable_value( target, @@ -643,6 +797,7 @@ fn send_review( ui.separator(); let mappings: Vec<_> = targets .iter() + .filter(|(_, destination)| !destination.is_empty()) .map(|(id, destination)| (*id, destination.clone())) .collect(); match Plan::prepare( @@ -806,6 +961,7 @@ mod tests { ); assert_ne!(app.layout.layers()[0], app.layout.layers()[1]); app.device.snapshot = Some(snapshot); + app.device.scope = TransferScope::Selected; for i in [1, 0] { app.layout.select(Some(i)); app.open_midra_export(); @@ -894,14 +1050,16 @@ mod tests { layout.set_visible(0, false); layout.set_locked(1, true); layout.select(None); - assert!(state.linked_plans(&layout, false).is_err()); - let plans = state.linked_plans(&layout, true).unwrap(); + state.scope = TransferScope::Selected; + assert!(state.linked_plans(&layout).is_err()); + state.scope = TransferScope::All; + let plans = state.linked_plans(&layout).unwrap(); assert_eq!(plans.len(), 2); assert_eq!(plans[0].screen, "1"); assert_eq!(plans[1].screen, "2"); assert!(plans.iter().all(|p| !p.changes.is_empty())); state.reset_mappings(); - assert_eq!(state.linked_plans(&layout, true).unwrap().len(), 2); + assert_eq!(state.linked_plans(&layout).unwrap().len(), 2); layout .set_midra_link( 1, @@ -911,9 +1069,9 @@ mod tests { }), ) .unwrap(); - assert!(state.linked_plans(&layout, true).is_err()); + assert!(state.linked_plans(&layout).is_err()); layout.set_midra_link(1, None).unwrap(); - assert_eq!(state.linked_plans(&layout, true).unwrap().len(), 1); + assert_eq!(state.linked_plans(&layout).unwrap().len(), 1); } #[test] fn program_destination_is_hidden_and_reset_until_enabled() { @@ -937,6 +1095,7 @@ mod tests { send_review( ui, &layout, + &TransferScope::All.indices(&layout), &snapshot, 0, &mut targets, @@ -1027,7 +1186,7 @@ mod tests { }), ) .unwrap(); - assert!(app.device.linked_plans(&app.layout, false).is_ok()); + assert!(app.device.linked_plans(&app.layout).is_ok()); } let before = app.layout.layers().clone(); super::super::tests::frame(&mut app, &ctx, vec![]); @@ -1084,6 +1243,7 @@ mod tests { send_review( ui, &layout, + &TransferScope::Selected.indices(&layout), &snapshot, 0, &mut targets, @@ -1105,6 +1265,7 @@ mod tests { send_review( ui, &layout, + &TransferScope::Selected.indices(&layout), &snapshot, 0, &mut targets, @@ -1190,4 +1351,208 @@ mod tests { assert!(app.device.pending.is_none()); assert_eq!(*app.layout.layers(), before); } + fn linked_folders() -> Editor { + let mut app = Editor::default(); + app.device.snapshot = Some(linked_test_snapshot()); + for i in 0..2 { + app.layout + .set_midra_link( + i, + Some(midra_layout::MidraLink { + screen: "1".into(), + layer: (i + 1).to_string(), + }), + ) + .unwrap(); + let id = app.layout.layer_info(i).id; + app.layout + .assign_folder(&[id], if i == 0 { "Intro" } else { "Talk" }) + .unwrap(); + } + app + } + + #[test] + fn default_scope_ignores_selection_for_send_load_and_import_mapping() { + let mut app = linked_folders(); + assert_eq!(app.device.scope, TransferScope::All); + app.layout.select(Some(1)); + assert_eq!(app.device.scoped_links(&app.layout).len(), 2); + assert_eq!(app.device.linked_plans(&app.layout).unwrap().len(), 1); + app.device.seed_import_mapping(&app.layout); + assert!(matches!( + app.device.destinations[0], + Destination::Existing(2) + )); + assert!(matches!( + app.device.destinations[1], + Destination::Existing(1) + )); + // Selection never changes explicit All scope or its manual remapping. + app.device.destinations[0] = Destination::Skip; + app.layout.select(None); + app.device.seed_import_mapping(&app.layout); + assert!(matches!(app.device.destinations[0], Destination::Skip)); + app.device.scope = TransferScope::Selected; + assert!(app.device.scoped_links(&app.layout).is_empty()); + assert!(app.device.linked_plans(&app.layout).is_err()); + app.layout.select(Some(0)); + app.device.seed_import_mapping(&app.layout); + assert!(matches!( + app.device.destinations[0], + Destination::Existing(2) + )); + assert!(matches!(app.device.destinations[1], Destination::Skip)); + } + + #[test] + fn folder_memories_reuse_destinations_without_overwriting_other_links() { + let mut app = linked_folders(); + let link = app.layout.layer_info(0).midra_link.clone(); + app.layout.set_midra_link(1, link).unwrap(); + let before = midra_layout::project::Project::from_layout(&app.layout); + assert!( + app.device + .linked_plans(&app.layout) + .unwrap_err() + .contains("Choose one folder") + ); + app.device.scope = TransferScope::Folder("Intro".into()); + let first = app.device.linked_plans(&app.layout).unwrap(); + assert_eq!(app.device.scoped_links(&app.layout)[0].0, 2); + app.device.follow_folder("Talk"); + let second = app.device.linked_plans(&app.layout).unwrap(); + assert_eq!(app.device.scoped_links(&app.layout)[0].0, 1); + let values = |plan: &Plan| { + plan.changes + .iter() + .map(|change| (change.path.clone(), change.after.clone())) + .collect::>() + }; + assert_ne!(values(&first[0]), values(&second[0])); + assert_eq!( + midra_layout::project::Project::from_layout(&app.layout), + before + ); + app.device.follow_folder("Removed"); + assert!(app.device.scoped_links(&app.layout).is_empty()); + assert!(app.device.linked_plans(&app.layout).is_err()); + } + + #[test] + fn folder_import_remapping_is_scoped_and_saves_links_with_atomic_undo() { + let mut app = linked_folders(); + app.device.scope = TransferScope::Folder("Talk".into()); + app.device.seed_import_mapping(&app.layout); + assert!(matches!(app.device.destinations[0], Destination::Skip)); + assert!(matches!( + app.device.destinations[1], + Destination::Existing(1) + )); + let before = midra_layout::project::Project::from_layout(&app.layout); + app.device.destinations = vec![Destination::Existing(2), Destination::Skip]; + assert!( + app.apply_device_import() + .unwrap_err() + .contains("outside the current scope") + ); + assert_eq!( + midra_layout::project::Project::from_layout(&app.layout), + before + ); + app.device.destinations = vec![Destination::Existing(1), Destination::New]; + app.apply_device_import().unwrap(); + assert_eq!( + app.layout.layer_info(1).midra_link.as_ref().unwrap().layer, + "1" + ); + assert_eq!(app.layout.layer_info(2).folder, "Talk"); + assert_eq!( + app.layout.layer_info(2).midra_link.as_ref().unwrap().layer, + "2" + ); + assert_eq!( + app.layout.layer_info(0), + &before.layout().unwrap().layer_info(0).clone() + ); + app.layout.undo(); + assert_eq!( + midra_layout::project::Project::from_layout(&app.layout).layers, + before.layers + ); + } + + #[test] + fn changing_folder_during_read_keeps_the_original_load_destinations() { + let mut app = linked_folders(); + app.device.scope = TransferScope::Folder("Intro".into()); + let links = app.device.scoped_links(&app.layout); + let before_other = app.layout.layers()[1]; + app.device.loading = Some(links); + let (tx, rx) = mpsc::channel(); + app.device.pending = Some(rx); + app.device.follow_folder("Talk"); + tx.send(Ok(linked_test_snapshot())).unwrap(); + app.device.poll(); + app.finish_linked_load(); + assert_eq!( + app.layout.layers()[0], + linked_test_snapshot().screens[0].layers[0].geometry + ); + assert_eq!(app.layout.layers()[1], before_other); + assert_eq!(app.device.scope, TransferScope::Folder("Talk".into())); + } + + #[test] + fn all_scope_send_review_lists_unselected_layers_and_keeps_manual_destinations() { + let app = linked_folders(); + let ctx = egui::Context::default(); + let mut targets = std::collections::BTreeMap::from([(1, "2".into()), (2, "1".into())]); + let before = targets.clone(); + let _ = ctx.run(egui::RawInput::default(), |ctx| { + egui::CentralPanel::default().show(ctx, |ui| { + send_review( + ui, + &app.layout, + &TransferScope::All.indices(&app.layout), + app.device.snapshot.as_ref().unwrap(), + 0, + &mut targets, + &mut Target::Preview, + &mut Sizing::OutputBox, + false, + false, + ); + }); + }); + assert_eq!(targets, before); + } + #[test] + fn status_scope_picker_changes_transfer_filter_without_changing_selection() { + let mut app = linked_folders(); + let ctx = egui::Context::default(); + let before = app.layout.selection_mask(); + super::super::tests::click_text(&mut app, &ctx, "All layers"); + super::super::tests::click_text(&mut app, &ctx, "Only selected layers"); + assert_eq!(app.device.scope, TransferScope::Selected); + assert_eq!(app.layout.selection_mask(), before); + assert!(app.device.pending.is_none()); + assert!(!app.device.sending); + } + #[test] + fn selected_scope_never_creates_unselected_import_destinations() { + let mut app = linked_folders(); + app.device.scope = TransferScope::Selected; + app.device.destinations = vec![Destination::New, Destination::Skip]; + let before = midra_layout::project::Project::from_layout(&app.layout); + assert!( + app.apply_device_import() + .unwrap_err() + .contains("cannot create new layers") + ); + assert_eq!( + midra_layout::project::Project::from_layout(&app.layout), + before + ); + } } diff --git a/crates/midra-layout/src/gui.rs b/crates/midra-layout/src/gui.rs index 250d88d..3056d7c 100644 --- a/crates/midra-layout/src/gui.rs +++ b/crates/midra-layout/src/gui.rs @@ -3222,9 +3222,16 @@ impl Editor { Vec2::new(145.0, 25.0), )), |ui| { - self.midra_load_button(ui, true); + self.midra_load_button(ui); }, ); + ui.scope_builder( + egui::UiBuilder::new().max_rect(Rect::from_min_size( + r.min + Vec2::new(540.0, 5.0), + Vec2::new(180.0, 25.0), + )), + |ui| self.midra_scope_picker(ui), + ); ink.text( r.width() - 278.0, 10.0, diff --git a/crates/midra-layout/src/layers_ui.rs b/crates/midra-layout/src/layers_ui.rs index 6c30b6b..e3ee62d 100644 --- a/crates/midra-layout/src/layers_ui.rs +++ b/crates/midra-layout/src/layers_ui.rs @@ -523,6 +523,7 @@ impl Editor { } if row.clicked() { self.layer_ui.last_folder_click = Some(folder.into()); + self.device.follow_folder(folder); self.layout.select_folder(folder, click_shift_modifier(ui)); self.sync(); } @@ -558,10 +559,16 @@ impl Editor { } row.context_menu(|ui| { if ui.button("Select folder contents").clicked() { + self.device.follow_folder(folder); self.layout.select_folder(folder, false); self.sync(); ui.close_menu(); } + if ui.button("Use folder for Midra transfers").clicked() { + self.device + .set_scope(device_ui::TransferScope::Folder(folder.into())); + ui.close_menu(); + } if ui.button("Rename folder…").clicked() { self.layer_ui.folder_rename = Some((Some(folder.into()), folder.into(), vec![])); self.layer_ui.rename_focus = true; @@ -723,6 +730,11 @@ impl Editor { }; match result { Ok(()) => { + if old.as_ref().is_some_and(|old| { + self.device.scope == device_ui::TransferScope::Folder(old.clone()) + }) { + self.device.follow_folder(name.trim()); + } if let Some(old) = old && self.layer_ui.collapsed.remove(&old) { @@ -1156,4 +1168,28 @@ mod tests { app.layout.undo(); assert_eq!(app.layout.folder_members("Video"), vec![0, 1]); } + #[test] + fn folder_selection_changes_midra_scope_only_in_folder_mode() { + for scope in [ + device_ui::TransferScope::All, + device_ui::TransferScope::Selected, + device_ui::TransferScope::Folder("Previous".into()), + ] { + let mut app = Editor::default(); + let ctx = egui::Context::default(); + app.layout.assign_folder(&[1, 2], "Talk").unwrap(); + app.device.scope = scope.clone(); + click_tree(&mut app, &ctx, egui::Id::new(("folder", "Talk"))); + assert_eq!( + app.device.scope, + if matches!(scope, device_ui::TransferScope::Folder(_)) { + device_ui::TransferScope::Folder("Talk".into()) + } else { + scope + } + ); + assert_eq!(app.layout.selected_indices(), vec![0, 1]); + assert!(!app.device.sending); + } + } } diff --git a/crates/midra-layout/src/lib.rs b/crates/midra-layout/src/lib.rs index 149855f..967a363 100644 --- a/crates/midra-layout/src/lib.rs +++ b/crates/midra-layout/src/lib.rs @@ -1244,6 +1244,41 @@ impl Layout { self.remember(before); Ok(()) } + /// Import geometry/crops and its reviewed device links as one undoable edit. + /// New layers inherit the chosen local folder; existing membership is preserved. + pub fn import_linked_device_layers( + &mut self, + values: &[DeviceLayerImport], + links: &[MidraLink], + new_folder: &str, + ) -> Result<(), String> { + if values.len() != links.len() || new_folder.chars().count() > 128 { + return Err("Every imported layer needs a valid device link and folder.".into()); + } + for link in links { + link.validate()?; + } + let mut draft = self.clone(); + draft.import_device_layers(values)?; + let mut next_new = self.layers.len(); + for ((id, _, _), link) in values.iter().zip(links) { + let i = if let Some(id) = id { + draft.info.iter().position(|info| info.id == *id).unwrap() + } else { + let i = next_new; + next_new += 1; + draft.info[i].folder = new_folder.trim().into(); + i + }; + draft.info[i].midra_link = Some(link.clone()); + } + self.finish_drag(); + let before = self.snapshot(); + self.restore(draft.snapshot()); + self.next_id = draft.next_id; + self.remember(before); + Ok(()) + } /// Import device containers into stable layer IDs, or new layers (`None`). /// Independent of selection; the complete mapping is one atomic undo step. pub fn import_mapped_layers( diff --git a/crates/midra-layout/src/project_ui.rs b/crates/midra-layout/src/project_ui.rs index 79fb522..f7bab4d 100644 --- a/crates/midra-layout/src/project_ui.rs +++ b/crates/midra-layout/src/project_ui.rs @@ -232,9 +232,10 @@ impl Editor { ui.menu_button("Export", |ui| self.export_menu(ui)); } pub(super) fn export_menu(&mut self, ui: &mut egui::Ui) { + self.midra_scope_picker(ui); self.midra_apply_button(ui); self.midra_send_button(ui); - self.midra_load_button(ui, true); + self.midra_load_button(ui); if ui.button("Configure Midra export…").clicked() { self.open_midra_export(); ui.close_menu(); diff --git a/docs/interfaces/midra-device-send.md b/docs/interfaces/midra-device-send.md index 827def3..ce0881b 100644 --- a/docs/interfaces/midra-device-send.md +++ b/docs/interfaces/midra-device-send.md @@ -73,11 +73,11 @@ partial/uncertain outcomes without blind retries or automatic rollback. Program selection is explicit. The application defaults to Preview and hides Program unless the persisted `allow_sending_to_program` preference is enabled. Turning it off resets the exporter to Preview, including quick Apply. Layer screen/destination links are saved in project version 5. 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 preserve saved links. Physical display validation remains separate from the successful device-field and import round trips. -The status-bar and Export-menu **Apply changes…** actions only open export configuration, even when current layers have valid saved links. They never start a write. The user chooses layers, mappings, target and sizing, then explicitly clicks **Send mapped layers**. Busy/offline actions are disabled. **Send all linked layers** remains a separate direct-send action using saved links. No persistent schema changes are involved. +The status-bar and Export-menu **Apply changes…** actions only open export configuration, even when current layers have valid saved links. They never start a write. The user chooses a transfer scope, mappings, target and sizing, then explicitly clicks **Send mapped layers** for the displayed screen. Empty/unlinked rows are skipped. The load button uses all saved links in the scope, including links to other screens. Busy/offline actions are disabled. **Send all linked layers** remains a separate direct-send action using saved links. No persistent schema changes are involved. Snapshot layer lists omit unassigned source slots (`NONE` or empty), before geometry validation. Assigned layers remain available even when OFF. -**Send all linked layers** includes all linked document layers, even unselected, hidden or locked ones. Plans are grouped by saved screen ID and all groups are validated before starting. Screen groups send sequentially with readback; on failure later groups are not sent, and the result reports the failed screen and completed-group count. Links never auto-send and are not tied to an IP address. +The direct send button uses the shared transfer scope. Its default **All layers** includes all linked document layers, even unselected, hidden or locked ones. **Only selected layers** uses exactly the current selection (an empty selection does not mean All); **Folder: …** uses all members of the named folder, independently of selection/visibility/locks. Unlinked layers are skipped. Plans are grouped by saved screen ID and all groups are validated before starting. Screen groups send sequentially with readback; on failure later groups are not sent, and the result reports the failed screen and completed-group count. Links never auto-send and are not tied to an IP address. ## Preset apply pulse @@ -96,9 +96,10 @@ included in geometry comparisons, because it is a command rather than geometry. **Send all linked layers** sends immediately using saved links and the current target and sizing settings, without opening the export window. The button shows progress and its tooltip reports completion. Invalid links or send failures open the export window with the error. **Load linked layers**, beside the connection status and in Export, reads fresh -Midra Preview geometry and crop framing into all linked editor layers, regardless -of selection. **Apply changes… → Load mapped layers** reads only the selected -editor layers using the links chosen in that window. Both actions are read-only +Midra Preview geometry and crop framing into linked editor layers in the shared +transfer scope. The default **All layers** ignores canvas selection; **Only selected +layers** and **Folder: …** explicitly restrict the operation. The load button inside +**Apply changes…** uses that same scope and the saved links. Both actions are read-only on the device and always load Preview (independent of the send target). They do not recall device memories or presets. Loading is one atomic Undo step; links remain saved. Missing screens/layers, mismatched output resolutions, unsupported @@ -111,3 +112,33 @@ 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. + +## Shared transfer scopes and folder layouts + +The desktop keeps a session-only scope: All (default), Selected, or one folder name. +Scope controls both direct linked send/load and the destination candidates in manual +Midra import/export review. All does not depend on selection; Selected with no selection +and Folder with no members are empty scopes, never implicit All. Scope changes do not +edit viewport selection or saved links. In Folder mode, clicking a folder name changes +the scope. Folder rename follows the renamed scope; a missing folder requires choosing +another scope. The scope is omitted from project/settings/export representations. + +Direct send/load captures stable layer IDs and their saved `(screen, layer)` links +when clicked. Switching scope while a read is pending cannot redirect that import. +Direct sends validate destination uniqueness within the chosen scope, across each +screen. Duplicate destinations across different folders are valid persistent links, +but those folders cannot be sent together. Loading the same device layer into multiple +local linked copies is allowed; destination editor IDs must still be unique, visible, +and unlocked. Existing geometry validation and atomic import guarantees are unchanged. + +The send review lists all scoped editor layers on the currently browsed screen. +Saved links on that screen populate editable destinations; empty rows are skipped. +Browsing another screen does not rewrite existing links. An explicit destination +change saves the new link; a scope change never removes out-of-scope links. +Manual device import suggests unique saved links within scope, while retaining manual +row remapping until scope/screen changes or refresh. Ambiguous/unlinked rows start +skipped. Creating layers is explicit and available only in All/Folder scopes; new layers +inherit the scope's folder (root in All). A successful manual import saves reviewed device links, geometry, +source/crop data and new-layer membership in one undoable transaction. Invalid mapping, +link or geometry rejects the entire transaction. This uses existing project-v9 fields; +there is no schema/version change. Source routing and device memories are not imported. diff --git a/docs/interfaces/midra-layout.md b/docs/interfaces/midra-layout.md index 89f7c2a..63f837a 100644 --- a/docs/interfaces/midra-layout.md +++ b/docs/interfaces/midra-layout.md @@ -227,3 +227,14 @@ layer's saved link. Direct send/load actions use each layer's saved screen, independently of the screen currently displayed in the configuration window. Automatic session recovery wraps this project representation in a separate [recovery file](midra-layout-recovery.md); named project JSON remains version 9. + +## Folder-scoped Midra transfers + +The shared Midra transfer scope is session-only and is not saved. Defaults use all +layers; Selected/Folder modes filter by the existing selection or `folder` fields. +Folders may store alternative layouts whose `midra_link` values reuse the same screen +and layer; each individual send requires unique destinations within its scope. +Manual device import now saves the reviewed `midra_link` with imported geometry/crops +in one Undo step. New layers inherit the chosen folder; existing folder names remain. +All these values use the existing version-9 representation. See +[device transfer scopes](midra-device-send.md#shared-transfer-scopes-and-folder-layouts). diff --git a/docs/midra-layout-plan.md b/docs/midra-layout-plan.md index c6d2e13..7953460 100644 --- a/docs/midra-layout-plan.md +++ b/docs/midra-layout-plan.md @@ -556,9 +556,12 @@ and Centered-crop import round trips passed Eikos 3.3.10 hardware checks. limits before implementation. Preview availability is not yet verified. Start with explicit capture; automatic refresh and image saving remain to specify. -- [ ] **Export and workflow cleanup.** Revisit the export experience and overall - workflow. The user will provide the requested changes; detailed scope and - acceptance criteria are pending. +- [x] **Folder-based local Midra layouts.** Shared All/Selected/Folder transfer + scope defaults to All; folder mode follows folder selection for send/load. + Saved links can be reused across alternative folders and manually remapped. + Manual import saves links and new-layer folder membership with geometry. +- [ ] **Further export and workflow cleanup.** The shared transfer scope is + implemented; additional workflow changes still await specifications. - [ ] **Multiple saved layer links and link picking.** Extend the current single saved screen/layer destination per editor layer to support multiple saved links. Provide an **Add link** action to append extra destinations without replacing diff --git a/docs/midra-layout.md b/docs/midra-layout.md index 30cae9b..8a45d85 100644 --- a/docs/midra-layout.md +++ b/docs/midra-layout.md @@ -34,6 +34,39 @@ are removed automatically; collapse state lasts for this session. The existing **Manage…** window remains available for bulk name/folder editing. Grouping does not affect device links or source assignments. All document edits support Undo. +## Use folders as local Midra layouts + +The Midra **Apply to** selector is shared by the status bar, Export menu, and +send/import windows. It starts at **All layers**, regardless of canvas selection. +Choose **Only selected layers** for an explicit selection filter, or **Folder: …** +for a complete folder. The choice lasts for the session; it is not a project setting. +It affects Midra transfers, not clipboard/file import or geometry export scopes. + +To prepare several layouts that reuse the same device layers: + +1. Put each layout in a folder and configure its saved screen/layer links through + **Apply changes…**. Every row can still be remapped or unlinked. +2. Choose **Folder: …** in the status selector, or right-click a folder and choose + **Use folder for Midra transfers**. +3. Click **Send folder links**. Then click another folder name and send again: + Folder mode follows the clicked folder. Clicking a folder never sends by itself. +4. **Load folder links** reads fresh Preview geometry/cropping into that folder. + Loading requires visible, unlocked destinations and supports Undo. + +Different folders may link to the same device destinations. One send cannot +include conflicting destinations: choose a single folder/selection or remap them. +Linked send/load skip unlinked layers. An empty selection or missing folder never +falls back to All. Transfers already started retain the links captured at click time. +These are local geometry layouts, not device preset recalls or source-routing memories. + +**Import layers from Midra** proposes unambiguous saved links within the scope. +Each row offers Skip or a scoped existing layer; All/Folder scopes also allow New layer. **Use saved links** +restores those suggestions; **Import unmapped as new layers** fills unused rows. +New layers join the chosen folder, and importing saves their reviewed screen/layer +links with the geometry as one Undo step. Existing layers keep their folder. Multiple +local copies of the same device layer can be updated together with linked Load; +the manual import dialog requires one unambiguous destination per device row. + ## Paste layer values and import geometry 1. Choose destinations using **Choose destination layers…** in the Import menu @@ -853,16 +886,17 @@ continue resizing, or hold Alt to temporarily invert snapping. Shift/Ctrl+Shift Midra layer lists omit unassigned source slots (`NONE` or empty). Assigned inputs remain listed even if the layer is off. The exporter defaults to Preview and hides Program until **Settings → Midra integration → Allow sending to Program** is checked. This preference is saved automatically; turning it off returns the exporter and quick Apply action to Preview. -Destination choices in **Configure Midra export…** now save immediately on the editor layer and support Undo. Save the project JSON to keep links across sessions. Links include screen and layer IDs and survive refreshes and selection changes. Choose the empty destination on the linked screen to unlink. **Send all linked layers** is available beside Apply, in Export and in the send window; it includes unselected, hidden and locked linked layers, grouped by screen. Apply changes… opens configuration for the chosen layers. Preview/Program and sizing still use the current export options. +Destination choices in **Configure Midra export…** now save immediately on the editor layer and support Undo. Save the project JSON to keep links across sessions. Links include screen and layer IDs and survive refreshes and selection changes. Choose the empty destination on the linked screen to unlink. The direct send button is available beside Apply and in Export; in **All layers** scope it includes unselected, hidden and locked linked layers, grouped by screen. Its label changes to **Send selected links** or **Send folder links** in those scopes. Apply changes… opens mapping configuration for the current scope. Preview/Program and sizing still use the current export options. Every explicit send now includes WebRCS’s preset apply pulse (`xUpdate` false → true). This applies staged geometry when automatic updates are disabled, including a repeat send where WebRCS already shows the desired values. **Send all linked layers** sends immediately using saved links and the current target and sizing settings, without opening the export window. The button shows progress and its tooltip reports completion. Invalid links or send failures open the export window with the error. **Load linked layers**, beside the connection status and in Export, reads fresh -Midra Preview geometry and crop framing into all linked editor layers, regardless -of selection. **Apply changes… → Load mapped layers** reads only the selected -editor layers using the links chosen in that window. Both actions are read-only +Midra Preview geometry and crop framing into linked editor layers in the shared +transfer scope. The default **All layers** ignores canvas selection; **Only selected +layers** and **Folder: …** explicitly restrict the operation. The load button inside +**Apply changes…** uses that same scope and the saved links. Both actions are read-only on the device and always load Preview (independent of the send target). They do not recall device memories or presets. Loading is one atomic Undo step; links remain saved. Missing screens/layers, mismatched output resolutions, unsupported @@ -874,7 +908,7 @@ settings schema changes are involved. Midra destinations are identified by the pair **screen ID + layer ID**: Screen 1 Layer 1 and Screen 2 Layer 1 are distinct links. Both IDs are already persisted in project version 5; no schema change is needed. Opening **Apply changes…** or -**Configure Midra export…** restores the first selected layer's available linked +**Configure Midra export…** restores the first scoped layer's available linked screen. Destination choices display both IDs. Browsing another screen does not retarget existing links; choosing a destination there explicitly replaces that layer's saved link. Direct send/load actions use each layer's saved screen, diff --git a/docs/midralayout/changelog.md b/docs/midralayout/changelog.md index 7911555..b662c43 100644 --- a/docs/midralayout/changelog.md +++ b/docs/midralayout/changelog.md @@ -4,6 +4,8 @@ ## Unreleased +- Default Midra transfers to All layers with a shared All/Selected/Folder selector. Folder mode follows clicked folders for quick alternate-layout sends/loads; links remain editable and out-of-scope links are preserved. Import suggests saved links and saves remapped/new-layer links and folder membership atomically with geometry. Tests cover scope isolation, reused destinations, in-flight reads and Undo; no hardware writes were needed. + - Organize the flat layer sidebar into collapsible folder groups: select contents, double-click rename, group eye/lock controls, drag layers between folders/root, and reorder folders as blocks. Add new-folder and right-click actions, with atomic Undo and existing project compatibility; empty groups disappear and nesting is not introduced. - Reorder the viewport toolbar into shared bordered groups: Project/Import, Undo/Redo, Select/Move, view controls, Align/Snap/Pivot, and Output/Options. Groups wrap together on narrow windows and preserve optional icon captions.