diff --git a/AGENTS.md b/AGENTS.md index 69f60ccf..c6bdd48e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -66,7 +66,7 @@ dispel-extractor/ │ ├── dispatch_table.rs # Editor message dispatch table │ ├── binary_layout.rs # Binary layout helpers │ ├── indexation/ # File/asset caching + full-text search -│ ├── tests/ # Dedicated GUI test suite (28 test files) +│ ├── tests/ # Dedicated GUI test suite (29 test files) │ └── recording_tests.rs # Mod recording integration tests (38 tests) ├── examples/ # e.g. check_save_roundtrip.rs ├── docs/ # Overview .md files + docs/files/ (36 per-format + CROSS_REFERENCES.md = 37) @@ -228,7 +228,7 @@ Structure: - Top level: `app.rs`, `config.rs`, `state.rs`, `message.rs`, `main.rs` - `domain/` (~16 files): editing, goto, pattern, provider, search, selection, vanilla_diff, … - `ui/`: coloring, inspector, update, view/, theme -- `tests/`: 16 dedicated test files (**25 `.rs` files with `#[cfg(test)]` total**) +- `tests/`: 16 dedicated test files (**26 `.rs` files with `#[cfg(test)]` total**) **Used by `dispel-gui`:** stored as `HashMap` in `EditorRegistry`, rendered in tabs, with save wired to mod packager via the domain-level `SavePort` (`SaveRequest` → `SaveOutcome`) in `hex_save.rs`. diff --git a/dispel-gui/src/components/command_palette.rs b/dispel-gui/src/components/command_palette.rs index 0e2333e0..5595344c 100644 --- a/dispel-gui/src/components/command_palette.rs +++ b/dispel-gui/src/components/command_palette.rs @@ -74,16 +74,6 @@ impl Command { action: || Message::System(crate::message::system::SystemMessage::ClearWorkspace), applicable_editors: vec![], }, - // ── Tool views ────────────────────────────────────────────────── - Command { - id: "open-store-editor", - label: "Open: Store Editor", - shortcut: None, - action: || { - Message::Workspace(WorkspaceMessage::OpenToolTab(EditorType::StoreEditor)) - }, - applicable_editors: vec![], - }, // ── File operations ────────────────────────────────────────────── Command { id: "open-as-hex", @@ -115,421 +105,6 @@ impl Command { }, applicable_editors: vec![], }, - // ── Weapon Editor ──────────────────────────────────────────────── - Command { - id: "scan-weapons", - label: "Scan: Load Weapon catalog", - shortcut: None, - action: || { - Message::weapon(crate::editors::weapon::WeaponEditorMessage::LoadCatalog) - }, - applicable_editors: vec![EditorType::WeaponEditor], - }, - Command { - id: "save-weapons", - label: "Save: Weapon Editor", - shortcut: None, - action: || Message::weapon(crate::editors::weapon::WeaponEditorMessage::Save), - applicable_editors: vec![EditorType::WeaponEditor], - }, - // ── Heal Item Editor ───────────────────────────────────────────── - Command { - id: "scan-heal-items", - label: "Scan: Load Heal Item catalog", - shortcut: None, - action: || { - Message::heal_item( - crate::editors::heal_item::HealItemEditorMessage::LoadCatalog, - ) - }, - applicable_editors: vec![EditorType::HealItemEditor], - }, - Command { - id: "save-heal-items", - label: "Save: Heal Item Editor", - shortcut: None, - action: || { - Message::heal_item(crate::editors::heal_item::HealItemEditorMessage::Save) - }, - applicable_editors: vec![EditorType::HealItemEditor], - }, - // ── Misc Item Editor ───────────────────────────────────────────── - Command { - id: "scan-misc-items", - label: "Scan: Load Misc Item catalog", - shortcut: None, - action: || { - Message::misc_item( - crate::editors::misc_item::MiscItemEditorMessage::LoadCatalog, - ) - }, - applicable_editors: vec![EditorType::MiscItemEditor], - }, - Command { - id: "save-misc-items", - label: "Save: Misc Item Editor", - shortcut: None, - action: || { - Message::misc_item(crate::editors::misc_item::MiscItemEditorMessage::Save) - }, - applicable_editors: vec![EditorType::MiscItemEditor], - }, - // ── Magic Editor ───────────────────────────────────────────────── - Command { - id: "scan-magic", - label: "Scan: Load Magic catalog", - shortcut: None, - action: || Message::magic(crate::editors::magic::MagicEditorMessage::LoadCatalog), - applicable_editors: vec![EditorType::MagicEditor], - }, - Command { - id: "save-magic", - label: "Save: Magic Editor", - shortcut: None, - action: || Message::magic(crate::editors::magic::MagicEditorMessage::Save), - applicable_editors: vec![EditorType::MagicEditor], - }, - // ── Monster Editor ─────────────────────────────────────────────── - Command { - id: "scan-monsters", - label: "Scan: Load Monster catalog", - shortcut: None, - action: || { - Message::monster(crate::editors::monster::MonsterEditorMessage::LoadCatalog) - }, - applicable_editors: vec![EditorType::MonsterEditor], - }, - Command { - id: "save-monsters", - label: "Save: Monster Editor", - shortcut: None, - action: || Message::monster(crate::editors::monster::MonsterEditorMessage::Save), - applicable_editors: vec![EditorType::MonsterEditor], - }, - // ── Party Ref Editor ───────────────────────────────────────────── - Command { - id: "scan-party-ref", - label: "Scan: Load Party Ref catalog", - shortcut: None, - action: || { - Message::party_ref( - crate::editors::party_ref::PartyRefEditorMessage::LoadCatalog, - ) - }, - applicable_editors: vec![EditorType::PartyRefEditor], - }, - Command { - id: "save-party-ref", - label: "Save: Party Ref Editor", - shortcut: None, - action: || { - Message::party_ref(crate::editors::party_ref::PartyRefEditorMessage::Save) - }, - applicable_editors: vec![EditorType::PartyRefEditor], - }, - // ── Party Ini Editor ───────────────────────────────────────────── - Command { - id: "scan-party-ini", - label: "Scan: Load Party Ini catalog", - shortcut: None, - action: || { - Message::party_ini( - crate::editors::party_ini::PartyIniEditorMessage::LoadCatalog, - ) - }, - applicable_editors: vec![EditorType::PartyIniEditor], - }, - Command { - id: "save-party-ini", - label: "Save: Party Ini Editor", - shortcut: None, - action: || { - Message::party_ini(crate::editors::party_ini::PartyIniEditorMessage::Save) - }, - applicable_editors: vec![EditorType::PartyIniEditor], - }, - // ── ChData Editor ──────────────────────────────────────────────── - Command { - id: "load-chdata", - label: "Scan: Load ChData catalog", - shortcut: None, - action: || { - Message::chdata(crate::editors::chdata::ChDataEditorMessage::LoadCatalog) - }, - applicable_editors: vec![EditorType::ChDataEditor], - }, - Command { - id: "save-chdata", - label: "Save: ChData Editor", - shortcut: None, - action: || Message::chdata(crate::editors::chdata::ChDataEditorMessage::Save), - applicable_editors: vec![EditorType::ChDataEditor], - }, - // ── Map Ini Editor ─────────────────────────────────────────────── - Command { - id: "load-map-ini", - label: "Scan: Load Map Ini catalog", - shortcut: None, - action: || { - Message::map_ini(crate::editors::map_ini::MapIniEditorMessage::LoadCatalog) - }, - applicable_editors: vec![EditorType::MapIniEditor], - }, - Command { - id: "save-map-ini", - label: "Save: Map Ini Editor", - shortcut: None, - action: || Message::map_ini(crate::editors::map_ini::MapIniEditorMessage::Save), - applicable_editors: vec![EditorType::MapIniEditor], - }, - // ── Wave Ini Editor ────────────────────────────────────────────── - Command { - id: "load-wave-ini", - label: "Scan: Load Wave Ini catalog", - shortcut: None, - action: || { - Message::wave_ini(crate::editors::wave_ini::WaveIniEditorMessage::LoadCatalog) - }, - applicable_editors: vec![EditorType::WaveIniEditor], - }, - Command { - id: "save-wave-ini", - label: "Save: Wave Ini Editor", - shortcut: None, - action: || Message::wave_ini(crate::editors::wave_ini::WaveIniEditorMessage::Save), - applicable_editors: vec![EditorType::WaveIniEditor], - }, - // ── Event Ini Editor ───────────────────────────────────────────── - Command { - id: "load-event-ini", - label: "Scan: Load Event Ini catalog", - shortcut: None, - action: || { - Message::event_ini( - crate::editors::event_ini::EventIniEditorMessage::LoadCatalog, - ) - }, - applicable_editors: vec![EditorType::EventIniEditor], - }, - Command { - id: "save-event-ini", - label: "Save: Event Ini Editor", - shortcut: None, - action: || { - Message::event_ini(crate::editors::event_ini::EventIniEditorMessage::Save) - }, - applicable_editors: vec![EditorType::EventIniEditor], - }, - // ── NPC Ini Editor ─────────────────────────────────────────────── - Command { - id: "scan-npc-ini", - label: "Scan: Load NPC Ini catalog", - shortcut: None, - action: || { - Message::npc_ini(crate::editors::npc_ini::NpcIniEditorMessage::LoadCatalog) - }, - applicable_editors: vec![EditorType::NpcIniEditor], - }, - Command { - id: "save-npc-ini", - label: "Save: NPC Ini Editor", - shortcut: None, - action: || Message::npc_ini(crate::editors::npc_ini::NpcIniEditorMessage::Save), - applicable_editors: vec![EditorType::NpcIniEditor], - }, - // ── Quest Scr Editor ───────────────────────────────────────────── - Command { - id: "load-quest-scr", - label: "Scan: Load Quest catalog", - shortcut: None, - action: || { - Message::quest_scr( - crate::editors::quest_scr::QuestScrEditorMessage::LoadCatalog, - ) - }, - applicable_editors: vec![EditorType::QuestScrEditor], - }, - Command { - id: "save-quest-scr", - label: "Save: Quest Scr Editor", - shortcut: None, - action: || { - Message::quest_scr(crate::editors::quest_scr::QuestScrEditorMessage::Save) - }, - applicable_editors: vec![EditorType::QuestScrEditor], - }, - // ── Message Scr Editor ─────────────────────────────────────────── - Command { - id: "load-message-scr", - label: "Scan: Load Message catalog", - shortcut: None, - action: || { - Message::message_scr( - crate::editors::message_scr::MessageScrEditorMessage::LoadCatalog, - ) - }, - applicable_editors: vec![EditorType::MessageScrEditor], - }, - Command { - id: "save-message-scr", - label: "Save: Message Scr Editor", - shortcut: None, - action: || { - Message::message_scr(crate::editors::message_scr::MessageScrEditorMessage::Save) - }, - applicable_editors: vec![EditorType::MessageScrEditor], - }, - // ── Extra Ini Editor ───────────────────────────────────────────── - Command { - id: "load-extra-ini", - label: "Scan: Load Extra Ini catalog", - shortcut: None, - action: || { - Message::extra_ini( - crate::editors::extra_ini::ExtraIniEditorMessage::LoadCatalog, - ) - }, - applicable_editors: vec![EditorType::ExtraIniEditor], - }, - Command { - id: "save-extra-ini", - label: "Save: Extra Ini Editor", - shortcut: None, - action: || { - Message::extra_ini(crate::editors::extra_ini::ExtraIniEditorMessage::Save) - }, - applicable_editors: vec![EditorType::ExtraIniEditor], - }, - // ── Event NpcRef Editor ────────────────────────────────────────── - Command { - id: "load-event-npc-ref", - label: "Scan: Load Event NPC Ref catalog", - shortcut: None, - action: || { - Message::event_npc_ref( - crate::editors::event_npc_ref::EventNpcRefEditorMessage::LoadCatalog, - ) - }, - applicable_editors: vec![EditorType::EventNpcRefEditor], - }, - Command { - id: "save-event-npc-ref", - label: "Save: Event NPC Ref Editor", - shortcut: None, - action: || { - Message::event_npc_ref( - crate::editors::event_npc_ref::EventNpcRefEditorMessage::Save, - ) - }, - applicable_editors: vec![EditorType::EventNpcRefEditor], - }, - // ── All Map Ini Editor ─────────────────────────────────────────── - Command { - id: "load-all-map-ini", - label: "Scan: Load All Map Ini catalog", - shortcut: None, - action: || { - Message::all_map_ini( - crate::editors::all_map_ini::AllMapIniEditorMessage::LoadCatalog, - ) - }, - applicable_editors: vec![EditorType::AllMapIniEditor], - }, - Command { - id: "save-all-map-ini", - label: "Save: All Map Ini Editor", - shortcut: None, - action: || { - Message::all_map_ini(crate::editors::all_map_ini::AllMapIniEditorMessage::Save) - }, - applicable_editors: vec![EditorType::AllMapIniEditor], - }, - // ── Party Level Db Editor ──────────────────────────────────────── - Command { - id: "load-party-level-db", - label: "Scan: Load Party Level Db catalog", - shortcut: None, - action: || { - Message::party_level_db( - crate::editors::party_level_db::PartyLevelDbEditorMessage::LoadCatalog, - ) - }, - applicable_editors: vec![EditorType::PartyLevelDbEditor], - }, - Command { - id: "save-party-level-db", - label: "Save: Party Level Db Editor", - shortcut: None, - action: || { - Message::party_level_db( - crate::editors::party_level_db::PartyLevelDbEditorMessage::Save, - ) - }, - applicable_editors: vec![EditorType::PartyLevelDbEditor], - }, - // ── Draw Item Editor ───────────────────────────────────────────── - Command { - id: "load-draw-item", - label: "Scan: Load Draw Item catalog", - shortcut: None, - action: || { - Message::draw_item( - crate::editors::draw_item::DrawItemEditorMessage::LoadCatalog, - ) - }, - applicable_editors: vec![EditorType::DrawItemEditor], - }, - Command { - id: "save-draw-item", - label: "Save: Draw Item Editor", - shortcut: None, - action: || { - Message::draw_item(crate::editors::draw_item::DrawItemEditorMessage::Save) - }, - applicable_editors: vec![EditorType::DrawItemEditor], - }, - // ── Edit Item Editor ───────────────────────────────────────────── - Command { - id: "scan-edit-items", - label: "Scan: Load Edit Item catalog", - shortcut: None, - action: || { - Message::edit_item( - crate::editors::edit_item::EditItemEditorMessage::LoadCatalog, - ) - }, - applicable_editors: vec![EditorType::EditItemEditor], - }, - Command { - id: "save-edit-items", - label: "Save: Edit Item Editor", - shortcut: None, - action: || { - Message::edit_item(crate::editors::edit_item::EditItemEditorMessage::Save) - }, - applicable_editors: vec![EditorType::EditItemEditor], - }, - // ── Event Item Editor ──────────────────────────────────────────── - Command { - id: "scan-event-items", - label: "Scan: Load Event Item catalog", - shortcut: None, - action: || { - Message::event_item( - crate::editors::event_item::EventItemEditorMessage::LoadCatalog, - ) - }, - applicable_editors: vec![EditorType::EventItemEditor], - }, - Command { - id: "save-event-items", - label: "Save: Event Item Editor", - shortcut: None, - action: || { - Message::event_item(crate::editors::event_item::EventItemEditorMessage::Save) - }, - applicable_editors: vec![EditorType::EventItemEditor], - }, ] } } diff --git a/dispel-gui/src/components/composite_item.rs b/dispel-gui/src/components/composite_item.rs index d237c7ff..18d1e4df 100644 --- a/dispel-gui/src/components/composite_item.rs +++ b/dispel-gui/src/components/composite_item.rs @@ -7,18 +7,45 @@ use iced::{Element, Length}; use crate::message::Message; use crate::style; +const LABEL_W: f32 = 140.0; + +/// Render a picker body, optionally prefixed with a fixed-width label column. +/// +/// Callers that already render a label above the field pass `show_label = false` +/// so the text is not drawn twice. +fn with_optional_label<'a>( + label: &'static str, + body: Element<'a, Message>, + show_label: bool, +) -> Element<'a, Message> { + if show_label { + row![ + text(label) + .size(11) + .width(LABEL_W) + .style(style::subtle_text), + body, + ] + .spacing(6) + .align_y(iced::Alignment::Center) + .into() + } else { + body + } +} + /// Build a cascading item-type + item-id picker for `CompositeItem` fields. /// /// Renders two pick-lists (type then item). Falls back to a plain `text_input` -/// when `entries` is `None` (lookups unavailable). +/// when `entries` is `None` (lookups unavailable). `show_label` controls whether +/// the label column is drawn by this component or by the caller. pub fn composite_item_picker( label: &'static str, value: &str, entries: Option<&[(String, String)]>, + show_label: bool, on_change: impl Fn(String) -> Message + 'static, ) -> Element<'static, Message> { - const LABEL_W: f32 = 140.0; - let current_type_byte: u8 = value .split(':') .next() @@ -31,20 +58,13 @@ pub fn composite_item_picker( let Some(entries) = entries else { let oc = on_change; - return row![ - text(label) - .size(11) - .width(LABEL_W) - .style(style::subtle_text), - text_input("", value.to_owned()) - .on_input(move |v| oc(v)) - .padding(4) - .size(11) - .width(Length::Fill), - ] - .spacing(6) - .align_y(iced::Alignment::Center) - .into(); + let input: Element<'static, Message> = text_input("", value.to_owned()) + .on_input(move |v| oc(v)) + .padding(4) + .size(11) + .width(Length::Fill) + .into(); + return with_optional_label(label, input, show_label); }; // Deduplicated type list, preserving insertion order @@ -125,5 +145,38 @@ pub fn composite_item_picker( .into() }; - col![type_picker, item_picker].spacing(4).into() + let pickers: Element<'static, Message> = col![type_picker, item_picker].spacing(4).into(); + with_optional_label(label, pickers, show_label) +} + +#[cfg(all(test, feature = "iced_test"))] +mod tests { + use super::*; + use iced_test::simulator; + + fn label_rendered(entries: Option<&[(String, String)]>, show_label: bool) -> bool { + let element: Element<'_, Message> = + composite_item_picker("Invented Item", "1:0", entries, show_label, |_| { + Message::FileTree(crate::message::FileTreeMessage::Search(String::new())) + }); + let mut ui = simulator(element); + ui.find("Invented Item").is_ok() + } + + #[test] + fn test_composite_picker_label_follows_show_label() { + let entries = [("1:0".to_string(), "Invented Sword".to_string())]; + for show_label in [true, false] { + assert_eq!( + label_rendered(None, show_label), + show_label, + "fallback picker label must follow show_label" + ); + assert_eq!( + label_rendered(Some(&entries), show_label), + show_label, + "lookup picker label must follow show_label" + ); + } + } } diff --git a/dispel-gui/src/components/file_tree/filter.rs b/dispel-gui/src/components/file_tree/filter.rs index cf5bdf15..2d4db3ab 100644 --- a/dispel-gui/src/components/file_tree/filter.rs +++ b/dispel-gui/src/components/file_tree/filter.rs @@ -62,6 +62,27 @@ impl FileTreeFilter { self.matching_paths = paths; } + /// Expand every directory that is an ancestor of a match so the matching + /// files are actually visible in the collapsible tree. + pub fn expand_matching_directories(&self, root: Option<&mut TreeNode>) { + fn visit(node: &mut TreeNode, paths: &HashSet) { + if node.data.is_dir && paths.contains(&node.data.path) { + node.expanded = true; + } + for child in &mut node.children { + visit(child, paths); + } + } + + let Some(root) = root else { + return; + }; + let Some(paths) = &self.matching_paths else { + return; + }; + visit(root, paths); + } + /// Walk the entire tree and collect paths of files that match the current /// fuzzy search query. Also includes ancestor directories so the tree /// structure is preserved when rendering. diff --git a/dispel-gui/src/components/file_tree/tests.rs b/dispel-gui/src/components/file_tree/tests.rs index 23067c24..5a5538d8 100644 --- a/dispel-gui/src/components/file_tree/tests.rs +++ b/dispel-gui/src/components/file_tree/tests.rs @@ -152,6 +152,37 @@ fn test_file_tree_search_filters_matching_files() { ); } +#[test] +fn test_search_expands_collapsed_ancestor_of_match() { + use super::filter::FileTreeFilter; + + let temp_dir = tempdir().unwrap(); + let game = temp_dir.path().join("game"); + let folder = game.join("InventedFolder"); + std::fs::create_dir_all(&folder).unwrap(); + std::fs::File::create(folder.join("InventedWibble.txt")).unwrap(); + + let mut tree = FileTree::scan(&game); + { + let root = tree.data.root.as_mut().expect("scanned tree has a root"); + let dir = root + .find_mut(&|n: &GameFileNode| n.path == folder) + .expect("folder node"); + dir.expanded = false; + assert!(!dir.expanded, "folder starts collapsed"); + } + + let mut filter = FileTreeFilter::new().with_search_query("wibble".to_string()); + filter.build_matching_paths(tree.data.root.as_ref()); + filter.expand_matching_directories(tree.data.root.as_mut()); + + let root = tree.data.root.as_mut().expect("scanned tree has a root"); + let dir = root + .find_mut(&|n: &GameFileNode| n.path == folder) + .expect("folder node"); + assert!(dir.expanded, "ancestor of a search match must be expanded"); +} + /// Test filter functionality #[test] fn test_file_tree_filter_functionality() { diff --git a/dispel-gui/src/components/map_render/draw_helpers.rs b/dispel-gui/src/components/map_render/draw_helpers.rs index 39027043..4ba16ed0 100644 --- a/dispel-gui/src/components/map_render/draw_helpers.rs +++ b/dispel-gui/src/components/map_render/draw_helpers.rs @@ -34,6 +34,29 @@ pub fn draw_tile_layer( } } +/// Mirror an RGBA image horizontally, one pixel row at a time. Flipped +/// entities need their pixels mirrored as well as their origin offset shifted, +/// otherwise the sprite is drawn in the wrong direction. +pub fn mirror_rgba_rows(pixels: &[u8], width: u32, height: u32) -> Vec { + let w = width as usize; + let row_len = w.saturating_mul(4); + if row_len == 0 { + return Vec::new(); + } + let mut mirrored = vec![0u8; pixels.len()]; + for y in 0..height as usize { + let start = y.saturating_mul(row_len); + let Some(row) = pixels.get(start..start.saturating_add(row_len)) else { + break; + }; + for (x, px) in row.as_chunks::<4>().0.iter().enumerate() { + let dst = start.saturating_add((w - 1 - x) * 4); + mirrored[dst..dst + 4].copy_from_slice(px); + } + } + mirrored +} + /// Render an entity sprite handle onto the canvas frame. pub fn draw_entity_sprite( frame: &mut Frame, @@ -79,3 +102,23 @@ pub fn diamond_path(cx: f32, cy: f32, r: f32) -> canvas::Path { b.close(); }) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_mirror_rgba_rows_reverses_each_row() { + // 2×2 image with a distinct colour per pixel. + let pixels = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; + assert_eq!( + mirror_rgba_rows(&pixels, 2, 2), + vec![5, 6, 7, 8, 1, 2, 3, 4, 13, 14, 15, 16, 9, 10, 11, 12] + ); + } + + #[test] + fn test_mirror_rgba_rows_zero_width_is_empty() { + assert!(mirror_rgba_rows(&[1, 2, 3, 4], 0, 2).is_empty()); + } +} diff --git a/dispel-gui/src/components/map_render/geometry.rs b/dispel-gui/src/components/map_render/geometry.rs index 55f275d3..ebd58d60 100644 --- a/dispel-gui/src/components/map_render/geometry.rs +++ b/dispel-gui/src/components/map_render/geometry.rs @@ -3,6 +3,16 @@ use crate::components::map_render::{TILE_H, TILE_W}; use iced::Rectangle; +/// Anchor point for a zoom operation. Toolbar buttons supply no cursor +/// position (NaN), so they zoom around the viewport centre instead. +pub fn zoom_anchor(cx: f32, cy: f32, viewport_w: f32, viewport_h: f32) -> (f32, f32) { + if cx.is_finite() && cy.is_finite() { + (cx, cy) + } else { + (viewport_w * 0.5, viewport_h * 0.5) + } +} + /// World pixel centre of an isometric tile. pub fn tile_world_center(tx: i32, ty: i32, diagonal: i32) -> (f32, f32) { let (px, py) = dispel_core::map::types::convert_map_coords_to_image_coords(tx, ty, diagonal); @@ -91,3 +101,35 @@ pub fn screen_to_tile( pub fn is_visible(x: f32, y: f32, w: f32, h: f32, bounds: Rectangle) -> bool { x + w > 0.0 && x < bounds.width && y + h > 0.0 && y < bounds.height } + +#[cfg(test)] +mod tests { + use super::*; + + fn zoom_once(pan: f32, zoom: f32, factor: f32, anchor: f32) -> (f32, f32) { + let new_zoom = (zoom * factor).clamp(0.05, 8.0); + let ratio = new_zoom / zoom; + (anchor - (anchor - pan) * ratio, new_zoom) + } + + #[test] + fn test_toolbar_zoom_uses_viewport_center() { + assert_eq!( + zoom_anchor(f32::NAN, f32::NAN, 800.0, 600.0), + (400.0, 300.0) + ); + let (ax, _) = zoom_anchor(f32::NAN, f32::NAN, 800.0, 600.0); + + let mut pan = 0.0; + let mut zoom = 1.0; + (pan, zoom) = zoom_once(pan, zoom, 1.25, ax); + (pan, zoom) = zoom_once(pan, zoom, 1.0 / 1.25, ax); + assert!((zoom - 1.0).abs() < 1e-5, "zoom must return to 1.0"); + assert!(pan.abs() < 1e-4, "viewport centre must stay put, pan={pan}"); + } + + #[test] + fn test_cursor_zoom_keeps_explicit_anchor() { + assert_eq!(zoom_anchor(123.0, 45.0, 800.0, 600.0), (123.0, 45.0)); + } +} diff --git a/dispel-gui/src/components/map_render/mod.rs b/dispel-gui/src/components/map_render/mod.rs index c73ab5f0..aa30fa4a 100644 --- a/dispel-gui/src/components/map_render/mod.rs +++ b/dispel-gui/src/components/map_render/mod.rs @@ -8,8 +8,10 @@ pub mod traits; pub mod view_state; pub use decode::decode_tileset_file; -pub use draw_helpers::{diamond_path, draw_item_color}; -pub use geometry::{is_visible, screen_to_tile, tile_center, tile_to_screen, tile_world_center}; +pub use draw_helpers::{diamond_path, draw_item_color, mirror_rgba_rows}; +pub use geometry::{ + is_visible, screen_to_tile, tile_center, tile_to_screen, tile_world_center, zoom_anchor, +}; pub use input::handle_input; pub use render_tiles::GenericTilesLayer; pub use state::{EntitySpriteHandle, InternalSpriteHandle, MapCanvasState}; diff --git a/dispel-gui/src/editors/event_scr/functions.rs b/dispel-gui/src/editors/event_scr/functions.rs index d58b3bf3..7f9a69c1 100644 --- a/dispel-gui/src/editors/event_scr/functions.rs +++ b/dispel-gui/src/editors/event_scr/functions.rs @@ -12,7 +12,11 @@ use dispel_core::references::event_scr::EventScript; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EventScriptFunctionIndex { pub functions: Vec, + /// Files whose names matched the scan pattern (including unreadable ones). pub scanned_file_count: usize, + /// Files that were actually parsed and contributed functions. + #[serde(default)] + pub parsed_file_count: usize, pub scanned_at: i64, } @@ -54,6 +58,14 @@ pub fn index_file_path() -> std::path::PathBuf { dir.join("event_scr_functions.json") } +/// Persist the index, returning a description of any serialization or I/O +/// failure so callers can surface it instead of silently dropping the index. +pub fn save_index(index_path: &Path, index: &EventScriptFunctionIndex) -> Result<(), String> { + let json = serde_json::to_string_pretty(index).map_err(|e| format!("serialize index: {e}"))?; + std::fs::write(index_path, &json) + .map_err(|e| format!("write index {}: {e}", index_path.display())) +} + /// Scan all `Event*.scr` files under `game_path/Ref/` and build a /// frequency-sorted function index. Reports progress (and checks the /// cancellation flag) through `progress`. @@ -89,9 +101,51 @@ pub fn build_index( progress.total.store(files.len() as u32, Ordering::Relaxed); - let mut counter: HashMap<(String, usize), u32> = HashMap::new(); + let (counter, parsed_file_count) = index_files(&files, &progress, |file| { + ::read_file(file) + })?; + + let mut functions: Vec = counter + .into_iter() + .map(|((name, param_count), frequency)| IndexedFunction { + name, + param_count, + frequency, + }) + .collect(); + + functions.sort_by_key(|a| std::cmp::Reverse(a.frequency)); + + let scanned_at = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs() as i64; + + Ok(EventScriptFunctionIndex { + functions, + scanned_file_count: files.len(), + parsed_file_count, + scanned_at, + }) +} - for file in &files { +type FunctionCounts = HashMap<(String, usize), u32>; + +/// Count functions across the candidate files, tracking only files that were +/// actually parsed. A file that fails to parse is skipped, never counted as a +/// successful scan. +fn index_files( + files: &[std::path::PathBuf], + progress: &IndexProgress, + mut read: F, +) -> Result<(FunctionCounts, usize), String> +where + F: FnMut(&Path) -> std::io::Result>, +{ + let mut counter: FunctionCounts = HashMap::new(); + let mut parsed_file_count = 0; + + for file in files { if progress.cancelled.load(Ordering::Relaxed) { return Err("Cancelled".to_string()); } @@ -101,7 +155,8 @@ pub fn build_index( .map(|n| n.to_string_lossy().to_string()) .unwrap_or_default(); - if let Ok(scripts) = ::read_file(file) { + if let Ok(scripts) = read(file) { + parsed_file_count += 1; for script in &scripts { for action in &script.actions { if action.raw_content.is_none() && !action.function_name.is_empty() { @@ -115,25 +170,61 @@ pub fn build_index( progress.processed.fetch_add(1, Ordering::Relaxed); } - let mut functions: Vec = counter - .into_iter() - .map(|((name, param_count), frequency)| IndexedFunction { - name, - param_count, - frequency, - }) - .collect(); + Ok((counter, parsed_file_count)) +} - functions.sort_by_key(|a| std::cmp::Reverse(a.frequency)); +#[cfg(test)] +mod tests { + use super::*; + use dispel_core::references::event_scr::{ActionFunction, EventScript}; + use std::ffi::OsStr; + + fn script_calling(name: &str) -> Vec { + let mut script = EventScript::default(); + script.actions.push(ActionFunction { + prefix: None, + function_name: name.to_string(), + parameters: vec!["1".to_string()], + raw_content: None, + }); + vec![script] + } - let scanned_at = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default() - .as_secs() as i64; + #[test] + fn test_index_files_counts_only_parsed_files() { + let files = vec![ + std::path::PathBuf::from("EventWidget.scr"), + std::path::PathBuf::from("EventGadget.scr"), + ]; + let progress = IndexProgress::new(); + let (counter, parsed) = index_files(&files, &progress, |file| { + if file.file_name() == Some(OsStr::new("EventGadget.scr")) { + Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "unparseable script", + )) + } else { + Ok(script_calling("invented_call")) + } + }) + .expect("indexing must tolerate one unparseable file"); - Ok(EventScriptFunctionIndex { - functions, - scanned_file_count: files.len(), - scanned_at, - }) + assert_eq!(parsed, 1, "only the parsed file may be counted"); + assert_eq!(counter.get(&("invented_call".to_string(), 1)), Some(&1)); + assert_eq!(progress.processed.load(Ordering::Relaxed), 2); + } + + #[test] + fn test_save_index_reports_write_error() { + let dir = tempfile::tempdir().expect("temp dir"); + let path = dir.path().join("missing-dir").join("index.json"); + let index = EventScriptFunctionIndex { + functions: vec![], + scanned_file_count: 0, + parsed_file_count: 0, + scanned_at: 0, + }; + let err = save_index(&path, &index).expect_err("a missing parent directory must fail"); + assert!(err.contains("write index"), "unexpected error: {err}"); + } } diff --git a/dispel-gui/src/editors/event_scr/update.rs b/dispel-gui/src/editors/event_scr/update.rs index ffb52ed7..942fb2b7 100644 --- a/dispel-gui/src/editors/event_scr/update.rs +++ b/dispel-gui/src/editors/event_scr/update.rs @@ -329,9 +329,10 @@ pub fn handle(message: EventScrEditorMessage, app: &mut App) -> Task { progress_clone, ); if let Ok(ref index) = result - && let Ok(json) = serde_json::to_string_pretty(index) + && let Err(e) = + crate::editors::event_scr::functions::save_index(&index_path, index) { - std::fs::write(&index_path, &json).ok(); + eprintln!("Failed to save event-script function index: {e}"); } result }) diff --git a/dispel-gui/src/editors/map_editor/canvas/render_overlays.rs b/dispel-gui/src/editors/map_editor/canvas/render_overlays.rs index fe356f60..7afa639d 100644 --- a/dispel-gui/src/editors/map_editor/canvas/render_overlays.rs +++ b/dispel-gui/src/editors/map_editor/canvas/render_overlays.rs @@ -13,6 +13,12 @@ use iced::widget::canvas::{self, Action, Frame, Geometry, Text as CanvasText}; use iced::widget::text::Alignment as TextAlignment; use iced::{Color, Event, Font, Point, Rectangle, alignment, mouse}; +/// The hover ring is shown for any hovered entity except the one already +/// selected. With no selection every hovered entity gets a ring. +fn should_show_hover_ring(hovered: SelectedEntity, selected: Option) -> bool { + selected != Some(hovered) +} + /// Canvas Program for overlay elements (collisions, events, entities). /// Drawn on top of tiles canvas using a separate canvas in a Stack. pub struct MapCanvasOverlaysLayer<'a> { @@ -491,7 +497,7 @@ impl<'a> canvas::Program for MapCanvasOverlaysLayer<'a> { // Hover ring for entities (monsters/NPCs/extras only — shown with a yellow ring) if let Some(hov) = &hovered_element - && *hov != self.state.view.selected_entity.unwrap_or(*hov) + && should_show_hover_ring(*hov, self.state.view.selected_entity) && let Some((htx, hty)) = entity_tile(*hov, self.state) { let (px, py) = tile_to_screen(htx, hty, diagonal, pan_x, pan_y, zoom); @@ -640,3 +646,26 @@ impl<'a> canvas::Program for MapCanvasOverlaysLayer<'a> { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_hover_ring_shown_with_no_selection() { + assert!(should_show_hover_ring(SelectedEntity::Monster(3), None)); + assert!(should_show_hover_ring(SelectedEntity::Npc(7), None)); + } + + #[test] + fn test_hover_ring_hidden_for_selected_entity() { + assert!(!should_show_hover_ring( + SelectedEntity::Monster(3), + Some(SelectedEntity::Monster(3)) + )); + assert!(should_show_hover_ring( + SelectedEntity::Monster(3), + Some(SelectedEntity::Npc(3)) + )); + } +} diff --git a/dispel-gui/src/editors/map_editor/state.rs b/dispel-gui/src/editors/map_editor/state.rs index 62c13480..0152d264 100644 --- a/dispel-gui/src/editors/map_editor/state.rs +++ b/dispel-gui/src/editors/map_editor/state.rs @@ -1,7 +1,7 @@ use super::message::{MapDataHandle, SelectedEntity}; use crate::components::loading_state::LoadingState; pub use crate::components::map_render::{EntitySpriteHandle, InternalSpriteHandle, MapViewState}; -use gui_widgets::components::toast::{Status, Toast}; +use gui_widgets::components::toast::{Status, Toast, ToastId}; use iced::widget::image::Handle; use std::collections::{HashMap, VecDeque}; use std::path::PathBuf; @@ -149,6 +149,12 @@ impl Default for MapDataState { /// Maximum number of toasts kept on screen. const MAX_TOASTS: usize = 4; +fn next_id() -> u64 { + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: AtomicU64 = AtomicU64::new(1); + NEXT.fetch_add(1, Ordering::Relaxed) +} + impl MapDataState { pub fn map_data(&self) -> Option<&MapDataHandle> { self.loading_state.data() @@ -169,6 +175,7 @@ impl MapDataState { return; } self.toasts.push(Toast { + id: ToastId::new(next_id()), title, body, status, @@ -445,6 +452,16 @@ mod tests { assert_eq!(s.toasts.len(), 2); } + #[test] + fn test_notify_replace_keeps_toast_id() { + let mut s = MapDataState::default(); + s.notify_replace("Collision", Status::Primary, "Collision", "(1,1)"); + let id = s.toasts[0].id.clone(); + s.notify_replace("Collision", Status::Primary, "Collision", "(2,2)"); + assert_eq!(s.toasts[0].id, id, "replace must keep the timer identity"); + assert_eq!(s.toasts[0].body, "(2,2)"); + } + #[test] fn test_notify_caps_at_four_dropping_oldest() { let mut s = MapDataState::default(); diff --git a/dispel-gui/src/editors/map_editor/update/map.rs b/dispel-gui/src/editors/map_editor/update/map.rs index c7f46456..fd8ef771 100644 --- a/dispel-gui/src/editors/map_editor/update/map.rs +++ b/dispel-gui/src/editors/map_editor/update/map.rs @@ -813,8 +813,13 @@ fn decoded_from_frame( ) -> DecodedEntitySprite { let w = frame.image.width(); let h = frame.image.height(); + let pixels = if flip { + crate::components::map_render::mirror_rgba_rows(frame.image.as_raw(), w, h) + } else { + frame.image.as_raw().to_vec() + }; DecodedEntitySprite { - pixels: frame.image.as_raw().to_vec(), + pixels, width: w, height: h, origin_x: frame.origin_x, diff --git a/dispel-gui/src/editors/map_editor/update/mod.rs b/dispel-gui/src/editors/map_editor/update/mod.rs index d3186164..f37dc2ca 100644 --- a/dispel-gui/src/editors/map_editor/update/mod.rs +++ b/dispel-gui/src/editors/map_editor/update/mod.rs @@ -142,12 +142,15 @@ pub fn handle(message: MapEditorMessage, app: &mut App) -> Task { let old_zoom = state.view.zoom; let new_zoom = (old_zoom * factor).clamp(0.05, 8.0); let ratio = new_zoom / old_zoom; - // cx/cy are NaN when triggered from a toolbar button (no cursor - // position). - if cx.is_finite() && cy.is_finite() { - state.view.pan_x = cx - (cx - state.view.pan_x) * ratio; - state.view.pan_y = cy - (cy - state.view.pan_y) * ratio; - } + // Toolbar buttons pass NaN; zoom around the viewport centre. + let (ax, ay) = crate::components::map_render::zoom_anchor( + cx, + cy, + state.view.last_canvas_w, + state.view.last_canvas_h, + ); + state.view.pan_x = ax - (ax - state.view.pan_x) * ratio; + state.view.pan_y = ay - (ay - state.view.pan_y) * ratio; state.view.zoom = new_zoom; state.view.tile_layer_cache.clear(); state.view.overlay_cache.clear(); diff --git a/dispel-gui/src/editors/map_editor/view/fields.rs b/dispel-gui/src/editors/map_editor/view/fields.rs index f53bc2d5..14831f2a 100644 --- a/dispel-gui/src/editors/map_editor/view/fields.rs +++ b/dispel-gui/src/editors/map_editor/view/fields.rs @@ -155,7 +155,7 @@ pub fn inspector_field_row<'a>( FieldKind::CompositeItem { lookup_key } => { let entries = lookups.get(*lookup_key).map(|v| v.as_slice()); - composite_item_picker(label, value, entries, move |v| { + composite_item_picker(label, value, entries, true, move |v| { Message::map_editor(MapEditorMessage::EntityFieldChanged( tab_id, sel, @@ -166,3 +166,47 @@ pub fn inspector_field_row<'a>( } } } + +#[cfg(all(test, feature = "iced_test"))] +mod tests { + use super::*; + use iced_test::selector::{Candidate, Target}; + use iced_test::simulator; + + fn count_label_text(element: Element<'_, Message>, label: &str) -> usize { + let mut ui = simulator(element); + let mut count = 0usize; + let mut selector = |candidate: Candidate<'_>| -> Option { + if let Candidate::Text { content, .. } = candidate + && content == label + { + count += 1; + } + None + }; + let _ = ui.find(&mut selector); + count + } + + #[test] + fn test_map_editor_composite_field_keeps_its_label() { + let kind = FieldKind::CompositeItem { + lookup_key: "invented_items", + }; + let lookups = HashMap::new(); + let element = inspector_field_row( + "Invented Item:", + "item_type", + &kind, + "1:0", + 0, + SelectedEntity::DrawItem(0), + &lookups, + ); + assert_eq!( + count_label_text(element, "Invented Item:"), + 1, + "map editor has no outer label, so the picker must render exactly one" + ); + } +} diff --git a/dispel-gui/src/editors/map_editor/view/mod.rs b/dispel-gui/src/editors/map_editor/view/mod.rs index 8f12aea9..db0d0d57 100644 --- a/dispel-gui/src/editors/map_editor/view/mod.rs +++ b/dispel-gui/src/editors/map_editor/view/mod.rs @@ -6,9 +6,7 @@ use crate::message::{Message, MessageExt}; use crate::style; use gui_widgets::components::toast; use gui_widgets::lucide::{LUCIDE_FONT, icon_char}; -use iced::widget::{ - button, canvas, column, container, progress_bar, row, stack, text, text_input, toggler, -}; +use iced::widget::{button, canvas, column, container, row, stack, text, text_input, toggler}; use iced::{Element, Fill}; use lucide_icons::Icon; @@ -49,7 +47,7 @@ pub fn view(app: &App) -> Element<'_, Message> { LoadingState::Loading => container( column![ text("Loading map…").size(12).style(style::subtle_text), - progress_bar(0.0..=1.0, 0.5).style(style::primary_progress_bar), + text("Working…").size(10).style(style::subtle_text), ] .spacing(8) .padding(24), @@ -524,8 +522,8 @@ pub fn view(app: &App) -> Element<'_, Message> { .on_press(Message::map_editor(MapEditorMessage::ZoomChanged( tab_id, 1.25, - f32::NAN, - f32::NAN + state.view.last_canvas_w * 0.5, + state.view.last_canvas_h * 0.5 ))) .padding([5, 10]) .style(style::browse_button), @@ -534,8 +532,8 @@ pub fn view(app: &App) -> Element<'_, Message> { .on_press(Message::map_editor(MapEditorMessage::ZoomChanged( tab_id, 1.0 / 1.25, - f32::NAN, - f32::NAN + state.view.last_canvas_w * 0.5, + state.view.last_canvas_h * 0.5 ))) .padding([5, 10]) .style(style::browse_button), diff --git a/dispel-gui/src/editors/save_file_viewer/map_preview/update.rs b/dispel-gui/src/editors/save_file_viewer/map_preview/update.rs index 3573a5e5..86a5e47a 100644 --- a/dispel-gui/src/editors/save_file_viewer/map_preview/update.rs +++ b/dispel-gui/src/editors/save_file_viewer/map_preview/update.rs @@ -63,10 +63,15 @@ pub fn handle(msg: PreviewMessage, state: &mut MapPreviewState) -> Task let old_zoom = state.view.zoom; let new_zoom = (old_zoom * factor).clamp(0.05, 8.0); let ratio = new_zoom / old_zoom; - if cx.is_finite() && cy.is_finite() { - state.view.pan_x = cx - (cx - state.view.pan_x) * ratio; - state.view.pan_y = cy - (cy - state.view.pan_y) * ratio; - } + // Toolbar buttons pass NaN; zoom around the viewport centre. + let (ax, ay) = crate::components::map_render::zoom_anchor( + cx, + cy, + state.view.last_canvas_w, + state.view.last_canvas_h, + ); + state.view.pan_x = ax - (ax - state.view.pan_x) * ratio; + state.view.pan_y = ay - (ay - state.view.pan_y) * ratio; state.view.zoom = new_zoom; state.view.tile_layer_cache.clear(); Task::none() diff --git a/dispel-gui/src/editors/save_file_viewer/map_preview/view.rs b/dispel-gui/src/editors/save_file_viewer/map_preview/view.rs index d73f32f8..514123ac 100644 --- a/dispel-gui/src/editors/save_file_viewer/map_preview/view.rs +++ b/dispel-gui/src/editors/save_file_viewer/map_preview/view.rs @@ -8,7 +8,7 @@ use crate::editors::save_file_viewer::map_preview::state::{ MapPreviewLoading, MapPreviewState, PreviewLayer, }; use crate::message::{Message, MessageExt}; -use iced::widget::{button, canvas, column, container, progress_bar, row, stack, text}; +use iced::widget::{button, canvas, column, container, row, stack, text}; use iced::{Element, Fill}; /// Render the map preview control panel and canvas. @@ -21,7 +21,7 @@ pub fn view<'a>(state: &'a MapPreviewState) -> Element<'a, Message> { .into(), MapPreviewLoading::Loading => container( - column![text("Loading map…").size(12), progress_bar(0.0..=1.0, 0.5),] + column![text("Loading map…").size(12), text("Working…").size(10),] .spacing(8) .padding(16), ) @@ -48,12 +48,9 @@ pub fn view<'a>(state: &'a MapPreviewState) -> Element<'a, Message> { MapPreviewLoading::Loaded => { if !state.tiles_ready { return container( - column![ - text("Decoding tiles…").size(12), - progress_bar(0.0..=1.0, 0.5), - ] - .spacing(8) - .padding(16), + column![text("Decoding tiles…").size(12), text("Working…").size(10),] + .spacing(8) + .padding(16), ) .width(Fill) .height(Fill) @@ -98,8 +95,8 @@ pub fn view<'a>(state: &'a MapPreviewState) -> Element<'a, Message> { .on_press(Message::save_file_viewer( SaveFileViewerMessage::MapPreview(PreviewMessage::Zoom( 1.25, - f32::NAN, - f32::NAN + state.view.last_canvas_w * 0.5, + state.view.last_canvas_h * 0.5 ),) )) .padding([5, 10]), @@ -108,8 +105,8 @@ pub fn view<'a>(state: &'a MapPreviewState) -> Element<'a, Message> { .on_press(Message::save_file_viewer( SaveFileViewerMessage::MapPreview(PreviewMessage::Zoom( 1.0 / 1.25, - f32::NAN, - f32::NAN + state.view.last_canvas_w * 0.5, + state.view.last_canvas_h * 0.5 ),) )) .padding([5, 10]), diff --git a/dispel-gui/src/editors/save_file_viewer/update/preview.rs b/dispel-gui/src/editors/save_file_viewer/update/preview.rs index 98ff3b5e..144e8b90 100644 --- a/dispel-gui/src/editors/save_file_viewer/update/preview.rs +++ b/dispel-gui/src/editors/save_file_viewer/update/preview.rs @@ -93,8 +93,17 @@ pub async fn load_preview_sprites( let frame = frames.get(seq).or_else(|| frames.first())?; let w = frame.image.width(); let h = frame.image.height(); + let pixels = if flip { + crate::components::map_render::mirror_rgba_rows( + frame.image.as_raw(), + w, + h, + ) + } else { + frame.image.as_raw().to_vec() + }; return Some(EntitySpriteHandle { - handle: Handle::from_rgba(w, h, frame.image.as_raw().to_vec()), + handle: Handle::from_rgba(w, h, pixels), width: w, height: h, origin_x: frame.origin_x, diff --git a/dispel-gui/src/editors/sprite_editor/state.rs b/dispel-gui/src/editors/sprite_editor/state.rs index 7ed11484..a133be78 100644 --- a/dispel-gui/src/editors/sprite_editor/state.rs +++ b/dispel-gui/src/editors/sprite_editor/state.rs @@ -1,7 +1,21 @@ use crate::editors::sprite_editor::ExportFormat; use dispel_core::sprite::{SpriteFile, SpriteRenderOptions, read_sprite_file}; +use iced::Size; use std::path::{Path, PathBuf}; +/// Scale that fits a frame inside the preview viewport while preserving its +/// aspect ratio. A zero-sized frame or viewport falls back to 1:1 so the +/// preview cannot collapse before layout has run. +pub fn fit_scale(viewport: Size, frame: (u32, u32)) -> f32 { + let (w, h) = frame; + if w == 0 || h == 0 || viewport.width <= 0.0 || viewport.height <= 0.0 { + return 1.0; + } + (viewport.width / w as f32) + .min(viewport.height / h as f32) + .max(0.01) +} + /// A decoded sprite frame ready for display, editing, and export. #[derive(Debug, Clone)] pub struct SpriteFrame { @@ -59,6 +73,9 @@ pub struct SpriteViewerState { // Zoom /// Zoom multiplier (1.0 = 100%, clamped to [0.1, 10.0]). pub zoom: f32, + /// When true the frame is scaled to the live preview viewport instead of + /// using the fixed `zoom` multiplier. + pub fit_mode: bool, // Playback pub is_playing: bool, pub is_looping: bool, @@ -90,6 +107,7 @@ impl Default for SpriteViewerState { undo_stack: Vec::new(), redo_stack: Vec::new(), zoom: 1.0, + fit_mode: true, is_playing: false, is_looping: true, speed_100x: 100, @@ -317,3 +335,30 @@ impl SpriteViewerState { self.dirty = false; } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_fit_scale_uses_the_limiting_viewport_axis() { + let scale = fit_scale(Size::new(640.0, 480.0), (32, 32)); + assert!( + (scale - 15.0).abs() < 1e-5, + "expected 480/32 = 15, got {scale}" + ); + let scale = fit_scale(Size::new(100.0, 400.0), (100, 50)); + assert!( + (scale - 1.0).abs() < 1e-5, + "expected 100/100 = 1, got {scale}" + ); + } + + #[test] + fn test_fit_scale_handles_unlaid_out_viewport() { + assert_eq!(fit_scale(Size::new(0.0, 0.0), (32, 32)), 1.0); + assert_eq!(fit_scale(Size::new(100.0, 100.0), (0, 10)), 1.0); + assert!(fit_scale(Size::new(100.0, 100.0), (10000, 1)) >= 0.01); + assert!(SpriteViewerState::default().fit_mode); + } +} diff --git a/dispel-gui/src/editors/sprite_editor/update.rs b/dispel-gui/src/editors/sprite_editor/update.rs index 3e8ead91..125b0e3e 100644 --- a/dispel-gui/src/editors/sprite_editor/update.rs +++ b/dispel-gui/src/editors/sprite_editor/update.rs @@ -110,18 +110,22 @@ pub fn handle(message: SpriteViewerMessage, app: &mut App) -> Task { + viewer.fit_mode = false; viewer.zoom = (viewer.zoom * 1.25).min(10.0); } SpriteViewerMessage::ZoomOut => { + viewer.fit_mode = false; viewer.zoom = (viewer.zoom / 1.25).max(0.1); } SpriteViewerMessage::ZoomReset => { + viewer.fit_mode = false; viewer.zoom = 1.0; } SpriteViewerMessage::ZoomToFit => { - // Zoom to make the frame fill the available preview area - // Rough fit: use 4× as the max auto-zoom - viewer.zoom = 4.0; + // The actual scale is computed from the live viewport in the view, + // so the frame fits exactly instead of using a fixed multiplier. + viewer.fit_mode = true; + viewer.zoom = 1.0; } SpriteViewerMessage::TogglePreserveBlack => { viewer.preserve_black = !viewer.preserve_black; diff --git a/dispel-gui/src/editors/sprite_editor/view.rs b/dispel-gui/src/editors/sprite_editor/view.rs index a021410f..37caaf24 100644 --- a/dispel-gui/src/editors/sprite_editor/view.rs +++ b/dispel-gui/src/editors/sprite_editor/view.rs @@ -216,13 +216,30 @@ fn view_sequence_chips(viewer: &SpriteViewerState) -> Element<'_, Message> { // ── Main preview ────────────────────────────────────────────────────────────── fn view_preview(viewer: &SpriteViewerState) -> Element<'_, Message> { - let inner: Element<'_, Message> = - if let Some(frame) = viewer.frames.get(viewer.selected_frame_global()) { - let w = (frame.width as f32 * viewer.zoom).ceil(); - let h = (frame.height as f32 * viewer.zoom).ceil(); - image(frame.image.clone()) - .width(Length::Fixed(w)) - .height(Length::Fixed(h)) + use crate::editors::sprite_editor::fit_scale; + use iced::{Size, widget::responsive}; + + let fit_mode = viewer.fit_mode; + let zoom = viewer.zoom; + let frame_info = viewer + .frames + .get(viewer.selected_frame_global()) + .map(|f| (f.image.clone(), f.width, f.height)); + + // `responsive` sits outside the scrollable so it sees a finite viewport; + // the image is clipped by the scrollable instead of painting over controls. + responsive(move |size: Size| { + let inner: Element<'_, Message> = if let Some((handle, w, h)) = &frame_info { + let scale = if fit_mode { + fit_scale(size, (*w, *h)) + } else { + 1.0 + } * zoom; + let draw_w = (*w as f32 * scale).ceil().max(1.0); + let draw_h = (*h as f32 * scale).ceil().max(1.0); + container(image(handle.clone()).width(draw_w).height(draw_h)) + .width(draw_w) + .height(draw_h) .into() } else { text("No frames loaded") @@ -231,13 +248,19 @@ fn view_preview(viewer: &SpriteViewerState) -> Element<'_, Message> { .into() }; - container(inner) - .width(Fill) - .height(Fill) - .center_x(Fill) - .center_y(Fill) - .padding(8) - .into() + let result: Element<'_, Message> = scrollable(inner) + .direction(scrollable::Direction::Both { + vertical: Default::default(), + horizontal: Default::default(), + }) + .width(Fill) + .height(Fill) + .into(); + result + }) + .width(Fill) + .height(Fill) + .into() } // ── Zoom controls ───────────────────────────────────────────────────────────── @@ -263,9 +286,13 @@ fn view_zoom_controls(viewer: &SpriteViewerState) -> Element<'_, Message> { .padding([2, 6]) .style(style::chip); - let zoom_label = text(format!("{}%", (viewer.zoom * 100.0).round() as u32)) - .size(11) - .style(style::subtle_text); + let zoom_label = text(if viewer.fit_mode { + "Fit".to_string() + } else { + format!("{}%", (viewer.zoom * 100.0).round() as u32) + }) + .size(11) + .style(style::subtle_text); let preserve_black = row![ checkbox(viewer.preserve_black).on_toggle(|_| sv(SpriteViewerMessage::TogglePreserveBlack)), diff --git a/dispel-gui/src/editors/store/update.rs b/dispel-gui/src/editors/store/update.rs index de733c30..de3a6cac 100644 --- a/dispel-gui/src/editors/store/update.rs +++ b/dispel-gui/src/editors/store/update.rs @@ -82,14 +82,30 @@ pub fn handle(message: StoreEditorMessage, app: &mut App) -> Task { match result { Ok((weapons, heals, misc, edit, stores, warnings)) => { - app.state.editors.weapon_editor.catalog = weapons.clone(); - app.state.editors.weapon_editor.refresh(); - app.state.editors.heal_item_editor.catalog = heals.clone(); - app.state.editors.heal_item_editor.refresh(); - app.state.editors.misc_item_editor.catalog = misc.clone(); - app.state.editors.misc_item_editor.refresh(); - app.state.editors.edit_item_editor.catalog = edit.clone(); - app.state.editors.edit_item_editor.refresh(); + // These four item catalogs are shared with their own editors. + // A scan must never discard edits that are still in the + // editor's undo history, so keep a loaded, modified catalog. + macro_rules! apply_scanned { + ($editor:expr, $scanned:expr) => { + if let Some(records) = $scanned.as_ref() { + let editor = &mut $editor; + let has_unsaved_edits = + editor.catalog.is_some() && editor.edit_history.can_undo(); + if !has_unsaved_edits { + editor.catalog = Some(records.clone()); + editor.refresh(); + editor.spreadsheet.apply_filter(records); + editor + .spreadsheet + .compute_all_caches(records, &app.state.lookups); + } + } + }; + } + apply_scanned!(app.state.editors.weapon_editor, weapons); + apply_scanned!(app.state.editors.heal_item_editor, heals); + apply_scanned!(app.state.editors.misc_item_editor, misc); + apply_scanned!(app.state.editors.edit_item_editor, edit); app.state.editors.store_editor.catalog = Some(stores.clone()); let weapons_count = weapons.as_ref().map(|w| w.len()).unwrap_or(0); @@ -313,6 +329,130 @@ mod tests { use super::*; use dispel_core::Store; + fn scanned_with_weapons(weapons: Vec) -> StoreEditorMessage { + StoreEditorMessage::Scanned(Ok(( + Some(weapons), + Some(vec![]), + Some(vec![]), + Some(vec![]), + vec![Store::default()], + vec![], + ))) + } + + #[test] + fn test_store_scan_initializes_filtered_indices() { + let mut app = App::test_new(crate::workspace::Workspace::new()); + let weapons = vec![ + WeaponItem { + name: "Invented Blade".to_string(), + ..Default::default() + }, + WeaponItem { + name: "Invented Shield".to_string(), + ..Default::default() + }, + ]; + + let _ = handle(scanned_with_weapons(weapons), &mut app); + + let editor = &app.state.editors.weapon_editor; + assert_eq!(editor.catalog.as_ref().unwrap().len(), 2); + assert_eq!( + editor.spreadsheet.filtered_indices, + vec![0, 1], + "scan must initialize filtered_indices for every loaded record" + ); + } + + #[cfg(feature = "iced_test")] + #[test] + fn test_store_scan_table_is_not_empty() { + use crate::view::editor::spreadsheet::view::table::build_table_content; + use iced_test::simulator; + + let mut app = App::test_new(crate::workspace::Workspace::new()); + let weapons = vec![ + WeaponItem { + name: "Invented Blade".to_string(), + ..Default::default() + }, + WeaponItem { + name: "Invented Shield".to_string(), + ..Default::default() + }, + ]; + let _ = handle(scanned_with_weapons(weapons), &mut app); + + let editor = &app.state.editors.weapon_editor; + let name_col = WeaponItem::field_descriptors() + .iter() + .position(|d| d.name == "name") + .expect("weapon records have a name field"); + // TableWidget paints each cell from display_cache; an empty cache draws + // blank cells even though filtered_indices already lists the rows. + assert_eq!( + editor.spreadsheet.get_display(0, name_col), + "Invented Blade", + "the scanned row's name must be cached for rendering" + ); + assert_eq!( + editor.spreadsheet.get_display(1, name_col), + "Invented Shield", + "every scanned row must have cached cell values" + ); + + let element: iced::Element<'_, crate::message::Message> = build_table_content::( + WeaponItem::field_descriptors(), + editor.catalog.as_ref(), + &editor.spreadsheet, + |_| crate::message::Message::System(crate::message::SystemMessage::DismissError), + ); + let mut ui = simulator(element); + ui.find("No matching records") + .expect_err("scanned records must be visible instead of the empty-filter message"); + } + + #[test] + fn test_store_scan_preserves_unsaved_item_edits() { + let mut app = App::test_new(crate::workspace::Workspace::new()); + let weapon = WeaponItem { + name: "Edited In Editor".to_string(), + ..Default::default() + }; + app.state.editors.weapon_editor.catalog = Some(vec![weapon]); + app.state.editors.weapon_editor.refresh(); + app.state.editors.weapon_editor.select(0); + assert!(app.state.editors.weapon_editor.update_field( + 0, + "name", + "Unsaved Name".to_string() + )); + assert!(app.state.editors.weapon_editor.edit_history.can_undo()); + + let from_disk = WeaponItem { + name: "From Disk".to_string(), + ..Default::default() + }; + let _ = handle( + StoreEditorMessage::Scanned(Ok(( + Some(vec![from_disk]), + Some(vec![]), + Some(vec![]), + Some(vec![]), + vec![Store::default()], + vec![], + ))), + &mut app, + ); + + let catalog = app.state.editors.weapon_editor.catalog.as_ref().unwrap(); + assert_eq!( + catalog[0].name, "Unsaved Name", + "scan must not discard an unsaved edit" + ); + } + #[test] fn test_store_scan_tolerates_missing_item_file_with_warning() { let tmp = tempfile::tempdir().expect("tempdir"); diff --git a/dispel-gui/src/state.rs b/dispel-gui/src/state.rs index e71dc0f5..ce2ea82d 100644 --- a/dispel-gui/src/state.rs +++ b/dispel-gui/src/state.rs @@ -81,7 +81,11 @@ impl AppState { } pub fn load_workspace(&mut self) -> io::Result<()> { - self.workspace = Workspace::load(&Self::workspace_path()).unwrap_or_default(); + self.load_workspace_from(&Self::workspace_path()) + } + + fn load_workspace_from(&mut self, path: &PathBuf) -> io::Result<()> { + self.workspace = Workspace::load(path)?; // Sync game_path from workspace to shared_game_path if let Some(ref path) = self.workspace.game_path { self.shared_game_path = path.to_string_lossy().to_string(); @@ -435,6 +439,29 @@ impl Default for PaneState { mod tests { use super::*; + #[test] + fn test_load_workspace_propagates_corrupt_json() { + let dir = tempfile::tempdir().expect("temp dir"); + let path = dir.path().join("workspace.json"); + std::fs::write(&path, b"{ this is not json").expect("write corrupt workspace"); + let mut state = AppState::default(); + state + .load_workspace_from(&path) + .expect_err("corrupt workspace must fail to load"); + } + + #[test] + fn test_load_workspace_missing_file_yields_fresh_workspace() { + let dir = tempfile::tempdir().expect("temp dir"); + let path = dir.path().join("workspace.json"); + let mut state = AppState::default(); + state + .load_workspace_from(&path) + .expect("missing workspace is not an error"); + assert!(state.workspace.game_path.is_none()); + assert!(state.recent_files.is_empty()); + } + #[test] fn test_validate_unsupported_type_reports_not_available() { let mut state = AppState::default(); diff --git a/dispel-gui/src/style.rs b/dispel-gui/src/style.rs index a4a477f6..3041e322 100644 --- a/dispel-gui/src/style.rs +++ b/dispel-gui/src/style.rs @@ -2,7 +2,6 @@ pub mod button; pub mod context_menu; pub mod event_script; pub mod layout; -pub mod pane_grid; pub mod progress_bar; pub mod spreadsheet; pub mod text; @@ -11,7 +10,59 @@ pub use button::*; pub use context_menu::*; pub use event_script::*; pub use layout::*; -pub use pane_grid::*; pub use progress_bar::*; pub use spreadsheet::*; pub use text::*; + +#[cfg(test)] +mod tests { + use std::path::Path; + + #[test] + fn test_unused_style_helpers_stay_removed() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/style"); + let removed = [ + ("layout.rs", "log_container"), + ("layout.rs", "sql_editor_container"), + ("layout.rs", "normal_mode_chip"), + ("layout.rs", "edit_mode_chip"), + ("spreadsheet.rs", "grid_cell"), + ("spreadsheet.rs", "grid_cell_dirty"), + ("spreadsheet.rs", "grid_row"), + ("spreadsheet.rs", "grid_row_even"), + ("spreadsheet.rs", "resize_handle"), + ("spreadsheet.rs", "spreadsheet_cell"), + ("spreadsheet.rs", "spreadsheet_id_cell"), + ("spreadsheet.rs", "spreadsheet_id_cell_selected"), + ("spreadsheet.rs", "spreadsheet_cell_editor"), + ("spreadsheet.rs", "spreadsheet_cell_invalid"), + ("button.rs", "grid_header_button"), + ("button.rs", "grid_cell_button"), + ("button.rs", "pane_header_button"), + ("button.rs", "spreadsheet_header_button"), + ("button.rs", "spreadsheet_row"), + ("button.rs", "spreadsheet_cell_btn"), + ("button.rs", "tree_menu_button"), + ("progress_bar.rs", "loading_progress_bar"), + ("progress_bar.rs", "secondary_progress_bar"), + ("text.rs", "progress_text_style"), + ("text.rs", "pane_title_focused"), + ("text.rs", "pane_title_unfocused"), + ("text.rs", "normal_mode_text"), + ("text.rs", "edit_mode_text"), + ]; + for (file, name) in removed { + let path = root.join(file); + let source = std::fs::read_to_string(&path) + .unwrap_or_else(|e| panic!("cannot read {}: {e}", path.display())); + assert!( + !source.contains(&format!("pub fn {name}")), + "{file} must not redefine unused helper {name}" + ); + } + assert!( + !root.join("pane_grid.rs").exists(), + "the unused pane_grid style module must stay removed" + ); + } +} diff --git a/dispel-gui/src/style/button.rs b/dispel-gui/src/style/button.rs index 45fc2b95..800d92cb 100644 --- a/dispel-gui/src/style/button.rs +++ b/dispel-gui/src/style/button.rs @@ -1,6 +1,27 @@ use iced::widget::button; use iced::{Background, Border, Color, Shadow, Theme, Vector, color}; +/// Mute every colour in a style for a control that cannot be pressed. +fn dimmed(base: button::Style) -> button::Style { + let dim = |c: Color| Color { a: c.a * 0.45, ..c }; + button::Style { + background: base.background.map(|bg| match bg { + Background::Color(c) => Background::Color(dim(c)), + other => other, + }), + text_color: dim(base.text_color), + border: Border { + color: dim(base.border.color), + ..base.border + }, + shadow: Shadow { + color: dim(base.shadow.color), + ..base.shadow + }, + ..base + } +} + pub fn tab_button(_theme: &Theme, status: button::Status) -> button::Style { let base = button::Style { background: Some(Background::Color(Color::TRANSPARENT)), @@ -127,6 +148,7 @@ pub fn chip(_theme: &Theme, status: button::Status) -> button::Style { }, ..base }, + button::Status::Disabled => dimmed(base), _ => base, } } @@ -152,6 +174,7 @@ pub fn active_chip(_theme: &Theme, status: button::Status) -> button::Style { background: Some(Background::Color(color!(0x8b5a2b, 0.3))), ..base }, + button::Status::Disabled => dimmed(base), _ => base, } } @@ -173,6 +196,7 @@ pub fn browse_button(_theme: &Theme, status: button::Status) -> button::Style { text_color: Color::WHITE, ..base }, + button::Status::Disabled => dimmed(base), _ => base, } } @@ -198,48 +222,6 @@ pub fn command_palette_button(_theme: &Theme, status: button::Status) -> button: } } -pub fn grid_header_button(_theme: &Theme, status: button::Status) -> button::Style { - let base = button::Style { - background: Some(Background::Color(Color::TRANSPARENT)), - text_color: color!(0xd7ccc8), // Light tan for dark background - border: Border { - color: Color::TRANSPARENT, - width: 0.0, - radius: 0.into(), - }, - ..Default::default() - }; - match status { - button::Status::Hovered => button::Style { - text_color: color!(0xeae0c8), - background: Some(Background::Color(color!(0x4e342e))), - ..base - }, - _ => base, - } -} - -pub fn grid_cell_button(_theme: &Theme, status: button::Status) -> button::Style { - let base = button::Style { - background: Some(Background::Color(Color::TRANSPARENT)), - text_color: color!(0xd7ccc8), // Light tan for dark background - border: Border { - color: Color::TRANSPARENT, - width: 0.0, - radius: 0.into(), - }, - ..Default::default() - }; - match status { - button::Status::Hovered => button::Style { - background: Some(Background::Color(color!(0x333333))), - text_color: color!(0xeae0c8), - ..base - }, - _ => base, - } -} - pub fn commit_button(_theme: &Theme, status: button::Status) -> button::Style { let base = button::Style { background: Some(Background::Color(color!(0x2d5a27))), // Forest Green @@ -327,124 +309,6 @@ pub fn normal_row_button(_theme: &Theme, status: button::Status) -> button::Styl } } -pub fn pane_header_button(_theme: &Theme, status: button::Status) -> button::Style { - let base = button::Style { - background: Some(Background::Color(Color::TRANSPARENT)), - text_color: color!(0xcccccc), - border: Border { - color: Color::TRANSPARENT, - width: 0.0, - radius: 2.into(), - }, - ..Default::default() - }; - match status { - button::Status::Hovered => button::Style { - background: Some(Background::Color(color!(0x5d4037))), - text_color: color!(0xffd700), - ..base - }, - _ => base, - } -} -/// Header cell button — transparent base, column separator via border, hover highlight -pub fn spreadsheet_header_button(_theme: &Theme, status: button::Status) -> button::Style { - let base = button::Style { - background: None, - text_color: color!(0xb8a898), - border: Border { - color: color!(0x3d2b1f), - width: 1.0, - radius: 0.into(), - }, - ..Default::default() - }; - match status { - button::Status::Hovered => button::Style { - background: Some(Background::Color(color!(0x2d2218))), - text_color: color!(0xeae0c8), - ..base - }, - button::Status::Pressed => button::Style { - background: Some(Background::Color(color!(0x3d2b1f))), - text_color: color!(0xffd700), - ..base - }, - _ => base, - } -} -/// border). -pub fn spreadsheet_row( - is_selected: bool, - row_idx: usize, - is_highlighted: bool, - is_current_highlight: bool, -) -> impl Fn(&Theme, button::Status) -> button::Style { - move |_theme, status| { - let (bg, tc) = if is_current_highlight { - // "Find next match" target — brightest, most prominent - (color!(0x7a6a2a), color!(0xffffff)) - } else if is_highlighted { - // Other rows that match in highlight mode - (color!(0x5a4e1a), color!(0xfff2c0)) - } else if is_selected { - (color!(0x3a2e1a), color!(0xffd700)) - } else if row_idx.is_multiple_of(2) { - (color!(0x1e1b17), color!(0xd4c5a9)) - } else { - (color!(0x232019), color!(0xd4c5a9)) - }; - - let final_bg = match status { - button::Status::Hovered if !is_selected && !is_highlighted && !is_current_highlight => { - color!(0x2d2820) - } - _ => bg, - }; - - let border_color = if is_current_highlight { - color!(0xffd700, 0.85) - } else if is_highlighted { - color!(0xdaa520, 0.7) - } else if is_selected { - color!(0xdaa520, 0.5) - } else { - color!(0x2a2520) - }; - - let border_width = if is_current_highlight { - 2.0 - } else if is_selected || is_highlighted { - 1.0 - } else { - 0.5 - }; - - button::Style { - background: Some(Background::Color(final_bg)), - text_color: tc, - border: Border { - color: border_color, - width: border_width, - radius: 0.into(), - }, - ..Default::default() - } - } -} -/// Data cell button — fully transparent, no decoration; row background and selection show through -pub fn spreadsheet_cell_btn(_theme: &Theme, _status: button::Status) -> button::Style { - button::Style { - background: None, - text_color: color!(0xd4c5a9), - border: Border { - color: Color::TRANSPARENT, - width: 0.0, - radius: 0.into(), - }, - ..Default::default() - } -} /// Highlighted (selected) filter mode button — gold accent. pub fn filter_mode_active(_theme: &Theme, status: button::Status) -> button::Style { let base = button::Style { @@ -584,27 +448,6 @@ pub fn tree_file_row(_theme: &Theme, status: button::Status) -> button::Style { _ => base, } } -/// File tree menu button (⋮) — minimal, subtle -pub fn tree_menu_button(_theme: &Theme, status: button::Status) -> button::Style { - let base = button::Style { - background: None, - text_color: color!(0x8d6e63), - border: Border { - color: Color::TRANSPARENT, - width: 0.0, - radius: 0.into(), - }, - ..Default::default() - }; - match status { - button::Status::Hovered => button::Style { - background: Some(Background::Color(color!(0x3d2b1f))), - text_color: color!(0xd7ccc8), - ..base - }, - _ => base, - } -} pub fn menu_disabled_item(_theme: &Theme, _status: button::Status) -> button::Style { button::Style { @@ -667,6 +510,7 @@ pub fn playback_button(_theme: &Theme, status: button::Status) -> button::Style text_color: color!(0xffee58), ..base }, + button::Status::Disabled => dimmed(base), _ => base, } } @@ -713,6 +557,43 @@ pub fn export_button(_theme: &Theme, status: button::Status) -> button::Style { background: Some(Background::Color(color!(0x4e342e))), ..base }, + button::Status::Disabled => dimmed(base), _ => base, } } + +#[cfg(test)] +mod tests { + use super::*; + + fn assert_dimmed(style_fn: fn(&Theme, button::Status) -> button::Style, name: &str) { + let theme = Theme::Dark; + let active = style_fn(&theme, button::Status::Active); + let disabled = style_fn(&theme, button::Status::Disabled); + assert!( + disabled.text_color.a < active.text_color.a, + "{name}: disabled text must be dimmer than active" + ); + let bg_alpha = |s: button::Style| match s.background { + Some(Background::Color(c)) => c.a, + _ => 1.0, + }; + assert!( + bg_alpha(disabled) < bg_alpha(active), + "{name}: disabled background must be dimmer than active" + ); + assert!( + disabled.border.color.a < active.border.color.a, + "{name}: disabled border must be dimmer than active" + ); + } + + #[test] + fn test_shared_button_styles_dim_when_disabled() { + assert_dimmed(chip, "chip"); + assert_dimmed(active_chip, "active_chip"); + assert_dimmed(playback_button, "playback_button"); + assert_dimmed(export_button, "export_button"); + assert_dimmed(browse_button, "browse_button"); + } +} diff --git a/dispel-gui/src/style/layout.rs b/dispel-gui/src/style/layout.rs index fdadc710..46349cd9 100644 --- a/dispel-gui/src/style/layout.rs +++ b/dispel-gui/src/style/layout.rs @@ -26,18 +26,6 @@ pub fn sidebar_container(_theme: &Theme) -> container::Style { } } -pub fn log_container(_theme: &Theme) -> container::Style { - container::Style { - background: Some(Background::Color(color!(0x121212))), // Deep stone - border: Border { - color: color!(0x424242), - width: 1.0, - radius: 0.into(), - }, - ..Default::default() - } -} - pub fn info_card(_theme: &Theme) -> container::Style { container::Style { background: Some(Background::Color(color!(0x2d1f1b))), // Dark leather card @@ -62,18 +50,6 @@ pub fn toolbar_container(_theme: &Theme) -> container::Style { } } -pub fn sql_editor_container(_theme: &Theme) -> container::Style { - container::Style { - background: Some(Background::Color(color!(0x121212))), - border: Border { - color: color!(0x5d4037), - width: 1.0, - radius: 4.into(), - }, - ..Default::default() - } -} - pub fn status_bar(_theme: &Theme) -> container::Style { container::Style { background: Some(Background::Color(color!(0x1a1510))), @@ -127,32 +103,6 @@ pub fn normal_row(_theme: &Theme) -> container::Style { ..Default::default() } } -/// Mode chip container (NORMAL). -pub fn normal_mode_chip(_theme: &Theme) -> container::Style { - container::Style { - background: Some(Background::Color(color!(0x2a1f18))), - border: Border { - color: color!(0x5d4037), - width: 1.0, - radius: 3.into(), - }, - text_color: Some(color!(0xbcaaa4)), - ..Default::default() - } -} -/// Mode chip container (EDIT) — leather brown with gold border. -pub fn edit_mode_chip(_theme: &Theme) -> container::Style { - container::Style { - background: Some(Background::Color(color!(0x8b5a2b))), - border: Border { - color: color!(0xffd700), - width: 1.0, - radius: 3.into(), - }, - text_color: Some(color!(0xffd700)), - ..Default::default() - } -} /// Container for the export modal dialog. pub fn export_dialog_container(_theme: &Theme) -> container::Style { container::Style { diff --git a/dispel-gui/src/style/pane_grid.rs b/dispel-gui/src/style/pane_grid.rs deleted file mode 100644 index c2edb7db..00000000 --- a/dispel-gui/src/style/pane_grid.rs +++ /dev/null @@ -1,50 +0,0 @@ -use iced::widget::container; -use iced::{Background, Border, Color, Theme, color}; - -pub fn pane_focused(_theme: &Theme) -> container::Style { - container::Style { - background: Some(Background::Color(color!(0x2a2a2a))), - border: Border { - color: color!(0xdaa520, 0.6), - width: 2.0, - radius: 4.into(), - }, - ..Default::default() - } -} - -pub fn pane_unfocused(_theme: &Theme) -> container::Style { - container::Style { - background: Some(Background::Color(color!(0x222222))), - border: Border { - color: color!(0x3d2b1f, 0.4), - width: 1.0, - radius: 4.into(), - }, - ..Default::default() - } -} - -pub fn pane_header_focused(_theme: &Theme) -> container::Style { - container::Style { - background: Some(Background::Color(color!(0x3d2b1f))), - border: Border { - color: Color::TRANSPARENT, - width: 0.0, - radius: 0.into(), - }, - ..Default::default() - } -} - -pub fn pane_header_unfocused(_theme: &Theme) -> container::Style { - container::Style { - background: Some(Background::Color(color!(0x2d2d2d))), - border: Border { - color: Color::TRANSPARENT, - width: 0.0, - radius: 0.into(), - }, - ..Default::default() - } -} diff --git a/dispel-gui/src/style/progress_bar.rs b/dispel-gui/src/style/progress_bar.rs index 422d0bf1..86ba5c6d 100644 --- a/dispel-gui/src/style/progress_bar.rs +++ b/dispel-gui/src/style/progress_bar.rs @@ -1,18 +1,6 @@ use iced::widget::progress_bar; use iced::{Background, Border, Theme, color}; -pub fn loading_progress_bar(_theme: &Theme) -> progress_bar::Style { - progress_bar::Style { - background: Background::Color(color!(0x3d2b1f)), - bar: Background::Color(color!(0xdaa520)), // Gold bar - border: Border { - color: color!(0x5d4037), - width: 1.0, - radius: 2.into(), - }, - } -} - pub fn primary_progress_bar(_theme: &Theme) -> progress_bar::Style { progress_bar::Style { background: Background::Color(color!(0x3d2b1f)), // Dark brown background @@ -24,15 +12,3 @@ pub fn primary_progress_bar(_theme: &Theme) -> progress_bar::Style { }, } } - -pub fn secondary_progress_bar(_theme: &Theme) -> progress_bar::Style { - progress_bar::Style { - background: Background::Color(color!(0x3d2b1f)), // Dark brown background - bar: Background::Color(color!(0xff8c00)), // Orange warning color - border: Border { - color: color!(0x5d4037), - width: 1.0, - radius: 2.into(), - }, - } -} diff --git a/dispel-gui/src/style/spreadsheet.rs b/dispel-gui/src/style/spreadsheet.rs index b7abc8e1..0524597b 100644 --- a/dispel-gui/src/style/spreadsheet.rs +++ b/dispel-gui/src/style/spreadsheet.rs @@ -1,5 +1,5 @@ use iced::widget::{container, text_input}; -use iced::{Background, Border, Color, Theme, color}; +use iced::{Background, Border, Theme, color}; pub fn grid_header_cell(_theme: &Theme) -> container::Style { container::Style { @@ -13,45 +13,6 @@ pub fn grid_header_cell(_theme: &Theme) -> container::Style { } } -pub fn grid_cell(_theme: &Theme) -> container::Style { - container::Style { - background: Some(Background::Color(Color::TRANSPARENT)), - border: Border { - color: color!(0x3d2b1f), - width: 0.5, - radius: 0.into(), - }, - text_color: Some(color!(0xd7ccc8)), - ..Default::default() - } -} - -pub fn grid_cell_dirty(_theme: &Theme) -> container::Style { - container::Style { - background: Some(Background::Color(color!(0x3d2b1f))), // Darker brown for dirty - border: Border { - color: color!(0xdaa520), // Gold border for dirty cell - width: 1.0, - radius: 0.into(), - }, - text_color: Some(color!(0xeae0c8)), - ..Default::default() - } -} - -pub fn grid_row(_theme: &Theme) -> container::Style { - container::Style { - background: Some(Background::Color(color!(0x262626))), - ..Default::default() - } -} - -pub fn grid_row_even(_theme: &Theme) -> container::Style { - container::Style { - background: Some(Background::Color(color!(0x1f1f1f))), - ..Default::default() - } -} /// Header row container — dark background, bottom separator via border pub fn spreadsheet_header(_theme: &Theme) -> container::Style { container::Style { @@ -65,56 +26,6 @@ pub fn spreadsheet_header(_theme: &Theme) -> container::Style { ..Default::default() } } -/// click-and-drag handle for resizing a column. -pub fn resize_handle(_theme: &Theme) -> container::Style { - container::Style { - background: Some(Background::Color(color!(0x4a3728))), - border: Border { - color: color!(0x2a1f17), - width: 0.0, - radius: 0.into(), - }, - ..Default::default() - } -} -/// Data cell container — provides subtle gridline border, no own background -pub fn spreadsheet_cell(_theme: &Theme) -> container::Style { - container::Style { - background: None, - border: Border { - color: color!(0x2e2824), - width: 0.5, - radius: 0.into(), - }, - ..Default::default() - } -} -/// Row-number (#) column — darker "frozen column" look matching Excel -pub fn spreadsheet_id_cell(_theme: &Theme) -> container::Style { - container::Style { - background: Some(Background::Color(color!(0x171411))), - border: Border { - color: color!(0x3d2b1f), - width: 1.0, - radius: 0.into(), - }, - text_color: Some(color!(0x6a5e54)), - ..Default::default() - } -} -/// Row-number (#) column — lighter tint when the row is selected -pub fn spreadsheet_id_cell_selected(_theme: &Theme) -> container::Style { - container::Style { - background: Some(Background::Color(color!(0x2a2010))), - border: Border { - color: color!(0xdaa520, 0.5), - width: 1.0, - radius: 0.into(), - }, - text_color: Some(color!(0xdaa520)), - ..Default::default() - } -} pub fn spreadsheet_filter_input(_theme: &Theme, _status: text_input::Status) -> text_input::Style { text_input::Style { @@ -129,34 +40,3 @@ pub fn spreadsheet_filter_input(_theme: &Theme, _status: text_input::Status) -> selection: color!(0xdaa520, 0.3), } } -/// Text input used for in-cell editing — brighter border to signal "active edit". -pub fn spreadsheet_cell_editor(_theme: &Theme, status: text_input::Status) -> text_input::Style { - let border_color = match status { - text_input::Status::Focused { .. } => color!(0xffd700), - _ => color!(0xdaa520, 0.6), - }; - text_input::Style { - background: Background::Color(color!(0x2a1f18)), - border: Border { - color: border_color, - width: 1.5, - radius: 2.into(), - }, - placeholder: color!(0x666666), - value: color!(0xffee58), - selection: color!(0xdaa520, 0.4), - } -} -/// Data cell that failed validation — red border, subtle red tint. -pub fn spreadsheet_cell_invalid(_theme: &Theme) -> container::Style { - container::Style { - background: Some(Background::Color(color!(0x3a1a18))), - border: Border { - color: color!(0xff5252), - width: 1.5, - radius: 0.into(), - }, - text_color: Some(color!(0xffcdd2)), - ..Default::default() - } -} diff --git a/dispel-gui/src/style/text.rs b/dispel-gui/src/style/text.rs index fa547868..6913672f 100644 --- a/dispel-gui/src/style/text.rs +++ b/dispel-gui/src/style/text.rs @@ -19,35 +19,6 @@ pub fn primary_text(_theme: &Theme) -> text::Style { } } -pub fn progress_text_style(_theme: &Theme) -> text::Style { - text::Style { - color: Some(color!(0xeae0c8)), // Light tan text for contrast - } -} - -pub fn pane_title_focused(_theme: &Theme) -> text::Style { - text::Style { - color: Some(color!(0xffd700)), - } -} - -pub fn pane_title_unfocused(_theme: &Theme) -> text::Style { - text::Style { - color: Some(color!(0x888888)), - } -} -/// Text inside a NORMAL mode chip. -pub fn normal_mode_text(_theme: &Theme) -> text::Style { - text::Style { - color: Some(color!(0xd2b48c)), - } -} -/// Text inside an EDIT mode chip. -pub fn edit_mode_text(_theme: &Theme) -> text::Style { - text::Style { - color: Some(color!(0xffd700)), - } -} /// Text style used for filter-bar status (e.g. "12 of 350 rows" / "7 highlighted"). pub fn filter_status_text(_theme: &Theme) -> text::Style { text::Style { diff --git a/dispel-gui/src/tests/command_palette.rs b/dispel-gui/src/tests/command_palette.rs index 81e1432b..0080555c 100644 --- a/dispel-gui/src/tests/command_palette.rs +++ b/dispel-gui/src/tests/command_palette.rs @@ -190,4 +190,48 @@ mod command_palette_tests { let task = app.update(Message::Workspace(WorkspaceMessage::CommandPaletteArrowUp)); assert_eq!(task.units(), 0); } + + #[test] + fn test_palette_does_not_duplicate_store_editor() { + let commands = crate::components::command_palette::Command::all(); + assert!( + !commands.iter().any(|c| c.id == "open-store-editor"), + "the Store Editor is opened from the sidebar, not the palette" + ); + assert!( + !commands.iter().any(|c| c.label == "Open: Store Editor"), + "no palette label may duplicate the sidebar Store Editor button" + ); + } + + #[cfg(feature = "iced_test")] + #[test] + fn test_sidebar_store_button_still_opens_editor() { + use crate::workspace::EditorType; + use iced_test::simulator; + + let mut app = App::test_new(Workspace::new()); + let mut ui = simulator(app.view()); + ui.click("Store Editor") + .expect("sidebar must keep a Store Editor button"); + let messages: Vec = ui.into_messages().collect(); + assert!( + messages.iter().any(|m| matches!( + m, + Message::Workspace(WorkspaceMessage::OpenToolTab(EditorType::StoreEditor)) + )), + "sidebar Store Editor must emit OpenToolTab(StoreEditor), got {messages:?}" + ); + for msg in messages { + let _ = app.update(msg); + } + assert!( + app.state + .workspace + .tabs + .iter() + .any(|t| t.editor_type == EditorType::StoreEditor), + "sidebar Store Editor button must open the editor" + ); + } } diff --git a/dispel-gui/src/tests/editor_catalog.rs b/dispel-gui/src/tests/editor_catalog.rs index 3ddb5bda..8433aa99 100644 --- a/dispel-gui/src/tests/editor_catalog.rs +++ b/dispel-gui/src/tests/editor_catalog.rs @@ -180,11 +180,10 @@ mod exhaustive { // ── Catalog-derived mapping agreement ─────────────────────────────────── - /// The command palette's `applicable_editors` used to be hand-copied and - /// wrong in two places (`load-message-scr` → QuestScr, all-map commands → - /// MapIni). Derive the expected target from the catalog by comparing the - /// message a command produces with the catalog's own load/save message - /// constructors, then assert the command points at that editor. + /// Scan/save is reached from each editor's own buttons and global Ctrl+S, + /// so the palette must not repeat those actions. The catalog still owns the + /// load/save messages those buttons send; the remaining palette commands + /// keep their editor scoping. #[test] fn command_applicability_agrees_with_catalog() { let mut load_by_msg: HashMap = HashMap::new(); @@ -198,39 +197,41 @@ mod exhaustive { save_by_msg.insert(format!("{:?}", save(0)), et); } } + assert!( + load_by_msg.len() >= 20 && save_by_msg.len() >= 20, + "the catalog must still declare load/save messages for per-editor buttons" + ); - let mut checked = 0; + let mut scoped = 0; for cmd in crate::components::command_palette::Command::all() { - let is_load = cmd.id.starts_with("scan-") || cmd.id.starts_with("load-"); - let is_save = cmd.id.starts_with("save-"); - if !is_load && !is_save { - continue; - } - assert_eq!( - cmd.applicable_editors.len(), - 1, - "catalog command '{}' should target exactly one editor", - cmd.id - ); - let actual = format!("{:?}", (cmd.action)()); - let table = if is_load { &load_by_msg } else { &save_by_msg }; - let expected = table.get(&actual).unwrap_or_else(|| { - panic!( - "command '{}' produces a message no catalog editor declares: {}", - cmd.id, actual - ) - }); - assert_eq!( - cmd.applicable_editors[0], *expected, - "command '{}' is scoped to the wrong editor", + let is_scan_save = cmd.id.starts_with("scan-") + || cmd.id.starts_with("load-") + || cmd.id.starts_with("save-"); + assert!( + !is_scan_save, + "palette must not duplicate a per-editor scan/save action: {}", cmd.id ); - checked += 1; + let _ = (cmd.action)(); + if cmd.id.starts_with("hex-") { + assert_eq!( + cmd.applicable_editors, + vec![EditorType::HexEditor], + "hex commands must stay scoped to the hex editor" + ); + scoped += 1; + } else { + assert!( + cmd.applicable_editors.is_empty(), + "command '{}' should be universal, got {:?}", + cmd.id, + cmd.applicable_editors + ); + } } assert!( - checked >= 20, - "expected the catalog to drive at least 20 scan/save commands, found {}", - checked + scoped >= 2, + "expected the hex editor commands to remain in the palette, found {scoped}" ); } diff --git a/dispel-gui/src/tests/loading_indicator.rs b/dispel-gui/src/tests/loading_indicator.rs new file mode 100644 index 00000000..152ffb53 --- /dev/null +++ b/dispel-gui/src/tests/loading_indicator.rs @@ -0,0 +1,29 @@ +//! Guards against fake 50% progress bars in loading views. Loading has no +//! measurable progress, so the views show an indeterminate "Working…" label. + +const LOADING_VIEW_SOURCES: [&str; 4] = [ + include_str!("../view/mod.rs"), + include_str!("../editors/map_editor/view/mod.rs"), + include_str!("../view/editor/spreadsheet/view/status_bar.rs"), + include_str!("../editors/save_file_viewer/map_preview/view.rs"), +]; + +#[test] +fn test_loading_views_have_no_half_progress_bar() { + for source in LOADING_VIEW_SOURCES { + assert!( + !source.contains("progress_bar(0.0..=1.0, 0.5)"), + "loading view must not render a fake 50% progress bar" + ); + assert!( + !source.contains("progress_bar(0.0..=100.0, 50.0)"), + "loading view must not render a fake 50% progress bar" + ); + } + assert!( + LOADING_VIEW_SOURCES + .iter() + .all(|source| source.contains("Working…")), + "every loading view must show an indeterminate indicator" + ); +} diff --git a/dispel-gui/src/tests/mod.rs b/dispel-gui/src/tests/mod.rs index 910213ad..34df1234 100644 --- a/dispel-gui/src/tests/mod.rs +++ b/dispel-gui/src/tests/mod.rs @@ -35,6 +35,7 @@ pub(crate) mod global_search; pub(crate) mod hex_config_parity; pub(crate) mod hex_inspector_toggle; pub(crate) mod indexation; +pub(crate) mod loading_indicator; pub(crate) mod map_editor; pub(crate) mod message_routing; pub(crate) mod pane_grid; diff --git a/dispel-gui/src/tests/sprite_viewer.rs b/dispel-gui/src/tests/sprite_viewer.rs index f5162355..47950bab 100644 --- a/dispel-gui/src/tests/sprite_viewer.rs +++ b/dispel-gui/src/tests/sprite_viewer.rs @@ -54,6 +54,7 @@ mod sprite_viewer_tests { undo_stack: Vec::new(), redo_stack: Vec::new(), zoom: 1.0, + fit_mode: false, }, ); app @@ -97,6 +98,7 @@ mod sprite_viewer_tests { undo_stack: Vec::new(), redo_stack: Vec::new(), zoom: 1.0, + fit_mode: false, }, ); app @@ -238,6 +240,59 @@ mod sprite_viewer_tests { ); } + // ── Zoom / Fit ──────────────────────────────────────────────────────────── + + #[test] + fn test_zoom_to_fit_resets_manual_zoom() { + let mut app = app_with_sprite_viewer_frames(); + for _ in 0..5 { + let _ = crate::editors::sprite_editor::handle(SpriteViewerMessage::ZoomIn, &mut app); + } + assert!(app.state.editors.sprite_viewers[&0].zoom > 1.0); + assert!(!app.state.editors.sprite_viewers[&0].fit_mode); + + let _ = crate::editors::sprite_editor::handle(SpriteViewerMessage::ZoomToFit, &mut app); + let viewer = &app.state.editors.sprite_viewers[&0]; + assert!(viewer.fit_mode); + assert_eq!( + viewer.zoom, 1.0, + "Fit must clear the manual multiplier so the effective scale is exactly fit_scale" + ); + + let viewport = iced::Size::new(640.0, 480.0); + let frame = (viewer.frames[0].width, viewer.frames[0].height); + let effective = crate::editors::sprite_editor::fit_scale(viewport, frame) * viewer.zoom; + assert_eq!( + effective, + crate::editors::sprite_editor::fit_scale(viewport, frame) + ); + } + + #[cfg(feature = "iced_test")] + #[test] + fn test_zoom_to_fit_clears_stale_percentage_label() { + use iced_test::simulator; + + let mut app = app_with_sprite_viewer_frames(); + for _ in 0..5 { + let _ = crate::editors::sprite_editor::handle(SpriteViewerMessage::ZoomIn, &mut app); + } + let stale = format!( + "{}%", + (app.state.editors.sprite_viewers[&0].zoom * 100.0).round() as u32 + ); + { + let mut ui = simulator(app.view()); + ui.find(stale.clone()) + .expect("manual zoom shows a percentage"); + } + + let _ = crate::editors::sprite_editor::handle(SpriteViewerMessage::ZoomToFit, &mut app); + let mut ui = simulator(app.view()); + ui.find(stale) + .expect_err("Fit must not keep showing a stale manual zoom percentage"); + } + // ── Export dialog ──────────────────────────────────────────────────────── #[test] diff --git a/dispel-gui/src/update/file_tree.rs b/dispel-gui/src/update/file_tree.rs index a3bc1678..abe29eba 100644 --- a/dispel-gui/src/update/file_tree.rs +++ b/dispel-gui/src/update/file_tree.rs @@ -73,6 +73,11 @@ pub fn handle(message: FileTreeMessage, app: &mut App) -> Task( .width(Length::Fill) .into() } else { + let field_name = descriptor.name.to_string(); text_input("", value.clone()) + .on_input(move |v| field_changed_msg(orig_idx, field_name.clone(), v)) .padding(4) .size(11) .width(Length::Fill) @@ -168,7 +170,7 @@ fn build_inspector_field<'a>( FieldKind::CompositeItem { lookup_key } => { let entries = lookups.get(*lookup_key).map(|v| v.as_slice()); let field_name = descriptor.name.to_string(); - composite_item_picker(descriptor.label, &value, entries, move |v| { + composite_item_picker(descriptor.label, &value, entries, false, move |v| { spreadsheet_msg(SpreadsheetMessage::InspectorFieldChanged( orig_idx, field_name.clone(), @@ -206,3 +208,125 @@ fn build_inspector_field<'a>( } field_column.into() } + +#[cfg(all(test, feature = "iced_test"))] +mod tests { + use super::*; + use iced_test::selector::{Candidate, Target}; + use iced_test::simulator; + + fn field_changed(idx: usize, name: String, value: String) -> Message { + Message::Editor(crate::message::editor::EditorMessage::Weapon( + crate::editors::weapon::WeaponEditorMessage::FieldChanged(idx, name, value), + )) + } + + fn spreadsheet_msg(_: SpreadsheetMessage) -> Message { + Message::System(crate::message::SystemMessage::DismissError) + } + + fn count_label_text(element: Element<'_, Message>, label: &str) -> usize { + let mut ui = simulator(element); + let mut count = 0usize; + let mut selector = |candidate: Candidate<'_>| -> Option { + if let Candidate::Text { content, .. } = candidate + && content == label + { + count += 1; + } + None + }; + let _ = ui.find(&mut selector); + count + } + + #[test] + fn test_composite_field_label_appears_once() { + let descriptor = FieldDescriptor { + name: "item_type", + label: "Invented Item:", + kind: FieldKind::CompositeItem { + lookup_key: "invented_items", + }, + }; + let empty_lookups = HashMap::new(); + let contents = HashMap::new(); + + // Fallback path (no lookups): the inspector wraps the body with one label. + let element = build_inspector_field( + &descriptor, + "1:0".into(), + 0, + &empty_lookups, + None, + field_changed, + &contents, + spreadsheet_msg, + ); + assert_eq!( + count_label_text(element, "Invented Item:"), + 1, + "composite field must not render its label twice without lookups" + ); + + // Picker path (lookups loaded): same single-label guarantee. + let lookups = HashMap::from([( + "invented_items".to_string(), + vec![("1:0".to_string(), "Invented Sword".to_string())], + )]); + let element = build_inspector_field( + &descriptor, + "1:0".into(), + 0, + &lookups, + None, + field_changed, + &contents, + spreadsheet_msg, + ); + assert_eq!( + count_label_text(element, "Invented Item:"), + 1, + "composite field must not render its label twice with lookups" + ); + } + + #[test] + fn test_lookup_fallback_input_emits_field_changed() { + let descriptor = FieldDescriptor { + name: "monster_db_id", + label: "Monster ID:", + kind: FieldKind::Lookup("monster_names"), + }; + let lookups = HashMap::new(); + let contents = HashMap::new(); + let element: Element<'_, Message> = build_inspector_field( + &descriptor, + String::new(), + 0, + &lookups, + None, + field_changed, + &contents, + spreadsheet_msg, + ); + let mut ui = simulator(element); + let mut pick_input = |candidate: Candidate<'_>| match candidate { + Candidate::TextInput { .. } => Some(Target::from(candidate)), + _ => None, + }; + ui.click(&mut pick_input) + .expect("fallback text input must be present"); + ui.typewrite("42"); + let messages: Vec = ui.into_messages().collect(); + assert!( + messages.iter().any(|m| matches!( + m, + Message::Editor(crate::message::editor::EditorMessage::Weapon( + crate::editors::weapon::WeaponEditorMessage::FieldChanged(_, _, _) + )) + )), + "fallback text input must emit a FieldChanged message, got {messages:?}" + ); + } +} diff --git a/dispel-gui/src/view/editor/spreadsheet/view/status_bar.rs b/dispel-gui/src/view/editor/spreadsheet/view/status_bar.rs index 5d66974a..b9bc255a 100644 --- a/dispel-gui/src/view/editor/spreadsheet/view/status_bar.rs +++ b/dispel-gui/src/view/editor/spreadsheet/view/status_bar.rs @@ -8,7 +8,7 @@ use crate::message::Message; use crate::style; use crate::view::editor::spreadsheet::message::SpreadsheetMessage; use crate::view::editor::spreadsheet::state::SpreadsheetState; -use iced::widget::{button, column, container, progress_bar, row, text}; +use iced::widget::{button, column, container, row, text}; use iced::{Element, Fill, Length}; pub fn build_status_bar<'a, R: EditableRecord>( @@ -23,9 +23,7 @@ pub fn build_status_bar<'a, R: EditableRecord>( text("Loading spreadsheet...") .size(11) .style(style::subtle_text), - container(progress_bar(0.0..=100.0, 50.0)) - .width(Fill) - .height(Length::Fixed(6.0)), + text("Working…").size(10).style(style::subtle_text), ] .spacing(4) .width(Length::Fixed(160.0)), diff --git a/dispel-gui/src/view/editor/spreadsheet/view/table.rs b/dispel-gui/src/view/editor/spreadsheet/view/table.rs index 022772fc..145a3fea 100644 --- a/dispel-gui/src/view/editor/spreadsheet/view/table.rs +++ b/dispel-gui/src/view/editor/spreadsheet/view/table.rs @@ -19,19 +19,27 @@ pub fn build_table_content<'a, R: EditableRecord>( spreadsheet_msg: fn(SpreadsheetMessage) -> Message, ) -> Element<'a, Message> { if catalog.is_none() { - return container( - text("No data loaded. Click Scan to load records.") - .size(13) - .style(style::subtle_text), - ) - .width(Fill) - .padding(20) - .into(); + return empty_table_message("No records. Click Scan to load records."); + } + + if catalog.is_some_and(|c| c.is_empty()) { + return empty_table_message("No records"); + } + + if spreadsheet.filtered_indices.is_empty() { + return empty_table_message("No matching records"); } build_table_content_widget(descriptors, spreadsheet, spreadsheet_msg) } +fn empty_table_message<'a>(message: &'static str) -> Element<'a, Message> { + container(text(message).size(13).style(style::subtle_text)) + .width(Fill) + .padding(20) + .into() +} + fn build_table_content_widget<'a>( descriptors: &'a [FieldDescriptor], spreadsheet: &'a SpreadsheetState, @@ -104,3 +112,59 @@ fn build_table_content_widget<'a>( body } } + +#[cfg(all(test, feature = "iced_test"))] +mod tests { + use super::*; + use crate::components::editable::EditableRecord; + use crate::message::SystemMessage; + use dispel_core::WeaponItem; + use iced_test::simulator; + + fn msg(_: SpreadsheetMessage) -> Message { + Message::System(SystemMessage::DismissError) + } + + #[test] + fn test_empty_catalog_shows_no_records_message() { + let spreadsheet = SpreadsheetState::new(); + let element: Element<'_, Message> = build_table_content::( + WeaponItem::field_descriptors(), + None, + &spreadsheet, + msg, + ); + let mut ui = simulator(element); + assert!( + ui.find("No records. Click Scan to load records.").is_ok(), + "an unloaded catalog must explain how to load records" + ); + } + + #[test] + fn test_empty_and_filtered_results_render_a_message() { + let spreadsheet = SpreadsheetState::new(); + let empty: Vec = Vec::new(); + let element: Element<'_, Message> = build_table_content::( + WeaponItem::field_descriptors(), + Some(&empty), + &spreadsheet, + msg, + ); + let mut ui = simulator(element); + assert!(ui.find("No records").is_ok()); + + let populated = vec![WeaponItem::default()]; + let element: Element<'_, Message> = build_table_content::( + WeaponItem::field_descriptors(), + Some(&populated), + &spreadsheet, + msg, + ); + let mut ui = simulator(element); + assert!( + ui.find("No matching records").is_ok(), + "zero filter results must be explained" + ); + } +} diff --git a/dispel-gui/src/view/mod.rs b/dispel-gui/src/view/mod.rs index f8cd6907..2edf69e6 100644 --- a/dispel-gui/src/view/mod.rs +++ b/dispel-gui/src/view/mod.rs @@ -12,7 +12,7 @@ use crate::workspace::EditorType; use gui_widgets::components::modal::modal; use gui_widgets::lucide::{LUCIDE_FONT, icon_char}; use iced::widget::{Space, pane_grid}; -use iced::widget::{button, column, container, progress_bar, row, stack, text}; +use iced::widget::{button, column, container, row, stack, text}; use iced::{Element, Fill, Font, Length, alignment}; use lucide_icons::Icon; @@ -302,7 +302,7 @@ impl App { container( column![ text("Indexing files…").size(11).style(style::subtle_text), - progress_bar(0.0..=1.0, 0.5).style(style::primary_progress_bar), + text("Working…").size(10).style(style::subtle_text), ] .spacing(8) .align_x(iced::Alignment::Center), diff --git a/gui-widgets/src/components/toast.rs b/gui-widgets/src/components/toast.rs index 836aba7e..556bb5dc 100644 --- a/gui-widgets/src/components/toast.rs +++ b/gui-widgets/src/components/toast.rs @@ -40,6 +40,12 @@ mod tests; pub const DEFAULT_TIMEOUT: u64 = 4; +fn next_toast_id() -> u64 { + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: AtomicU64 = AtomicU64::new(1); + NEXT.fetch_add(1, Ordering::Relaxed) +} + /// Severity / visual style of a toast notification. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum Status { @@ -51,9 +57,21 @@ pub enum Status { Warning, } +/// A single toast notification. The `id` is stable across rewrites of an +/// existing toast's content so its timer keeps following the same slot. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ToastId(u64); + +impl ToastId { + pub fn new(id: u64) -> Self { + ToastId(id) + } +} + /// A single toast notification. #[derive(Debug, Clone)] pub struct Toast { + pub id: ToastId, pub title: String, pub body: String, pub status: Status, @@ -63,6 +81,7 @@ impl Toast { /// Create a success toast. pub fn success(title: impl Into, body: impl Into) -> Self { Toast { + id: ToastId::new(next_toast_id()), title: title.into(), body: body.into(), status: Status::Success, @@ -72,6 +91,7 @@ impl Toast { /// Create an error/danger toast. pub fn error(title: impl Into, body: impl Into) -> Self { Toast { + id: ToastId::new(next_toast_id()), title: title.into(), body: body.into(), status: Status::Danger, @@ -81,6 +101,7 @@ impl Toast { /// Create an info/primary toast. pub fn info(title: impl Into, body: impl Into) -> Self { Toast { + id: ToastId::new(next_toast_id()), title: title.into(), body: body.into(), status: Status::Primary, @@ -90,6 +111,7 @@ impl Toast { /// Create a warning toast. pub fn warning(title: impl Into, body: impl Into) -> Self { Toast { + id: ToastId::new(next_toast_id()), title: title.into(), body: body.into(), status: Status::Warning, @@ -100,9 +122,50 @@ impl Toast { /// A widget that displays [`Toast`] notifications as an overlay on top of /// `content`. Toasts are stacked vertically at the top-right and auto-dismiss /// after a configurable timeout. +/// Timer for one toast, keyed by its stable id. `title`/`body`/`status` are +/// the content the timer started with; any change resets the countdown. +#[derive(Clone)] +struct ToastTimer { + id: ToastId, + title: String, + body: String, + status: Status, + started: Instant, +} + +type ToastTimers = Vec; + +/// Reconcile timers against the current toast list. Timers follow stable ids, +/// so removing a toast from the middle leaves the other countdowns untouched; +/// a content change restarts only that toast's countdown. +fn sync_timers(timers: &mut ToastTimers, entries: &[(ToastId, String, String, Status)]) { + timers.retain(|timer| entries.iter().any(|(id, _, _, _)| *id == timer.id)); + for (id, title, body, status) in entries { + match timers.iter_mut().find(|timer| timer.id == *id) { + Some(timer) + if timer.title == *title && timer.body == *body && timer.status == *status => {} + Some(timer) => { + timer.title = title.clone(); + timer.body = body.clone(); + timer.status = *status; + timer.started = Instant::now(); + } + None => timers.push(ToastTimer { + id: id.clone(), + title: title.clone(), + body: body.clone(), + status: *status, + started: Instant::now(), + }), + } + } +} + pub struct Manager<'a, Message> { content: Element<'a, Message>, toasts: Vec>, + /// Stable id + content snapshot for each toast, in display order. + entries: Vec<(ToastId, String, String, Status)>, timeout_secs: u64, on_close: Box Message + 'a>, } @@ -120,6 +183,17 @@ where toasts: &'a [Toast], on_close: impl Fn(usize) -> Message + 'a, ) -> Self { + let entries = toasts + .iter() + .map(|toast| { + ( + toast.id.clone(), + toast.title.clone(), + toast.body.clone(), + toast.status, + ) + }) + .collect(); let toasts = toasts .iter() .enumerate() @@ -159,6 +233,7 @@ where Self { content: content.into(), toasts, + entries, timeout_secs: DEFAULT_TIMEOUT, on_close: Box::new(on_close), } @@ -195,22 +270,13 @@ impl Widget for Manager<'_, Message> { } fn state(&self) -> widget::tree::State { - widget::tree::State::new(Vec::>::new()) + widget::tree::State::new(ToastTimers::new()) } fn diff(&mut self, tree: &mut Tree) { - let instants = tree.state.downcast_mut::>>(); - - instants.retain(Option::is_some); - - match (instants.len(), self.toasts.len()) { - (old, new) if old > new => { - instants.truncate(new); - } - (old, new) if old < new => { - instants.extend(std::iter::repeat_n(Some(Instant::now()), new - old)); - } - _ => {} + { + let timers = tree.state.downcast_mut::(); + sync_timers(timers, &self.entries); } tree.diff_children( @@ -305,7 +371,7 @@ impl Widget for Manager<'_, Message> { viewport: &Rectangle, translation: Vector, ) -> Option> { - let instants = tree.state.downcast_mut::>>(); + let timers = tree.state.downcast_mut::(); let (content_state, toasts_state) = tree.children.split_at_mut(1); @@ -323,7 +389,8 @@ impl Widget for Manager<'_, Message> { viewport: *viewport, toasts: &mut self.toasts, trees: toasts_state, - instants, + timers, + entries: &self.entries, on_close: &self.on_close, timeout_secs: self.timeout_secs, })) @@ -341,7 +408,8 @@ struct Overlay<'a, 'b, Message> { viewport: Rectangle, toasts: &'b mut [Element<'a, Message>], trees: &'b mut [Tree], - instants: &'b mut [Option], + timers: &'b mut ToastTimers, + entries: &'b [(ToastId, String, String, Status)], on_close: &'b dyn Fn(usize) -> Message, timeout_secs: u64, } @@ -374,32 +442,29 @@ impl overlay::Overlay for Overlay<'_, '_, Mes shell: &mut Shell<'_, Message>, ) { if let Event::Window(iced::window::Event::RedrawRequested(now)) = &event { - self.instants - .iter_mut() - .enumerate() - .for_each(|(index, maybe_instant)| { - if let Some(instant) = maybe_instant.as_mut() { - let remaining = - time::seconds(self.timeout_secs).saturating_sub(instant.elapsed()); - - if remaining == Duration::ZERO { - maybe_instant.take(); - shell.publish((self.on_close)(index)); - } else { - shell.request_redraw_at(*now + remaining); - } - } - }); + for (index, (id, _, _, _)) in self.entries.iter().enumerate() { + let Some(timer) = self.timers.iter_mut().find(|t| t.id == *id) else { + continue; + }; + let remaining = + time::seconds(self.timeout_secs).saturating_sub(timer.started.elapsed()); + if remaining == Duration::ZERO { + self.timers.retain(|t| t.id != *id); + shell.publish((self.on_close)(index)); + } else { + shell.request_redraw_at(*now + remaining); + } + } } let viewport = layout.bounds(); - for (((child, state), layout), instant) in self + for (((child, state), layout), (id, _, _, _)) in self .toasts .iter_mut() .zip(self.trees.iter_mut()) .zip(layout.children()) - .zip(self.instants.iter_mut()) + .zip(self.entries.iter()) { let mut local_messages = Bus::new(); let mut local_shell = shell.local(&mut local_messages); @@ -414,8 +479,9 @@ impl overlay::Overlay for Overlay<'_, '_, Mes &viewport, ); + // Any interaction with the toast pauses auto-dismiss entirely. if !local_shell.is_empty() { - instant.take(); + self.timers.retain(|timer| timer.id != *id); } shell.merge(local_shell, std::convert::identity); diff --git a/gui-widgets/src/components/toast/tests.rs b/gui-widgets/src/components/toast/tests.rs index cff603bf..eaa578d2 100644 --- a/gui-widgets/src/components/toast/tests.rs +++ b/gui-widgets/src/components/toast/tests.rs @@ -11,6 +11,58 @@ fn redraw() -> Event { Event::Window(iced::window::Event::RedrawRequested(Instant::now())) } +fn entry(id: u64, title: &str, body: &str) -> (ToastId, String, String, Status) { + (ToastId::new(id), title.into(), body.into(), Status::Primary) +} + +fn old_timer(id: u64, title: &str, body: &str) -> ToastTimer { + ToastTimer { + id: ToastId::new(id), + title: title.into(), + body: body.into(), + status: Status::Primary, + started: Instant::now() - Duration::from_secs(100), + } +} + +#[test] +fn test_remove_middle_toast_keeps_other_timers() { + let entries = [entry(1, "A", "a"), entry(2, "B", "b"), entry(3, "C", "c")]; + let old = Instant::now() - Duration::from_secs(100); + let mut timers: ToastTimers = entries + .iter() + .map(|(id, title, body, status)| ToastTimer { + id: id.clone(), + title: title.clone(), + body: body.clone(), + status: *status, + started: old, + }) + .collect(); + + sync_timers(&mut timers, &[entries[0].clone(), entries[2].clone()]); + + assert_eq!( + timers.iter().map(|t| t.id.0).collect::>(), + vec![1, 3], + "removing the middle toast must keep the surviving timers" + ); + assert!(timers.iter().all(|t| t.started == old)); +} + +#[test] +fn test_replace_toast_content_resets_its_timer() { + let old = old_timer(7, "A", "old body"); + let started_before = old.started; + let mut timers = vec![old]; + sync_timers(&mut timers, &[entry(7, "A", "new body")]); + assert_eq!(timers.len(), 1, "replacing content must not add a toast"); + assert!( + timers[0].started > started_before, + "replacing content must restart the countdown" + ); +} + #[test] fn test_toast_status_constructors() { assert_eq!(Toast::success("t", "b").status, Status::Success); diff --git a/hexedit/src/main.rs b/hexedit/src/main.rs index 85eafcba..3f727f22 100644 --- a/hexedit/src/main.rs +++ b/hexedit/src/main.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use iced::widget::{button, column, container, row, text}; use iced::{Element, Fill, Font, Task, Theme}; -use hexedit::ui::theme::DARK_THEME; +use hexedit::ui::theme::ThemeVariant; use hexedit::{ AppMessage, EncodingEntry, HexEditorApp, HexEditorConfig, HexEditorDocument, HexEditorMessage, HexEditorState, SaveOutcome, SaveRequest, WriteMode, app_update, app_view, standalone_config, @@ -54,22 +54,32 @@ fn load_settings() -> PersistedSettings { } } +/// Iced palette seed for the given hex-editor theme variant. +fn seed_for_variant(variant: ThemeVariant) -> iced::theme::palette::Seed { + let palette = variant.theme(); + iced::theme::palette::Seed { + background: palette.iced_bg, + text: palette.iced_text, + primary: palette.iced_primary, + success: palette.iced_success, + danger: palette.iced_danger, + warning: palette.iced_warning, + } +} + +/// Theme variant of the active document, or Dark when no file is open. +fn active_variant(app: &App) -> ThemeVariant { + app.app + .active_tab + .and_then(|idx| app.app.documents.get(idx)) + .map(|doc| doc.state.theme_variant) + .unwrap_or_default() +} + fn main() -> iced::Result { iced::application(App::new, App::update, App::view) .title("HexEdit") - .theme(|_: &App| { - Theme::custom( - "HexEdit", - iced::theme::palette::Seed { - background: DARK_THEME.iced_bg, - text: DARK_THEME.iced_text, - primary: DARK_THEME.iced_primary, - success: DARK_THEME.iced_success, - danger: DARK_THEME.iced_danger, - warning: DARK_THEME.iced_warning, - }, - ) - }) + .theme(|app: &App| Theme::custom("HexEdit", seed_for_variant(active_variant(app)))) .window_size((1100.0, 800.0)) .run() } @@ -276,3 +286,36 @@ impl App { .into() } } + +#[cfg(test)] +mod tests { + use super::*; + use hexedit::ui::theme::{DARK_THEME, LIGHT_THEME}; + + #[test] + fn test_seed_for_variant_uses_that_palette() { + let dark = seed_for_variant(ThemeVariant::Dark); + let light = seed_for_variant(ThemeVariant::Light); + assert_eq!(dark.background, DARK_THEME.iced_bg); + assert_eq!(dark.text, DARK_THEME.iced_text); + assert_eq!(light.background, LIGHT_THEME.iced_bg); + assert_eq!(light.text, LIGHT_THEME.iced_text); + assert_ne!(dark.background, light.background); + } + + #[test] + fn test_active_variant_defaults_to_dark_without_documents() { + let mut app = App { + app: HexEditorApp::new(), + status: String::new(), + }; + assert_eq!(active_variant(&app), ThemeVariant::Dark); + app.app.documents.push(HexEditorDocument { + state: HexEditorState::from_bytes("Invented.bin", vec![], None, None), + pinned: false, + }); + app.app.active_tab = Some(0); + app.app.documents[0].state.theme_variant = ThemeVariant::Light; + assert_eq!(active_variant(&app), ThemeVariant::Light); + } +} diff --git a/hexedit/src/tests/diff.rs b/hexedit/src/tests/diff.rs index a2d73d69..c1c3b9e4 100644 --- a/hexedit/src/tests/diff.rs +++ b/hexedit/src/tests/diff.rs @@ -130,3 +130,39 @@ fn test_diff_drag_on_comparison_side_publishes_side() { "drag on the comparison side must publish DiffExtendTo with is_baseline=false, got {messages:?}" ); } + +#[test] +fn test_diff_text_colors_contrast_in_both_themes() { + use crate::coloring::contrast_ratio; + use crate::ui::theme::{DARK_THEME, LIGHT_THEME}; + use crate::ui::view::diff::diff_text_color; + + for theme in [&DARK_THEME, &LIGHT_THEME] { + let bg = theme.diff_bg; + let (dr, dg, db) = (bg.r, bg.g, bg.b); + let baseline_bg = iced::Color::from_rgb( + (dr + 0.25).min(1.0), + (dg * 0.4).max(0.0), + (db * 0.3).max(0.0), + ); + let comparison_bg = iced::Color::from_rgb( + (dr * 0.4).max(0.0), + (dg + 0.25).min(1.0), + (db * 0.4).max(0.0), + ); + for (cell_bg, baseline) in [(baseline_bg, true), (comparison_bg, false)] { + let fg = diff_text_color(theme, cell_bg, baseline); + let cr = contrast_ratio(&fg, &cell_bg); + assert!( + cr >= 4.0, + "{} theme {} text contrast {cr:.2} is too low", + if std::ptr::eq(theme, &DARK_THEME) { + "dark" + } else { + "light" + }, + if baseline { "baseline" } else { "comparison" } + ); + } + } +} diff --git a/hexedit/src/tests/header.rs b/hexedit/src/tests/header.rs index 139628d4..40ac933b 100644 --- a/hexedit/src/tests/header.rs +++ b/hexedit/src/tests/header.rs @@ -136,3 +136,19 @@ fn test_reset_settings_syncs_bpr_input() { "bpr_input should reset alongside bytes_per_row" ); } + +#[test] +fn test_column_header_labels_are_two_digit_hex_at_32_columns() { + use crate::ui::view::matrix::column_label; + let labels: Vec = (0..32).map(|c| column_label(c, false)).collect(); + assert_eq!(labels[0], "00"); + assert_eq!(labels[15], "0F"); + assert_eq!(labels[16], "10"); + assert_eq!(labels[31], "1F"); + assert!( + labels.iter().all(|l| l.len() == 2 && l != "?"), + "every 32-column label must be a two-digit hex value, got {labels:?}" + ); + assert_eq!(column_label(63, false), "3F"); + assert_eq!(column_label(10, true), "10"); +} diff --git a/hexedit/src/ui/coloring.rs b/hexedit/src/ui/coloring.rs index 893a8556..db286aad 100644 --- a/hexedit/src/ui/coloring.rs +++ b/hexedit/src/ui/coloring.rs @@ -13,7 +13,7 @@ use std::ops::RangeInclusive; use iced::Color; -use crate::ui::theme::DARK_THEME; +use crate::ui::theme::{DARK_THEME, HexEditorTheme}; use crate::selection::Selection; @@ -309,20 +309,19 @@ pub fn scheme_color(scheme: ColorScheme, b: u8) -> Color { } /// Convenience wrapper: apply `SchemeProvider` + `DimNullsProvider` in the -/// correct order and return the `(fg, bg)` pair. Uses [`DEFAULT_NULL_DIM`] -/// as the dim-null colour. -/// -/// This is the single source of truth for the provider chain so the matrix -/// widget and the settings-modal palette preview stay in sync. +/// correct order and return the `(fg, bg)` pair. Both the scheme palette and +/// the dim-null colour come from `theme`, so the matrix, minimap, diff view +/// and settings preview all agree with the active palette. pub fn default_byte_colors( + theme: &HexEditorTheme, scheme: ColorScheme, byte: u8, dim_nulls: bool, ) -> (Option, Option) { - let scheme_prov = SchemeProvider { scheme }; + let scheme_prov = SchemeProvider { scheme, theme }; let dim_prov = DimNullsProvider { enabled: dim_nulls, - null_color: DEFAULT_NULL_DIM, + null_color: theme.default_null_dim, }; fold_color( [ @@ -337,14 +336,17 @@ pub fn default_byte_colors( // ── Providers for the CellColorProvider chain ───────────────────────────── /// Applies a [`ColorScheme`] as a foreground provider in the chain. -/// Always returns `Some(fg)` and never touches the background. -pub struct SchemeProvider { +/// Always returns `Some(fg)` and never touches the background. The palette is +/// taken from the active theme so it stays legible on both light and dark +/// backgrounds. +pub struct SchemeProvider<'a> { pub scheme: ColorScheme, + pub theme: &'a HexEditorTheme, } -impl CellColorProvider for SchemeProvider { +impl CellColorProvider for SchemeProvider<'_> { fn color(&self, _addr: u64, byte: u8) -> (Option, Option) { - (Some(scheme_color(self.scheme, byte)), None) + (Some(self.theme.scheme_color(self.scheme, byte)), None) } } @@ -512,6 +514,7 @@ mod tests { fn scheme_provider_monochrome_constant() { let p = SchemeProvider { scheme: ColorScheme::Monochrome, + theme: &DARK_THEME, }; // All bytes get the same colour. let c0 = p.color(0, 0x00).0.unwrap(); @@ -527,6 +530,7 @@ mod tests { fn scheme_provider_nybble_delegates_to_nybble_color() { let p = SchemeProvider { scheme: ColorScheme::Nybble, + theme: &DARK_THEME, }; for b in [0x00, 0x01, 0x0F, 0x10, 0x7F, 0x80, 0xFF] { let expected = nybble_color(b); @@ -556,6 +560,7 @@ mod tests { fn scheme_provider_categories_delegates() { let p = SchemeProvider { scheme: ColorScheme::Categories, + theme: &DARK_THEME, }; // Spot-check each category boundary. let checkpoints = [0x00, 0x01, 0x09, 0x0D, 0x0E, 0x20, 0x7E, 0x7F, 0x80, 0xFF]; @@ -577,6 +582,7 @@ mod tests { fn scheme_provider_rainbow_delegates() { let p = SchemeProvider { scheme: ColorScheme::Rainbow, + theme: &DARK_THEME, }; for b in [0x00, 0x01, 0x40, 0x80, 0xBF, 0xCC, 0xFF] { let expected = rainbow_color(b); @@ -893,6 +899,7 @@ mod tests { fn scheme_provider_heatmap_delegates() { let p = SchemeProvider { scheme: ColorScheme::Heatmap, + theme: &DARK_THEME, }; for b in [0x00, 0x01, 0x40, 0x80, 0xBF, 0xFF] { let expected = heatmap_color(b); @@ -980,7 +987,7 @@ mod tests { #[test] fn default_byte_colors_provider_chain() { // With dim_nulls=true, a null byte should get DEFAULT_NULL_DIM. - let (fg, bg) = default_byte_colors(ColorScheme::Monochrome, 0x00, true); + let (fg, bg) = default_byte_colors(&DARK_THEME, ColorScheme::Monochrome, 0x00, true); assert!(bg.is_none(), "should not touch background"); let fg = fg.unwrap(); assert!( @@ -991,7 +998,7 @@ mod tests { ); // With dim_nulls=false, scheme passes through. - let (fg2, _) = default_byte_colors(ColorScheme::Monochrome, 0x00, false); + let (fg2, _) = default_byte_colors(&DARK_THEME, ColorScheme::Monochrome, 0x00, false); let expected = scheme_color(ColorScheme::Monochrome, 0x00); assert!( (fg2.unwrap().r - expected.r).abs() < 0.001, @@ -999,9 +1006,41 @@ mod tests { ); } + #[test] + fn default_byte_colors_follow_active_theme() { + use crate::ui::theme::LIGHT_THEME; + for scheme in ColorScheme::ALL { + let mut any_difference = false; + for b in [0x01, 0x42, 0xFF] { + let (dark, _) = default_byte_colors(&DARK_THEME, scheme, b, false); + let (light, _) = default_byte_colors(&LIGHT_THEME, scheme, b, false); + let dark = dark.unwrap(); + let light = light.unwrap(); + if (dark.r - light.r).abs() > 0.01 + || (dark.g - light.g).abs() > 0.01 + || (dark.b - light.b).abs() > 0.01 + { + any_difference = true; + } + assert!( + contrast_ratio(&light, &LIGHT_THEME.matrix_bg) >= 2.0, + "light byte {b:#04X} under {scheme} lacks contrast" + ); + assert!( + contrast_ratio(&dark, &DARK_THEME.matrix_bg) >= 2.0, + "dark byte {b:#04X} under {scheme} lacks contrast" + ); + } + assert!( + any_difference, + "scheme {scheme} must produce different colours between themes" + ); + } + } + #[test] fn default_byte_colors_non_null_not_dimmed() { - let (fg, _) = default_byte_colors(ColorScheme::Nybble, 0x42, true); + let (fg, _) = default_byte_colors(&DARK_THEME, ColorScheme::Nybble, 0x42, true); let expected = scheme_color(ColorScheme::Nybble, 0x42); let fg = fg.unwrap(); assert!( diff --git a/hexedit/src/ui/view/diff/draw.rs b/hexedit/src/ui/view/diff/draw.rs index 38b3aed0..3ae129ba 100644 --- a/hexedit/src/ui/view/diff/draw.rs +++ b/hexedit/src/ui/view/diff/draw.rs @@ -27,6 +27,34 @@ use super::layout::{ use super::state::State; use super::{DiffView, DisplayRow}; +/// Pick a readable text colour for a tinted diff cell. +/// +/// The theme's diff foreground supplies the hue (shifted toward red for the +/// baseline side and toward green for the comparison side); its brightness is +/// then set from the cell background luminance so both light and dark themes +/// keep legible text. +pub(crate) fn diff_text_color(theme: &HexEditorTheme, background: Color, baseline: bool) -> Color { + let fg = theme.diff_fg; + let tinted = if baseline { + Color::from_rgb(fg.r, fg.g * 0.4, fg.b * 0.4) + } else { + Color::from_rgb(fg.r * 0.4, fg.g, fg.b * 0.4) + }; + let bg_luma = crate::coloring::relative_luminance(&background); + // Blend most of the way toward black on bright cells and toward white on + // dark cells; the retained quarter keeps the red/green tint visible. + let (tr, tg, tb) = if bg_luma > 0.18 { + (0.0, 0.0, 0.0) + } else { + (1.0, 1.0, 1.0) + }; + Color::from_rgb( + tinted.r * 0.25 + tr * 0.75, + tinted.g * 0.25 + tg * 0.75, + tinted.b * 0.25 + tb * 0.75, + ) +} + /// Render the entire diff view into the given viewport. pub fn draw_diff_view<'a, Message>( widget: &DiffView<'a, Message>, @@ -118,8 +146,8 @@ pub fn draw_diff_view<'a, Message>( (dg + 0.25).min(1.0), (db * 0.4).max(0.0), ); - let diff_text_baseline = Color::from_rgb(1.0, 0.7, 0.7); - let diff_text_comparison = Color::from_rgb(0.7, 1.0, 0.7); + let diff_text_baseline = diff_text_color(widget.theme, diff_bg_baseline, true); + let diff_text_comparison = diff_text_color(widget.theme, diff_bg_comparison, false); let sel_range = widget.selection.range(); let cursor_addr = widget.selection.cursor; @@ -356,6 +384,7 @@ pub fn draw_diff_view<'a, Message>( h_px, color_scheme: widget.color_scheme, dim_nulls: widget.dim_nulls, + theme: widget.theme, pattern_hash: minimap::pattern_hash(widget.patterns), dirty_fingerprint: minimap::set_fingerprint(&empty_dirty), diff_fingerprint: minimap::set_fingerprint(widget.diff), @@ -536,7 +565,8 @@ fn render_byte_cell( }; // Foreground via provider chain. - let (default_fg, _) = default_byte_colors(widget.color_scheme, byte, widget.dim_nulls); + let (default_fg, _) = + default_byte_colors(widget.theme, widget.color_scheme, byte, widget.dim_nulls); let default_fg = default_fg.unwrap_or(hex_color); let text_color = if in_sel { diff --git a/hexedit/src/ui/view/diff/mod.rs b/hexedit/src/ui/view/diff/mod.rs index d684ff4a..d6eb0ad4 100644 --- a/hexedit/src/ui/view/diff/mod.rs +++ b/hexedit/src/ui/view/diff/mod.rs @@ -15,6 +15,8 @@ //! normal hex matrix pane instead. mod draw; +#[cfg(test)] +pub(crate) use draw::diff_text_color; mod event; pub(crate) mod layout; mod state; diff --git a/hexedit/src/ui/view/matrix/draw.rs b/hexedit/src/ui/view/matrix/draw.rs index 96726ba9..08f2a6f2 100644 --- a/hexedit/src/ui/view/matrix/draw.rs +++ b/hexedit/src/ui/view/matrix/draw.rs @@ -32,6 +32,16 @@ use super::state::State; type Paragraph = GraphicsParagraph; +/// Label for a column header: a decimal ordinal or a two-digit uppercase hex +/// index, which stays meaningful for 32- and 64-byte rows. +pub(crate) fn column_label(col: usize, show_decimal: bool) -> String { + if show_decimal { + format!("{col}") + } else { + format!("{col:02X}") + } +} + // ── Top-level draw entry-point ──────────────────────────────────────── /// Render the hex matrix into the given viewport. @@ -195,20 +205,11 @@ pub fn draw_matrix<'a, Message>( Background::Color(header_bg), ); - // Hex column numbers (e.g. "0 1 2 3 4 5 6 7 8 9 A B C D E F"). + // Hex column numbers ("00".."1F" at 32 bytes per row, "00".."3F" at 64). for col in 0..widget.bytes_per_row as usize { let group = col / 8; let cell_x = hex_start_x + col as f32 * HEX_CELL_WIDTH + group as f32 * GROUP_GAP; - let label = if widget.show_decimal { - format!("{}", col) - } else { - let c = match col { - 0..=9 => (b'0' + col as u8) as char, - 10..=15 => (b'A' + col as u8 - 10) as char, - _ => '?', - }; - c.to_string() - }; + let label = column_label(col, widget.show_decimal); let label_w = label.len() as f32 * 9.0; let text_x = cell_x + (HEX_CELL_WIDTH - label_w) / 2.0; draw_glyph_string( @@ -343,7 +344,8 @@ pub fn draw_matrix<'a, Message>( }; // Default foreground via the shared provider chain. - let (default_fg, _) = default_byte_colors(widget.color_scheme, b, widget.dim_nulls); + let (default_fg, _) = + default_byte_colors(theme, widget.color_scheme, b, widget.dim_nulls); let default_fg = default_fg.unwrap_or(hex_color); let text_color = if is_editing { @@ -573,6 +575,7 @@ pub fn draw_matrix<'a, Message>( h_px, color_scheme: widget.color_scheme, dim_nulls: widget.dim_nulls, + theme: widget.theme, pattern_hash: minimap::pattern_hash(widget.patterns), dirty_fingerprint: minimap::set_fingerprint(widget.dirty), diff_fingerprint: minimap::set_fingerprint(widget.vanilla_diff), diff --git a/hexedit/src/ui/view/matrix/mod.rs b/hexedit/src/ui/view/matrix/mod.rs index 948d83a3..f37daad0 100644 --- a/hexedit/src/ui/view/matrix/mod.rs +++ b/hexedit/src/ui/view/matrix/mod.rs @@ -19,6 +19,8 @@ mod event; mod layout; mod state; +#[cfg(test)] +pub(crate) use draw::column_label; pub use draw::{first_hex_char, first_printable_char}; pub use state::{EditView, State}; diff --git a/hexedit/src/ui/view/minimap.rs b/hexedit/src/ui/view/minimap.rs index e14a696d..ff885284 100644 --- a/hexedit/src/ui/view/minimap.rs +++ b/hexedit/src/ui/view/minimap.rs @@ -235,7 +235,7 @@ fn block_mean_variance_color(block_start: u64, block_end: u64, ctx: &BlockContex if n == 0.0 { // Block outside the mapped range → fall back to dim default. - let (fg, _) = default_byte_colors(ctx.color_scheme, 0, ctx.dim_nulls); + let (fg, _) = default_byte_colors(ctx.theme, ctx.color_scheme, 0, ctx.dim_nulls); let c = fg.unwrap_or(ctx.theme.monochrome_fg); return Color::from_rgb( c.r * 0.55 * MINIMAP_MIN_BRIGHTNESS, @@ -258,7 +258,7 @@ fn block_mean_variance_color(block_start: u64, block_end: u64, ctx: &BlockContex let brightness = MINIMAP_MIN_BRIGHTNESS + norm * MINIMAP_VARIANCE_BOOST; let mean_byte = mean_f.round() as u8; - let (fg, _) = default_byte_colors(ctx.color_scheme, mean_byte, ctx.dim_nulls); + let (fg, _) = default_byte_colors(ctx.theme, ctx.color_scheme, mean_byte, ctx.dim_nulls); let c = fg.unwrap_or(ctx.theme.monochrome_fg); Color::from_rgb( c.r * 0.55 * brightness, @@ -442,6 +442,9 @@ pub(crate) struct MinimapCache { pub color_scheme: ColorScheme, /// Dim-nulls setting when cached. pub dim_nulls: bool, + /// Theme identity when cached: the byte and block palettes differ between + /// themes, so a theme change must force a recompute. + pub theme: &'static HexEditorTheme, /// Hash of pattern_by_addr contents (*not* the full map — just a /// checksum so we can cheaply detect changes). pub pattern_hash: u64, @@ -492,6 +495,7 @@ pub(crate) fn minimap_cache_valid(cache: &MinimapCache, h_px: u32, ctx: &BlockCo && cache.h_px == h_px && cache.color_scheme == ctx.color_scheme && cache.dim_nulls == ctx.dim_nulls + && *cache.theme == *ctx.theme && cache.pattern_hash == pattern_hash(ctx.pattern_by_addr) && cache.dirty_fingerprint == set_fingerprint(ctx.dirty) && cache.diff_fingerprint == set_fingerprint(ctx.vanilla_diff) @@ -1101,6 +1105,7 @@ mod tests { h_px: 10, color_scheme: ColorScheme::Monochrome, dim_nulls: false, + theme: &DARK_THEME, pattern_hash: pattern_hash(&patterns), dirty_fingerprint: set_fingerprint(&dirty), diff_fingerprint: set_fingerprint(&diff), @@ -1130,6 +1135,7 @@ mod tests { h_px: 10, color_scheme: ColorScheme::Monochrome, dim_nulls: false, + theme: &DARK_THEME, pattern_hash: 0, dirty_fingerprint: set_fingerprint(&empty), diff_fingerprint: set_fingerprint(&empty), @@ -1159,6 +1165,7 @@ mod tests { h_px: 10, color_scheme: ColorScheme::Monochrome, dim_nulls: false, + theme: &DARK_THEME, pattern_hash: 0, dirty_fingerprint: set_fingerprint(&empty), diff_fingerprint: set_fingerprint(&empty), @@ -1178,6 +1185,37 @@ mod tests { assert!(!minimap_cache_valid(&cache, 10, &ctx)); } + #[test] + fn minimap_cache_valid_detects_theme_change() { + use crate::ui::theme::LIGHT_THEME; + let empty: BTreeSet = BTreeSet::new(); + let empty_ptr = (&[] as &[u8]).as_ptr() as usize; + let cache = MinimapCache { + columns: [vec![Color::WHITE], vec![], vec![], vec![]], + total_len: 100, + h_px: 10, + color_scheme: ColorScheme::Monochrome, + dim_nulls: false, + theme: &DARK_THEME, + pattern_hash: 0, + dirty_fingerprint: set_fingerprint(&empty), + diff_fingerprint: set_fingerprint(&empty), + content_ptr: empty_ptr, + }; + let ctx = BlockContext { + bytes: &[], + total_len: 100, + pattern_by_addr: &BTreeMap::new(), + alternate_patterns: &BTreeSet::new(), + dirty: &empty, + vanilla_diff: &empty, + color_scheme: ColorScheme::Monochrome, + dim_nulls: false, + theme: &LIGHT_THEME, + }; + assert!(!minimap_cache_valid(&cache, 10, &ctx)); + } + #[test] fn minimap_cache_valid_detects_dirty_fingerprint_change() { let empty: BTreeSet = BTreeSet::new(); @@ -1188,6 +1226,7 @@ mod tests { h_px: 10, color_scheme: ColorScheme::Monochrome, dim_nulls: false, + theme: &DARK_THEME, pattern_hash: 0, dirty_fingerprint: set_fingerprint(&empty), diff_fingerprint: set_fingerprint(&empty), @@ -1237,7 +1276,7 @@ mod tests { assert_eq!(cols[3].len(), 3); let brightness = 0.30_f32; - let (fg0, _) = default_byte_colors(ColorScheme::Monochrome, 0x00, false); + let (fg0, _) = default_byte_colors(&DARK_THEME, ColorScheme::Monochrome, 0x00, false); let c0 = fg0.unwrap(); let dim = Color::from_rgb( c0.r * 0.55 * brightness, @@ -1245,7 +1284,7 @@ mod tests { c0.b * 0.55 * brightness, ); - let (fg1, _) = default_byte_colors(ColorScheme::Monochrome, 0xFF, false); + let (fg1, _) = default_byte_colors(&DARK_THEME, ColorScheme::Monochrome, 0xFF, false); let c1 = fg1.unwrap(); let bright = Color::from_rgb( c1.r * 0.55 * brightness, diff --git a/hexedit/src/ui/view/settings_modal.rs b/hexedit/src/ui/view/settings_modal.rs index 28bed3b9..7f3046d4 100644 --- a/hexedit/src/ui/view/settings_modal.rs +++ b/hexedit/src/ui/view/settings_modal.rs @@ -63,7 +63,8 @@ pub fn view(state: &HexEditorState) -> Element<'_, HexEditorMessage> { let palette: Vec> = (0..=15) .map(|i| { let b = (i * 17) as u8; - let (fg_opt, _) = default_byte_colors(state.color_scheme, b, state.dim_nulls); + let (fg_opt, _) = + default_byte_colors(state.theme, state.color_scheme, b, state.dim_nulls); let fg = fg_opt.unwrap_or(state.theme.hex_fg); container(text(" ").size(10)) .style(move |_: &_| container::Style { diff --git a/src/map/reader.rs b/src/map/reader.rs index 754b0cba..39599197 100644 --- a/src/map/reader.rs +++ b/src/map/reader.rs @@ -72,7 +72,28 @@ pub fn read_tiled_object_refs(reader: &mut BufReader) -> Result) -> Result> { let size = reader.read_i32::()?; - let mut table = Vec::with_capacity(size as usize); + let size = usize::try_from(size).map_err(|_| { + std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("Invalid overlay-id table size {size}"), + ) + })?; + + // Every entry is two bytes. Refuse a count that cannot fit in the bytes + // left in the file before reserving, so a corrupt size cannot trigger a + // huge allocation. + let file_len = reader.get_ref().metadata()?.len(); + let pos = reader.stream_position()?; + let remaining = file_len.saturating_sub(pos); + let max_entries = usize::try_from(remaining / 2).unwrap_or(usize::MAX); + if size > max_entries { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("Overlay-id table size {size} exceeds the {max_entries} entries left in file"), + )); + } + + let mut table = Vec::with_capacity(size); for _ in 0..size { table.push(reader.read_u16::()?); } @@ -87,8 +108,28 @@ pub fn read_overlay_id_table(reader: &mut BufReader) -> Result> { /// (stamps are always 6 or 9; anything else is a parse error). pub fn sprite_block(reader: &mut BufReader) -> Result<(Vec, Vec)> { let sprite_count = reader.read_i32::()?; + let sprite_count = usize::try_from(sprite_count).map_err(|_| { + std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("Invalid sprite count {sprite_count}"), + ) + })?; + + // Each sprite reads at least one four-byte image stamp. Cap the capacity + // by the bytes actually left in the file before reserving. + let file_len = reader.get_ref().metadata()?.len(); + let pos = reader.stream_position()?; + let remaining = file_len.saturating_sub(pos); + let max_sprites = usize::try_from(remaining / 4).unwrap_or(usize::MAX); + if sprite_count > max_sprites { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("Sprite count {sprite_count} exceeds the {max_sprites} sprites left in file"), + )); + } + let mut sprites = vec![]; - let mut stamps = Vec::with_capacity(sprite_count.unsigned_abs() as usize); + let mut stamps = Vec::with_capacity(sprite_count); for _ in 0..sprite_count { let image_stamp = reader.read_i32::()?; let image_offset: i32 = if image_stamp == 6 { @@ -445,6 +486,54 @@ pub fn read_roof_tiles( #[cfg(test)] mod tests { + use super::*; + + fn reader_from_bytes(name: &str, bytes: &[u8]) -> BufReader { + let path = std::env::temp_dir().join(format!("dispel-{name}-{}.bin", std::process::id())); + std::fs::write(&path, bytes).expect("write crafted map block"); + BufReader::new(File::open(&path).expect("open crafted map block")) + } + + #[test] + fn test_overlay_table_rejects_negative_size() { + let mut reader = reader_from_bytes("overlay-negative", &(-5_i32).to_le_bytes()); + let err = super::read_overlay_id_table(&mut reader).expect_err("negative size must fail"); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); + } + + #[test] + fn test_overlay_table_rejects_size_larger_than_file() { + // Size claims a million u16 entries but the file only holds the size. + let mut reader = reader_from_bytes("overlay-oversized", &1_000_000_i32.to_le_bytes()); + let err = super::read_overlay_id_table(&mut reader).expect_err("oversized size must fail"); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); + } + + #[test] + fn test_sprite_block_rejects_negative_count() { + let mut reader = reader_from_bytes("sprite-count-negative", &(-1_i32).to_le_bytes()); + let err = super::sprite_block(&mut reader).expect_err("negative count must fail"); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); + } + + #[test] + fn test_sprite_block_rejects_count_larger_than_file() { + let mut reader = reader_from_bytes("sprite-count-oversized", &1_000_000_i32.to_le_bytes()); + let err = super::sprite_block(&mut reader).expect_err("oversized count must fail"); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidData); + } + + #[test] + fn test_overlay_table_reads_valid_entries() { + let mut bytes = 2_i32.to_le_bytes().to_vec(); + bytes.extend_from_slice(&7_u16.to_le_bytes()); + bytes.extend_from_slice(&9_u16.to_le_bytes()); + let mut reader = reader_from_bytes("overlay-valid", &bytes); + assert_eq!( + super::read_overlay_id_table(&mut reader).unwrap(), + vec![7, 9] + ); + } #[test] fn test_tile_access_round_trip_synthetic_word() { diff --git a/src/snf.rs b/src/snf.rs index 7cdb6628..3febb923 100644 --- a/src/snf.rs +++ b/src/snf.rs @@ -225,8 +225,11 @@ impl SnfFile { let wav_header_size = 44usize; let mut out = Vec::with_capacity(wav_header_size + self.pcm_data.len()); + // The RIFF/data sizes must describe the PCM bytes actually written, + // even if a divergent header `data_size` was parsed from the source. + let pcm_len = u32::try_from(self.pcm_data.len()).unwrap_or(u32::MAX); // RIFF chunk: size = total file size - 8 ("RIFF" + size field) - let riff_size = (36u32).saturating_add(self.data_size.max(0) as u32); + let riff_size = (36u32).saturating_add(pcm_len); out.extend_from_slice(b"RIFF"); out.extend_from_slice(&riff_size.to_le_bytes()); out.extend_from_slice(b"WAVE"); @@ -241,7 +244,7 @@ impl SnfFile { out.extend_from_slice(&self.bits_per_sample.to_le_bytes()); // data sub-chunk out.extend_from_slice(b"data"); - out.extend_from_slice(&(self.data_size.max(0) as u32).to_le_bytes()); + out.extend_from_slice(&pcm_len.to_le_bytes()); out.extend_from_slice(&self.pcm_data); out } @@ -373,6 +376,30 @@ pub fn import_wav(wav_path: &Path, snf_path: &Path) -> Result<()> { mod tests { use super::*; + #[test] + fn wav_sizes_follow_pcm_length_not_header_data_size() { + let file = SnfFile { + pcmaudio_format: 1, + number_of_channels: 1, + sample_rate: 44100, + byte_rate: 88200, + block_align: 2, + bits_per_sample: 16, + data_size: 9999, + pcm_data: vec![0u8; 6], + }; + let wav = file.to_wav_bytes(); + let riff_size = u32::from_le_bytes([wav[4], wav[5], wav[6], wav[7]]); + let data_size = u32::from_le_bytes([wav[40], wav[41], wav[42], wav[43]]); + assert_eq!(data_size, 6, "data chunk must describe written PCM bytes"); + assert_eq!( + riff_size, + 36 + 6, + "RIFF size must describe written PCM bytes" + ); + assert_eq!(wav.len(), 44 + 6); + } + #[test] fn wav_round_trip() { let original = SnfFile { diff --git a/src/sprite.rs b/src/sprite.rs index 81c4e483..5ba33337 100644 --- a/src/sprite.rs +++ b/src/sprite.rs @@ -215,8 +215,9 @@ pub fn get_sequence_info(reader: &mut BufReader) -> Result