diff --git a/crates/midra-layout/src/exchange.rs b/crates/midra-layout/src/exchange.rs index c2d1bc3..d2ae9d8 100644 --- a/crates/midra-layout/src/exchange.rs +++ b/crates/midra-layout/src/exchange.rs @@ -123,7 +123,7 @@ fn background(project: &Project) -> Result { let oh = project.output_resolution.height as f64; let [w, h] = thumbnail_size(ow, oh, 1920.0); let mut canvas = RgbaImage::from_pixel(w, h, Rgba([18, 37, 49, 255])); - if let Some(reference) = project.reference.as_ref().filter(|r| r.visible) { + for reference in project.references.iter().filter(|r| r.visible) { let bytes = reference.bytes()?; let mut reader = image::ImageReader::new(Cursor::new(bytes)) .with_guessed_format() diff --git a/crates/midra-layout/src/gui.rs b/crates/midra-layout/src/gui.rs index 452a1e3..ab73ddf 100644 --- a/crates/midra-layout/src/gui.rs +++ b/crates/midra-layout/src/gui.rs @@ -17,6 +17,8 @@ mod project_ui; mod ratio_ui; #[path = "recovery_ui.rs"] mod recovery_ui; +#[path = "reference_ui.rs"] +mod reference_ui; #[path = "viewport_guides.rs"] mod viewport_guides; use format_ui::{FormatDraft, OutputDraft, PropertyTab}; @@ -78,9 +80,11 @@ pub struct Editor { crop_tab_editing: bool, show_pattern: bool, show_toolbar_icon_names: bool, - reference: Option, - reference_pending: - Option>>, + references: Vec, + reference_selected: Option, + reference_pending: std::collections::VecDeque< + std::sync::mpsc::Receiver>, + >, outline_layers: bool, backdrop_title: String, reference_open: bool, @@ -297,8 +301,9 @@ impl Default for Editor { crop_tab_editing: false, show_pattern: false, show_toolbar_icon_names: false, - reference: None, - reference_pending: None, + references: Vec::new(), + reference_selected: None, + reference_pending: Default::default(), outline_layers: false, backdrop_title: midra_layout::project::DEFAULT_BACKDROP_TITLE.into(), reference_open: false, @@ -374,7 +379,11 @@ impl Editor { } fn load_reference(&mut self, ctx: &egui::Context, file: &egui::DroppedFile) { let (tx, rx) = std::sync::mpsc::channel(); - self.reference_pending = Some(rx); + if self.references.len() + self.reference_pending.len() >= 32 { + self.reference_error = "Up to 32 reference images can be stored.".into(); + return; + } + self.reference_pending.push_back(rx); self.reference_error.clear(); let ctx = ctx.clone(); let file = file.clone(); @@ -385,7 +394,7 @@ impl Editor { }); } fn poll_reference(&mut self) { - let Some(rx) = &self.reference_pending else { + let Some(rx) = self.reference_pending.front() else { return; }; let result = match rx.try_recv() { @@ -393,11 +402,19 @@ impl Editor { Err(std::sync::mpsc::TryRecvError::Empty) => return, Err(_) => Err("Reference reader stopped. Please import again.".into()), }; - self.reference_pending = None; + self.reference_pending.pop_front(); match result { Ok(reference) => { - self.reference = Some(reference); - self.reference_error.clear(); + if self.references.iter().map(|r| r.bytes.len()).sum::() + + reference.bytes.len() + > 64 * 1024 * 1024 + { + self.reference_error = + "Reference images exceed the combined 64 MiB limit.".into(); + return; + } + self.references.push(reference); + self.reference_selected = Some(self.references.len() - 1); } Err(error) => self.reference_error = error, } @@ -405,24 +422,26 @@ impl Editor { #[cfg(test)] fn wait_reference(&mut self) { let until = std::time::Instant::now() + std::time::Duration::from_secs(5); - while self.reference_pending.is_some() && std::time::Instant::now() < until { + while !self.reference_pending.is_empty() && std::time::Instant::now() < until { self.poll_reference(); std::thread::sleep(std::time::Duration::from_millis(1)); } - assert!(self.reference_pending.is_none()); + assert!(self.reference_pending.is_empty()); } fn import_reference_file(&mut self, ctx: &egui::Context) { - if let Some(path) = rfd::FileDialog::new() + if let Some(paths) = rfd::FileDialog::new() .add_filter("Pictures", &["png", "jpg", "jpeg", "bmp"]) - .pick_file() + .pick_files() { - self.load_reference( - ctx, - &egui::DroppedFile { - path: Some(path), - ..Default::default() - }, - ); + for path in paths { + self.load_reference( + ctx, + &egui::DroppedFile { + path: Some(path), + ..Default::default() + }, + ); + } } } fn reference_window(&mut self, ctx: &egui::Context) { @@ -435,17 +454,31 @@ impl Editor { if ui.button("Import picture…").clicked() { self.import_reference_file(ctx); } - ui.label("Or drag one PNG, JPEG or BMP into the window."); - if self.reference_pending.is_some() { + ui.label("Or drag PNG, JPEG or BMP images into the window."); + if !self.reference_pending.is_empty() { ui.spinner(); ui.label("Loading image… current reference remains available."); if ui.button("Cancel image import").clicked() { - self.reference_pending = None; + self.reference_pending.clear(); } } + if !self.references.is_empty() { + let mut index = self.reference_selected.unwrap_or(self.references.len() - 1); + egui::ComboBox::from_id_salt("reference-settings-choice") + .selected_text(&self.references[index].name) + .show_ui(ui, |ui| { + for (i, reference) in self.references.iter().enumerate() { + ui.selectable_value(&mut index, i, &reference.name); + } + }); + self.reference_selected = Some(index); + } ui.checkbox(&mut self.outline_layers, "Outline-only layers"); let mut remove = false; - if let Some(reference) = &mut self.reference { + if let Some(reference) = self + .reference_selected + .and_then(|i| self.references.get_mut(i)) + { ui.label(format!( "{} · {} × {} px", reference.name, reference.size[0], reference.size[1] @@ -503,10 +536,8 @@ impl Editor { } remove = ui.button("Remove reference").clicked(); } - if remove { - self.reference = None; - self.reference_pending = None; - self.reference_error.clear(); + if remove && let Some(i) = self.reference_selected { + self.remove_reference(i); } if !self.reference_error.is_empty() { ui.colored_label(ui.visuals().error_fg_color, &self.reference_error); @@ -1014,7 +1045,13 @@ impl Editor { } fn inspector(&mut self, ui: &mut egui::Ui) { let rows = self.layer_tree_rows(); - let row_count = rows.len(); + let layer_row_count = rows.len(); + let row_count = layer_row_count + + if self.references.is_empty() { + 0 + } else { + self.references.len() + 1 + }; let palette = theme::palette(ui.ctx()); let (r, _) = ui.allocate_exact_size( Vec2::new( @@ -1041,6 +1078,15 @@ impl Editor { { self.manage_layers(); } + if ui + .put( + Rect::from_min_size(ink.point(w - 195.0, -5.0), Vec2::new(105.0, 24.0)), + egui::Button::new("Add image…"), + ) + .clicked() + { + self.import_reference_file(ui.ctx()); + } self.layer_tree_header(ui, &ink); let mut reorder = None; for (row_index, tree_row) in rows.into_iter().enumerate() { @@ -1166,6 +1212,7 @@ impl Editor { Err(error) => self.error = error, } } + self.reference_rows(ui, &ink, 28.0 + layer_row_count as f32 * 44.0, w); let r = r.translate(Vec2::new(0.0, (row_count as f32 - 2.0) * 44.0)); let ink = Ink::new(ui, r); ink.line([0.0, 130.0], [w, 130.0], palette.line); @@ -1174,6 +1221,20 @@ impl Editor { return; } let Some(i) = self.layout.selected() else { + if self + .reference_selected + .is_some_and(|i| i < self.references.len()) + { + ink.text(0.0, 153.0, "REFERENCE IMAGE", 16.0, palette.purple); + ink.text( + 0.0, + 182.0, + "Fixed guide · double-click its row for settings.", + 12.0, + palette.muted, + ); + return; + } ink.text( 0.0, 153.0, @@ -1758,6 +1819,7 @@ impl Editor { } ui.separator(); } + ui.menu_button("Reference images", |ui| self.reference_actions_menu(ui)); if ui.button("Output format…").clicked() { self.output_draft = Some(OutputDraft::new(self.layout.formats().output)); ui.close_menu(); @@ -2386,9 +2448,11 @@ impl Editor { let (text, color) = if !self.reference_error.is_empty() { (self.reference_error.clone(), ui.visuals().error_fg_color) } else if let Some((severe, warning)) = self - .reference - .as_ref() - .and_then(|r| r.warning(self.layout.formats().output)) + .references + .iter() + .filter(|r| r.visible) + .filter_map(|r| r.warning(self.layout.formats().output)) + .max_by_key(|(severe, _)| *severe) { ( warning, @@ -2400,8 +2464,8 @@ impl Editor { ) } else { ( - self.reference - .as_ref() + self.reference_selected + .and_then(|i| self.references.get(i)) .map(|r| format!("Reference: {} · {} × {} px", r.name, r.size[0], r.size[1])) .unwrap_or_default(), palette.muted, @@ -2422,7 +2486,7 @@ impl Editor { } // Artwork uses half-screen coordinates at twice the camera scale. Since // the output stays centered, allow the label's overhang on both sides. - let label_margin = if self.reference.is_none() { + let label_margin = if self.references.is_empty() { SCREEN_LABEL_TOP * 4.0 * artwork_scale(output) } else { 0.0 @@ -2759,16 +2823,23 @@ impl Editor { origin, scale: scale * 2.0, }; - if let Some(reference) = &self.reference { - reference.paint( - &screen.painter, + if !self.references.is_empty() { + screen.painter.rect_filled( Rect::from_min_size(origin, Vec2::new(sw, sh) * scale), - output, + 0.0, + palette.canvas, ); + for reference in &self.references { + reference.paint( + &screen.painter, + Rect::from_min_size(origin, Vec2::new(sw, sh) * scale), + output, + ); + } } else { screen_artwork(&screen, &self.backdrop_title, output); } - if self.reference.is_none() { + if self.references.is_empty() { screen_reference_hint(&screen, output); } if self.edit_content @@ -2806,7 +2877,7 @@ impl Editor { 0.0, if self.outline_layers { Color32::TRANSPARENT - } else if self.reference.as_ref().is_some_and(|r| r.visible) { + } else if self.references.iter().any(|r| r.visible) { Color32::from_rgba_unmultiplied( palette.layer.r(), palette.layer.g(), @@ -3151,13 +3222,8 @@ impl Editor { self.poll_reference(); let palette = theme::palette(ctx); let dropped = ctx.input(|i| i.raw.dropped_files.clone()); - if !dropped.is_empty() { - if dropped.len() == 1 { - self.load_reference(ctx, &dropped[0]); - } else { - self.reference_error = - "Drop one reference image at a time; current image kept.".into(); - } + for file in &dropped { + self.load_reference(ctx, file); } if !blocked { self.shortcuts(ctx); @@ -3548,13 +3614,24 @@ fn layer_state_icon( lock: bool, active: bool, ) -> egui::Response { - let palette = theme::palette(ui.ctx()); let label = match (lock, active) { (true, true) => "Unlock layer", (true, false) => "Lock layer", (false, true) => "Show layer", (false, false) => "Hide layer", }; + state_icon(ui, rect, id, lock, active, label) +} + +fn state_icon( + ui: &mut egui::Ui, + rect: Rect, + id: egui::Id, + lock: bool, + active: bool, + label: &str, +) -> egui::Response { + let palette = theme::palette(ui.ctx()); let response = ui.interact(rect, id, egui::Sense::click()); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label)); let painter = ui.painter(); @@ -5920,8 +5997,8 @@ mod tests { ); app.wait_reference(); assert!( - app.reference - .as_ref() + app.references + .first() .unwrap() .warning([1920, 1080]) .unwrap() @@ -5930,7 +6007,7 @@ mod tests { assert_eq!(*app.layout.layers(), before); let output = frame(&mut app, &ctx, vec![]); assert!(output.shapes.iter().any(|s| matches!(&s.shape, egui::epaint::Shape::Text(t) if t.galley.job.text.contains("SEVERE WARNING")))); - let texture = app.reference.as_ref().unwrap().texture.id(); + let texture = app.references.first().unwrap().texture.id(); app.load_reference( &ctx, &egui::DroppedFile { @@ -5940,12 +6017,12 @@ mod tests { ); app.wait_reference(); assert!(!app.reference_error.is_empty()); - assert_eq!(app.reference.as_ref().unwrap().texture.id(), texture); + assert_eq!(app.references.first().unwrap().texture.id(), texture); app.layout.nudge(1.0, 0.0).unwrap(); assert_eq!(app.layout.layers()[1].x, before[1].x + 1.0); app.layout.undo(); assert_eq!(*app.layout.layers(), before); - assert_eq!(app.reference.as_ref().unwrap().texture.id(), texture); + assert_eq!(app.references.first().unwrap().texture.id(), texture); } #[test] fn paste_without_selection_maps_directly_from_rectangle_dropdown() { diff --git a/crates/midra-layout/src/menu_ui.rs b/crates/midra-layout/src/menu_ui.rs index 0c57ee2..d9d3ff3 100644 --- a/crates/midra-layout/src/menu_ui.rs +++ b/crates/midra-layout/src/menu_ui.rs @@ -63,15 +63,8 @@ impl Editor { Self::request_layer_paste(ui.ctx()); } ui.separator(); - ui.weak("Screen reference"); - if ui.button("Reference image…").clicked() { - ui.close_menu(); - self.import_reference_file(ui.ctx()); - } - if self.reference.is_some() && ui.button("Reference settings…").clicked() { - ui.close_menu(); - self.reference_open = true; - } + ui.weak("Screen references"); + self.reference_actions_menu(ui); } pub(super) fn snapping_options(&mut self, ui: &mut egui::Ui) { ui.checkbox(&mut self.snapping.enabled, "Snap movement & resizing"); @@ -114,7 +107,7 @@ impl Editor { if ui.button("Reset example title").clicked() { self.backdrop_title = midra_layout::project::DEFAULT_BACKDROP_TITLE.into(); } - if self.reference.is_some() { + if !self.references.is_empty() { ui.weak("The reference image replaces this example backdrop."); } } diff --git a/crates/midra-layout/src/project.rs b/crates/midra-layout/src/project.rs index 8cf577d..046a318 100644 --- a/crates/midra-layout/src/project.rs +++ b/crates/midra-layout/src/project.rs @@ -116,14 +116,14 @@ pub struct Project { pub output_resolution: Resolution, pub inputs: Vec, pub layers: Vec, - pub reference: Option, + pub references: Vec, pub editor: EditorSettings, } impl Project { pub fn from_layout(layout: &Layout) -> Self { Self { format: FORMAT.into(), - version: 9, + version: 10, next_layer_id: layout.next_id, output_resolution: layout.formats.output.into(), inputs: (0..layout.formats.sources.len()) @@ -151,7 +151,7 @@ impl Project { locked: layout.locked[i], }) .collect(), - reference: None, + references: Vec::new(), editor: EditorSettings { backdrop_title: DEFAULT_BACKDROP_TITLE.into(), selected_layer_ids: layout @@ -172,9 +172,9 @@ impl Project { } /// Build a fresh document only after validating the entire file. No history is restored. pub fn layout(&self) -> Result { - if self.format != FORMAT || self.version != 9 { + if self.format != FORMAT || self.version != 10 { return Err( - "Unsupported project format/version; expected beffroi.midra-layout version 9." + "Unsupported project format/version; expected beffroi.midra-layout version 10." .into(), ); } @@ -279,8 +279,15 @@ impl Project { layout.selected[index] = true; } - if let Some(r) = &self.reference { - r.bytes()?; + if self.references.len() > 32 { + return Err("A project supports up to 32 reference images.".into()); + } + let mut reference_bytes = 0; + for r in &self.references { + reference_bytes += r.bytes()?.len(); + } + if reference_bytes > 64 * 1024 * 1024 { + return Err("Reference images exceed the combined 64 MiB limit.".into()); } Ok(layout) } @@ -302,8 +309,8 @@ impl Project { } let header: Header = serde_json::from_str(text).map_err(|e| format!("Invalid project JSON: {e}"))?; - if !(1..=9).contains(&header.version) { - return Err("Unsupported project version; expected versions 1–9.".into()); + if !(1..=10).contains(&header.version) { + return Err("Unsupported project version; expected versions 1–10.".into()); } let mut migrated: serde_json::Value = if header.version == 1 || header.version == 2 { let mut value: serde_json::Value = @@ -427,6 +434,24 @@ impl Project { } migrated["version"] = 9.into(); } + if (1..=9).contains(&header.version) { + let object = migrated.as_object_mut().ok_or("Invalid project")?; + if object.contains_key("references") { + return Err("Unexpected reference collection in old project".into()); + } + let reference = object + .remove("reference") + .ok_or("Missing reference field")?; + object.insert( + "references".into(), + if reference.is_null() { + serde_json::json!([]) + } else { + serde_json::json!([reference]) + }, + ); + object.insert("version".into(), 10.into()); + } let p: Self = serde_json::from_value(migrated).map_err(|e| format!("Invalid project JSON: {e}"))?; p.layout()?; diff --git a/crates/midra-layout/src/project_ui.rs b/crates/midra-layout/src/project_ui.rs index c8e7c5a..2589a01 100644 --- a/crates/midra-layout/src/project_ui.rs +++ b/crates/midra-layout/src/project_ui.rs @@ -31,15 +31,19 @@ impl Editor { p.editor.show_source_pattern = self.show_pattern; p.editor.outline_layers = self.outline_layers; p.editor.show_toolbar_icon_names = self.show_toolbar_icon_names; - p.reference = self.reference.as_ref().map(|r| SavedReference { - name: r.name.clone(), - image_base64: STANDARD.encode(&r.bytes), - visible: r.visible, - opacity: r.opacity, - preserve_ratio: r.preserve_ratio, - native_size: r.native_size, - offset: r.offset, - }); + p.references = self + .references + .iter() + .map(|r| SavedReference { + name: r.name.clone(), + image_base64: STANDARD.encode(&r.bytes), + visible: r.visible, + opacity: r.opacity, + preserve_ratio: r.preserve_ratio, + native_size: r.native_size, + offset: r.offset, + }) + .collect(); p } pub(super) fn install_project( @@ -53,9 +57,9 @@ impl Editor { ); } let layout = project.layout()?; - let reference = project - .reference - .as_ref() + let references = project + .references + .iter() .map(|r| { let file = egui::DroppedFile { name: r.name.clone(), @@ -70,7 +74,7 @@ impl Editor { reference.offset = r.offset; Ok::<_, String>(reference) }) - .transpose()?; + .collect::, _>>()?; let e = project.editor; self.device.reset_mappings(); self.device.input_edits.clear(); @@ -85,7 +89,8 @@ impl Editor { pivot_tool: self.pivot_tool, navigation_tool: self.navigation_tool, layout, - reference, + reference_selected: references.len().checked_sub(1), + references, corner: e.position_point, position_layer_point: e.position_layer_point, backdrop_title: e.backdrop_title, @@ -214,7 +219,7 @@ impl Editor { ui.close_menu(); self.save_project_as(); } - ui.small("Saves applied values and the reference image."); + ui.small("Saves applied values and reference images."); ui.separator(); if ui .add_enabled( @@ -253,7 +258,7 @@ impl Editor { "Include background layer", ) .on_hover_text(if format.artwork() { - "Embed the visible reference image on a screen-sized background, or a plain backdrop when none is visible." + "Composite the visible reference images on a screen-sized background, or a plain backdrop when none is visible." } else { "Include a screen-sized background rectangle. This format cannot embed its picture." }); @@ -655,12 +660,17 @@ mod tests { }; app.load_reference(&ctx, &file); app.wait_reference(); - let reference = app.reference.as_mut().unwrap(); + let reference = app.references.first_mut().unwrap(); reference.opacity = 0.4; reference.visible = false; reference.preserve_ratio = true; reference.native_size = true; reference.offset = [-12.5, 34.25]; + let mut second_file = file.clone(); + second_file.name = "second-guide.png".into(); + app.load_reference(&ctx, &second_file); + app.wait_reference(); + assert_eq!(app.references.len(), 2); app.outline_layers = true; app.zoom = 2.5; app.pan = Vec2::new(-20.5, 40.0); @@ -693,10 +703,10 @@ mod tests { assert_eq!(restored.pivot_for(0), [-0.25, 0.75]); assert_eq!(restored.pivot_for(1), [0.1, 0.9]); assert!(!restored.edit_content); - assert_eq!(restored.reference.as_ref().unwrap().bytes, original_bytes); + assert_eq!(restored.references.first().unwrap().bytes, original_bytes); let mut broken = project.clone(); broken.output_resolution.width = 3000; - broken.reference.as_mut().unwrap().image_base64 = STANDARD.encode(b"not an image"); + broken.references.last_mut().unwrap().image_base64 = STANDARD.encode(b"not an image"); assert!(restored.install_project(&ctx, broken).is_err()); assert_eq!(restored.project(), project); } diff --git a/crates/midra-layout/src/recovery_ui.rs b/crates/midra-layout/src/recovery_ui.rs index 2db8905..029922a 100644 --- a/crates/midra-layout/src/recovery_ui.rs +++ b/crates/midra-layout/src/recovery_ui.rs @@ -11,10 +11,17 @@ use std::{ #[serde(deny_unknown_fields)] struct Snapshot { version: u32, + #[serde(deserialize_with = "deserialize_project")] project: Project, project_path: Option, manual_saved_at: Option, } +fn deserialize_project<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result { + let value = serde_json::Value::deserialize(deserializer)?; + Project::from_json(&value.to_string()).map_err(serde::de::Error::custom) +} #[derive(Default)] pub(super) struct Recovery { pub path: Option, diff --git a/crates/midra-layout/src/reference.rs b/crates/midra-layout/src/reference.rs index ca679ee..dabe566 100644 --- a/crates/midra-layout/src/reference.rs +++ b/crates/midra-layout/src/reference.rs @@ -73,7 +73,6 @@ impl Reference { } } pub fn paint(&self, painter: &egui::Painter, screen: Rect, output: [u32; 2]) { - painter.rect_filled(screen, 0.0, theme::palette(painter.ctx()).canvas); if !self.visible { return; } diff --git a/crates/midra-layout/src/reference_ui.rs b/crates/midra-layout/src/reference_ui.rs new file mode 100644 index 0000000..a402bca --- /dev/null +++ b/crates/midra-layout/src/reference_ui.rs @@ -0,0 +1,299 @@ +use super::*; + +impl Editor { + pub(super) fn remove_reference(&mut self, i: usize) { + if i >= self.references.len() { + return; + } + self.references.remove(i); + self.reference_selected = match self.reference_selected { + Some(selected) if selected > i => Some(selected - 1), + Some(selected) if selected == i => { + self.references.len().checked_sub(1).map(|last| i.min(last)) + } + selected => selected, + }; + self.reference_error.clear(); + } + pub(super) fn reference_actions_menu(&mut self, ui: &mut egui::Ui) { + if ui.button("Add reference images…").clicked() { + ui.close_menu(); + self.import_reference_file(ui.ctx()); + } + if self.references.is_empty() { + return; + } + let mut selected = self.reference_selected.unwrap_or(self.references.len() - 1); + egui::ComboBox::from_id_salt("reference-choice") + .selected_text(&self.references[selected].name) + .show_ui(ui, |ui| { + for (i, reference) in self.references.iter().enumerate() { + ui.selectable_value(&mut selected, i, &reference.name); + } + }); + self.reference_selected = Some(selected); + if ui.button("Reference settings…").clicked() { + self.reference_open = true; + ui.close_menu(); + } + if ui.button("Show only this reference").clicked() { + self.show_only_reference(selected); + ui.close_menu(); + } + if ui.button("Remove reference image").clicked() { + self.remove_reference(selected); + ui.close_menu(); + } + } + fn show_only_reference(&mut self, selected: usize) { + for (i, reference) in self.references.iter_mut().enumerate() { + reference.visible = i == selected; + } + } + pub(super) fn reference_rows(&mut self, ui: &mut egui::Ui, ink: &Ink, y: f32, w: f32) { + if self.references.is_empty() { + return; + } + let palette = theme::palette(ui.ctx()); + ink.text(0., y + 8., "REFERENCE IMAGES", 11., palette.purple); + if ui + .put( + Rect::from_min_size(ink.point(w - 65., y), Vec2::new(65., 28.)), + egui::Button::new("+ Add…"), + ) + .clicked() + { + self.import_reference_file(ui.ctx()); + } + let mut remove = None; + for i in (0..self.references.len()).rev() { + let row_y = y + 44. + (self.references.len() - 1 - i) as f32 * 44.; + let selected = + self.reference_selected == Some(i) && self.layout.selected_indices().is_empty(); + ink.card( + 0., + row_y, + w, + 38., + palette.field, + if selected { + palette.purple + } else { + palette.line + }, + ); + let label_rect = + Rect::from_min_size(ink.point(10., row_y), Vec2::new((w - 90.).max(0.), 38.)); + ui.painter().with_clip_rect(label_rect).text( + label_rect.left_center(), + Align2::LEFT_CENTER, + &self.references[i].name, + FontId::proportional(14.), + if self.references[i].visible { + palette.purple + } else { + palette.muted + }, + ); + let row = ui + .interact( + label_rect, + egui::Id::new(("reference-row", i)), + egui::Sense::click(), + ) + .on_hover_text( + "Fixed reference image · double-click for settings · right-click for actions", + ); + if row.clicked() || row.secondary_clicked() { + self.reference_selected = Some(i); + self.layout.select(None); + self.edit_content = false; + self.sync(); + } + if row.double_clicked() { + self.reference_open = true; + } + row.context_menu(|ui| { + if ui.button("Reference settings…").clicked() { + self.reference_selected = Some(i); + self.reference_open = true; + ui.close_menu(); + } + if ui.button("Show only this reference").clicked() { + self.show_only_reference(i); + ui.close_menu(); + } + if ui.button("Remove reference image").clicked() { + remove = Some(i); + ui.close_menu(); + } + }); + let eye = Rect::from_min_size(ink.point(w - 72., row_y + 5.), Vec2::splat(28.)); + if state_icon( + ui, + eye, + egui::Id::new(("reference-visible", i)), + false, + !self.references[i].visible, + if self.references[i].visible { + "Hide reference image" + } else { + "Show reference image" + }, + ) + .clicked() + { + self.references[i].visible = !self.references[i].visible; + } + let close = Rect::from_min_size(ink.point(w - 36., row_y + 5.), Vec2::splat(28.)); + let response = ui + .interact( + close, + egui::Id::new(("reference-remove", i)), + egui::Sense::click(), + ) + .on_hover_text("Remove reference image"); + let color = if response.hovered() { + palette.purple + } else { + palette.muted + }; + for sign in [-1., 1.] { + ui.painter().line_segment( + [ + close.center() + Vec2::new(-4., sign * -4.), + close.center() + Vec2::new(4., sign * 4.), + ], + Stroke::new(1.5_f32, color), + ); + } + response.widget_info(|| { + egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Remove reference image") + }); + if response.clicked() { + remove = Some(i); + } + // References deliberately have no drag payload, resize handles or device mapping. + } + if let Some(i) = remove { + self.remove_reference(i); + } + } +} + +#[cfg(test)] +mod tests { + use super::super::tests::{frame, mouse}; + use super::*; + + fn file(name: &str, color: [u8; 4]) -> egui::DroppedFile { + let mut bytes = std::io::Cursor::new(Vec::new()); + image::RgbaImage::from_pixel(4, 4, image::Rgba(color)) + .write_to(&mut bytes, image::ImageFormat::Png) + .unwrap(); + egui::DroppedFile { + name: name.into(), + bytes: Some(bytes.into_inner().into()), + ..Default::default() + } + } + fn click_id(app: &mut Editor, ctx: &egui::Context, id: egui::Id) { + frame(app, ctx, vec![]); + frame(app, ctx, vec![]); + let pos = ctx.read_response(id).unwrap().rect.center(); + frame( + app, + ctx, + vec![egui::Event::PointerMoved(pos), mouse(pos, true)], + ); + frame(app, ctx, vec![mouse(pos, false)]); + } + + #[test] + fn references_append_paint_and_toggle_independently_without_editable_geometry() { + let ctx = egui::Context::default(); + let mut app = Editor::default(); + let geometry = app.layout.layers().clone(); + app.load_reference(&ctx, &file("First", [255, 0, 0, 255])); + app.load_reference(&ctx, &file("Second", [0, 0, 255, 128])); + app.wait_reference(); + assert_eq!( + app.references + .iter() + .map(|r| r.name.as_str()) + .collect::>(), + ["First", "Second"] + ); + let output = frame(&mut app, &ctx, vec![]); + for reference in &app.references { + assert!(output.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Mesh(mesh) if mesh.texture_id == reference.texture.id()))); + } + click_id(&mut app, &ctx, egui::Id::new(("reference-row", 1_usize))); + assert!(app.layout.selected_indices().is_empty()); + let pos = ctx + .read_response(egui::Id::new(("reference-row", 1_usize))) + .unwrap() + .rect + .center(); + frame( + &mut app, + &ctx, + vec![egui::Event::PointerMoved(pos), mouse(pos, true)], + ); + frame( + &mut app, + &ctx, + vec![egui::Event::PointerMoved(pos + Vec2::new(0., 60.))], + ); + frame(&mut app, &ctx, vec![mouse(pos + Vec2::new(0., 60.), false)]); + assert_eq!(app.references[1].offset, [0.; 2]); + assert_eq!(*app.layout.layers(), geometry); + click_id( + &mut app, + &ctx, + egui::Id::new(("reference-visible", 1_usize)), + ); + assert!(!app.references[1].visible); + assert!(app.references[0].visible); + let output = frame(&mut app, &ctx, vec![]); + assert!(!output.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Mesh(mesh) if mesh.texture_id == app.references[1].texture.id()))); + app.show_only_reference(1); + assert!(!app.references[0].visible); + assert!(app.references[1].visible); + click_id(&mut app, &ctx, egui::Id::new(("reference-remove", 1_usize))); + assert_eq!(app.references.len(), 1); + assert_eq!(app.references[0].name, "First"); + assert_eq!(app.reference_selected, Some(0)); + app.remove_reference(0); + assert!(app.references.is_empty()); + assert_eq!(app.reference_selected, None); + assert_eq!(*app.layout.layers(), geometry); + } + + #[test] + fn removal_keeps_current_reference_identity_and_bad_addition_keeps_existing_images() { + let ctx = egui::Context::default(); + let mut app = Editor::default(); + for name in ["First", "Second", "Third"] { + app.load_reference(&ctx, &file(name, [0, 255, 0, 255])); + } + app.wait_reference(); + app.remove_reference(0); + assert_eq!(app.reference_selected, Some(1)); + assert_eq!(app.references[1].name, "Third"); + app.load_reference( + &ctx, + &egui::DroppedFile { + bytes: Some(Vec::from(b"bad image").into()), + ..Default::default() + }, + ); + app.wait_reference(); + assert!(!app.reference_error.is_empty()); + assert_eq!(app.references.len(), 2); + let project = app.project(); + let mut restored = Editor::default(); + restored.install_project(&ctx, project.clone()).unwrap(); + assert_eq!(restored.project(), project); + } +} diff --git a/crates/midra-layout/tests/exchange.rs b/crates/midra-layout/tests/exchange.rs index 7307d3e..3c4b5c0 100644 --- a/crates/midra-layout/tests/exchange.rs +++ b/crates/midra-layout/tests/exchange.rs @@ -300,7 +300,7 @@ fn reference_image_is_embedded_and_missing_ids_or_invalid_versions_fail() { image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])) .write_to(&mut png, image::ImageFormat::Png) .unwrap(); - p.reference = Some(midra_layout::project::Reference { + p.references.push(midra_layout::project::Reference { name: "red".into(), image_base64: STANDARD.encode(png.into_inner()), visible: true, @@ -397,3 +397,55 @@ fn documented_examples_import_and_limits_are_enforced() { p.layers[0].bounds.width = 0.1; assert!(exchange::export(&p, &[p.layers[0].id], Format::Svg, Options::default()).is_err()); } + +#[test] +fn exported_background_composites_visible_references_in_order() { + let mut project = fixture(); + for (name, color, visible) in [ + ("Red", [255, 0, 0, 255], true), + ("Blue", [0, 0, 255, 128], true), + ("Hidden green", [0, 255, 0, 255], false), + ] { + let mut png = std::io::Cursor::new(Vec::new()); + image::RgbaImage::from_pixel(2, 2, image::Rgba(color)) + .write_to(&mut png, image::ImageFormat::Png) + .unwrap(); + project.references.push(midra_layout::project::Reference { + name: name.into(), + image_base64: STANDARD.encode(png.into_inner()), + visible, + opacity: 1.0, + preserve_ratio: false, + native_size: false, + offset: [0.; 2], + }); + } + let xml = exchange::export( + &project, + &[project.layers[0].id], + Format::Svg, + Options { + background: true, + placeholders: false, + }, + ) + .unwrap(); + let doc = roxmltree::Document::parse(&xml).unwrap(); + let data = doc + .descendants() + .find(|n| n.has_tag_name("image")) + .unwrap() + .attribute(("http://www.w3.org/1999/xlink", "href")) + .unwrap(); + let image = image::load_from_memory( + &STANDARD + .decode(data.strip_prefix("data:image/png;base64,").unwrap()) + .unwrap(), + ) + .unwrap() + .to_rgba8(); + assert_eq!(*image.get_pixel(0, 0), image::Rgba([127, 0, 128, 255])); + let shapes = parse_values(&xml).unwrap().shapes; + assert_eq!(shapes.len(), 2); // one flattened background and one real layer + assert!(shapes[0].background_only); +} diff --git a/crates/midra-layout/tests/project.rs b/crates/midra-layout/tests/project.rs index 9fdb73d..07dea98 100644 --- a/crates/midra-layout/tests/project.rs +++ b/crates/midra-layout/tests/project.rs @@ -230,7 +230,7 @@ fn persistent_midra_links_roundtrip_migrate_and_undo() { include_str!("../../../docs/interfaces/midra-layout-v5.example.json"), ] { let p = Project::from_json(text).unwrap(); - assert_eq!(p.version, 9); + assert_eq!(p.version, 10); assert!(p.layers.iter().all(|l| l.midra_link.is_none())); } let mut value = serde_json::to_value(&project).unwrap(); @@ -307,7 +307,7 @@ fn position_point_schema_migrates_corners_and_rejects_mislabeled_files() { .unwrap(); old["editor"]["position_corner"] = name.into(); let loaded = Project::from_json(&old.to_string()).unwrap(); - assert_eq!(loaded.version, 9); + assert_eq!(loaded.version, 10); assert_eq!(loaded.editor.position_point, expected); old["editor"]["position_corner"] = "center".into(); assert!(Project::from_json(&old.to_string()).is_err()); @@ -316,7 +316,7 @@ fn position_point_schema_migrates_corners_and_rejects_mislabeled_files() { assert!(Project::from_json(&old.to_string()).is_err()); } let value: serde_json::Value = serde_json::from_str(¤t.to_json().unwrap()).unwrap(); - for version in [0, 10] { + for version in [0, 11] { let mut invalid = value.clone(); invalid["version"] = version.into(); assert!( @@ -357,7 +357,7 @@ fn backdrop_title_roundtrips_and_older_projects_gain_the_default() { } let old = include_str!("../../../docs/interfaces/midra-layout-v6.example.json"); let migrated = Project::from_json(old).unwrap(); - assert_eq!(migrated.version, 9); + assert_eq!(migrated.version, 10); assert_eq!(migrated.editor.backdrop_title, DEFAULT_BACKDROP_TITLE); let mut invalid: serde_json::Value = serde_json::from_str(old).unwrap(); invalid["editor"]["backdrop_title"] = "Unexpected".into(); @@ -428,7 +428,7 @@ fn saved_pivots_roundtrip_and_old_projects_default_to_center() { assert_eq!(loaded.layer_info(0).pivot, custom); assert_eq!(loaded.layer_info(1).pivot, [0.5; 2]); let example = include_str!("../../../docs/interfaces/midra-layout-v9.example.json"); - assert_eq!(Project::from_json(example).unwrap().version, 9); + assert_eq!(Project::from_json(example).unwrap().version, 10); let old = include_str!("../../../docs/interfaces/midra-layout-v8.example.json"); let migrated = Project::from_json(old).unwrap(); assert!(migrated.layers.iter().all(|l| l.pivot == [0.5; 2])); @@ -449,3 +449,36 @@ fn saved_pivots_roundtrip_and_old_projects_default_to_center() { value["layers"][0].as_object_mut().unwrap().remove("pivot"); assert!(Project::from_json(&value.to_string()).is_err()); } + +#[test] +fn reference_collection_migrates_single_images_and_rejects_mislabeled_or_oversized_collections() { + use base64::{Engine, engine::general_purpose::STANDARD}; + let mut old: serde_json::Value = serde_json::from_str(include_str!( + "../../../docs/interfaces/midra-layout-v9.example.json" + )) + .unwrap(); + let reference = serde_json::json!({"name":"guide.png","image_base64":STANDARD.encode(b"image bytes"),"visible":false,"opacity":0.4,"preserve_ratio":true,"native_size":false,"offset":[0.0,0.0]}); + old["reference"] = reference.clone(); + let migrated = Project::from_json(&old.to_string()).unwrap(); + assert_eq!(migrated.version, 10); + assert_eq!(migrated.references.len(), 1); + assert!(!migrated.references[0].visible); + assert_eq!(migrated.references[0].opacity, 0.4); + let mut gallery = migrated.clone(); + gallery.references.push(migrated.references[0].clone()); + gallery.references[1].name = "other.png".into(); + gallery.references[1].visible = true; + assert_eq!( + Project::from_json(&gallery.to_json().unwrap()).unwrap(), + gallery + ); + old["references"] = serde_json::json!([]); + assert!(Project::from_json(&old.to_string()).is_err()); + let mut wrong = serde_json::to_value(&gallery).unwrap(); + wrong["reference"] = reference; + assert!(Project::from_json(&wrong.to_string()).is_err()); + gallery.references = vec![migrated.references[0].clone(); 33]; + assert!(gallery.to_json().unwrap_err().contains("32 reference")); + let example = include_str!("../../../docs/interfaces/midra-layout-v10.example.json"); + assert_eq!(Project::from_json(example).unwrap().version, 10); +} diff --git a/docs/interfaces/midra-device-send.md b/docs/interfaces/midra-device-send.md index adad26d..01e4139 100644 --- a/docs/interfaces/midra-device-send.md +++ b/docs/interfaces/midra-device-send.md @@ -1,7 +1,6 @@ # Midra reviewed layer exchange -This is a transient device protocol, not a project/save schema. Project v9 remains -unchanged. Compatibility exercised: Eikos 4K firmware 3.3.10, installed WebRCS +This is a transient device protocol, not a project/save schema. Reference collections in project v10 do not change device layer mapping. Compatibility exercised: Eikos 4K firmware 3.3.10, installed WebRCS `app.e42fce4879f318b28cde.js`. Other firmware needs verification. ## Addressing and fields @@ -141,7 +140,7 @@ row remapping until scope/screen changes or refresh. Ambiguous/unlinked rows sta 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; +link or geometry rejects the entire transaction. This uses existing layer fields (unchanged in project v10); there is no schema/version change. Source routing and device memories are not imported. Layer properties → **Mapping** edits the existing per-layer `midra_link.screen` diff --git a/docs/interfaces/midra-layout-exchange.md b/docs/interfaces/midra-layout-exchange.md index 9888ae5..78dfefe 100644 --- a/docs/interfaces/midra-layout-exchange.md +++ b/docs/interfaces/midra-layout-exchange.md @@ -3,7 +3,7 @@ The Export menu writes **SVG v2**, **draw.io v1**, **geometry JSON v1**, **geometry CSV v1**, **DXF**, **HTML/CSS v1**, **PPTX**, **Figma FIG** and **Illustrator AI** (the latter via a local VectorCraft CLI). Project -JSON remains version 9 and is the full-fidelity save format. These exchanges +JSON is version 10 and is the full-fidelity save format. These exchanges preserve layer **visible-box geometry**, not sources, crop settings, zoom, pivots, Midra links, locks, visibility, camera or selection. Pictures illustrate current cropping; importing a picture does not reconstruct its crop or source settings. @@ -62,8 +62,8 @@ they do not modify the project/settings schema: - **Include background layer** adds a first, full-screen shape with ID `midra-background`, explicitly marked as background. SVG, draw.io, JSON, HTML, PPTX, FIG and AI - embed a visible reference composited over a dark backdrop using the current - fit/stretch/native-size, offset and opacity; otherwise they embed a plain dark + embed all visible references composited in project order over a dark backdrop + using each image's fit/stretch/native-size, offset and opacity; otherwise they embed a plain dark backdrop. This is a baked visual reference, not an editable copy of reference settings. Image raster dimensions are proportional to the screen, capped at 1920 pixels on the longest side; the exported shape still has the exact screen @@ -228,7 +228,7 @@ UTF-8 JSON with root fields `format: "beffroi.midra-geometry"`, `version: 1`, `layer` or `background`. Unknown fields, versions and units are rejected. IDs must be unique and at most 255 characters; names are limited to 1024 characters without controls. This JSON is the preferred small machine interface. It is not -the version-9 project save file and does not contain sources, crop or device links. +the version-10 project save file and does not contain sources, crop or device links. ## Geometry CSV v1 @@ -323,3 +323,8 @@ Protocol references: [draw.io diagram format](https://www.drawio.com/docs/refere and [desktop CLI](https://github.com/jgraph/drawio/wiki/Desktop-App), [SVG 2](https://www.w3.org/TR/SVG/), [CSV RFC 4180](https://datatracker.ietf.org/doc/rfc4180/), and Autodesk's [DXF group-code reference](https://help.autodesk.com/cloudhelp/2025/ENU/AutoCAD-DXF/files/GUID-89CB823D-614D-4D1E-8204-568EC72DF869.htm). + +Multiple references are flattened into the same single background image in +artwork-capable exports; no format version changes. Reimport reconstructs that +background as a geometry/artwork item, not the editable reference collection. +Use project JSON v10 to preserve independent images and visibility. diff --git a/docs/interfaces/midra-layout-recovery.md b/docs/interfaces/midra-layout-recovery.md index 340ca61..28b3cd5 100644 --- a/docs/interfaces/midra-layout-recovery.md +++ b/docs/interfaces/midra-layout-recovery.md @@ -7,7 +7,7 @@ not a named project export. Headless/default editors never access this path. | Field | Meaning | | --- | --- | | `version` | Integer `1`; other versions rejected | -| `project` | Complete [project v9](midra-layout.md), including embedded reference bytes; its units, precision and validation apply without display rounding | +| `project` | Complete [project v10](midra-layout.md), including embedded reference bytes; its units, precision and validation apply without display rounding | | `project_path` | Last opened/successfully saved named JSON path, or null; geometry exports do not change it | | `manual_saved_at` | Unix UTC seconds of the last successful explicit project save, or null when unknown; recovery and measurement-point autosaves do not update it | @@ -28,7 +28,7 @@ last successful writer wins. Recovery retains applied values only: no undo history, pending text/format/import drafts, transient tools, or credentials. A normal exit cancels unfinished canvas gestures before the final checkpoint. The schema does not replace named project -JSON: Save continues to emit a bare project v9 document. Opening/New replaces the +JSON: Save continues to emit a bare project v10 document. Opening/New replaces the single recovery slot; New warns with the manual-save age and Save/Discard/Cancel. A failed or cancelled manual save never completes Save-and-create-new. @@ -36,3 +36,7 @@ A failed or cancelled manual save never completes Save-and-create-new. Future breaking envelope changes require a version bump and explicit migration or rejection. Recovery is not an interchange format; use Save for portable files. + +Recovery envelope version 1 is unchanged. Nested project versions 1–9 migrate +through the normal project loader before typed decoding, including the former +single `reference` field. All reference images and visibility settings are saved. diff --git a/docs/interfaces/midra-layout-v10.example.json b/docs/interfaces/midra-layout-v10.example.json new file mode 100644 index 0000000..df0dbd4 --- /dev/null +++ b/docs/interfaces/midra-layout-v10.example.json @@ -0,0 +1,109 @@ +{ + "format": "beffroi.midra-layout", + "version": 10, + "output_resolution": { + "width": 1920, + "height": 1080 + }, + "inputs": [ + { + "id": 1, + "source_format": "sixteen_nine", + "native_resolution": { + "width": 1920, + "height": 1080 + }, + "input_crop": { + "left": 0.0, + "right": 0.0, + "top": 0.0, + "bottom": 0.0 + } + }, + { + "id": 2, + "source_format": "sixteen_nine", + "native_resolution": { + "width": 1920, + "height": 1080 + }, + "input_crop": { + "left": 0.0, + "right": 0.0, + "top": 0.0, + "bottom": 0.0 + } + } + ], + "layers": [ + { + "id": 2, + "source_id": 1, + "bounds": { + "x": 120.0, + "y": 180.0, + "width": 640.0, + "height": 360.0 + }, + "advanced_crop": { + "left": 0.0, + "right": 0.0, + "top": 0.0, + "bottom": 0.0 + }, + "visible": true, + "locked": false, + "name": "Slides", + "folder": "", + "midra_link": null, + "pivot": [ + 0.5, + 0.5 + ] + }, + { + "id": 1, + "source_id": 2, + "bounds": { + "x": 1160.0, + "y": 180.0, + "width": 640.0, + "height": 360.0 + }, + "advanced_crop": { + "left": 0.0, + "right": 0.0, + "top": 0.0, + "bottom": 0.0 + }, + "visible": true, + "locked": false, + "name": "Presenter", + "folder": "", + "midra_link": null, + "pivot": [ + 0.5, + 0.5 + ] + } + ], + "editor": { + "backdrop_title": "Example Conference Name", + "selected_layer_ids": [ + 1 + ], + "position_point": "top_left", + "keep_aspect_ratio": true, + "viewport_zoom": 1.0, + "viewport_pan": [ + 0.0, + 0.0 + ], + "show_source_pattern": false, + "show_toolbar_icon_names": false, + "outline_layers": false, + "position_layer_point": null + }, + "next_layer_id": 3, + "references": [] +} diff --git a/docs/interfaces/midra-layout.md b/docs/interfaces/midra-layout.md index 63f837a..4d1ffe7 100644 --- a/docs/interfaces/midra-layout.md +++ b/docs/interfaces/midra-layout.md @@ -5,7 +5,7 @@ These are offline editor formats, not Analog Way REST payloads. Implementation: [`project.rs`](../../crates/midra-layout/tests/project.rs). Update this contract, examples and tests in the same change as any save/export schema change. -## Project JSON, version 9 +## Project JSON, version 10 Suggested filename: `layout.midra.json`. Encoding: UTF-8, pretty-printed JSON, with a trailing newline. A project preserves applied document values at their @@ -18,10 +18,10 @@ and `next_layer_id: 3`; other values are preserved. The [version 1 example](midra-layout-v1.example.json) remains a migration fixture. Version 4 adds `editor.outline_layers: false`, and reference `native_size: false` and `offset: [0, 0]` when migrating versions 1–3. Old fitting behavior is preserved. -Version 5 adds required `midra_link` to every layer. Versions 1–4 migrate with null links; links cannot be supplied under an older version. Version 6 renames `editor.position_corner` to `editor.position_point` and adds `center`. Versions 1–5 retain their original corner; center and the new field are rejected in those older schemas. Version 7 adds `editor.backdrop_title`; versions 1–6 gain `"Example Conference Name"` and cannot supply this field under the old schema. Version 8 adds required `editor.position_layer_point`: null keeps matched points; a point enables independent measurement. Versions 1–7 migrate to null and cannot supply this field. Version 9 adds required `layers[].pivot`; versions 1–8 migrate to `[0.5, 0.5]` and cannot supply this field. Saving always writes version 9; older applications reject it. +Version 5 adds required `midra_link` to every layer. Versions 1–4 migrate with null links; links cannot be supplied under an older version. Version 6 renames `editor.position_corner` to `editor.position_point` and adds `center`. Versions 1–5 retain their original corner; center and the new field are rejected in those older schemas. Version 7 adds `editor.backdrop_title`; versions 1–6 gain `"Example Conference Name"` and cannot supply this field under the old schema. Version 8 adds required `editor.position_layer_point`: null keeps matched points; a point enables independent measurement. Versions 1–7 migrate to null and cannot supply this field. Version 9 adds required `layers[].pivot`; versions 1–8 migrate to `[0.5, 0.5]` and cannot supply this field. Version 10 replaces `reference` with the required ordered `references` array. Versions 1–9 migrate null to `[]` and a single image to a one-element array, preserving all image settings. Saving always writes version 10; older applications reject it. Incompatible files are never partially applied. -[Complete example](midra-layout-v9.example.json) is a valid default project, +[Complete example](midra-layout-v10.example.json) is a valid default project, without a reference image. New projects label the lower layer `02 / Slides` and the upper layer `01 / Presenter`; existing projects retain their saved IDs/names. It is loaded by the regression tests. @@ -29,12 +29,12 @@ It is loaded by the regression tests. | Root field | Representation / meaning | | --- | --- | | `format` | Exactly `"beffroi.midra-layout"` | -| `version` | Integer `9` | +| `version` | Integer `10` | | `next_layer_id` | Positive integer strictly greater than every layer ID; not rewound by undo | | `output_resolution` | `{ "width": integer, "height": integer }`, screen pixels | | `inputs` | 1–1024 input objects, consecutive IDs starting at 1 | | `layers` | 1–256 layer objects, unique positive stable IDs, in back-to-front stacking order (last is topmost) | -| `reference` | `null` or an embedded reference-image object | +| `references` | Required array of 0–32 embedded reference-image objects, back-to-front compositing order | | `editor` | Selection, positioning and viewport preferences | Input objects: @@ -72,7 +72,7 @@ not duplicated in the save file. Retained source pixels must have the same ratio as the box. Crop zoom must be 1–100 (100–10000%). Shared input assignments and both crop stages survive round trips without rewriting the crop values. -Reference object: +Each reference object: | Field | Representation / meaning | | --- | --- | @@ -84,7 +84,16 @@ Reference object: | `native_size` | Boolean: image pixels map 1:1 to screen pixels; anchored at screen top-left before offset | | `offset` | `[x, y]` finite screen-pixel translation, each within ±1,000,000; applies after fitting/native placement | -The image is embedded, so moving the project does not break the reference. No +Images are embedded, so moving the project does not break the references. Each +image retains independent visibility, opacity and fitting settings. Later entries +paint over earlier ones; hidden entries do not erase earlier images. The editor +lists them topmost first with distinct reference coloring, eye/remove controls +and Show only this reference. They have no layer IDs, geometry handles, device +links or selection/alignment participation. The currently focused reference row +is session-only; saved visibility determines the reopened composite. + +At most 32 images and 64 MiB of combined original image bytes are accepted. +The existing 96 MiB project JSON limit still applies. No external files, URLs or device endpoints are accessed on load. Image dimensions are decoded from the bytes. The existing image loader enforces a 64 MiB encoded file limit, maximum 8192 pixels per side (or the GPU texture limit if smaller), @@ -128,7 +137,7 @@ files require explicit replacement confirmation for Save/exports. Measurement-po clicks and the independent-point toggle are an exception: they reread the current project and atomically update only `editor.position_point` and `editor.position_layer_point`, preserving its other stored values (including external edits). -Older schemas migrate to v9 on this write. No project path is stored in settings; +Older schemas migrate to v10 on this write. No project path is stored in settings; new documents require a first Save. Geometry exports never change the active project path. Missing/invalid/unwritable projects are left untouched and an error is shown; active in-memory choices remain available for a manual Save. A failed no-overwrite write @@ -208,7 +217,7 @@ and `viewBox="0 0 W H"` equal to the output screen. The root carries ## Compatibility changes -Project version 9 and the versioned geometry exchanges are strict contracts. A breaking project field/meaning change must bump +Project version 10 and the versioned geometry exchanges are strict contracts. A breaking project field/meaning change must bump `version` and either implement a tested migration or clearly reject older/newer files. Changing rectangle/marker semantics requires a corresponding documented exchange-interface revision and importer tests. Update this document and its example @@ -226,7 +235,7 @@ retarget existing links; choosing a destination there explicitly replaces that 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. +Automatic session recovery wraps this project representation in a separate [recovery file](midra-layout-recovery.md); named project JSON is version 10. ## Folder-scoped Midra transfers @@ -236,5 +245,5 @@ Folders may store alternative layouts whose `midra_link` values reuse the same s 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 +All these values use the existing layer fields (unchanged in version 10). See [device transfer scopes](midra-device-send.md#shared-transfer-scopes-and-folder-layouts). diff --git a/docs/midra-layout.md b/docs/midra-layout.md index 154183b..ff86886 100644 --- a/docs/midra-layout.md +++ b/docs/midra-layout.md @@ -332,13 +332,28 @@ selection state, including when several layers are selected. ### Reference pictures +Imported images accumulate in a purple **Reference images** section below the +layer list, newest/topmost first. **Add image…** and **+ Add…** accept multiple +files. Use each eye icon to show/hide a guide, the remove icon to delete it, +or right-click **Show only this reference** to switch guides quickly. Double-click +opens that image's settings. Reference rows cannot be dragged, resized, aligned +or sent to Midra; selecting one clears the editable-layer selection. + +Removal is also available in **Import → Remove reference image** and the viewport +context menu's **Reference images** submenu, with a picker for the target image. +Images remain fixed behind the layers; their existing explicit fit/opacity settings +remain available. Visible images composite back-to-front. Saves and recovery retain +all images and settings, while background-enabled exports flatten visible guides. +Older single-image projects migrate automatically to the new v10 collection. + + The **Import** dropdown groups layer-value imports and screen references. -Layer imports require selected destinations. After importing a reference picture, +Layer imports offer destination mapping. After importing a reference picture, **Import → Reference settings…** opens its visibility, opacity and scaling controls. -Drop one PNG, JPEG or BMP into the window, or choose **Import → Reference image…**. The image is fixed behind the layers in screen coordinates; zooming +Drop one or more PNG, JPEG or BMP images into the window, or choose **Import → Add reference images…**. The image is fixed behind the layers in screen coordinates; zooming and panning keep it aligned. Layer fills become translucent to reveal the image. -Use the reference window to hide it, adjust opacity, replace it or remove it. +Use the reference window to pick an imported image, hide it, adjust opacity or remove it. **Fill screen** maps the entire image to the current output resolution. An exact pixel match needs no warning. Scaling up or down with matching proportions shows @@ -347,9 +362,10 @@ WARNING** because the image is distorted. Neither warning blocks importing or moving layers. **Fit inside** preserves proportions and centers the image with empty margins where needed; scaling still produces an amber warning. -Files are limited to 64 MiB and dimensions to 8192 pixels per side or the GPU's -texture limit, whichever is smaller. Invalid imports keep the previous image. -Reference settings are session-only and independent of layer undo/redo. +Up to 32 images with a combined 64 MiB of file bytes can be stored; dimensions +are limited to 8192 pixels per side or the GPU's texture limit, whichever is +smaller. Invalid imports keep all existing images. Reference images and settings +are saved with the project; their edits are independent of layer undo/redo. ### Optional independent positioning points @@ -633,7 +649,7 @@ Use viewport zoom/pan to reach content handles beyond the current view. Use the **Project** toolbar menu to **Save project…** or **Open project…**. Projects use readable, versioned `.midra.json` files and preserve applied output, inputs, layer bounds/crops, source assignments, locks, visibility, selection, -viewport preferences, and the embedded reference image. Apply pending edits +viewport preferences, and all embedded reference images. Apply pending edits before saving. Opening asks before replacing current work and starts a fresh undo history. Existing files require confirmation before replacement. @@ -824,7 +840,7 @@ Stable IDs survive removal and are independent of Midra layer numbers. Group movement, alignment and Same-handles resizing work across the selection; Mirror/Opposite resizing still require exactly two layers. -Project JSON is version 9, with tested migration from older supported versions. +Project JSON is version 10, with tested migration from older supported versions. Every format’s **Selected layers…** action exports just the current selection, including a single layer. All/visible export remains available. @@ -947,7 +963,7 @@ independently of the screen currently displayed in the configuration window. ### Recovery autosave and New project -Applied edits and the reference image are checkpointed to `last_project.json` +Applied edits and reference images are checkpointed to `last_project.json` beside the application settings, at most every two seconds between gestures and again on normal exit. The last session resumes automatically on launch without an Open dialog. Unchanged snapshots are not rewritten. Named project files remain diff --git a/docs/midralayout/changelog.md b/docs/midralayout/changelog.md index 1afca36..1a3cb6b 100644 --- a/docs/midralayout/changelog.md +++ b/docs/midralayout/changelog.md @@ -4,6 +4,8 @@ ## Unreleased +- Keep multiple reference images in a purple section of the layer list, with add, eye, remove, settings and Show only actions; references remain fixed and excluded from layer/device operations. Add removal to Import and viewport/reference context menus. Queue multi-file imports in order, composite visible guides in viewport/artwork exports, and save all images in project v10 with tested v1–v9/recovery migration. Corrupt additions or project images preserve existing work. + - Add Paste layer values beside Copy layer values in the layer context menu, using the existing clipboard import and mapping review before applying changes. - Make Source an advanced, opt-in section with explanations of input aspect correction and pre-layer input crop. Show the linked device input's actual WebRCS aspect/crop controls separately from the local geometry model. Stage only edited fields, include them in scoped sends only while enabled, and pulse input crop updates. The opt-in and staged device edits are session-only and clear on disconnect, address/project change or uncheck. Verified field names/ranges against the connected Eikos WebRCS; regression tests use mock devices, without hardware writes.