From 13f501eb68c384a5bfd76241060aa5ae14fd03e4 Mon Sep 17 00:00:00 2001
From: dimspell <141545384+dimspell@users.noreply.github.com>
Date: Wed, 25 Nov 2026 12:28:01 +0100
Subject: [PATCH 01/72] =?UTF-8?q?=F0=9F=9A=80=20Version=20v0.9.5?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
Cargo.lock | 12 ++++++------
Cargo.toml | 2 +-
dispel-encodings/Cargo.toml | 2 +-
dispel-gui/Cargo.toml | 2 +-
dispel-macros/Cargo.toml | 2 +-
gui-widgets/Cargo.toml | 2 +-
hexedit/Cargo.toml | 2 +-
7 files changed, 12 insertions(+), 12 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index e973f40f..0cfd17c4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1316,7 +1316,7 @@ dependencies = [
[[package]]
name = "dispel-encodings"
-version = "0.9.4"
+version = "0.9.5"
dependencies = [
"encoding_rs",
"serde",
@@ -1324,7 +1324,7 @@ dependencies = [
[[package]]
name = "dispel-extractor"
-version = "0.9.4"
+version = "0.9.5"
dependencies = [
"byteorder",
"clap",
@@ -1346,7 +1346,7 @@ dependencies = [
[[package]]
name = "dispel-gui"
-version = "0.9.4"
+version = "0.9.5"
dependencies = [
"bincode 1.3.3",
"chrono",
@@ -1382,7 +1382,7 @@ dependencies = [
[[package]]
name = "dispel-macros"
-version = "0.9.4"
+version = "0.9.5"
dependencies = [
"dispel-encodings",
"proc-macro2",
@@ -2012,7 +2012,7 @@ dependencies = [
[[package]]
name = "gui-widgets"
-version = "0.9.4"
+version = "0.9.5"
dependencies = [
"iced",
"iced_renderer",
@@ -2122,7 +2122,7 @@ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hexedit"
-version = "0.9.4"
+version = "0.9.5"
dependencies = [
"dirs",
"encoding_rs",
diff --git a/Cargo.toml b/Cargo.toml
index d94bb6ea..78bf6107 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -24,7 +24,7 @@ path = "src/lib.rs"
[package]
name = "dispel-extractor"
-version = "0.9.4"
+version = "0.9.5"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
diff --git a/dispel-encodings/Cargo.toml b/dispel-encodings/Cargo.toml
index 5df00030..543917aa 100644
--- a/dispel-encodings/Cargo.toml
+++ b/dispel-encodings/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "dispel-encodings"
-version = "0.9.4"
+version = "0.9.5"
edition = "2024"
[dependencies]
diff --git a/dispel-gui/Cargo.toml b/dispel-gui/Cargo.toml
index 3d631ae4..56cbbba8 100644
--- a/dispel-gui/Cargo.toml
+++ b/dispel-gui/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "dispel-gui"
-version = "0.9.4"
+version = "0.9.5"
edition = "2024"
[dependencies]
diff --git a/dispel-macros/Cargo.toml b/dispel-macros/Cargo.toml
index 049b4a52..1f523348 100644
--- a/dispel-macros/Cargo.toml
+++ b/dispel-macros/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "dispel-macros"
-version = "0.9.4"
+version = "0.9.5"
edition = "2024"
[lib]
diff --git a/gui-widgets/Cargo.toml b/gui-widgets/Cargo.toml
index 6d8febcb..c29700fc 100644
--- a/gui-widgets/Cargo.toml
+++ b/gui-widgets/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "gui-widgets"
-version = "0.9.4"
+version = "0.9.5"
edition = "2024"
[features]
diff --git a/hexedit/Cargo.toml b/hexedit/Cargo.toml
index f90a71a6..5db9ef4b 100644
--- a/hexedit/Cargo.toml
+++ b/hexedit/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "hexedit"
-version = "0.9.4"
+version = "0.9.5"
edition = "2024"
[[bin]]
From 459f37ba97a15e53e013b70a644bf28e80f9b48c Mon Sep 17 00:00:00 2001
From: dimspell <141545384+dimspell@users.noreply.github.com>
Date: Wed, 25 Nov 2026 13:29:23 +0100
Subject: [PATCH 02/72] docs: rewrite seven documents in plain English with
observable facts
---
README.md | 87 +++++-------
docs/database_and_references.md | 98 +++++++-------
docs/file_formats.md | 211 ++++++++++++++----------------
docs/iced-fork-config.md | 92 ++++---------
docs/overview.md | 67 +++++-----
docs/rendering.md | 53 ++++----
gui-widgets/src/sweeten/README.md | 2 +-
7 files changed, 268 insertions(+), 342 deletions(-)
diff --git a/README.md b/README.md
index 401362a8..b6992d5c 100644
--- a/README.md
+++ b/README.md
@@ -1,14 +1,18 @@
# DISPEL® Game File Extractor
-A modding toolkit for the **DISPEL®** RPG game. Reads and writes game files in native binary, INI, and DB formats. Includes a CLI, a desktop GUI with 46 editor types, a hex editor, and a full mod packaging pipeline. All edits are persisted directly to game files — no intermediate database.
+This toolkit reads and writes DISPEL® game files in binary, INI and DB formats. It includes a CLI, a desktop GUI with 46 editor types, a hex editor and a mod packaging pipeline. The tools write each edit into the game file. They do not keep a separate database.
-**Not affiliated with, endorsed by, or sponsored by the trademark owner.**
+## Scope and notice
----
+This project reads and writes data files for DISPEL®. It ships no game content. You provide the files you edit.
+
+DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark owner.
+
+The source code is licensed under the MIT License (LICENSE). Game content is not covered by this license.
## What's in this repository
-This is a 6-crate Cargo workspace (Rust 2024, version `0.9.3`):
+This Cargo workspace has six crates. The workspace uses Rust 2024 and version `0.9.3`.
| Crate | Type | Role |
| ------------------------- | ---------- | --------------------------------------------------------------- |
@@ -23,18 +27,16 @@ This is a 6-crate Cargo workspace (Rust 2024, version `0.9.3`):
| Directory | Contents |
| --------------------- | ------------------------------------------------------------------- |
-| `src/references/` | 30+ parsers for `.db`, `.ini`, `.ref` game data files |
+| `src/references/` | 51 source files with parsers for `.db`, `.ini` and `.ref` files |
| `src/map/` | `.map` parser + isometric tile/sprite/event renderer |
| `src/sprite.rs` | `.spr` sprite and animation parser (RGB 565) |
-| `src/snf.rs` | `.snf` audio parser (PCM → WAV conversion) |
+| `src/snf.rs` | `.snf` audio parser (PCM to WAV conversion) |
| `src/modding/` | Mod authoring pipeline (apply, patch, package, conflict resolution) |
| `src/commands/` | CLI command implementations (11 subcommands) |
| `src/queries/` | 118 SQL files (59 schema DDL + 59 parameterized INSERTs) |
-| `src/localization.rs` | Text export/import for translations |
+| `src/localization.rs` | Text export and import for translations |
| `src/database.rs` | SQLite schema bootstrap |
----
-
## Supported file formats
### Binary DB files (`.db`)
@@ -53,7 +55,7 @@ This is a 6-crate Cargo workspace (Rust 2024, version `0.9.3`):
| `DrawItem.db` | Draw items |
| `PartyLevelNpc.db` | Party level NPC data |
-### INI / text files
+### INI and text files
| File | Description |
| ------------- | -------------------------- |
@@ -79,15 +81,13 @@ This is a 6-crate Cargo workspace (Rust 2024, version `0.9.3`):
| Extension | Description |
| --------------- | ---------------------------------------------- |
| `.map` | Map geometry (tiles, sprites, events) |
-| `.gtl` / `.btl` | Tilesets (ground / roof, RGB 565, 32×32 tiles) |
+| `.gtl` / `.btl` | Tilesets (ground / roof, RGB 565, 32x32 tiles) |
| `.spr` | Character sprites and animations (RGB 565) |
-| `.snf` | Sound effects (custom PCM → WAV) |
+| `.snf` | Sound effects (custom PCM to WAV) |
| `.dlg` / `.pgp` | Dialogue scripts and text (EUC-KR / 1250) |
| `.scr` | Event scripts (1250) |
-Full format specs are in `docs/files/` (36 per-format documents plus `CROSS_REFERENCES.md`).
-
----
+Format specifications are in `docs/files/`. That directory holds 36 per-format documents and `CROSS_REFERENCES.md`.
## CLI usage
@@ -131,17 +131,18 @@ cargo run -- schema --type weapons
cargo run -- template --type weapons --pretty
```
-### Sprite and animation extraction
+### Extract sprites and animations
```bash
cargo run -- sprite fixtures/Dispel/CharacterInGame/M_BODY1.SPR --mode sprite
cargo run -- sprite fixtures/Dispel/CharacterInGame/M_BODY1.SPR --mode animation
```
-### Sound conversion
+### Convert sound files
```bash
-cargo run -- sound --input fixtures/Dispel/Sound/sample.snf --output output.wav
+cargo run -- sound to-wav fixtures/Dispel/Sound/sample.snf output.wav
+cargo run -- sound from-wav output.wav sample.snf
```
### Map operations
@@ -171,6 +172,8 @@ cargo run -- database import fixtures/Dispel/ db.sqlite
### Mod packaging
+The CLI `mod-pack` command reads `Event*.scr` files from the game `Ref/` folder and writes JSON.
+
```bash
cargo run -- mod-pack --help
```
@@ -181,8 +184,6 @@ cargo run -- mod-pack --help
cargo run -- --help
```
----
-
## GUI
Launch the desktop editor:
@@ -191,28 +192,26 @@ Launch the desktop editor:
cargo run -p dispel-gui
```
-The GUI provides:
-
-- **46 editor types** — spreadsheet views for every supported game data format
-- **3-pane layout** — sidebar (file tree), main content (editors), history panel (undo/redo)
-- **Undo/redo** with full edit history per editor
-- **Mod recording** — tracks every field change for mod changelog generation
-- **Full-text search** — nucleo-matcher fuzzy search across all loaded files
-- **Hex editor** — built-in hex editor (from `hexedit` crate)
-- **Map viewer** — isometric rendering with viewport + LRU cache
-- **SNF audio playback** — rodio-based sound preview
-- **Audio viewer** — read-only OGG/WAV playback with timeline and volume
-- **BMP viewer** — read-only image preview with zoom and fit-to-viewport
-- **Mod packager** — package changes into `dispel-mod` archives
+The GUI has these features:
----
+- 46 editor types with spreadsheet views for supported game data formats
+- A three-pane layout with a sidebar for the file tree, main content for editors and a history panel for undo and redo
+- Undo and redo with an edit history for each editor
+- Mod recording that tracks every field change for the mod changelog
+- Full-text search with nucleo-matcher fuzzy search across loaded files
+- A hex editor from the `hexedit` crate
+- A map viewer with isometric rendering, a viewport and an LRU cache
+- SNF audio playback with rodio
+- An audio viewer for read-only OGG and WAV playback with timeline and volume
+- A BMP viewer for read-only image preview with zoom and fit to viewport
+- A mod packager that stores work in `.dispel-mods`. It writes a zip with `manifest.json`, `changes.json`, `patches/` and `files/`.
## Project structure
```
dispel-extractor/
├── src/ # dispel-core library + CLI binary
-│ ├── references/ # 30+ game data file parsers
+│ ├── references/ # 51 game data file parsers
│ ├── map/ # .map parser + isometric renderer
│ ├── modding/ # Mod authoring pipeline
│ ├── commands/ # CLI command implementations
@@ -236,13 +235,9 @@ dispel-extractor/
└── release.sh # Automated release script
```
----
-
## Development
-The canonical build, format, lint and test commands live in
-`scripts/ci-commands.sh` (11 commands). CI and the Makefile delegate to that
-script, so use it or the matching `make` target rather than an inline command:
+The canonical build, format, lint and test commands live in `scripts/ci-commands.sh`. The script has 11 commands. CI and the Makefile call that script. Use the script or the matching `make` target.
```bash
bash scripts/ci-commands.sh --list # show all canonical commands
@@ -282,15 +277,3 @@ cargo run -p dispel-gui
| `make sprite-animation` | Extract animations |
| `make mod-pack` | Package a mod |
| `make help` | Show all Makefile targets |
-
----
-
-## Legal
-
-This project is **not affiliated with, endorsed by, or sponsored by** the DISPEL® trademark owner.
-
-This tool is for **independent file-format interoperability research based on observable program behavior** only. It does not redistribute copyrighted game files and does not circumvent technological protection measures.
-
-### License
-
-The source code is licensed under the **[MIT License](LICENSE)**. Game content, assets, and proprietary formats are not covered by this license.
diff --git a/docs/database_and_references.md b/docs/database_and_references.md
index 441a2064..2b0b11ff 100644
--- a/docs/database_and_references.md
+++ b/docs/database_and_references.md
@@ -1,57 +1,63 @@
-# Database & Entities
+# Database and entities
-The extractor populates a SQLite database (`database.sqlite`) using `database.rs`.
+The tool populates a SQLite database (`database.sqlite`) through `database.rs`.
-## Schema Overview
-Tables are created on the fly using SQL files found in `src/queries/`.
+## Schema overview
-### Core Entities
+Tables come from SQL files in `src/queries/`. The tool creates the tables when it imports data.
+
+### Core entities
#### Maps (`save_maps`)
-- **Table**: `create_table_maps.sql`
-- **Fields**: ID, Filename, Name, PGP Filename, DLG Filename, Is Light.
-#### Map Tiles (`save_map_tiles`)
-- Stored per coordinate (X, Y).
-- **Fields**: MapID, X, Y, GTL_ID (Ground), BTL_ID (Building), Collision (Bool), EventID.
+- Table: `create_table_maps.sql`
+- Fields: ID, Filename, Name, PGP Filename, DLG Filename, Is Light.
+
+#### Map tiles (`save_map_tiles`)
+
+- The tool stores one row per coordinate (X, Y).
+- Fields: MapID, X, Y, GTL_ID (ground), BTL_ID (building), Collision (Bool), EventID.
+
+#### Events and dialogs
-#### Events & Dialogs
-- **Events**: ID, Previous ID, Type, Filename, Counter.
-- **Dialogs**: ID, Prev Event ID, Next Dialog, Type, Owner, DLG ID, Event ID.
+- Events: ID, Previous ID, Type, Filename, Counter.
+- Dialogs: ID, Prev Event ID, Next Dialog, Type, Owner, DLG ID, Event ID.
#### Items
-Separate tables for different item categories:
-- **Weapons**: Stats (Str, Agi, Wis, Atk, Def), Price, Requirements.
-- **HealItems**: HP/MP/Status recovery effects.
-- **MiscItems**: Basic description/price.
-- **EventItems**: Name/Description.
-- **DrawItems**: Map items (MapID, X, Y, ItemID).
-- **Store**: Shop definitions and product lists.
-
-#### Characters & Monsters
-- **Monsters**: Huge stat block (HP/MP min/max, Atk/Def/Hit/Dodge min/max, XP/Gold, Spells, AI type).
- - **Monster Refs**: Placed monster instances on maps (Pos X, Y, Loot).
- - **Monster Inis**: Visual/Sprite references.
-- **NPCs**:
- - **NPC Refs**: Placed NPCs (Pos, Scripts, Dialog IDs).
- - **NPC Inis**: Visual/Sprite references.
-- **Party**:
- - **Party Refs**: Joinable components, Job names.
+
+The tool uses separate tables for item categories:
+
+- Weapons: Stats (Str, Agi, Wis, Atk, Def), Price, Requirements.
+- HealItems: HP, MP and status recovery effects.
+- MiscItems: Basic description and price.
+- EventItems: Name and description.
+- DrawItems: Map items with MapID, X, Y and ItemID.
+- Store: Shop definitions and product lists.
+
+#### Characters and monsters
+
+- Monsters: HP, MP, Atk, Def, Hit and Dodge minimum and maximum values, plus XP, Gold, Spells and AI type.
+- Monster refs: Placed monster instances on maps with Pos X, Y and Loot.
+- Monster inis: Visual and sprite references.
+- NPCs:
+ - NPC refs: Placed NPCs with Pos, Scripts and Dialog IDs.
+ - NPC inis: Visual and sprite references.
+- Party:
+ - Party refs: Joinable components and Job names.
#### Other
-- **Extras**: Interactive objects? (Sprite file, Description).
-- **Waves**: SNF filenames (Sound/Music triggers?).
-
-## Data Injection Logic
-The `save_all` function in `main.rs` reads from hardcoded paths (e.g., `fixtures/Dispel/Ref/Map.ini`) using parsers in the `references` module, then calls the corresponding `save_*` function in `database.rs`.
-
-Each `save_*` function:
-1. Executes a `create_table_*.sql`.
-2. Iterates over the parsed data vector.
-3. Executes an `insert_*.sql` for each record.
-
-**Exception:** the inserts for `chest_spawns`, `monster_spawns`, `map_info_multi` and
-`tile_grids` live inline in `src/references/chest_spawn.rs`, `monster_spawn.rs`,
-`map_info_multi.rs` and `tile_grid.rs` respectively (they use `conn.execute`
-directly rather than a prepared `include_str!` statement). There are deliberately
-no `insert_*.sql` files for those four tables — do not re-add them.
+
+- Extras: Sprite file and description.
+- Waves: SNF filenames.
+
+## Data import
+
+The CLI imports game data with `cargo run -- database import
`. The command reads files from the given directory with the parsers in `src/references/`. It calls the matching `save_*` function in `database.rs`.
+
+Each `save_*` function does three things:
+
+1. It runs a `create_table_*.sql` file.
+2. It iterates over the parsed records.
+3. It runs an `insert_*.sql` file for each record.
+
+The inserts for `chest_spawns`, `monster_spawns`, `map_info_multi` and `tile_grids` live inline in `src/references/chest_spawn.rs`, `src/references/monster_spawn.rs`, `src/references/map_info_multi.rs` and `src/references/tile_grid.rs`. They call `conn.execute` directly instead of a prepared `include_str!` statement. No `insert_*.sql` files exist for those four tables. Do not re-add them.
diff --git a/docs/file_formats.md b/docs/file_formats.md
index 2861b453..e391bf17 100644
--- a/docs/file_formats.md
+++ b/docs/file_formats.md
@@ -1,29 +1,24 @@
-# File Formats & Parsing
+# File formats and parsing
-## Legal Notice
+This document records the binary layouts that the extractor reads.
-This documentation describes the file formats parsed by the extractor, based on observable data behavior, for interoperability and re-implementation.
+## Common data types
-**DISPEL®** is a registered trademark. This documentation is **not affiliated with, endorsed by, or sponsored by** the trademark owner.
+The tool reads all integers as little-endian values.
-This document details the binary formats parsed by the extractor. This information is critical for re-implementation or generating parsers.
+Colors use a 16-bit RGB 565 value:
-## Common Data Types
-- **LittleEndian Integers**: Checking `read_i32::()` or `read_i16` confirms data is stored in Little Endian.
-- **Color Format (RGB 565)**:
- - 16-bit integer.
- - **Red**: 5 bits (Mask `0xF800` >> 11)
- - **Green**: 6 bits (Mask `0x07E0` >> 5)
- - **Blue**: 5 bits (Mask `0x001F`)
- - Expansion to 8-bit: `val << 3` (for R/B) or `val << 2` (for G).
+- Red takes 5 bits from mask `0xF800` after a shift of 11 places.
+- Green takes 6 bits from mask `0x07E0` after a shift of 5 places.
+- Blue takes 5 bits from mask `0x001F`.
+- Expansion to 8-bit values uses `val << 3` for red and blue, and `val << 2` for green.
----
+## 1. SNF audio (`snf.rs`)
-## 1. SNF Audio (`snf.rs`)
+The tool reads SNF files as PCM data with a 22-byte header.
-The SNF format appears to be a raw PCM container very similar to WAV but with a custom header.
+### Header structure
-### Header Structure
| Byte Offset | Type | Description |
|---|---|---|
| 0 | i32 | Data Size |
@@ -33,121 +28,107 @@ The SNF format appears to be a raw PCM container very similar to WAV but with a
| 12 | i32 | Byte Rate |
| 16 | i16 | Block Align |
| 18 | i16 | Bits Per Sample |
-| 20 | i16 | *Unknown / Padding* (skipped) |
+| 20 | i16 | Unknown value that the tool skips |
### Conversion
-The extractor writes a standard RIFF WAVE header followed by the raw PCM data read from the SNF file.
----
+The tool writes a standard RIFF WAVE header. It then appends the raw PCM data from the SNF file.
-## 2. Map Format (`map.rs`)
+## 2. Map format (`map.rs`)
-Map files are complex binary structures containing multiple blocks of data.
+Map files hold several blocks of binary data.
+
+### 2.1 Header and model
-### 2.1 Header / Model
- `Width` (i32)
- `Height` (i32)
-- Derived "Tiled Map Size": `Width * 25 - 1` by `Height * 25 - 1` (implying 25x25 chunks).
+- The tool derives the tiled map size as `Width * 25 - 1` by `Height * 25 - 1`. The formula uses 25x25 chunks.
+
+### 2.2 Data blocks
+
+The tool reads these blocks in sequence.
-### 2.2 Data Blocks
-The file is read sequentially.
+#### Block 1
-#### Block 1 (Unknown)
- `Multiplier` (i32)
- `Size` (i32)
-- Skips 8 bytes.
-- Skips `Multiplier * Size * 4` bytes.
+- The tool skips 8 bytes.
+- The tool skips `Multiplier * Size * 4` bytes.
+
+#### Block 2
-#### Block 2 (Unknown)
- `Size` (i32)
-- Skips `Size * 2` bytes.
+- The tool skips `Size * 2` bytes.
+
+#### Internal sprites block
-#### Internal Sprites Block
- `Count` (i32)
-- For each sprite:
- - `Image Stamp` (i32): Determines a static offset (1904 if 6, 2996 if 9).
- - Skip 264 bytes.
- - **Sequence Info**: Parsed (see Sprite Format).
- - Seek past image data based on the static offset logic.
+- For each sprite, the tool reads `Image Stamp` (i32). It uses a static offset of 1904 for stamp 6 and 2996 for stamp 9.
+- The tool skips 264 bytes.
+- The tool parses the sequence information (see Sprite format).
+- The tool seeks past the image data using that static offset.
+
+#### Sprite position block
-#### Sprite Position Block
- `Count` (i32)
-- For each entry:
- - `Sprite ID` (i32): Index into internal sprites.
- - Skip 2x i32.
- - Skip 2x i32 (bottom-right coords?).
- - `Sprite X` (i32)
- - `Sprite Y` (i32)
- - Skip calculated based on frames in the referenced sprite sequence.
-
-#### Tiled Objects Block
+- `Sprite ID` (i32) indexes the internal sprites.
+- The tool skips two `i32` values, then two more `i32` values.
+- `Sprite X` (i32)
+- `Sprite Y` (i32)
+- The tool skips a length based on the frame count in the referenced sprite sequence.
+
+#### Tiled objects block
+
- `Count` (i32)
- `Number1` (i32)
-- For each object:
- - Skip 264 bytes.
- - Read 4x i32 (s8, s0_1, s1, s0_2)
- - Read 4x i32 (v1..v4)
- - `X`, `Y` (i32)
- - Read 2x i32 (v7, v8)
- - `C1`, `C2`, `C3` (i32)
- - Read `C3` count of `i16` (IDs).
- - Skip 84 bytes.
- - Skip `(C1 + C2 + C3) * 4` bytes.
-- **Correction Logic**: Contains a specific seek-back-and-scan logic to handle a variable length footer or padding (looking for byte `1`).
-
-### 2.3 Tile & Event Layers
-The file reading jumps to the END of the file and seeks backwards to find tile data.
-
-- **Seek**: `-(TiledHeight * TiledWidth * 4 * 3)` from End.
-- **Event Block**: `TiledWidth * TiledHeight` entries of:
- - `Event ID` (i16)
- - `Unknown` (i16)
-- **GTL (Ground Tile Layer) / Collision**: `TiledWidth * TiledHeight` entries of:
- - `Value` (i32)
- - `ID` = `Value >> 10`
- - `Collision` = `(Value & 1) == 1`
-- **BTL (Building/Roof Tile Layer)**: `TiledWidth * TiledHeight` entries of:
- - `Tile ID` (i16)
- - `Flag` (i16)
-
----
-
-## 3. Tileset Format (`tileset.rs`)
-
-Simple contiguous array of raw pixels.
-- **File Length** is used to determine tile count.
-- **Tile Size**: 32x32 pixels.
-- **Pixel Format**: u16 (RGB 565).
-- Loop until EOF: Read 32*32*2 bytes.
-
-### Isometry Mask
-The code procedurally generates a diamond-shape mask (`decode::tile_mask()` in `src/decode.rs`) to render the 32x32 square tile into a 62x32 isometric projection.
-
----
-
-## 4. Sprite / Animation Format (`sprite.rs`)
-
-Starts at byte **268**.
-
-### Sequence Loop
-- Checks if file has enough bytes left.
-- **Validation**: Reads 15x `i32`. Checks specific values to determine if it's a valid sequence header (e.g., `ints[11] * ints[12] == ints[13]`).
-- If valid:
- - Read `Stamp` (i32).
- - If Stamp == 0, read `FrameCount` (i32).
- - **Frame Loop**:
- - Skip 24 bytes (6 * 4).
- - Read `Origin X`, `Origin Y`, `Width`, `Height` (i32).
- - Read `Size` (u32).
- - Actual Data Size = `Size * 2`.
- - **Image Data**: u16 pixels (RGB 565). `Width * Height`.
-
-## Legal Compliance
-
-This documentation:
-- Describes **file format specifications only**
-- Does **not** distribute any proprietary algorithms or game content
-- Focuses on **technical organization and data structures**
-- Provides information for **independent interoperability research based on observable behavior** only, without circumvention of technological protection measures
-- Maintains **nominative use** for trademark references
-- **No copyrighted content** is reproduced or distributed
+- For each object, the tool skips 264 bytes.
+- It reads four `i32` values: `s8`, `s0_1`, `s1` and `s0_2`.
+- It reads four `i32` values: `v1` through `v4`.
+- It reads `X` and `Y` (i32).
+- It reads two `i32` values: `v7` and `v8`.
+- It reads `C1`, `C2` and `C3` (i32).
+- It reads `C3` values of type `i16` as IDs.
+- It skips 84 bytes.
+- It skips `(C1 + C2 + C3) * 4` bytes.
+- The tool seeks back and scans for byte `1` to handle a variable-length footer or padding.
+
+### 2.3 Tile and event layers
+
+The tool jumps to the end of the file. It seeks backwards to find the tile data.
+
+- Seek: `-(TiledHeight * TiledWidth * 4 * 3)` from End.
+- Event block: `TiledWidth * TiledHeight` entries, each with `Event ID` (i16) and `Unknown` (i16).
+- GTL (ground tile layer) and collision: `TiledWidth * TiledHeight` entries, each with `Value` (i32). The tool computes `ID = Value >> 10` and `Collision = (Value & 1) == 1`.
+- BTL (building and roof tile layer): `TiledWidth * TiledHeight` entries, each with `Tile ID` (i16) and `Flag` (i16).
+
+## 3. Tileset format (`tileset.rs`)
+
+A tileset file holds a contiguous array of raw pixels.
+
+- The file length determines the tile count.
+- Each tile is 32x32 pixels.
+- Each pixel is a u16 RGB 565 value.
+- The tool reads 32*32*2 bytes at a time until it reaches EOF.
+
+### Isometry mask
+
+The tool generates a diamond-shape mask with `decode::tile_mask()` in `src/decode.rs`. The mask draws the 32x32 square tile as a 62x32 isometric projection.
+
+## 4. Sprite and animation format (`sprite.rs`)
+
+Sprite data starts at byte 268.
+
+### Sequence loop
+
+- The tool checks that enough bytes remain in the file.
+- The tool reads 15 `i32` values. It treats the header as a valid sequence when `ints[11] * ints[12] == ints[13]`.
+- For a valid sequence, the tool reads `Stamp` (i32).
+- When `Stamp` is 0, the tool reads `FrameCount` (i32).
+
+### Frame loop
+
+- The tool skips 24 bytes (6 * 4).
+- It reads `Origin X`, `Origin Y`, `Width` and `Height` (i32).
+- It reads `Size` (u32).
+- The actual data size is `Size * 2`.
+- The tool reads `Width * Height` pixels of type u16 in RGB 565 format.
diff --git a/docs/iced-fork-config.md b/docs/iced-fork-config.md
index 57a8d906..b7cc087d 100644
--- a/docs/iced-fork-config.md
+++ b/docs/iced-fork-config.md
@@ -1,14 +1,10 @@
-# Forked-Iced Configuration (single pin set & feature matrix)
+# Forked Iced configuration: single pin set and feature matrix
-The GUI stack builds against a git fork of Iced, `dimspell/iced`. This document
-is the authoritative description of how that fork is pinned, which features
-each workspace crate enables, and how headless tests select their renderer.
-`scripts/check-iced-config.sh` (also `make check_iced_config`) enforces the
-invariants below and runs in CI.
+The GUI builds against a git fork of Iced, `dimspell/iced`. This document records the pins, the features each crate enables and the renderer that headless tests select. `scripts/check-iced-config.sh` (also `make check_iced_config`) enforces these rules in CI.
-## 1. Single pin set
+## Single pin set
-All iced-family git dependencies must resolve to the **same** commit:
+All iced-family git dependencies must resolve to the same commit:
| Dependency | Source | Rev |
|---|---|---|
@@ -17,66 +13,37 @@ All iced-family git dependencies must resolve to the **same** commit:
| `iced_renderer` (hexedit **dev**-dep) | `https://github.com/dimspell/iced` | `c0ffdd8e7352df9283496f3db334731c00ef6d0d` |
| `winit` (`[patch.crates-io]`) | `https://github.com/iced-rs/winit.git` | `05b8ff17a06562f0a10bb46e6eaacbe2a95cb5ed` |
-Historically `hexedit`'s `iced_renderer` dev-dependency was pinned to a
-different commit (`48fb8fe…`). That produced two parallel copies of every
-iced crate in `Cargo.lock` with incompatible internal types. It is now aligned
-to the workspace pin; `Cargo.lock` contains a single `iced_renderer` entry.
-**Do not reintroduce a second iced rev** — enable the needed feature through
-the workspace pin instead.
+hexedit's `iced_renderer` dev-dependency uses the same commit as the workspace. A different commit (`48fb8fe...`) gave `Cargo.lock` two copies of each iced crate. The copies had incompatible internal types. `Cargo.lock` now has one `iced_renderer` entry. Do not add a second iced rev. Enable any needed feature through the workspace pin.
-## 2. Feature matrix
+## Feature matrix
-Cargo features are additive and unify across the dependency graph. The table
-lists the features each workspace crate turns on directly (everything uses
-`default-features = false` on `iced`):
+Cargo features are additive and unify across the dependency graph. The table lists the features each workspace crate turns on directly. Every crate sets `default-features = false` on `iced`.
| Crate | `iced` features (direct) | Own features | Forces on `gui-widgets` |
|---|---|---|---|
-| `gui-widgets` | `advanced`, `thread-pool`, `wgpu` | `default = [accessibility]`, `accessibility = [iced/accessibility]` | — |
-| `hexedit` | `advanced`, `tokio`, `wgpu`, `canvas`, `lazy` | — | `accessibility` |
+| `gui-widgets` | `advanced`, `thread-pool`, `wgpu` | `default = [accessibility]`, `accessibility = [iced/accessibility]` | none |
+| `hexedit` | `advanced`, `tokio`, `wgpu`, `canvas`, `lazy` | none | `accessibility` |
| `dispel-gui` | `tokio`, `wgpu`, `image`, `canvas`, `advanced`, `lazy`, `x11`, `wayland`, `accessibility` | `default = []`, `iced_test`, `debug` | `accessibility` |
-| `dispel-extractor` (root) | — (no iced dependency) | — | — |
+| `dispel-extractor` (root) | none (no iced dependency) | none | none |
Notes:
-- **Accessibility is default-on and force-enabled by both GUI consumers**, so
- the shared `table_widget` compiles with one shape workspace-wide. Turning it
- off in one crate only would not work: feature unification would turn it back
- on for everyone, producing unexpected build differences. Only `table_widget`
- implements full accesskit nodes today; the other custom widgets use iced's
- no-op defaults.
-- `dispel-gui/debug = ["iced/hot"]` enables the fork's experimental hot
- reload. `cargo test --workspace --all-features` therefore compiles hot
- reload *and* `iced_test` together.
-- `dispel-gui/iced_test = ["dep:iced_test", "iced/tiny-skia"]`, hexedit's
- `iced_renderer` dev-dep (`features = ["tiny-skia"]`) and the identical
- `gui-widgets` dev-dep all make the software renderer available; any one path
- is enough for feature unification, but each is kept so the crate's tests work
- standalone.
-- `gui-widgets` also enables `iced_test/accessibility` as a dev-dependency so
- its widget tests can inspect accessibility trees and dispatch accesskit
- actions. It matches the crate's default-on `accessibility` feature.
-
-## 3. Test backend
-
-`iced_test` reads the **`ICED_TEST_BACKEND`** environment variable at runtime
-(iced fork `test/src/simulator.rs` and `test/src/emulator.rs`). The value
-`software` selects the `tiny-skia` renderer; an unset value falls back to the
-`wgpu` renderer, which needs a GPU/window server and fails in headless CI.
-
-Consequences:
-
-- Every iced UI-simulation test target sets `ICED_TEST_BACKEND=software` in the
- Makefile (`iced_test`, `hexedit_test`). Use those targets, or export the
- variable yourself when running `cargo test -p dispel-gui -p hexedit -p
- gui-widgets`.
-- `tiny-skia` must also be compiled in (see the feature matrix above); the env
- variable alone is not enough.
-- `cargo test --workspace --all-features` enables `iced_test` and hot reload
- together. It compiles, but GPU-less environments must still export
- `ICED_TEST_BACKEND=software` for the UI-simulation tests to run.
-
-## 4. Validation
+- Accessibility is on by default, and both GUI consumers force it on. The shared `table_widget` then compiles with one shape across the workspace. A single crate cannot turn accessibility off. Feature unification turns it back on for all crates and changes the build. Only `table_widget` implements full accesskit nodes. The other custom widgets use iced's no-op defaults.
+- `dispel-gui/debug = ["iced/hot"]` enables the fork's experimental hot reload. So `cargo test --workspace --all-features` compiles hot reload and `iced_test` together.
+- Three paths make the software renderer available. The first is `dispel-gui/iced_test = ["dep:iced_test", "iced/tiny-skia"]`. The second is hexedit's `iced_renderer` dev-dep (`features = ["tiny-skia"]`). The third is the same `gui-widgets` dev-dep. One path is enough for feature unification. Each path stays so the crate's tests work on their own.
+- `gui-widgets` also enables `iced_test/accessibility` as a dev-dependency. Its widget tests can inspect accessibility trees and dispatch accesskit actions. This matches the crate's default-on `accessibility` feature.
+
+## Test backend
+
+`iced_test` reads the `ICED_TEST_BACKEND` environment variable at runtime. The fork handles this in `test/src/simulator.rs` and `test/src/emulator.rs`. The value `software` selects the `tiny-skia` renderer. An unset value falls back to the `wgpu` renderer. That renderer needs a GPU and a window server. It fails in headless CI.
+
+Rules:
+
+- Every iced UI-simulation test target sets `ICED_TEST_BACKEND=software` in the Makefile (`iced_test`, `hexedit_test`). Use those targets, or export the variable yourself when you run `cargo test -p dispel-gui -p hexedit -p gui-widgets`.
+- You must also compile `tiny-skia` (see the feature matrix above). The env variable alone is not enough.
+- `cargo test --workspace --all-features` enables `iced_test` and hot reload together. The command compiles. On a machine with no GPU, export `ICED_TEST_BACKEND=software` before the UI-simulation tests.
+
+## Validation
Run locally:
@@ -84,9 +51,4 @@ Run locally:
make check_iced_config # or: bash scripts/check-iced-config.sh
```
-The script checks: one iced rev in all manifests and in `Cargo.lock`; the
-expected winit patch rev; the `ICED_TEST_BACKEND=software` settings in the
-Makefile; `tiny-skia` compiled in on both iced_test paths; and consistent
-accessibility configuration. It runs as a CI step in both `pr.yml` (verify job)
-and `test.yml` (master push), in addition to the existing build/test/clippy
-steps — it does not replace or weaken them.
+The script checks for one iced rev in all manifests and in `Cargo.lock`. It checks the expected winit patch rev, the `ICED_TEST_BACKEND=software` settings in the Makefile, `tiny-skia` on both `iced_test` paths, and consistent accessibility configuration. It runs as a CI step in both `pr.yml` (the `verify` job) and `test.yml` (master push). Those steps do not replace the build, test or clippy steps.
diff --git a/docs/overview.md b/docs/overview.md
index 9dedebca..0f8ff860 100644
--- a/docs/overview.md
+++ b/docs/overview.md
@@ -1,41 +1,35 @@
-# Dispel Extractor Overview
+# Dispel Extractor overview
-A modding toolkit for **DISPEL®** game files. Written in Rust as a 6-crate Cargo workspace, this project provides a CLI for extraction/patching, a desktop GUI for editing game data, and a hex editor. All edits are persisted directly to game files — no intermediate database.
+This toolkit reads and writes DISPEL® game files. It is a Rust workspace with six crates. The workspace has a CLI for extraction and patching, a desktop GUI for editing game data and a hex editor. The tools write edits into the game files. They do not keep a separate database.
-**Not affiliated with, endorsed by, or sponsored by the trademark owner.**
+## Project structure
----
-
-## Project Structure
-
-The workspace consists of six crates:
+The workspace has six crates:
| Crate | Type | Role |
|---|---|---|
| `dispel-extractor` (root) | lib + bin | Core library (`dispel_core`) + CLI binary |
-| `dispel-encodings` | lib | Single source of truth for text-encoding spellings/labels |
-| `dispel-gui` | bin | Iced 0.15 desktop GUI |
+| `dispel-encodings` | lib | Single source of truth for text-encoding spellings and labels |
+| `dispel-gui` | bin | Iced 0.15 desktop GUI with 46 editor types, built on the `dimspell/iced` fork pinned at rev `c0ffdd8e7352df9283496f3db334731c00ef6d0d` |
| `dispel-macros` | proc-macro | 7 derive macros (Extractor, Localizable, RecordPatcher, etc.) |
| `gui-widgets` | lib | Reusable Iced widgets (ContextMenu, modal, ParagraphCache) |
| `hexedit` | lib + bin | Hex editor |
### Key source directories (`src/`)
-- **`src/main.rs`** — CLI entry point via `clap`
-- **`src/cli.rs`** — Subcommand definitions
-- **`src/database.rs`** — SQLite schema bootstrap
-- **`src/localization.rs`** — Text export/import for translations
-- **`src/references/`** — 51 game data file parsers (`.db`, `.ini`, `.ref`)
-- **`src/map/`** — `.map` parser + isometric renderer (tiles, sprites, events)
-- **`src/modding/`** — Mod authoring pipeline (apply, patch, package, resolve conflicts)
-- **`src/commands/`** — CLI command implementations
-- **`src/queries/`** — 118 SQL files (59 schema DDL + 59 INSERTs)
-- **`src/sprite.rs`** — `.spr` sprite/animation parser
-- **`src/snf.rs`** — `.snf` audio parser
+- `src/main.rs`: CLI entry point with `clap`
+- `src/cli.rs`: subcommand definitions
+- `src/database.rs`: SQLite schema bootstrap
+- `src/localization.rs`: text export and import for translations
+- `src/references/`: 51 game data file parsers (`.db`, `.ini`, `.ref`)
+- `src/map/`: `.map` parser and isometric renderer for tiles, sprites and events
+- `src/modding/`: mod authoring pipeline (apply, patch, package, resolve conflicts)
+- `src/commands/`: CLI command implementations
+- `src/queries/`: 118 SQL files (59 schema DDL + 59 INSERTs)
+- `src/sprite.rs`: `.spr` sprite and animation parser
+- `src/snf.rs`: `.snf` audio parser
----
-
-## CLI Commands
+## CLI commands
```
# Extract game data to JSON
@@ -44,13 +38,13 @@ cargo run -- extract -i "Monster.db"
# Patch game files from JSON
cargo run -- patch -i changes.json -t "Monster.db" --in-place
-# Validate JSON against expected schema
+# Validate JSON against an expected schema
cargo run -- validate -i weapons.json --type weapons
# List supported file types
cargo run -- list
-# Generate JSON schema for a file type
+# Generate a JSON schema for a file type
cargo run -- schema --type weapons
# Generate a minimal JSON template
@@ -59,8 +53,9 @@ cargo run -- template --type weapons --pretty
# Extract sprites or animations
cargo run -- sprite "M_BODY1.SPR" --mode sprite
-# Convert SNF audio to WAV
-cargo run -- sound --input sample.snf --output output.wav
+# Convert SNF audio to WAV and WAV audio to SNF
+cargo run -- sound to-wav sample.snf output.wav
+cargo run -- sound from-wav output.wav sample.snf
# Map operations (tiles, atlas, render)
cargo run -- map tiles "cat1.gtl" --output out/tiles/
@@ -70,18 +65,16 @@ cargo run -- map render --map cat1.map --btl cat1.btl --gtl cat1.gtl --output ma
# SQLite database import
cargo run -- database import "path/to/Dispel/" db.sqlite
-# Mod packaging
-cargo run -- mod-pack ...
+# Batch-export event scripts to JSON
+cargo run -- mod-pack --game-path "path/to/Dispel" --output mod-pack/
```
Full subcommand reference: `cargo run -- --help`.
----
-
## Workflow
-1. **Parsing** — Binary/INI formats are read using `byteorder` and encoding-aware text readers (`WINDOWS-1250` or `EUC-KR`).
-2. **Processing** — Raw data (RGB 565 colors, PCM audio, tile indexes) is converted to usable representations.
-3. **Editing** — The GUI provides 44 editor types for viewing and modifying records, plus a fallback for unknown file types, with undo/redo and mod recording.
-4. **Modding** — Changes can be packaged into `.dispel-mod` archives for distribution, with conflict detection and binary patching.
-5. **Output** — Images (PNG), audio (WAV), JSON (extraction), or direct in-place file patching.
+1. Parsing: The tools read binary and INI files with `byteorder` and encoding-aware text readers. The readers use `WINDOWS-1250` or `EUC-KR`.
+2. Conversion: The tools convert RGB 565 colors, PCM audio and tile indexes to other representations.
+3. GUI editing: The GUI has 46 editor types and a fallback for unknown file types. It supports undo, redo and mod recording.
+4. Mod packaging: The CLI `mod-pack` command exports event scripts to JSON. The GUI mod packager writes a zip with `manifest.json`, `changes.json`, `patches/` and `files/`. It stores work in `.dispel-mods`.
+5. Output: The tools write PNG images, WAV audio and extracted JSON. They can also patch files in place.
diff --git a/docs/rendering.md b/docs/rendering.md
index ec126c2b..a82fc465 100644
--- a/docs/rendering.md
+++ b/docs/rendering.md
@@ -1,31 +1,32 @@
-# Rendering Logic
+# Rendering logic
-## Map Rendering (`src/map/`)
-The tool can render a full map into a single image (`render_map`).
+## Map rendering (`src/map/`)
-### Isometric Projection
-The map logic handles conversion between "Map Coords" (grid) and "Image Coords" (pixel).
+The tool can render a full map into one image with `render_map`.
-- **Tile Dimensions**: 62x32 pixels.
-- **Formula**:
- ```rust
- start_x = (x + y) * 32; // TILE_HORIZONTAL_OFFSET_HALF
- start_y = (-x + y) * 16 + (diagonal / 2 * 16); // TILE_HEIGHT_HALF
- ```
+### Isometric projection
+
+The map code converts map coordinates on a grid to image coordinates in pixels.
+
+- Tile dimensions: 62x32 pixels.
+- The tool uses this formula:
+
+```rust
+start_x = (x + y) * 32; // TILE_HORIZONTAL_OFFSET_HALF
+start_y = (-x + y) * 16 + (diagonal / 2 * 16); // TILE_HEIGHT_HALF
+```
### Layers
-1. **Base (Ground)**: Iterates diagonally. Renders `gtl_tiles`.
- - Applies color mixing for Event tiles (Blue tint) or Collision tiles (optional).
- - Uses a mask to draw the diamond tile shape.
-2. **Objects**: Sprites and Tiled Objects.
- - Sorted by `ground_y` coordinate to handle depth/occlusion correctly (painter's algorithm).
- - **Sprites**: Rendered from `internal_sprites` extracted from the map file.
- - **Tiled Objects**: Collections of tiles designated by `tiled_infos` (multi-tile structures).
-3. **Roofs (BTL)**: Renders `btl_tiles`.
-
-## Sprite Rendering (`src/sprite.rs`)
-- **Transparency**: Pixels with value `0` are skipped/transparent.
-- **Positioning**: Uses `origin_x`, `origin_y` relative to a calculated bounding box for animations.
-
-## Tile Rendering (`src/map/tileset.rs`)
-- **Masking**: Since the source data is a 32x32 square but the output is isometric, `decode::tile_mask()` (in `src/decode.rs`, shared with the GUI) generates an offset array (`mask[0]` for start x, `mask[1]` for width) per line `y` to draw a diamond shape.
+
+1. Base ground: The tool iterates diagonally and renders `gtl_tiles`. It applies a blue tint to event tiles and an optional tint to collision tiles. It uses a mask to draw the diamond tile shape.
+2. Objects: The tool renders sprites and tiled objects. It sorts them by `ground_y` and draws them in that order. This order follows the painter's algorithm. Sprites come from `internal_sprites` in the map file. Tiled objects group tiles through `tiled_infos`.
+3. Roofs: The tool renders `btl_tiles`.
+
+## Sprite rendering (`src/sprite.rs`)
+
+- The tool skips pixels with value `0`.
+- Sprite position uses `origin_x` and `origin_y` relative to a calculated bounding box for animations.
+
+## Tile rendering (`src/map/tileset.rs`)
+
+`decode::tile_mask()` in `src/decode.rs` generates an offset array for each line `y`. The GUI also uses this mask. `mask[0]` gives the start x position. `mask[1]` gives the width. The array draws the diamond shape from the 32x32 source square.
diff --git a/gui-widgets/src/sweeten/README.md b/gui-widgets/src/sweeten/README.md
index 33f5b705..1463ed6f 100644
--- a/gui-widgets/src/sweeten/README.md
+++ b/gui-widgets/src/sweeten/README.md
@@ -1,3 +1,3 @@
# sweeten
-The code from this module comes from the https://github.com/airstrike/sweeten repository.
+The code in this module comes from https://github.com/airstrike/sweeten.
From cf17570dbdf95a0b6f65b08a15c9eadd1f50a137 Mon Sep 17 00:00:00 2001
From: dimspell <141545384+dimspell@users.noreply.github.com>
Date: Wed, 25 Nov 2026 13:35:32 +0100
Subject: [PATCH 03/72] docs: rewrite hexedit README in plain English and fix
version
---
README.md | 2 +-
hexedit/README.md | 769 ++++++++++++++++++++++------------------------
2 files changed, 370 insertions(+), 401 deletions(-)
diff --git a/README.md b/README.md
index b6992d5c..dfc95c9b 100644
--- a/README.md
+++ b/README.md
@@ -12,7 +12,7 @@ The source code is licensed under the MIT License (LICENSE). Game content is not
## What's in this repository
-This Cargo workspace has six crates. The workspace uses Rust 2024 and version `0.9.3`.
+This Cargo workspace has six crates. The workspace uses Rust 2024 and version `0.9.5`.
| Crate | Type | Role |
| ------------------------- | ---------- | --------------------------------------------------------------- |
diff --git a/hexedit/README.md b/hexedit/README.md
index ebc1f549..71cd3322 100644
--- a/hexedit/README.md
+++ b/hexedit/README.md
@@ -1,120 +1,96 @@
-# hexedit — A standalone, embeddable hex editor widget for Iced
+# hexedit: a standalone, embeddable hex editor widget for Iced
-**hexedit** is a full-featured hex editor library built on [Iced 0.15](https://iced.rs/).
-It ships as a reusable Rust library (`hexedit` crate) and one standalone binary
-(`hexedit`).
-
-Designed for the [Dispel RPG modding toolkit](https://github.com/piotr/dispel-extractor),
-it is embeddable inside any Iced application and powers the hex-editing tab in `dispel-gui`.
-
----
+hexedit is a hex editor library built on [Iced 0.15](https://iced.rs/). It ships as a reusable Rust library, the `hexedit` crate, and one binary, `hexedit`. The [Dispel RPG modding toolkit](https://github.com/piotr/dispel-extractor) uses the library for the hex editing tab in `dispel-gui`. You can also embed the library in any Iced application.
## Table of Contents
1. [Features](#features)
-2. [Architecture Overview](#architecture-overview)
-3. [Domain Layer (Pure Data Model)](#domain-layer-pure-data-model)
-4. [UI Layer (Iced-specific)](#ui-layer-iced-specific)
-5. [HexEditorState (Aggregate State)](#hexeditorstate-aggregate-state)
-6. [HexEditorConfig (Host Injection)](#hexeditorconfig-host-injection)
-7. [HexEditorMessage (Enum Reference)](#hexeditormessage-enum-reference)
-8. [HexMatrix Custom Widget](#hexmatrix-custom-widget)
-9. [Coloring System](#coloring-system)
-10. [Inspector Decoder System](#inspector-decoder-system)
-11. [Pattern System](#pattern-system)
-12. [Writing / Inline Editing](#writing--inline-editing)
-13. [Search & Navigation](#search--navigation)
-14. [Write Modes & Text Encoding](#write-modes--text-encoding)
-15. [Byte Statistics & Entropy Panel](#byte-statistics--entropy-panel)
-16. [Pane Grid Layout](#pane-grid-layout)
+2. [Architecture overview](#architecture-overview)
+3. [Domain layer (pure data model)](#domain-layer-pure-data-model)
+4. [UI layer (Iced-specific)](#ui-layer-iced-specific)
+5. [HexEditorState (aggregate state)](#hexeditorstate-aggregate-state)
+6. [HexEditorConfig (host injection)](#hexeditorconfig-host-injection)
+7. [HexEditorMessage (enum reference)](#hexeditormessage-enum-reference)
+8. [HexMatrix custom widget](#hexmatrix-custom-widget)
+9. [Cell colours](#the-coloring-system)
+10. [Inspector decoder system](#inspector-decoder-system)
+11. [Pattern system](#pattern-system)
+12. [Inline editing](#inline-editing-and-writing)
+13. [Search and navigation](#search-and-navigation)
+14. [Write modes and text encoding](#write-modes-and-text-encoding)
+15. [Byte statistics and entropy panel](#byte-statistics-and-entropy-panel)
+16. [Pane grid layout](#pane-grid-layout)
17. [Minimap](#minimap)
-18. [Theme System](#theme-system)
-19. [Test Structure](#test-structure)
+18. [Theme system](#theme-system)
+19. [Test structure](#test-structure)
20. [Usage (library)](#usage-library)
21. [Usage (standalone binaries)](#usage-standalone-binaries)
22. [Build](#build)
23. [Feature flags](#feature-flags)
24. [Keybindings](#keybindings)
25. [Dependencies](#dependencies)
-26. [LLM Guidance — Conventions & Invariants](#llm-guidance--conventions--invariants)
-
----
+26. [LLM guidance: conventions and invariants](#llm-guidance-conventions-and-invariants)
## Features
### Core editing
-- **Virtualized hex matrix** — Address gutter, hex bytes (grouped 8+8), ASCII column, and
- annotation column. Only rows in the viewport are rendered (virtualized scrolling).
-- **Inline overwrite editing** — Double-click or `F2` to begin editing a byte; type two hex
- digits to auto-commit and advance to the next byte. `Tab`/`Enter` to commit and advance,
- `Esc` to cancel.
-- **Selection** — Click, drag, or Shift+arrow to select byte ranges. Arrow keys, `Home`/`End`,
- `Page Up`/`Page Down`, `Ctrl+Home`/`Ctrl+End` for keyboard navigation.
-- **Copy / Paste** — `Ctrl+C` copies the selected range as hex text (`DE AD BE EF`);
- `Ctrl+V` pastes hex text from the clipboard back into the buffer.
-- **Write bytes** — `WriteBytes` message for programmatic inspector edits and other
- host-driven changes.
-
-### Search & navigation
-- **Search** (`Ctrl+F`) — Hex byte-sequence search (`DE AD BE EF` or `DEADBEEF`) and
- ASCII substring search. Next/prev match navigation with match highlighting in the matrix.
-- **Goto** (`Ctrl+G`) — Navigate to a specific address. Accepts hex (`0xFF`, `FF`),
- decimal (`255`), and relative offsets (`+10`, `-5`).
-- **Bytes-per-row toggle** — Set any row width from 1 to 64 bytes: preset buttons
- (8/16/32) plus a custom numeric input in the settings modal.
+
+- **Virtualized hex matrix:** The address gutter, hex bytes grouped 8+8, the ASCII column and the annotation column appear on screen. The widget draws only rows in the viewport.
+- **Inline overwrite editing:** Double-click or press `F2` to edit a byte. Type two hex digits to commit the byte and move to the next one. Press `Tab` or `Enter` to commit and advance. Press `Esc` to cancel.
+- **Selection:** Click, drag or press Shift with an arrow key to select a byte range. Arrow keys, `Home`, `End`, `Page Up`, `Page Down`, `Ctrl+Home` and `Ctrl+End` move the cursor.
+- **Copy and paste:** `Ctrl+C` copies the selected range as hex text (`DE AD BE EF`). `Ctrl+V` pastes hex text from the clipboard into the buffer.
+- **Write bytes:** The `WriteBytes` message supports inspector edits and other host changes.
+
+### Search and navigation
+
+- **Search (`Ctrl+F`):** The tool finds hex byte sequences (`DE AD BE EF` or `DEADBEEF`) and ASCII substrings. It highlights matches in the matrix. It moves to the next or previous match.
+- **Goto (`Ctrl+G`):** The tool moves to an address. The input accepts hex (`0xFF`, `FF`), decimal (`255`) and relative offsets (`+10`, `-5`).
+- **Bytes-per-row toggle:** The settings modal sets any row width from 1 to 64 bytes. Preset buttons cover 8, 16 and 32. A custom numeric input accepts other widths.
### Data inspector
-- **Built-in decoders** — `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `f32`, `f64`,
- ASCII char, UTF-8 char, RGB565 pixel, null-terminated C string, and raw hex dump.
-- **Editable values** — All numeric decoders support inline editing via a modal: type a
- decimal or `0x`-prefixed hex value and it's written back in the correct endianness.
+
+- **Built-in decoders:** `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `f32`, `f64`, ASCII char, UTF-8 char, RGB565 pixel, null-terminated C string and raw hex dump.
+- **Editable values:** Each numeric decoder has an inline edit modal. Type a decimal value or a `0x` hex value. The tool writes the bytes in the matching endianness.
### Pattern highlighting
-- **Named byte ranges** — Select a range, right-click → "Create Pattern" (or `Ctrl+E`).
- Patterns are rendered with a distinct background/foreground colour in the matrix.
-- **Repeated (zebra) patterns** — Create multi-instance repeating patterns with automatic
- annotation labels (e.g. `Monster[0]`, `Monster[1]`...).
-- **Pattern groups** — Organize related patterns into collapsible groups with rename, colour
- cycling, and bulk delete.
-- **Annotations** — Text annotations per pattern shown in the annotation column to the right
- of the ASCII area. Annotations of patterns under the cursor are highlighted.
-- **Import / Export** — Patterns and groups can be exported to and imported from a
- JSON file.
+
+- **Named byte ranges:** Select a range, right-click and choose `Create Pattern`. You can also press `Ctrl+E`. Patterns use a distinct background and foreground colour in the matrix.
+- **Repeated (zebra) patterns:** Create a repeating pattern with several instances. The tool adds annotation labels such as `Monster[0]` and `Monster[1]`.
+- **Pattern groups:** Group related patterns. Groups support rename, colour cycling and bulk delete.
+- **Annotations:** Each pattern can carry text in the annotation column to the right of the ASCII area. The tool highlights annotations for patterns under the cursor.
+- **Import and export:** The tool exports patterns and groups to a JSON file and imports them from a JSON file.
### Visual colouring
-- 5 colour schemes via the settings modal:
- - **Monochrome** — Single colour for all bytes (the classic hex editor look).
- - **Nybble** — 18 colour groups by high nibble (one per nybble + special `0x00`/`0xFF`).
- - **Categories** — 6 semantic groups (NULL, whitespace, printable, DEL, control, non-ASCII).
- - **Rainbow** — Continuous hue gradient across the full `0x00–0xFF` range.
- - **Heatmap** — Cold-to-hot heatmap (blue → cyan → green → yellow → red).
-- **Dim nulls** — Optionally render `0x00` bytes in a dim colour regardless of the active scheme.
-- **Dirty vs vanilla-diff colouring** — Bytes dirtied this session use one colour; bytes that
- differ cumulatively from the on-disk snapshot use another.
-
-### Layout & panels
-- **Pane grid** — Halloy-style movable, splittable, resizable panels. The default layout is a
- vertical split: hex matrix on the left, data inspector on the right. The pattern list opens
- as an additional split pane.
-- **Toolbar** — Save button, Goto, Patterns toggle, text export, settings, bytes-per-row toggle,
- and status message.
-- **Minimap** — Overview strip showing file structure at a glance, with cursor position marker
- and dirty/diff pixel indicators.
-
-### Save & integration
-- **Host-configurable save** — The host app provides a `SavePort` callback, a save label,
- and a `can_save` flag. The editor surfaces these in the toolbar.
-- **Dirty tracking** — `BufferProvider` tracks which addresses have been modified since load.
-- **Text export** — Export the file as a formatted hex dump text file (configurable: address
- gutter, decimal/hex addresses, ASCII column).
+
+The settings modal offers five colour schemes:
+
+- **Monochrome:** One colour for all bytes.
+- **Nybble:** 18 colour groups by high nibble, one per nybble plus special `0x00` and `0xFF`.
+- **Categories:** Six semantic groups, NULL, whitespace, printable, DEL, control and non-ASCII.
+- **Rainbow:** A continuous hue gradient across the full `0x00` to `0xFF` range.
+- **Heatmap:** Cold to hot, blue, cyan, green, yellow and red.
+
+- **Dim nulls:** The tool can draw `0x00` bytes in a dim colour under any scheme.
+- **Dirty and vanilla diff colouring:** Bytes changed in this session use one colour. Bytes that differ from the on-disk snapshot use another.
+
+### Layout and panels
+
+- **Pane grid:** Movable, splittable, resizable panels follow the Halloy style. The default layout splits the hex matrix on the left from the inspector on the right. The pattern list opens as another split pane.
+- **Toolbar:** The toolbar holds Save, Goto, Patterns toggle, text export, settings, bytes-per-row toggle and the status message.
+- **Minimap:** An overview strip shows file structure, the cursor position marker and dirty or diff pixels.
+
+### Save and integration
+
+- **Host-configurable save:** The host app supplies a `SavePort` callback, a save label and a `can_save` flag. The editor shows them in the toolbar.
+- **Dirty tracking:** `BufferProvider` tracks addresses that changed since load.
+- **Text export:** The tool exports a formatted hex dump text file. The address gutter, decimal or hex addresses and the ASCII column are configurable.
### File support
-- Library: `hexedit::HexEditorState::load_from_path(&path)` loads any file into memory.
-- Binaries: Open files via command-line argument (`hexedit path/to/file.bin`) or file dialog.
----
+- **Library:** `hexedit::HexEditorState::load_from_path(&path)` loads any file into memory.
+- **Binaries:** Open a file with a command-line argument (`hexedit path/to/file.bin`) or a file dialog.
-## Architecture Overview
+## Architecture overview
```
hexedit/
@@ -171,88 +147,95 @@ hexedit/
└── Cargo.toml
```
-**Design principle:** `domain/` is pure Rust — no Iced types, no widget dependencies.
-`ui/` contains all Iced-specific code. This lets the data model be tested and reused
-without a running UI.
+The `domain/` directory holds pure Rust data types. It imports no Iced widget types. The `ui/` directory holds all Iced code. This split lets you test and reuse the data model without a UI.
+
+## Domain layer (pure data model)
----
+Every file in `src/domain/` is free of Iced widget types. Unit tests cover them without a running UI.
-## Domain Layer (Pure Data Model)
+### `provider.rs`: Byte source abstraction
-All files in `src/domain/` are free of Iced widget types. They can be unit-tested
-without a running UI.
+- **`HexProvider` trait** (`read()`, `write()`, `len()`, `is_writable()`): A common interface for byte sources. It lets a vanilla snapshot and the live editing buffer coexist.
+- **`BufferProvider`**: An in-memory `Vec` with a `BTreeSet` of dirty addresses. It tracks bytes that changed since load. Key methods: `from_bytes()`, `dirty()`, `dirty_count()`, `clear_dirty()`, `as_slice()`.
+- **Rule:** `write()` marks an address dirty only when the new byte differs from the old one.
-### `provider.rs` — Byte source abstraction
-- **`HexProvider` trait** (`read()`, `write()`, `len()`, `is_writable()`): Abstraction over byte sources so vanilla snapshots and the live editing buffer can coexist.
-- **`BufferProvider`**: In-memory `Vec` with a `BTreeSet` of dirty addresses. Tracks which bytes have been modified since load. Key methods: `from_bytes()`, `dirty()`, `dirty_count()`, `clear_dirty()`, `as_slice()`.
-- **Rule:** `write()` only marks an address dirty if the new byte differs from the old one.
+### `selection.rs`: Cursor and selection model
-### `selection.rs` — Cursor & selection model
- **`Selection`**: `{ anchor: u64, cursor: u64 }`. The selected range is `min(anchor,cursor)..=max(anchor,cursor)`. Methods: `single()`, `range()`, `start()`, `end()`, `len()`, `is_single()`, `contains()`, `select()`, `extend()`.
- **`NavDir` enum**: Left, Right, Up, Down, LineStart, LineEnd, PageUp, PageDown, DocumentStart, DocumentEnd.
-- **`nav_target(cursor, dir, bytes_per_row, page_rows, max_addr) -> u64`**: Pure function computing the new cursor after navigation. All edge cases (saturating at 0, clamping to max_addr) are unit-tested.
+- **`nav_target(cursor, dir, bytes_per_row, page_rows, max_addr) -> u64`**: A pure function that computes the new cursor. Unit tests cover the edge cases. These include saturation at 0 and clamping to `max_addr`.
+
+### `pattern.rs`: Pattern highlighting
-### `pattern.rs` — Pattern highlighting
-- **`Pattern`**: `{ id, start, end, color_idx, group_id, annotation }`. Serializable via serde.
-- **`RepeatedPatternGroup`**: `{ id, label, color_idx }`. Groups related patterns together.
-- **`RepeatPatternDialog`**: Transient modal state for creating repeated patterns from a selection.
-- **`PatternExport`**: Versioned JSON envelope (`{ version, groups, patterns }`) for import/export.
-- **`pattern_bg(idx)` / `pattern_fg(idx)`**: Return palette colours (16-colour cyclic palette from `DARK_THEME`).
+- **`Pattern`**: `{ id, start, end, color_idx, group_id, annotation }`. Serde serializes it.
+- **`RepeatedPatternGroup`**: `{ id, label, color_idx }`. It groups related patterns.
+- **`RepeatPatternDialog`**: Transient modal state for repeated patterns created from a selection.
+- **`PatternExport`**: A versioned JSON envelope (`{ version, groups, patterns }`) for import and export.
+- **`pattern_bg(idx)` / `pattern_fg(idx)`**: Palette colours from the 16-colour cyclic palette in `DARK_THEME`.
+
+### `search.rs`: Search engine
-### `search.rs` — Search engine
- **`SearchMode`**: `Hex` or `Ascii`.
-- **`SearchState`**: `{ visible, query, mode, results: Vec, query_len, current_match, match_set: BTreeSet }`. The `match_set` is a precomputed O(log n) lookup table for the renderer.
-- **`parse_hex_query(s)`**: Parse `"DE AD BE EF"` or `"DEADBEEF"` into `Vec`. Requires even number of hex digits.
-- **`SearchMatchProvider`**: Implements `CellColorProvider` for search match highlighting in the matrix.
+- **`SearchState`**: `{ visible, query, mode, results: Vec, query_len, current_match, match_set: BTreeSet }`. The `match_set` holds a precomputed O(log n) lookup table for the renderer.
+- **`parse_hex_query(s)`**: Parses `"DE AD BE EF"` or `"DEADBEEF"` into `Vec`. The parser needs an even digit count.
+- **`SearchMatchProvider`**: Implements `CellColorProvider` for search matches in the matrix.
+
+### `goto.rs`: Goto address parsing
-### `goto.rs` — Goto address parsing
- **`GotoState`**: `{ draft, error }`.
-- **`parse(cursor, max_addr)`**: Accepts hex (`0xFF`, `FF`), decimal (`255`), relative (`+10`, `-5`). Clamps to `[0, max_addr]`. Pure function, fully unit-tested.
+- **`parse(cursor, max_addr)`**: Accepts hex (`0xFF`, `FF`), decimal (`255`) and relative values (`+10`, `-5`). It clamps the result to `[0, max_addr]`. Unit tests cover the function.
+
+### `editing.rs`: Inline edit state
-### `editing.rs` — Inline edit state
-- **`EditState`**: `{ addr, draft: String }`. Draft holds 0–2 uppercase hex characters. `push_char()`, `pop_char()`, `is_complete()`, `staged_byte()` (single-digit draft treated as low nibble, e.g., `"A"` → `0x0A`).
-- **`InspectorEditState`**: `{ entry_idx, addr, draft, error }`. Modal state for the inspector inline-edit flow.
+- **`EditState`**: `{ addr, draft: String }`. The draft holds 0 to 2 uppercase hex characters. Methods: `push_char()`, `pop_char()`, `is_complete()`, `staged_byte()`. A single-digit draft becomes the low nibble, so `"A"` gives `0x0A`.
+- **`InspectorEditState`**: `{ entry_idx, addr, draft, error }`. Modal state for inspector inline edits.
+
+### `write_mode.rs`: Text encoding modes
-### `write_mode.rs` — Text encoding modes
- **`WriteMode`**: `Hex`, `Ascii`, `Utf8`, `Windows1250`, `EucKr`, `Custom(usize)`.
-- **`EncodingEntry`**: `{ label, encoding_name }` for user-added encodings (persisted by host).
-- **`encode_text(text, mode, custom) -> Vec`**: Encode a single string character into bytes. Used by the inline text-typing path.
-- **`is_text_mode(mode) -> bool`**: `true` for any mode except `Hex`.
-- **`COMMON_ENCODINGS`**: Static list of 30+ `(label, encoding_rs_name)` pairs available for custom encoding entries.
-- **`remap_write_mode()`**: Re-indexes `WriteMode::Custom(i)` when items are removed from the custom list.
+- **`EncodingEntry`**: `{ label, encoding_name }` for user-added encodings. The host persists them.
+- **`encode_text(text, mode, custom) -> Vec`**: Converts one string character to bytes. The inline text typing path calls it.
+- **`is_text_mode(mode) -> bool`**: Returns `true` for every mode except `Hex`.
+- **`COMMON_ENCODINGS`**: A static list of 30+ `(label, encoding_rs_name)` pairs for custom encoding entries.
+- **`remap_write_mode()`**: Re-indexes `WriteMode::Custom(i)` when items leave the custom list.
+
+### `panel.rs`: Pane grid types
-### `panel.rs` — Pane grid types
- **`HexPanelContent`**: `Matrix`, `Inspector`, `PatternList`, `Statistics`.
-- **`HexPanel`**: Wrapper around `HexPanelContent`.
-- **`default_pane_grid() -> pane_grid::State`**: Creates the default vertical split (75/25 matrix/inspector).
+- **`HexPanel`**: A wrapper around `HexPanelContent`.
+- **`default_pane_grid() -> pane_grid::State`**: Creates the default vertical split, 75/25 matrix to inspector.
+
+### `layout.rs`: Structure overlay registry (future)
-### `layout.rs` — Structure overlay registry (future)
- **`BinaryLayout` trait**: `layout(bytes) -> Vec`.
- **`FieldSpan`**: `{ range, name, ty }`.
-- **`LayoutRegistry`**: Extension-keyed lookup table. Empty in v1 — reserved for future auto-derived structure overlays from `dispel_core`'s `#[extractor]` attributes.
+- **`LayoutRegistry`**: An extension-keyed lookup table. It is empty in v1. A future version may derive structure overlays from `dispel_core` `#[extractor]` attributes.
+
+### `byte_stats.rs`: Byte statistics and entropy
-### `byte_stats.rs` — Byte statistics & entropy
-- **`ByteStatistics`**: Counts, frequencies, min/max, Shannon entropy, structure heuristics.
+- **`ByteStatistics`**: Counts, frequencies, min/max, Shannon entropy and structure heuristics.
- **`RowEntropyCache`**: Per-row entropy values for the gutter colour band.
-- **`compute_statistics(bytes) -> ByteStatistics`**: Full analysis (async, via `Task::perform`).
+- **`compute_statistics(bytes) -> ByteStatistics`**: Full analysis. It runs asynchronously through `Task::perform`.
- **`compute_row_entropies(bytes, bpr) -> RowEntropyCache`**: Per-row entropy values.
-- **`entropy_to_color()`**: Maps entropy value to a colour for the gutter band.
-- **`StructureHeuristic`**: Detects uniform runs, high/low entropy patterns, mixed content.
+- **`entropy_to_color()`**: Maps an entropy value to a colour for the gutter band.
+- **`StructureHeuristic`**: Detects uniform runs, high and low entropy patterns and mixed content.
+
+### `vanilla_diff.rs`: Change tracking
-### `vanilla_diff.rs` — Change tracking
-- **`compute_diff(vanilla, current) -> BTreeSet`**: Linear scan comparing two byte slices, returning addresses where they differ.
+- **`compute_diff(vanilla, current) -> BTreeSet`**: Compares two byte slices in a linear scan. It returns the addresses that differ.
-### `fill_dialog.rs` — Fill selection
-- **`FillDialog`**: `{ draft, error }`. Parses a hex byte pattern string to repeat across the selected range.
+### `fill_dialog.rs`: Fill selection
-### `pattern_layout.rs` — Branch connectors
-- Types for rendering Git-log-style branch connectors in the pattern list panel for grouped patterns.
+- **`FillDialog`**: `{ draft, error }`. It parses a hex byte pattern string to repeat across the selected range.
----
+### `pattern_layout.rs`: Branch connectors
-## UI Layer (Iced-specific)
+- Types that draw Git-log-style branch connectors in the pattern list panel for grouped patterns.
+
+## UI layer (Iced-specific)
+
+### `update.rs`: Message handler
-### `update.rs` — Message handler
```rust
pub fn update(
state: &mut HexEditorState,
@@ -260,30 +243,33 @@ pub fn update(
message: HexEditorMessage,
) -> Task
```
-Pure update function (~1300 lines). Dispatches all message variants. Returns `Task::none()` for synchronous mutations, or an async `Task` for file I/O, clipboard, and analysis operations.
-
-Key handler sections:
-- Pane grid operations (click, resize, drag, split, close)
-- Cursor movement & selection (SelectAt, ExtendTo, Nav)
-- Inline editing (BeginEdit, EditTypeChar, EditBackspace, EditCancel, EditCommit)
-- Inspector (copy, begin edit, commit edit)
-- Save (delegates to config's `SavePort`)
-- Search (open, execute, toggle mode, next/prev, close)
+
+The `update()` function is pure and about 1300 lines long. It dispatches every message variant. Synchronous changes return `Task::none()`. File I/O, clipboard and analysis return an async `Task`.
+
+Handler sections:
+
+- Pane grid operations: click, resize, drag, split and close
+- Cursor movement and selection: `SelectAt`, `ExtendTo` and `Nav`
+- Inline editing: `BeginEdit`, `EditTypeChar`, `EditBackspace`, `EditCancel` and `EditCommit`
+- Inspector: copy, begin edit and commit edit
+- Save through the config `SavePort`
+- Search: open, execute, toggle mode, next, previous and close
- Goto dialog flow
-- Pattern CRUD (create, remove, clear, right-click)
+- Pattern create, remove, clear and right-click actions
- Repeated pattern dialog
-- Pattern list & group operations
-- Pattern import/export (async file dialogs)
-- Settings (theme, colour scheme, dim nulls, entropy band, minimap)
-- Write mode & encoding settings
-- Copy/Paste (clipboard)
+- Pattern list and group operations
+- Pattern import and export through async file dialogs
+- Settings: theme, colour scheme, dim nulls, entropy band and minimap
+- Write mode and encoding settings
+- Copy and paste through the clipboard
- Fill selection
-- Extend file (insert bytes at the cursor)
-- Text export (async file dialog + write)
-- Byte statistics analysis (async)
-- Navigation centering via `pending_center_on`
+- Extend file: insert bytes at the cursor
+- Text export through an async file dialog and write
+- Byte statistics analysis through async work
+- Navigation centering through `pending_center_on`
+
+### `inspector.rs`: Decoder registry
-### `inspector.rs` — Decoder registry
```rust
pub struct InspectorEntry {
pub name: String,
@@ -296,11 +282,13 @@ pub struct InspectorEntry {
pub static ENTRIES: Lazy>;
```
-15 built-in entries: u8, i8, u16, i16, u32, i32, u64, i64, f32, f64, ascii, utf8, rgb565, cstr, hex.
-Numeric entries are editable (have `encode`). The host can inject additional entries via `config.extra_entries`.
-### `coloring.rs` — Cell colouring system
-Layered provider chain pattern. Each provider implements `CellColorProvider`:
+The 15 built-in entries are u8, i8, u16, i16, u32, i32, u64 and i64. The tool also ships f32, f64, ascii, utf8, rgb565, cstr and hex. Numeric entries have `encode`, so you can edit them. The host can add entries through `config.extra_entries`.
+
+### `coloring.rs`: Cell colouring system
+
+The providers form a layered chain. Each one implements `CellColorProvider`:
+
```rust
pub trait CellColorProvider {
fn color(&self, addr: u64, byte: u8) -> (Option, Option);
@@ -308,29 +296,30 @@ pub trait CellColorProvider {
pub fn fold_color(providers, addr, byte) -> (Option, Option);
```
+
Later providers in the chain override earlier ones when they return `Some`.
-Built-in providers (in application order):
-1. **`SearchMatchProvider`** — highlights search matches and current match
-2. **`DiffVsVanillaProvider`** — highlights bytes differing from vanilla snapshot
-3. **`DirtyProvider`** — highlights bytes modified this session
-4. **`PatternBgProvider`** — applies pattern background colours
-5. **`AnnotationProvider`** — applies annotation foreground for active patterns
-6. **`SchemeProvider`** — applies the active `ColorScheme` (Monochrome/Nybble/Categories/Rainbow/Heatmap)
-7. **`DimNullsProvider`** — optionally dims `0x00` bytes
-8. **`SelectionProvider`** — highlights selection range and cursor cell
+Built-in providers in application order:
+
+1. **`SearchMatchProvider`**: highlights search matches and the current match
+2. **`DiffVsVanillaProvider`**: highlights bytes that differ from the vanilla snapshot
+3. **`DirtyProvider`**: highlights bytes changed in this session
+4. **`PatternBgProvider`**: applies pattern background colours
+5. **`AnnotationProvider`**: applies annotation foreground for active patterns
+6. **`SchemeProvider`**: applies the active `ColorScheme` (Monochrome, Nybble, Categories, Rainbow, Heatmap)
+7. **`DimNullsProvider`**: dims `0x00` bytes when enabled
+8. **`SelectionProvider`**: highlights the selection range and cursor cell
-### `theme/` — Theme system
-- **`HexEditorTheme`**: Flat struct with ~90+ colour fields covering matrix, header, selection, edit/dirty/diff, search matches, annotations, scrollbar, modals, minimap, pattern panel, statistics panel, byte-colouring schemes, pattern palettes, and Iced application palette.
-- **`DARK_THEME`**: Near-black background with warm amber/brown tones (original).
-- **`LIGHT_THEME`**: Warm parchment background for accessibility (WCAG AA).
-- Both are `const` values compiled at compile time using `const fn hex()`.
-- `ThemeVariant` enum: `Dark` / `Light` (with `Default` on `Dark`).
-- Theme includes HSL saturation/lightness params for gradient schemes (0.70 for dark, 0.35 for light).
+### `theme/`: Theme system
----
+- **`HexEditorTheme`**: A flat struct with 90+ colour fields. It covers the matrix, header, selection, edit, dirty and diff states. It also covers search matches, annotations, scrollbar, modals and minimap. Other groups are the pattern panel, statistics panel, byte-colouring schemes, pattern palettes and the Iced application palette.
+- **`DARK_THEME`**: Near-black background with warm amber and brown tones.
+- **`LIGHT_THEME`**: Warm parchment background for accessibility, WCAG AA.
+- Both are `const` values. They compile at build time through `const fn hex()`.
+- The `ThemeVariant` enum has `Dark` and `Light`, with `Default` on `Dark`.
+- The theme holds HSL saturation and lightness parameters for gradient schemes: 0.70 for dark and 0.35 for light.
-## HexEditorState (Aggregate State)
+## HexEditorState (aggregate state)
```rust
pub struct HexEditorState {
@@ -386,20 +375,19 @@ pub struct HexEditorState {
```
Key methods:
-- `load_from_path(path)` — constructs state from file (reads bytes, computes initial entropies, sets default pane layout)
-- `max_addr()` — `provider.len().saturating_sub(1)`
-- `recompute_vanilla_diff()` — linear scan, call after every write
-- `add_pattern(start, end) -> usize` — creates pattern, rebuilds lookups
-- `remove_pattern(id)` — removes pattern + orphan groups
-- `clear_patterns()` — wipes all patterns and groups
-- `rebuild_pattern_lookup()` — rebuilds `pattern_by_addr` BTreeMap
-- `recompute_row_annotations()` — rebuilds annotation map + refreshes active patterns
-- `refresh_active_patterns()` — recomputes which patterns contain the cursor
-- `invalidate_stats()` — clears cached byte statistics when content changes
----
+- `load_from_path(path)`: builds state from a file. It reads bytes, computes initial entropies and sets the default pane layout.
+- `max_addr()`: `provider.len().saturating_sub(1)`
+- `recompute_vanilla_diff()`: linear scan. Call it after every write.
+- `add_pattern(start, end) -> usize`: creates a pattern and rebuilds lookups
+- `remove_pattern(id)`: removes a pattern and orphan groups
+- `clear_patterns()`: removes all patterns and groups
+- `rebuild_pattern_lookup()`: rebuilds the `pattern_by_addr` BTreeMap
+- `recompute_row_annotations()`: rebuilds the annotation map and refreshes active patterns
+- `refresh_active_patterns()`: recomputes which patterns contain the cursor
+- `invalidate_stats()`: clears cached byte statistics when content changes
-## HexEditorConfig (Host Injection)
+## HexEditorConfig (host injection)
```rust
// domain/save.rs — plain data, no iced message types cross this boundary.
@@ -432,21 +420,16 @@ pub struct HexEditorConfig {
}
```
-Assemble the config with `HexEditorConfig::new()` and its chainable setters
-(`pane_gap`, `on_save`, `save_label`, `can_save`, `save_hint`, `extra_entries`,
-`custom_encodings`, `on_write_mode_changed`). Both embedders use this one
-builder; the standalone binary additionally uses the shared
-`standalone_config(...)` helper so its defaults cannot drift from the GUI's.
+Build the config with `HexEditorConfig::new()` and its chainable setters: `pane_gap`, `on_save`, `save_label`, `can_save`, `save_hint`, `extra_entries`, `custom_encodings` and `on_write_mode_changed`. Both embedders use this builder. The standalone binary also uses the shared `standalone_config(...)` helper to keep its defaults aligned with the GUI.
-Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can_save && on_save.is_some() && dirty_count > 0`).
+Helper methods: `save_label()`, `has_save()` and `can_save_now(state)`. The last one checks `can_save && on_save.is_some() && dirty_count > 0`.
----
+## HexEditorMessage (enum reference)
-## HexEditorMessage (Enum Reference)
-
-~48 variant categories, ~200+ total variants. All variants are `#[derive(Debug, Clone)]` and produce `iced::Task`.
+There are ~48 variant categories and ~200+ total variants. Every variant uses `#[derive(Debug, Clone)]` and produces `iced::Task`.
### Pane grid
+
| Variant | Purpose |
|---------|---------|
| `PaneClicked(pane)` | Set keyboard focus to pane |
@@ -455,17 +438,19 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can
| `SplitPane(Axis)` | Split focused pane (max 8 panes) |
| `ClosePane` | Close focused pane |
-### Cursor & selection
+### Cursor and selection
+
| Variant | Purpose |
|---------|---------|
| `SetBytesPerRow(u8)` | Set row width (any value 1–64) |
| `BytesPerRowInputChanged(String)` | Draft text of the custom bytes-per-row input |
| `BytesPerRowInputInvalid` | Custom BPR submitted with an out-of-range/non-numeric value |
-| `SelectAt(u64)` | Single click — set anchor=cursor=addr |
-| `ExtendTo(u64)` | Shift-click/drag — move cursor only |
+| `SelectAt(u64)` | Single click: set anchor=cursor=addr |
+| `ExtendTo(u64)` | Shift-click/drag: move cursor only |
| `Nav { dir, extend }` | Keyboard navigation |
### Inline editing
+
| Variant | Purpose |
|---------|---------|
| `BeginEdit(u64)` | Enter edit mode at addr |
@@ -477,6 +462,7 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can
| `WriteBytes { addr, bytes }` | Programmatic write (inspector/injection) |
### Inspector
+
| Variant | Purpose |
|---------|---------|
| `CopyInspectorValue(usize)` | Copy decoded value to clipboard |
@@ -486,6 +472,7 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can
| `CommitInspectorEdit` | Encode and write |
### Save
+
| Variant | Purpose |
|---------|---------|
| `SaveIntoRecording` | Trigger save (delegates to `SavePort`) |
@@ -493,6 +480,7 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can
| `ClearStatus` | Clear status message |
### Pattern highlighting
+
| Variant | Purpose |
|---------|---------|
| `CreatePattern` | From selection range |
@@ -502,6 +490,7 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can
| `RightClickAt(u64)` | For context menu targeting |
### Repeated pattern dialog
+
| Variant | Purpose |
|---------|---------|
| `BeginRepeatedPattern` | Open dialog from selection |
@@ -511,6 +500,7 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can
| `CloseRepeatedPattern` | Dismiss |
### Goto
+
| Variant | Purpose |
|---------|---------|
| `OpenGotoDialog` | Opens modal, focuses input |
@@ -519,6 +509,7 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can
| `CloseGotoDialog` | Dismiss |
### Search
+
| Variant | Purpose |
|---------|---------|
| `OpenSearch` | Show overlay |
@@ -527,7 +518,8 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can
| `SearchNext` / `SearchPrev` | Navigate matches |
| `CloseSearch` | Hide overlay |
-### Pattern list & groups
+### Pattern list and groups
+
| Variant | Purpose |
|---------|---------|
| `TogglePatternList` / `ToggleInspector` | Show/hide panels |
@@ -542,12 +534,14 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can
| `PatternsExported` / `PatternsImported` | Async results |
### Address format
+
| Variant | Purpose |
|---------|---------|
| `ToggleAddrFormat` | Hex ↔ decimal |
| `SetAddrFormat(bool)` | Explicit |
### Settings modal
+
| Variant | Purpose |
|---------|---------|
| `OpenSettings` / `CloseSettings` | Modal visibility |
@@ -558,7 +552,8 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can
| `SetShowMinimapEnabled(bool)` | Minimap toggle |
| `ResetSettings` | All defaults |
-### Write mode & encoding
+### Write mode and encoding
+
| Variant | Purpose |
|---------|---------|
| `SetWriteMode(WriteMode)` | Switch mode |
@@ -567,7 +562,8 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can
| `RemoveCustomEncoding(usize)` | Remove entry |
| `SetCustomEncodings(Vec)` | Bulk replace (deserialize) |
-### Copy / Paste
+### Copy and paste
+
| Variant | Purpose |
|---------|---------|
| `CopySelection` | Copy as hex text |
@@ -575,6 +571,7 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can
| `PasteContent(String)` | Parse and write |
### Fill selection
+
| Variant | Purpose |
|---------|---------|
| `BeginFill` | Open dialog |
@@ -583,6 +580,7 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can
| `CloseFill` | Dismiss |
### Extend file
+
| Variant | Purpose |
|---------|---------|
| `BeginExtend` | Open dialog (context menu at cursor) |
@@ -592,6 +590,7 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can
| `CloseExtend` | Dismiss |
### Byte statistics
+
| Variant | Purpose |
|---------|---------|
| `ToggleStats` | Show/hide panel |
@@ -601,6 +600,7 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can
| `SelectionAnalyzed(ByteStatistics)` | Async result |
### Text export
+
| Variant | Purpose |
|---------|---------|
| `OpenExportConfig` / `CloseExportConfig` | Modal visibility |
@@ -610,68 +610,69 @@ Helper methods: `save_label()`, `has_save()`, `can_save_now(state)` (checks `can
| `CommitExport` | File dialog + write |
| `TextExportCompleted(Result<...>)` | Async result |
----
-
-## HexMatrix Custom Widget
+## HexMatrix custom widget
-Located in `src/ui/view/matrix/` (5 files):
+The widget lives in `src/ui/view/matrix/` (5 files).
### `mod.rs`
-Public API: `HexMatrix` widget struct, `hex_matrix()` constructor function. Wraps `layout`, `state`, `draw`, and `event` modules.
+
+Public API: the `HexMatrix` widget struct and the `hex_matrix()` constructor. It wraps the `layout`, `state`, `draw` and `event` modules.
### `layout.rs`
-Computes the visual layout: column widths (address gutter, hex bytes grouped 8+8, ASCII column, annotation column), row height, total content height for scrolling. Returns sizing metrics consumed by the draw and event handlers.
+
+It computes column widths for the address gutter, hex bytes grouped 8+8, ASCII column and annotation column. It also computes row height and total content height for scrolling. It returns sizing metrics for the draw and event handlers.
### `state.rs`
-Internal mutable state cached between frames: scroll offset, selection/cursor visual positions, hot/cold state for click handling.
+
+Internal mutable state cached between frames: scroll offset, selection and cursor visual positions, and hot or cold state for click handling.
### `draw.rs` (~984 lines)
-The rendering core. Paints via Iced's `Renderer` (wgpu backend):
+
+The rendering core paints through Iced's `Renderer` on the wgpu backend:
+
- Address gutter with hex or decimal labels
-- Hex byte columns with 8+8 grouping and group separator lines
-- ASCII column with printable characters (0x20–0x7E), dots for non-printable
+- Hex byte columns grouped 8+8 with group separator lines
+- ASCII column with printable characters (0x20 to 0x7E) and dots for other values
- Annotation column with pattern text
-- Colour resolution via the provider chain (CellColorProvider)
-- Selection highlight, cursor cell
+- Colour resolution through the `CellColorProvider` chain
+- Selection highlight and cursor cell
- Edit-in-progress highlight
-- Scrollbar with search match dots and cursor dot
+- Scrollbar with search match dots and a cursor dot
### `event.rs` (~605 lines)
+
Mouse and keyboard event handling:
-- Click/drag selection
-- Double-click → `BeginEdit`
-- Keyboard navigation (arrows, Home/End, PageUp/Down, Ctrl+Home/End)
-- Hex digit typing → auto-starts edit
-- Shift+arrows → extend selection
-- Scroll wheel
-- All event handling defers to `HexEditorMessage` for state mutation
-**Virtualization:** Only rows in the viewport are drawn. The widget computes which rows are visible based on scroll offset and viewport height, then iterates byte addresses in that range.
+- Click and drag selection
+- Double-click to begin an edit
+- Keyboard navigation with arrows, `Home`, `End`, `PageUp`, `PageDown`, `Ctrl+Home` and `Ctrl+End`
+- Hex digit typing to start an edit
+- Shift with arrows to extend the selection
+- Scroll wheel
+- Every event defers state mutation to `HexEditorMessage`
----
+**Virtualization:** The widget draws only rows in the viewport. It computes visible rows from the scroll offset and viewport height. It then iterates byte addresses in that range.
-## Coloring System
+## The coloring system
The hex matrix resolves cell colours through a layered provider chain. The application order in `draw.rs` is:
-1. **Search match** — `SearchMatchProvider` highlights all bytes in search results (green tones)
-2. **Diff vs vanilla** — `DiffVsVanillaProvider` shows cumulative changes from on-disk snapshot
-3. **Dirty bytes** — `DirtyProvider` shows bytes modified this session
-4. **Pattern background** — `PatternBgProvider` applies pattern background colours
-5. **Pattern annotation** — `AnnotationProvider` adjusts foreground for active pattern annotations
-6. **Colour scheme** — `SchemeProvider` applies the base font colour (Monochrome/Nybble/Categories/Rainbow/Heatmap)
-7. **Dim nulls** — `DimNullsProvider` optionally dims `0x00` bytes
-8. **Selection** — `SelectionProvider` paints selection range and cursor cell
+1. **Search match:** `SearchMatchProvider` highlights all bytes in search results with green tones
+2. **Diff vs vanilla:** `DiffVsVanillaProvider` shows cumulative changes from the on-disk snapshot
+3. **Dirty bytes:** `DirtyProvider` shows bytes changed in this session
+4. **Pattern background:** `PatternBgProvider` applies pattern background colours
+5. **Pattern annotation:** `AnnotationProvider` adjusts foreground for active pattern annotations
+6. **Colour scheme:** `SchemeProvider` applies the base font colour (Monochrome, Nybble, Categories, Rainbow, Heatmap)
+7. **Dim nulls:** `DimNullsProvider` dims `0x00` bytes when enabled
+8. **Selection:** `SelectionProvider` paints the selection range and cursor cell
-Each provider returns `(Option, Option)`. `fold_color()` merges them: later providers override earlier ones. This means search highlights take priority over dirty/diff, which take priority over patterns, which take priority over the base scheme.
+Each provider returns `(Option, Option)`. `fold_color()` merges the results. Later providers override earlier ones. Search highlights take priority over dirty and diff colours. Those take priority over patterns. Patterns take priority over the base scheme.
-**`default_byte_colors(scheme, byte, dim_nulls)`** is the convenience function used by both the matrix widget and the settings-modal palette preview to ensure consistency.
+`default_byte_colors(scheme, byte, dim_nulls)` is the shared convenience function. The matrix widget and the settings modal palette preview both call it.
----
+## Inspector decoder system
-## Inspector Decoder System
-
-15 built-in `InspectorEntry` values in `ENTRIES` lazy static:
+15 built-in `InspectorEntry` values live in the `ENTRIES` lazy static:
| Name | Size | Editable | Category |
|------|------|----------|----------|
@@ -691,82 +692,84 @@ Each provider returns `(Option, Option)`. `fold_color()` merges them: la
| cstr | 1 | No | Text |
| hex | 1 | No | Binary |
-Each entry has a `decode` function that converts bytes to a display string, and optionally an `encode` function that parses user input and produces bytes.
-
-The host can add entries via `config.extra_entries`. The update handler selects between built-in and extra entries based on index: indices below `ENTRIES.len()` are built-in; higher indices index into `config.extra_entries`.
+Each entry has a `decode` function that converts bytes to a display string. Entries with an `encode` function also parse user input into bytes.
----
+The host can add entries through `config.extra_entries`. The update handler picks between built-in and extra entries by index. Indices below `ENTRIES.len()` refer to built-in entries. Higher indices refer to `config.extra_entries`.
-## Pattern System
+## Pattern system
### Data model
-- **`Pattern`**: Serializable struct with id, byte range, colour index (0–15, cyclic palette), optional group id, optional annotation string.
-- **`RepeatedPatternGroup`**: Named group with shared colour. All child patterns inherit the group's colour.
+
+- **`Pattern`**: A serializable struct with id, byte range, colour index (0 to 15, cyclic palette), optional group id and optional annotation string.
+- **`RepeatedPatternGroup`**: A named group with a shared colour. Child patterns inherit the group colour.
### Lookup structures
-- **`pattern_by_addr: BTreeMap`**: Maps every byte address to the pattern id and colour index that covers it. Rebuilt on every pattern mutation.
-- **`row_annotations: BTreeMap>`**: Maps row start addresses to annotation segments for the annotation column. Rebuilt on every pattern mutation.
-- **`active_patterns: BTreeSet`**: Pattern ids whose span includes the cursor. Refreshed on cursor movement.
+
+- **`pattern_by_addr: BTreeMap`**: Maps every byte address to its pattern id and colour index. A pattern mutation triggers a rebuild.
+- **`row_annotations: BTreeMap>`**: Maps row start addresses to annotation segments for the annotation column. A pattern mutation triggers a rebuild.
+- **`active_patterns: BTreeSet`**: Pattern ids whose span includes the cursor. Cursor movement refreshes this set.
### Creation flow
-1. User selects a byte range
-2. Right-click → "Create Pattern" or `Ctrl+E`
-3. `add_pattern(start, end)` creates `Pattern { id, start, end, color_idx }`, rebuilds lookups
+
+1. The user selects a byte range.
+2. The user right-clicks and chooses `Create Pattern`, or presses `Ctrl+E`.
+3. `add_pattern(start, end)` creates `Pattern { id, start, end, color_idx }` and rebuilds lookups.
### Repeated pattern flow
-1. User selects a block
-2. Right-click → "Add Repeated Pattern"
-3. Modal: enter repeat count and group label
-4. `CommitRepeatedPattern` creates alternating-colour `Pattern` entries, auto-fills annotations as `"GroupName[0]"`, `"GroupName[1]"`, etc.
-5. Group rename updates child annotations matching `"{old_label}[{digits}]"` pattern
-### Import/Export
-Patterns export as JSON via `PatternExport` struct (versioned, currently v1). Async file dialog flow.
+1. The user selects a block.
+2. The user right-clicks and chooses `Add Repeated Pattern`.
+3. The modal asks for a repeat count and a group label.
+4. `CommitRepeatedPattern` creates alternating-colour `Pattern` entries. It fills annotations such as `"GroupName[0]"` and `"GroupName[1]"`.
+5. A group rename updates child annotations that match `"{old_label}[{digits}]"`.
+
+### Import and export
----
+Patterns export as JSON through the `PatternExport` struct, currently v1. The flow uses an async file dialog.
-## Writing / Inline Editing
+## Inline editing and writing
### Hex mode (default)
-1. User presses a hex digit → auto-creates `EditState{ addr: cursor, draft: "" }` and appends the digit
-2. Second digit appended → auto-commits: `provider.write(addr, byte)`, advances cursor +1, creates new `EditState` at next address
-3. `Tab`/`Enter` → `EditCommit { advance: true }`: commit current draft (or nothing if empty), advance cursor
-4. `Esc` → `EditCancel`: discard draft
+
+1. A hex digit starts `EditState{ addr: cursor, draft: "" }` and appends the digit.
+2. A second digit commits the byte through `provider.write(addr, byte)`. The cursor advances by one. A new `EditState` starts at the next address.
+3. `Tab` or `Enter` sends `EditCommit { advance: true }`. It commits a nonempty draft and advances the cursor.
+4. `Esc` sends `EditCancel` and discards the draft.
### Text mode (ASCII, UTF-8, Windows-1250, EUC-KR, Custom)
-1. User types any printable character → immediately encoded via `encode_text()`, written to buffer, cursor advanced by encoded byte count
-2. No draft — each character is written atomically
-3. `Backspace` moves cursor left by one byte (no delete)
-4. `Delete` key writes 0x00 at cursor and advances
+
+1. A printable character goes through `encode_text()`. The tool writes the bytes and advances the cursor by the encoded byte count.
+2. There is no draft. The tool writes each character atomically.
+3. `Backspace` moves the cursor left by one byte. It does not delete.
+4. `Delete` writes 0x00 at the cursor and advances.
### Inspector edit
-1. User clicks "Edit" on an inspector entry → `BeginInspectorEdit(idx)` opens modal with pre-filled current value
-2. User edits draft → `SetInspectorDraft(String)`
-3. User confirms → `CommitInspectorEdit`: calls entry's `encode(&draft)`, writes bytes, closes modal
----
+1. The user clicks `Edit` on an inspector entry. `BeginInspectorEdit(idx)` opens a modal with the current value.
+2. `SetInspectorDraft(String)` updates the draft.
+3. `CommitInspectorEdit` calls the entry's `encode(&draft)`, writes bytes and closes the modal.
-## Search & Navigation
+## Search and navigation
### Search
+
- Two modes: Hex (`"DE AD BE EF"` or `"DEADBEEF"`) and ASCII (`"hello"`)
-- Results are `Vec` of match start addresses, pre-computed on every query change
-- `match_set: BTreeSet` for O(log n) lookup during rendering
-- Current match highlighted differently from other matches
-- Next/prev wrap around
-- Search overlay appears below toolbar, rendered in `search_overlay.rs`
+- Results are `Vec` of match start addresses. The tool precomputes them on every query change.
+- `match_set: BTreeSet` supports O(log n) lookup during rendering
+- The current match uses a different highlight
+- Next and previous wrap around
+- The search overlay sits below the toolbar and lives in `search_overlay.rs`
### Goto
-- Modal dialog activated by `Ctrl+G`
-- Input parsing: `0xFF` (hex prefix), `FF` (hex-detected if contains a-f), `255` (decimal), `+10` (relative forward), `-5` (relative backward)
-- On commit: selection jumps to target address, viewport centers on it via `pending_center_on`
-- Backed by `GotoState.parse(cursor, max_addr)`, fully unit-tested
----
+- The modal dialog opens with `Ctrl+G`.
+- Input parsing: `0xFF` has a hex prefix. The tool treats `FF` as hex when it contains a-f. `255` is decimal. `+10` moves forward. `-5` moves backward.
+- On commit, the selection jumps to the target address. The viewport centers on it through `pending_center_on`.
+- The flow uses `GotoState.parse(cursor, max_addr)`, which has full unit tests.
-## Write Modes & Text Encoding
+## Write modes and text encoding
-The `WriteMode` enum controls how keyboard input is interpreted:
+The `WriteMode` enum controls how keyboard input becomes bytes:
| Mode | Input → Bytes | Use case |
|------|--------------|----------|
@@ -777,71 +780,66 @@ The `WriteMode` enum controls how keyboard input is interpreted:
| `EucKr` | Each char → 1–2 bytes via encoding_rs | Korean text |
| `Custom(idx)` | Via `encoding_rs` for user-added encoding | Any encoding_rs-supported encoding |
-Users can add custom encodings from a list of 30+ `COMMON_ENCODINGS` via the encoding settings modal.
+Users can add custom encodings from a list of 30+ `COMMON_ENCODINGS` through the encoding settings modal.
-**Serde:** `WriteMode` serializes as string label. `Custom` stores its label, not index — index is resolved at deserialization through the custom encoding list.
+`WriteMode` serializes as a string label through Serde. `Custom` stores its label rather than its index. Deserialization resolves the index through the custom encoding list.
----
+## Byte statistics and entropy panel
-## Byte Statistics & Entropy Panel
+A toggleable panel shows:
-Toggleable panel showing:
-- **Byte distribution histogram** (bar chart of byte value frequencies)
-- **Shannon entropy** (file-level and per-row)
-- **Structure heuristics** (uniform runs, high/low entropy regions, mixed content)
-- **Entropy colour band** in the address gutter (visual entropy fingerprint)
+- **Byte distribution histogram:** a bar chart of byte value frequencies
+- **Shannon entropy:** file level and per row
+- **Structure heuristics:** uniform runs, high and low entropy regions, mixed content
+- **Entropy colour band** in the address gutter, a visual entropy fingerprint
-All analysis runs async via `Task::perform`. Selection-only analysis available. Statistics are cached and invalidated on content change or row-width change.
+All analysis runs asynchronously through `Task::perform`. The tool also analyzes the selection only. It caches statistics and invalidates them when content or row width changes.
----
+## Pane grid layout
-## Pane Grid Layout
+The editor uses the Halloy pattern for panes: `pane_grid::State` with movable, splittable, resizable panels.
-Hex editor uses the **Halloy pattern** for pane management: `pane_grid::State` with movable, splittable, resizable panels.
-
-**Default layout:** Vertical split — 75% hex matrix (left), 25% inspector (right).
+**Default layout:** a vertical split with 75% hex matrix on the left and 25% inspector on the right.
**Panel types** (`HexPanelContent`):
-- `Matrix` — The main hex byte display (always present)
-- `Inspector` — Decoded value inspector (shown by default)
-- `PatternList` — Pattern management panel (toggled via toolbar)
-- `Statistics` — Byte statistics & entropy panel (toggled via toolbar)
+
+- `Matrix`: the main hex byte display, always present
+- `Inspector`: decoded value inspector, shown by default
+- `PatternList`: pattern management panel, opened from the toolbar
+- `Statistics`: byte statistics and entropy panel, opened from the toolbar
**Operations:**
-- Panels can be split (`SplitPane`) up to 8 total
-- Panels can be reordered via drag (`PaneDragged`)
-- Panels can be closed (`ClosePane`, minimum 1 panel)
-- Focused panel receives keyboard input
-- Divider resize with configurable gap (`config.pane_gap`)
----
+- Split a panel with `SplitPane`, up to 8 total
+- Reorder panels by drag with `PaneDragged`
+- Close panels with `ClosePane`, with at least 1 left
+- The focused panel receives keyboard input
+- Resize dividers with the configurable `config.pane_gap`
## Minimap
-Overview strip at the bottom of the matrix panel shows:
-- **File structure** — each row of the minimap represents many file rows (pixel-per-row mapping)
-- **Cursor marker** — shows current position in the file
-- **Dirty/diff pixels** — shows which regions have been modified
-- Cached as `RefCell>` to avoid recomputing every frame
+An overview strip at the bottom of the matrix panel shows:
----
+- **File structure:** each minimap row represents many file rows through a pixel-per-row mapping
+- **Cursor marker:** the current position in the file
+- **Dirty and diff pixels:** the regions that changed
-## Theme System
+The tool caches the strip as `RefCell >` to avoid recomputing every frame.
-All colours consolidated into `HexEditorTheme` — a flat struct with ~90+ fields. Two built-in compile-time constants:
+## Theme system
-- **`DARK_THEME`**: Leather/amber (original). Near-black background `#14110f`, warm text `#d4cabd`, amber accents.
-- **`LIGHT_THEME`**: Warm parchment. Background `#F5EDE0`, dark text `#3A3228`, blue selection.
+All colours live in `HexEditorTheme`, a flat struct with 90+ fields. Two constants compile at build time:
-Both themes meet WCAG AA contrast ratio (4.5:1) for normal-size text across all byte colouring schemes (with the intentional exception of `dim_nulls` for `0x00`).
+- **`DARK_THEME`:** leather and amber, the original theme. Near-black background `#14110f`, warm text `#d4cabd` and amber accents.
+- **`LIGHT_THEME`:** warm parchment. Background `#F5EDE0`, dark text `#3A3228` and blue selection.
-The theme is stored as `&'static HexEditorTheme` on state (a reference to the static constant), so switching themes is just changing the pointer. The `ThemeVariant` enum tracks which is active for the settings UI.
+Both themes meet WCAG AA contrast ratio (4.5:1) for normal-size text across all byte colouring schemes. `dim_nulls` for `0x00` is the exception.
----
+State holds the theme as `&'static HexEditorTheme`, a reference to the static constant. A theme change only updates the pointer. The `ThemeVariant` enum tracks the active theme for the settings UI.
-## Test Structure
+## Test structure
-Located in `src/tests/`, using `iced_test::Simulator` for end-to-end view→update→view pipeline tests:
+Files in `src/tests/` use `iced_test::Simulator` for end-to-end view-update-view pipeline tests:
| File | Tests |
|------|-------|
@@ -860,8 +858,6 @@ Located in `src/tests/`, using `iced_test::Simulator` for end-to-end view→upda
| `toolbar.rs` | Toolbar buttons visibility |
| `pane_grid.rs` | Pane split, close, focus |
----
-
## Usage (library)
```rust
@@ -889,12 +885,7 @@ fn view(&self) -> iced::Element<'_, HexEditorMessage> {
}
```
-The host app provides a `SavePort` callback in `HexEditorConfig` if persistence
-should be wired to mod recording or direct file saves. It receives a
-domain-level `SaveRequest` (path + current bytes) and returns a task producing
-a `SaveOutcome`; it never constructs or matches on `HexEditorMessage`.
-
----
+The host provides a `SavePort` callback in `HexEditorConfig` when persistence should connect to mod recording or direct file saves. The callback receives a domain-level `SaveRequest` with the path and current bytes. It returns a task producing a `SaveOutcome`. It never constructs or matches on `HexEditorMessage`.
## Usage (standalone binaries)
@@ -906,8 +897,6 @@ cargo run -p hexedit
cargo run -p hexedit -- path/to/file.bin
```
----
-
## Build
```bash
@@ -916,14 +905,10 @@ cargo test -p hexedit # Unit + integration tests
cargo test -p hexedit --test '' -- --ignored # All tests (including slow ones)
```
----
-
## Feature flags
`hexedit` declares no crate-specific Cargo features.
----
-
## Keybindings
| Key | Action |
@@ -943,79 +928,63 @@ cargo test -p hexedit --test '' -- --ignored # All tests (including slow one
| `Ctrl+E` | Create pattern from selection |
| Hex digit (`0-9 A-F`) | Auto-start editing at cursor |
----
-
## Dependencies
-- **Iced 0.15** — UI framework (wgpu, advanced, canvas, lazy features)
-- **gui-widgets** — Reusable Iced widgets (context menu, modal, paragraph cache)
-- **lru 0.12** — LRU cache for inspector / internal use
-- **tokio 1** — Async file I/O
-- **rfd 0.17** — File dialogs (standalone binaries)
-- **encoding_rs** — Text encoding for write modes and custom encodings
-- **serde** + **serde_json** — Pattern import/export serialization
-- **once_cell** — Lazy static for inspector entries
+- **Iced 0.15:** UI framework with wgpu, advanced, canvas and lazy features
+- **gui-widgets:** reusable Iced widgets, context menu, modal and paragraph cache
+- **lru 0.12:** LRU cache for the inspector and internal use
+- **tokio 1:** async file I/O
+- **rfd 0.17:** file dialogs for the standalone binaries
+- **encoding_rs:** text encoding for write modes and custom encodings
+- **serde** and **serde_json:** pattern import and export serialization
+- **once_cell:** lazy static for inspector entries
----
+## LLM guidance: conventions and invariants
-## LLM Guidance — Conventions & Invariants
+Keep these invariants when you change the code:
-### When modifying this code, preserve these invariants:
+1. **Domain and UI separation:** Never import Iced widget types into `src/domain/`. Domain types hold pure data with no widget dependencies. Put UI code in `src/ui/`.
-1. **Domain/UI separation:** Never import Iced widget types into `src/domain/`. Domain types should be pure data structures with no widget dependencies. UI-specific code always goes in `src/ui/`.
+2. **State mutation discipline:** All state mutation happens in `update()`. `view()` stays pure. It never mutates state, apart from reading `Cell >` through `Cell::take()` for one-frame events.
-2. **State mutation discipline:** All state mutation happens in the `update()` function. The `view()` function is pure — it never mutates state (except reading `Cell >` via `Cell::take()` for one-frame events).
+3. **Provider chain order:** The `fold_color()` chain in the matrix renderer has a fixed order: search, diff, dirty, pattern, scheme, dim and selection. A new provider must go in the right position. The order sets priority.
-3. **Provider chain order:** The `fold_color()` provider chain in the matrix rendering has a specific layered order (search → diff → dirty → pattern → scheme → dim → selection). Adding a new provider means inserting it at the correct position. The order determines priority.
+4. **Pattern lookup consistency:** After any pattern mutation (create, remove, colour change or annotation change), call `rebuild_pattern_lookup()` and `recompute_row_annotations()`. These keep address lookups and annotation rendering in sync.
-4. **Pattern lookup consistency:** After any pattern mutation (create, remove, update colour, update annotation), you MUST call `rebuild_pattern_lookup()` + `recompute_row_annotations()` to keep address-based lookups and annotation rendering in sync.
+5. **Vanilla diff freshness:** Call `recompute_vanilla_diff()` after every `provider.write()` call. The linear scan is cheap. If you skip it, the diff highlighting becomes stale.
-5. **Vanilla diff freshness:** Call `recompute_vanilla_diff()` after every `provider.write()` call. It's a linear scan so it's cheap, but forgetting it will cause stale diff highlighting.
+6. **Statistics invalidation:** Call `invalidate_stats()` when file content or `bytes_per_row` changes. The tool caches statistics and computes them through async work.
-6. **Statistics invalidation:** Call `invalidate_stats()` whenever file content changes or `bytes_per_row` changes. Statistics are cached and computed async.
+7. **Error string handling:** Do not use `"."` or empty strings for errors. The host shows `status_msg` to the user. `error` records load-time failures. Both should be informative.
-7. **Error string handling:** Never use `"."` or empty strings for error cases. The host uses `status_msg` for user-facing messages and `error` for load-time failures. Both should be informative.
+8. **Message return discipline:** `update()` returns `Task`. Synchronous mutations return `Task::none()`. Async work (file I/O, clipboard, analysis) returns `Task::perform(...)`. Do not return `Task::none()` from an update that should produce follow-up messages.
-8. **Message return discipline:** The `update()` function returns `Task`. Synchronous mutations return `Task::none()`. Async operations (file I/O, clipboard, analysis) return a `Task::perform(...)`. Never return `Task::none()` from an update that should produce follow-up messages.
+9. **Pane count limit:** The maximum is 8 panes. Before a split, the `SplitPane` handler checks `state.panes.len() < 8`.
-9. **Pane count limit:** Maximum 8 panes (`state.panes.len() < 8` check before split). Enforced in the `SplitPane` handler.
+10. **Bytes-per-row validation:** Any value in `MIN_BYTES_PER_ROW..=MAX_BYTES_PER_ROW` (1 to 64) is valid. The `SetBytesPerRow` handler enforces the range. The settings modal custom input goes through `parse_bpr()` and shows a status message for invalid values. A BPR change also re-lays out pattern annotations through `recompute_row_annotations()`. The tool keys annotations by `row * bpr`.
-10. **Bytes-per-row validation:** Any value in `MIN_BYTES_PER_ROW..=MAX_BYTES_PER_ROW`
- (1–64) is valid. The `SetBytesPerRow` handler enforces this range; the settings
- modal's custom input goes through `parse_bpr()` and surfaces a status message
- for invalid submissions. Note that a BPR change also re-lays-out pattern
- annotations (`recompute_row_annotations()`) since they're keyed by `row * bpr`.
+11. **ParagraphCache:** The app shares `state.cache` across frames. The widget gets a cheap clone each frame. Use it for shaped text that survives between frames.
-11. **ParagraphCache:** The `state.cache` is shared across frames. It's cheaply cloned into the widget each frame. Always use it for shaped text that survives between frames.
+12. **Test pattern:** Integration tests use `iced_test::Simulator`. Construct state, call `view()`, assert the widget tree with `ui.find()`, send messages through `update()` and check the view again. See `tests/` for examples.
-12. **Test pattern:** Integration tests use `iced_test::Simulator`: construct state, call `view()`, assert widget tree with `ui.find()`, send messages via `update()`, re-check view. See `tests/` for examples.
+13. **New decoder:**
-13. **Adding a new decoder:**
- - Add a `dec_*` function and optional `enc_*` function in `ui/inspector.rs`
+ - Add a `dec_*` function and an optional `enc_*` function in `ui/inspector.rs`
- Add an `entry()` call in the `ENTRIES` lazy static
- Add a `call_decode` test in the `#[cfg(test)]` block
- - The host can also add entries via `config.extra_entries` (no code change needed)
+ - The host can also add entries through `config.extra_entries` without a code change
-14. **When adding a new message variant:**
- - Add the variant to `HexEditorMessage` in `message.rs`
- - Add a handler arm in the `match` in `update.rs`
- - Wire the update handler to any async returns or state mutations
- - If the message changes the view, write an iced_test for it
+14. **New message variant:**
----
+ - Add the variant to `HexEditorMessage` in `message.rs`
+ - Add a handler arm to the `match` in `update.rs`
+ - Connect async returns and state mutations to the handler
+ - Write an iced_test for the message if it changes the view
## Project context
-hexedit is part of the [Dispel RPG modding toolkit](https://github.com/piotr/dispel-extractor),
-a 5-crate Rust workspace. It powers the hex editor tab inside `dispel-gui` and can also
-be used standalone for general-purpose binary editing.
-
-**DISPEL®** is a registered trademark. This project is **not affiliated with, endorsed by,
-or sponsored by** the trademark owner.
-
----
+hexedit is part of the [Dispel RPG modding toolkit](https://github.com/piotr/dispel-extractor), a 6-crate Rust workspace: root `dispel-extractor`, `dispel-encodings`, `dispel-gui`, `dispel-macros`, `gui-widgets` and `hexedit`. It powers the hex editor tab inside `dispel-gui`. You can also use it standalone for general binary editing.
## License
-Like the rest of the Dispel Extractor workspace, this crate is distributed under
-the terms of the project license.
+The MIT License (LICENSE) covers `hexedit`.
From 958cf5280678a6a48061e7888527912827d18e63 Mon Sep 17 00:00:00 2001
From: dimspell <141545384+dimspell@users.noreply.github.com>
Date: Wed, 25 Nov 2026 13:41:34 +0100
Subject: [PATCH 04/72] docs: rewrite nine format documents in plain English
---
docs/files/AllMap.ini.md | 38 ++++------
docs/files/CROSS_REFERENCES.md | 45 +++++-------
docs/files/Event.ini.md | 106 +++++++++++++---------------
docs/files/Extra.ini.md | 84 ++++++++++------------
docs/files/Npc.ini.md | 68 +++++++++---------
docs/files/Save.ifo.md | 18 ++---
docs/files/SaveFile.md | 123 ++++++++++-----------------------
docs/files/Sprites.spr.md | 9 +--
docs/files/Wave.ini.md | 19 ++---
9 files changed, 195 insertions(+), 315 deletions(-)
diff --git a/docs/files/AllMap.ini.md b/docs/files/AllMap.ini.md
index 70b38088..5f2f2e06 100644
--- a/docs/files/AllMap.ini.md
+++ b/docs/files/AllMap.ini.md
@@ -1,27 +1,23 @@
-# AllMap.ini Documentation
+# AllMap.ini documentation
-> **DISPEL®** is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark
-> owner.
-
-## File Information
+## File information
- **Location**: `Dispel/AllMap.ini` (relative to game installation directory)
- **Encoding**: WINDOWS-1250
- **Format**: CSV (Comma-Separated Values)
-- **Comment lines**: Lines starting with `;` are ignored
+- **Comment lines**: The parser ignores lines starting with `;`
-`AllMap.ini` is a master map list file used by the game engine to index all available maps and their associated
-resources.
+The tool reads `AllMap.ini` as a master map list. Each row links a map ID to a map file name, two dialogue file names and a lighting value.
## Structure
-Each line represents one map with the following fields:
+Each non-comment line holds six comma-separated fields:
```
id,map_file,name,pgp,dlg,lit
```
-### Field Definitions
+### Field definitions
| Field | Type | Description |
|------------|-------------|---------------------------------------------------------------|
@@ -32,7 +28,7 @@ id,map_file,name,pgp,dlg,lit
| `dlg` | String/Null | Dialog text filename or "null" if absent |
| `lit` | Integer | Lighting indicator: `0` = dark/dungeon, `1` = lit/outdoor |
-### Example Entries
+### Example entries
```
1,cat1,Forest,Pgpcat1.pgp,Dlgcat1.dlg,1
@@ -40,26 +36,20 @@ id,map_file,name,pgp,dlg,lit
3,cat3,Village,null,null,1
```
-### Special Values
-
-- **"null"**: Used for `pgp` and `dlg` fields when the file is absent
-- **Lighting**: `0` indicates dark/dungeon maps, `1` indicates lit/outdoor maps
+### Special values
-## Purpose
+- **"null"**: The tool reads this string when a `pgp` or `dlg` value is absent.
+- **Light values**: `0` marks dark or dungeon maps. `1` marks lit or outdoor maps.
-This file serves as the master index for all game maps, linking map IDs to their respective filenames and metadata. The
-game engine uses this file to:
+## Tool use
-1. Load the correct map files
-2. Associate party (PGP) and dialog (DLG) files with maps
-3. Determine lighting conditions for rendering
+The tool links each map ID to a map file name. It also stores the dialogue file names and the lighting value.
## Parser
-The file is parsed by the `Map` struct in `src/references/all_map_ini.rs`, which implements the `Extractor` and
-`Localizable` traits.
+The `Map` struct in `src/references/all_map_ini.rs` parses the file. It implements the `Extractor` and `Localizable` traits.
-### How to Run
+### How to run
```bash
# Extract AllMap.ini to JSON
diff --git a/docs/files/CROSS_REFERENCES.md b/docs/files/CROSS_REFERENCES.md
index cf84d032..2a821570 100644
--- a/docs/files/CROSS_REFERENCES.md
+++ b/docs/files/CROSS_REFERENCES.md
@@ -1,9 +1,8 @@
-# Dispel Game File System - Cross References
+# Dispel game file system: cross references
## Overview
-This document maps the relationships and cross-references between all game data files in the Dispel game system. The
-files form a complex interconnected database that drives the game's mechanics, visuals, and interactions.
+This document maps the cross references between game data files. The tool reads and writes data files that you supply. Each row below links a field in one file to a file name or a field in another file.
## File Dependency Map
@@ -333,16 +332,16 @@ Message.scr (UI messages)
## Data Flow Summary
-1. **Map Loading**: AllMap.ini → Map.ini → Load map geometry (.map), place monsters (.ref), NPCs (.ref), objects (.ref)
-2. **Map Rendering**: Map.map → Map.gtl (ground tiles) + Map.btl (building tiles) + Sprites.spr (objects/NPCs)
-3. **NPC Interaction**: NpcMapFiles.ref → Npc.ini → Sprites.spr + DlgMapFiles.dlg → PgpMapFiles.pgp
-4. **Monster Combat**: MondunMonmap.ref → Monster.ini → Sprites.spr + Monster.db → Magic.db
-5. **Object Interaction**: Extra.ref → Extra.ini → Sprites.spr + Event.ini + Message.scr
-6. **Quest Progression**: Event.ini → Script files → Quest.scr
-7. **Character Development**: PartyRef.ref → PrtLevel.db → WeaponItem.db + Magic.db
-8. **Commerce**: Store.db → Item databases (WeaponItem.db, HealItem.db, etc.)
-9. **Audio**: Wave.ini → .snf files (referenced during events/dialogue)
-10. **Monster Loot**: MondunMonmap.ref → Item databases (loot drops)
+1. Map data: AllMap.ini → Map.ini → Map.map, MondunMonmap.ref, NpcMapFiles.ref and Extra.ref
+2. Map rendering: Map.map → Map.gtl (ground tiles), Map.btl (building tiles) and Sprites.spr (objects and NPCs)
+3. NPC data: NpcMapFiles.ref → Npc.ini → Sprites.spr, and DlgMapFiles.dlg → PgpMapFiles.pgp
+4. Monster data: MondunMonmap.ref → Monster.ini → Sprites.spr, and Monster.db → Magic.db
+5. Object data: Extra.ref → Extra.ini → Sprites.spr, Event.ini and Message.scr
+6. Quest data: Event.ini → script files → Quest.scr
+7. Character data: PartyRef.ref → PrtLevel.db → WeaponItem.db and Magic.db
+8. Commerce data: Store.db → item databases such as WeaponItem.db and HealItem.db
+9. Audio data: Wave.ini → .snf files
+10. Monster loot: MondunMonmap.ref → item databases
## Item Database Relationships
@@ -393,20 +392,13 @@ MiscItem.db (generic utility items)
| WINDOWS-1250 | AllMap.ini, Monster.ini, Store.db, WeaponItem.db, HealItem.db (names), MiscItem.db, EditItem.db, EventItem.db, Message.scr, Quest.scr, PgpMapFiles.pgp, Extra.ref, NpcMapFiles.ref, PartyRef.ref, Eventnpc.ref |
| Binary | Monster.db, WeaponItem.db, HealItem.db, MiscItem.db, EditItem.db, EventItem.db, Store.db, ChData.db, PrtLevel.db, Magic.db, DrawItem.db, Map.map, Map.gtl, Map.btl, Sprites.spr |
-## Legal Compliance
+## Scope
-This cross-reference documentation:
+The tool reads and writes data files that you supply. This document lists the field links between those files.
-- Describes **technical relationships between file formats only**
-- Does **not distribute any copyrighted game content**
-- Focuses on **data structure organization and system design**
-- Uses **generic descriptions** of game mechanics
-- Maintains **nominative use** for trademark references
-- Is intended for **independent interoperability research based on observable behavior** only, without circumvention of technological protection measures
+## Extractor commands
-## Extractor Commands
-
-The extractor tool (`src/`) provides commands to parse and extract data from all game files.
+The tool in `src/` parses and extracts data from game files. Run these commands from the repository root.
### Quick Reference
@@ -464,8 +456,3 @@ cargo run -- sound "path/to/file.snf" "output.wav"
# Import to SQLite database
cargo run -- database import "path/to/Dispel/" "database.sqlite"
```
-
----
-
-**DISPEL®** is a registered trademark. This documentation is **not affiliated with, endorsed by, or sponsored by** the
-trademark owner.
diff --git a/docs/files/Event.ini.md b/docs/files/Event.ini.md
index b4fa1d63..27821598 100644
--- a/docs/files/Event.ini.md
+++ b/docs/files/Event.ini.md
@@ -1,22 +1,18 @@
-# Event.ini Documentation
+# Event.ini documentation
-> **DISPEL®** is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark
-> owner.
-
-## File Information
+## File information
### Overview
-Text file that defines event scripts with execution conditions, prerequisites, and repetition limits for the game's
-event system.
+The tool reads `Event.ini` as a CSV file with comments. Each row holds an event ID, a prerequisite ID, a type code, a script filename and a counter.
-### File Structure
+### File structure
-**Location**: `Event.ini`
-**Encoding**: EUC-KR (Korean character encoding)
-**Format**: CSV (Comma-Separated Values) with comments
+- **Location**: `Event.ini`
+- **Encoding**: EUC-KR (Korean character encoding)
+- **Format**: CSV (Comma-Separated Values) with comments
-### Format Specification
+### Format specification
```ini
; Comment line explaining event types and execution conditions
@@ -27,7 +23,7 @@ event_id,required_event_id,event_type,script_filename,counter
...
```
-### Field Definitions
+### Field definitions
| Field | Type | Description |
|-------------------|--------|-----------------------------------------------------|
@@ -37,9 +33,9 @@ event_id,required_event_id,event_type,script_filename,counter
| script_filename | string | Script filename or "null" for no script |
| counter | i32 | Execution limit (0 = unlimited, N = max executions) |
-### Event Type System
+### Event type system
-The file includes a detailed comment header explaining the event type system:
+The file carries a comment header that defines the type codes:
```ini
; Event number, preceding event identifier, type:
@@ -55,31 +51,29 @@ The file includes a detailed comment header explaining the event type system:
; Script filename, number of times to execute (N)
```
-### Event Type Details
+### Event type details
-**Unconditional Execution (Types 0, 1, 2):**
+**Unconditional execution (types 0, 1 and 2):**
-- Execute regardless of previous event status
-- Type 0: Execute once
-- Type 1: Execute N times (uses counter)
-- Type 2: Execute unconditionally
+- Type 0 uses one execution and ignores the prerequisite.
+- Type 1 uses `N` executions through the counter and ignores the prerequisite.
+- Type 2 has no counter and ignores the prerequisite.
-**Conditional Execution (Types 3-8):**
+**Conditional execution (types 3 to 8):**
-- Execution depends on previous event status
-- Types 3-5: Execute when previous event unsatisfied
-- Types 6-8: Execute when previous event satisfied
-- Types 4, 7, 8: Use counter for repetition limits
+- Types 3 to 5 use an unsatisfied prerequisite.
+- Types 6 to 8 use a satisfied prerequisite.
+- Types 4, 7 and 8 use the counter for repetition limits.
-### Special Values
+### Special values
-- **"null"**: Literal string indicating no script filename
-- **counter = 0**: No execution limit (infinite)
-- **counter = N**: Maximum execution count
-- **;**: Lines starting with semicolon are comments
-- **Empty lines**: Ignored during processing
+- **"null"**: The tool reads this string when no script filename is present.
+- **counter = 0**: No execution limit.
+- **counter = N**: Maximum execution count.
+- **`;`**: Lines starting with this mark are comments.
+- **Empty lines**: The parser ignores them.
-### Example Format
+### Example format
```ini
; Default data
@@ -94,48 +88,42 @@ The file includes a detailed comment header explaining the event type system:
11,10,7,transition.scr,3
```
-### Technical Details
+### Technical details
**Encoding**: EUC-KR (Extended Unix Code Korea)
-- Supports Korean characters in comments
-- Requires proper encoding handling for reading/writing
-
-**File Processing**:
+- The encoding covers Korean characters in comments.
+- The reader and writer must use this encoding.
-- Comments (lines starting with ";") are ignored
-- Empty lines are skipped
-- CSV format with comma delimiter
-- "null" literal used for missing script filenames
+**File processing:**
-### Database Integration
+- The parser ignores comment lines that start with `;`.
+- It skips empty lines.
+- It splits rows on commas.
+- It reads `null` as a missing script filename.
-- Processed by the `Event` struct in `src/references/event_ini.rs`
-- Uses the `EventType` enum from `src/references/enums.rs` for type-safe event types
-- Stored in database with all field mappings
-- Referenced by other game systems (NPC, Extra objects)
+### Database integration
-### Event Chaining
+The `Event` struct in `src/references/event_ini.rs` parses the file. The `EventType` enum in `src/references/enums.rs` holds the type value. The tool stores every field in the database. Other file formats reference event IDs.
-The system supports complex event sequences:
+### Event chains
-- **Linear Progression**: Event A → Event B → Event C
-- **Conditional Branching**: Different paths based on success/failure
-- **Parallel Events**: Multiple independent event chains
-- **Repeating Events**: Limited or unlimited execution cycles
+- Linear progression: Event A → Event B → Event C
+- Conditional branching: paths based on a prerequisite state
+- Parallel events: independent event chains
+- Repeated events: limited or unlimited execution cycles
### Notes
-- File uses Windows-style line endings (`\r\n`)
-- Comments provide detailed explanations
-- Event system forms core of game progression mechanics
-- Integrated with multiple game subsystems
+- The file uses Windows-style line endings (`\r\n`).
+- The comment header defines the type codes.
+- Event IDs link to other file formats.
## Extractor
-The file is parsed by the `Event` struct in `src/references/event_ini.rs`, which implements the `Extractor` trait.
+The `Event` struct in `src/references/event_ini.rs` parses the file. It implements the `Extractor` trait.
-### How to Run
+### How to run
```bash
# Extract Event.ini to JSON
diff --git a/docs/files/Extra.ini.md b/docs/files/Extra.ini.md
index 5685a319..0d51ef41 100644
--- a/docs/files/Extra.ini.md
+++ b/docs/files/Extra.ini.md
@@ -1,21 +1,18 @@
-# Extra.ini Documentation
+# Extra.ini documentation
-> **DISPEL®** is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark
-> owner.
-
-## File Information
+## File information
### Overview
-Text file that defines interactive-object definitions with visual assets, activation-frame settings, and descriptions.
+The tool reads `Extra.ini` as a CSV file with comments. Each row defines an interactive object with a sprite filename, an activation-frame mode and a description.
-### File Structure
+### File structure
-**Location**: `Extra.ini`
-**Encoding**: EUC-KR (Korean character encoding)
-**Format**: CSV (Comma-Separated Values) with comments
+- **Location**: `Extra.ini`
+- **Encoding**: EUC-KR (Korean character encoding)
+- **Format**: CSV (Comma-Separated Values) with comments
-### Format Specification
+### Format specification
```ini
; Comment line explaining field structure
@@ -26,7 +23,7 @@ id,sprite_filename,activation_sprite_frame_mode,description
...
```
-### Field Definitions
+### Field definitions
| Field | Type | Description |
|------------------------------|--------|---------------------------------------------------------------------------------------------------------------|
@@ -35,19 +32,17 @@ id,sprite_filename,activation_sprite_frame_mode,description
| activation_sprite_frame_mode | i32 | Selects the sprite frame used after activation for the object handlers that use this setting. |
| description | string | Editor-facing description or "null". This column is not loaded by the game into its runtime definition table. |
-### Activation-Frame Mode
-Every placed instance using the definition carries a copy of this field. For
-object handlers 5, 6, and 8, values greater than `1` choose activated sprite
-frame `1`; values `0` and `1` choose frame `0`. Observed files contain `0`,
-`1`, and `2`, so this field is not a boolean or a quest flag.
+### Activation-frame mode
+
+The placement records in `Ext*.ref` carry a copy of this value. For object handlers 5, 6 and 8, values greater than `1` select sprite frame `1`. Values `0` and `1` select frame `0`. Observed files contain `0`, `1` and `2`.
-### Text-Format Details
+### Text-format details
-- **"null"**: Literal string indicating no sprite or description
-- **;**: Lines starting with semicolon are comments
-- **Empty lines**: Ignored during processing
+- **"null"**: The tool reads this string when no sprite or description is present.
+- **`;`**: Lines starting with this mark are comments.
+- **Empty lines**: The parser ignores them.
-### Example Format
+### Example format
```ini
; Default entry
@@ -62,28 +57,25 @@ frame `1`; values `0` and `1` choose frame `0`. Observed files contain `0`,
11,unique.spr,1,Interactive object
```
-### Technical Details
+### Technical details
**Encoding**: EUC-KR (Extended Unix Code Korea)
-- Supports Korean characters in descriptions
-- Requires proper encoding handling for reading/writing
+- The encoding covers Korean characters in descriptions.
+- The reader and writer must use this encoding.
-**File Processing**:
+**File processing:**
-- Comments (lines starting with ";") are ignored
-- Empty lines are skipped
-- CSV format with comma delimiter
-- "null" literal used for missing fields
+- The parser ignores comment lines that start with `;`.
+- It skips empty lines.
+- It splits rows on commas.
+- It reads `null` as a missing field.
-### Database Integration
+### Database integration
-- Processed by the `Extra` struct in `src/references/extra_ini.rs`
-- Stored in database with all field mappings
-- Linked to object placement files (Ext*.ref)
-- Referenced by interaction and puzzle systems
+The `Extra` struct in `src/references/extra_ini.rs` parses the file. The tool stores every field in the database. Object placement files (`Ext*.ref`) reference these IDs.
-### Object Type System
+### Object type system
The codebase defines the structure for interactive objects:
@@ -98,23 +90,23 @@ pub struct Extra {
### Usage
-1. **Environment Interaction**: Defines objects players can interact with
-2. **Visual Mapping**: Links object IDs to sprite files
-3. **Activation visuals**: Selects an activated sprite frame for supported object handlers
-4. **Puzzle Systems**: Objects used in environmental puzzles
-5. **Map Placement**: Referenced by Ext*.ref placement files
+1. The tool defines objects with an ID and a sprite filename.
+2. It links object IDs to sprite files.
+3. It selects an activated sprite frame for supported handlers.
+4. Environmental puzzles can use these objects.
+5. `Ext*.ref` placement files reference the IDs.
### Notes
-- File uses Windows-style line endings (`\r\n`)
-- Descriptions use EUC-KR encoding for international characters
-- Integrated with map placement and interaction systems
+- The file uses Windows-style line endings (`\r\n`).
+- Descriptions use EUC-KR encoding for international characters.
+- The tool links these definitions to map placement files.
## Extractor
-The file is parsed by the `Extra` struct in `src/references/extra_ini.rs`, which implements the `Extractor` trait.
+The `Extra` struct in `src/references/extra_ini.rs` parses the file. It implements the `Extractor` trait.
-### How to Run
+### How to run
```bash
# Extract Extra.ini to JSON
diff --git a/docs/files/Npc.ini.md b/docs/files/Npc.ini.md
index 920337e1..6bc2d78e 100644
--- a/docs/files/Npc.ini.md
+++ b/docs/files/Npc.ini.md
@@ -1,21 +1,18 @@
-# Npc.ini Documentation
+# Npc.ini documentation
-> **DISPEL®** is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark
-> owner.
-
-## File Information
+## File information
### Overview
-Text file that defines visual appearances and descriptions for NPC (Non-Player Character) types in the game.
+The tool reads `Npc.ini` as a CSV file with comments. Each row holds a visual type ID, a sprite filename and a description.
-### File Structure
+### File structure
-**Location**: `Npc.ini`
-**Encoding**: EUC-KR (Korean character encoding)
-**Format**: CSV (Comma-Separated Values) with comments
+- **Location**: `Npc.ini`
+- **Encoding**: EUC-KR (Korean character encoding)
+- **Format**: CSV (Comma-Separated Values) with comments
-### Format Specification
+### Format specification
```ini
; Comment line
@@ -25,7 +22,7 @@ id,sprite_filename,description
...
```
-### Field Definitions
+### Field definitions
| Field | Type | Description |
|-----------------|--------|--------------------------------------------------|
@@ -33,13 +30,13 @@ id,sprite_filename,description
| sprite_filename | string | SPR filename or "null" for no sprite |
| description | string | NPC role/appearance description (EUC-KR encoded) |
-### Special Values
+### Special values
-- `null`: Literal string indicating no sprite filename
-- `;`: Lines starting with semicolon are comments
-- Empty lines are ignored
+- `null`: The tool reads this string when no sprite filename is present.
+- `;`: Lines starting with a semicolon are comments.
+- Empty lines: The parser ignores them.
-### Example Entries
+### Example entries
```ini
; Party members
@@ -55,40 +52,39 @@ id,sprite_filename,description
17,King2.spr,Royal Guard
```
-### Technical Details
+### Technical details
**Encoding**: EUC-KR (Extended Unix Code Korea)
-- Supports Korean characters used in descriptions
-- Requires proper encoding handling for reading/writing
+- The encoding covers Korean characters in descriptions.
+- The reader and writer must use this encoding.
-**File Processing**:
+**File processing:**
-- Comments (lines starting with ";") are ignored
-- Empty lines are skipped
-- CSV format with comma delimiter
-- "null" literal used for missing sprite filenames
+- The parser ignores comment lines that start with `;`.
+- It skips empty lines.
+- It splits rows on commas.
+- It reads `null` as a missing sprite filename.
### Usage
-1. Game loads NPC definitions from Npc.ini
-2. Links NPC visual types to behavior scripts
-3. Renders NPCs using specified sprite files
-4. Displays descriptions in appropriate contexts
-5. Manages NPC interactions based on type
+1. The tool reads NPC definitions from `Npc.ini`.
+2. It links visual type IDs to sprite files.
+3. It stores each description with its ID.
+4. Other file formats reference these IDs.
### Notes
-- Some entries have "null" sprite filenames when no visual is needed
-- Descriptions are in Korean (EUC-KR encoding)
-- File uses Windows-style line endings (`\r\n`)
-- IDs may have gaps in the sequence
+- Some entries have a `null` sprite filename.
+- Descriptions are in Korean and use EUC-KR encoding.
+- The file uses Windows-style line endings (`\r\n`).
+- IDs may have gaps in the sequence.
## Extractor
-The file is parsed by the `NpcIni` struct in `src/references/npc_ini.rs`, which implements the `Extractor` trait.
+The `NpcIni` struct in `src/references/npc_ini.rs` parses the file. It implements the `Extractor` trait.
-### How to Run
+### How to run
```bash
# Extract Npc.ini to JSON
diff --git a/docs/files/Save.ifo.md b/docs/files/Save.ifo.md
index 7348c421..8fed629d 100644
--- a/docs/files/Save.ifo.md
+++ b/docs/files/Save.ifo.md
@@ -1,20 +1,14 @@
# Save.ifo
-> **DISPEL®** is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark
-> owner.
-
## Purpose
-`Save.ifo` is the save-slot metadata index. It describes the six save slots (`0.sav` … `5.sav`): whether each slot is
-occupied and when it was last written. It also snapshots a small amount of global state needed to resume the session
-from the `game.tmp` append-log.
+`Save.ifo` is the save-slot metadata index. It describes six save slots (`0.sav` … `5.sav`). It records a timestamp and an occupied flag for each slot. It also holds a small global tail.
-## File Structure
+## File structure
- **Location**: `Save.ifo` (game root directory)
- **Encoding**: binary, little-endian
-- **Format**: fixed size of 224 bytes — six 32-byte slot records followed by a 32-byte global tail, addressed as two
- blocks: bytes 0–191 (slots) and 192–223 (tail).
+- **Format**: fixed size of 224 bytes with six 32-byte slot records followed by a 32-byte global tail. The tool addresses two blocks: bytes 0–191 for slots and 192–223 for the tail.
### Slot records (offsets 0–191, record *p* at *p* × 32)
@@ -42,10 +36,8 @@ from the `game.tmp` append-log.
## Usage
-Written on every save alongside the `%d.sav` payload file. The save/load menu reads it at startup and lists each
-occupied slot as `MM / DD HH : MM`. The tail snapshots the state needed to traverse the current session's payloads
-inside the `game.tmp` append-log.
+The tool reads and writes this file alongside the `%d.sav` payload files. Each occupied slot carries month, day, hour and minute values. The documented display format is `MM / DD HH : MM`. The tool preserves the tail values.
## Parser
-The Rust parser is in `src/references/save_ifo.rs` (`SaveIfo` / `SaveSlotInfo` structs, `Extractor` trait).
+The Rust parser is in `src/references/save_ifo.rs`. It defines the `SaveIfo` and `SaveSlotInfo` structs and implements the `Extractor` trait.
diff --git a/docs/files/SaveFile.md b/docs/files/SaveFile.md
index eb9a4a36..1324204c 100644
--- a/docs/files/SaveFile.md
+++ b/docs/files/SaveFile.md
@@ -1,8 +1,5 @@
# Save File Documentation
-> DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark
-> owner.
-
## File Information
- **Location**: `Dispel/Save/` directory (relative to game installation directory)
@@ -10,13 +7,11 @@
- **Format**: Binary (little-endian)
- **Extension**: `.sav` (or similar save file extension)
-The save file is a binary serialization of the player's game state, including character stats, inventory, party members,
-journal entries, and map-specific data.
+The tool reads and writes data files that you supply. This file holds character stats, inventory, party members, journal entries and map-specific data. All integers use little-endian byte order.
## Structure
-The save file is parsed sequentially from start to end. The top-level structure is defined by the `SaveFile` struct in
-`src/references/save_file/mod.rs`.
+The tool reads the file from start to end. The `SaveFile` struct in `src/references/save_file/mod.rs` defines the top-level layout.
### Top-Level Layout
@@ -43,15 +38,11 @@ The save file is parsed sequentially from start to end. The top-level structure
### Header
-The first 8 bytes contain:
-
-1. `game_tmp_blob_size` (4 bytes, `u32`): A jump address pointing to the byte offset after all map data. The reader uses
- this to seek past the map sections if needed.
-2. `number_of_visited_maps` (4 bytes, `u32`): The number of `MapSectionData` records that follow.
+The first 8 bytes hold two values. `game_tmp_blob_size` is a 4-byte `u32`. It gives the byte offset after all map data. The reader can seek to that offset. `number_of_visited_maps` is a 4-byte `u32`. It gives the count of `MapSectionData` records that follow.
### Map Sections (`maps`)
-Each visited map is serialized as a `MapSectionData` record containing:
+Each visited map uses a `MapSectionData` record with these fields:
| Field | Type | Description |
|-------------------------|---------------------------|-------------------------------------------------------------|
@@ -66,14 +57,13 @@ Each visited map is serialized as a `MapSectionData` record containing:
| `draw_items_misc` | `Vec` | Ground items — Misc type (268 bytes each) |
| `draw_items_event` | `Vec` | Ground items — Event type (252 bytes each) |
-Each collection is prefixed with a count (`u32` for monsters/NPCs/extra objects, `u16` for ground items).
+A count precedes each collection. It uses `u32` for monsters, NPCs and extra objects. It uses `u16` for ground items.
-Each ground-item record ends with a one-based `u16` ground-object ID and two preserved padding bytes. The item category
-determines the ID range used by the game.
+Each ground-item record ends with a one-based `u16` ground-object ID and two preserved padding bytes. The item category sets the ID range.
An NPC record stores an active path-step direction at byte 161 and its animation frame at byte 162. The direction values
are `0=(0,+32)`, `1=(-32,+16)`, `2=(-64,0)`, `3=(-32,-16)`,
-`4=(0,-32)`, `5=(+32,-16)`, `6=(+64,0)`, `7=(+32,+16)`, and `255=inactive`. The pairs are screen-space offsets from the
+`4=(0,-32)`, `5=(+32,-16)`, `6=(+64,0)`, `7=(+32,+16)`, and `255=inactive`. The pairs give screen-space offsets from the
destination cell.
Monster runtime data includes the current combat target, timed status-effect type and duration, movement-animation frame
@@ -81,9 +71,7 @@ and offsets, path-buffer length and index, and temporary visual effects. Tempora
and duration fields for status, ground, special-attack, guard, blood, and timed-overlay effects. Blood-effect directions
use values `0..=7`.
-The monster status-effect type uses `0=none`; observed active values are `1`,
-`2`, `3`, `4`, `7`, and `12`. Its parameter is `-1` when unused. Type `3`
-stores a monster identifier in the parameter field.
+The monster status-effect type uses `0=none`. Observed active values are `1`, `2`, `3`, `4`, `7` and `12`. Its parameter is `-1` when unused. Type `3` stores a monster identifier in the parameter field.
NPC runtime flags use these values:
@@ -94,17 +82,13 @@ NPC runtime flags use these values:
- `player_interaction_latched`: `0=not interacting`, `1=interaction started`.
- `start_dialogue_on_arrival`: `0=normal arrival`, `1=start arrival dialogue`.
-The arrival dialogue ID follows the arrival-action flag. Two intervening runtime words are reserved, initialized to
-zero, and preserved without interpretation.
+The arrival dialogue ID follows the arrival-action flag. The tool reserves two intervening runtime words. They are zero in known files. It preserves them.
-An extra-object record begins with its selected render state, render variant, and current sprite frame. It ends with the
-activation effect ID, one reserved byte, two padding bytes, the overlay flag, the map-active flag, and the pending
-interaction latch. Boolean controls use `0=disabled` and non-zero `enabled`; the pending latch uses `0=no request` and
-`1=activation requested`.
+An extra-object record starts with its selected render state, render variant and current sprite frame. It ends with the activation effect ID, one reserved byte, two padding bytes, the overlay flag, the map-active flag and the pending interaction latch. Boolean controls use `0=disabled` and non-zero `enabled`. The pending latch uses `0=no request` and `1=activation requested`.
### Post-Maps Data (`post_maps`)
-Contains save-world header values and the list of visited map IDs:
+The section holds save-world header values and a list of visited map IDs:
| Field | Type | Description |
|--------------------------------|------------|--------------------------------------------------------------------------------------------------|
@@ -120,13 +104,11 @@ Contains save-world header values and the list of visited map IDs:
| `number_of_visited_maps` | `u32` | Number of visited maps (must match the map section count) |
| `map_ids` | `Vec` | IDs of the visited maps |
-The two map identifiers address different tables. `all_map_ini_id` selects the map itself. `ref_map_ini_id` selects the
-route or entrance used to initialize that map. Multiple `Ref/Map.ini` records can target the same `AllMap.ini` map while
-providing different spawn coordinates.
+The two map identifiers address different tables. `all_map_ini_id` refers to the map entry in `AllMap.ini`. `ref_map_ini_id` refers to an entrance record in `Ref/Map.ini`. Several `Ref/Map.ini` records can share one `AllMap.ini` ID with different spawn coordinates.
### Map Viewport State (`map_viewport_state`)
-A fixed-size (10,148 bytes) serialized state of the game's isometric map viewport:
+A fixed-size block of 10,148 bytes with these fields:
| Field | Type | Description |
|--------------------------------|-------------------------|-------------------------------------------------------------------------------------------------------------------------------------|
@@ -240,9 +222,7 @@ Four fixed-size (60-byte) null-terminated WINDOWS-1250 strings representing char
| `player_class_name` | String (20 bytes) | Player class name (WINDOWS-1250, null-terminated) |
| `selected_spell_ui_index` | `u16` | UI index of selected spell |
-**Note**: The full identity block in the save file is larger than 35 bytes. The `CharacterIdentity::read_from` method
-skips over many runtime fields (inventory serial counters, waypoint data, movement state, pathfinding scratch, etc.) and
-only retains the trailing 35 bytes.
+**Note**: The full identity block in the save file is larger than 35 bytes. The `CharacterIdentity::read_from` method skips many runtime fields. These include inventory serial counters, waypoint data, movement state and pathfinding scratch. It keeps the trailing 35 bytes.
### Inventory Data (`inventory`)
@@ -256,9 +236,7 @@ Raw inventory data for 5 item categories, each prefixed with a `u16` count:
| Weapon items | 292 bytes | Weapon-type items |
| Heal items | 256 bytes | Heal-type items |
-Each item record contains a copy of its database definition followed by save-runtime fields. The runtime category is
-zero-based: `0`=weapon, `1`=heal, `2`=edit,
-`3`=misc, and `4`=event. This numbering differs from the one-based item type used by some map and object files.
+Each item record holds a copy of its database definition followed by save-runtime fields. The runtime category uses zero-based values: `0` for weapon, `1` for heal, `2` for edit, `3` for misc and `4` for event. Other map and object files use one-based item types.
| Category | Runtime fields after/copied into the definition |
|----------|--------------------------------------------------------------------------------------------|
@@ -268,9 +246,7 @@ zero-based: `0`=weapon, `1`=heal, `2`=edit,
| Weapon | Category, global inventory-instance ID |
| Heal | Reserved definition byte, category, category-local record index, two runtime scratch bytes |
-The global inventory-instance ID connects a weapon to equipped slots and connects weapon or miscellaneous items to
-inventory placement cells. Heal runtime scratch bytes are normally zero, but saved games show that they are not
-initialized consistently.
+The global inventory-instance ID links a weapon to equipped slots. It links weapon and miscellaneous items to inventory placement cells. Heal runtime scratch bytes are usually zero. Some saved games store other values.
### Inventory Slots (`inventory_slots`)
@@ -284,7 +260,7 @@ initialized consistently.
### Learned Spells (`learned_spells`)
-41 bytes, one byte per spell, indicating whether each spell has been learned.
+The block holds 41 bytes, one byte per spell. A byte holds the learned state of one spell.
### Party Members (`party_members`)
@@ -295,11 +271,7 @@ Variable-length records, each consisting of:
- An optional 52-byte combat snapshot (48 bytes + 4-byte terminator), present when the companion has an active combat
object
-The 300-byte payload is a serialized stream of overlapping four-byte runtime snapshots. Adjacent snapshots frequently
-begin one or two bytes apart. As a result, the stream repeats parts of health, mana, class, level, spell IDs, animation
-flags, coordinates, and other fields. The parser exposes the primary values and preserves each repeated snapshot tail or
-overlap under an explicit
-`*_snapshot_tail` or `*_snapshot_overlap` name.
+The 300-byte payload holds overlapping four-byte runtime snapshots. Adjacent snapshots often start one or two bytes apart. The stream repeats parts of health, mana, class, level, spell IDs, animation flags, coordinates and other fields. The parser exposes the primary values. It preserves each repeated snapshot tail or overlap under a `*_snapshot_tail` or `*_snapshot_overlap` name.
### Events (`events`)
@@ -336,8 +308,7 @@ Each dismissed-companion progression record contains three bytes:
| `companion_level` | `u8` | Companion level when the progression was retained |
| `player_level` | `u8` | Player level when the progression was retained |
-Milestone records are written at walk animation milestones (walk progress reaching `path_length - 2`, or the walk frame
-counter reaching 4). Completion records are written when a walk cycle finishes.
+The tool writes milestone records at walk animation milestones. These occur when walk progress reaches `path_length - 2` or the walk frame counter reaches 4. It writes completion records when a walk cycle finishes.
#### Walk Milestone Record (24 bytes)
@@ -404,8 +375,7 @@ counter reaching 4). Completion records are written when a walk cycle finishes.
## Binary Record Macro
-Several structs in this module use the `#[derive(BinaryRecord)]` macro from `dispel-macros`, which generates `parse` and
-`write` methods for binary serialization. The `#[binary_record(...)]` attribute controls field encoding, including:
+Several structs in this module use the `#[derive(BinaryRecord)]` macro from `dispel-macros`. The macro generates `parse` and `write` methods for binary serialization. The `#[binary_record(...)]` attribute controls field encoding:
- `string(encoding = "WINDOWS-1250", size = N)`: Fixed-size null-terminated string
- `size = N`: Fixed-size byte array
@@ -413,19 +383,16 @@ Several structs in this module use the `#[derive(BinaryRecord)]` macro from `dis
## Validation
-The writer performs preflight validation before serializing:
+The writer runs preflight validation before it writes bytes. It checks these rules:
-1. **Count limits**: All collection counts must fit in their wire types (`u16` or `u32`)
-2. **Fixed collection lengths**: Sprite paths (4), learned spells (41), events (2,251), journal entries (100 per
- section), map viewport cells (500)
-3. **Cross-field consistency**: Visited-map count must match map section count and map ID count; party member count must
- match the stored count
-4. **Trailer size validation**: Map extra-object trailer size must match the computed expected size
+1. Count limits: Each collection count must fit its wire type (`u16` or `u32`).
+2. Fixed collection lengths: Sprite paths use 4 entries, learned spells 41, events 2,251, journal entries 100 per section and map viewport cells 500.
+3. Cross-field consistency: The visited-map count must match the map section count and map ID count. The party member count must match the stored count.
+4. Trailer size: The map extra-object trailer size must match the computed expected size.
## Extractor
-The save file format is parsed by the `SaveFile` struct in `src/references/save_file/mod.rs`, which implements the
-`Extractor` trait.
+The `SaveFile` struct in `src/references/save_file/mod.rs` parses the file. It implements the `Extractor` trait.
### How to Run
@@ -439,7 +406,7 @@ cargo run -- database import "fixtures/Dispel/" "database.sqlite"
## Purpose
-This file stores the complete player game state, including:
+The file holds these values:
1. Character progression (stats, level, XP, gold)
2. Inventory and equipment
@@ -449,34 +416,16 @@ This file stores the complete player game state, including:
6. Event script flags
7. Isometric viewport state
-## Legal Notice
-
-⚠️ **DISCLAIMER**: This documentation describes technical file format specifications only. It does not distribute any
-copyrighted game content, save data, or proprietary assets. All references to save file structures are for **independent
-interoperability research based on observable behavior** to document file organization and data structures, without
-circumvention of technological protection measures.
-
-**DISPEL®** is a registered trademark. This documentation is **not affiliated with, endorsed by, or sponsored by** the
-trademark owner.
-
-### Legal Compliance
-
-This documentation:
+## Scope
-- Describes **file format specifications only**
-- Does **not** distribute any save data or game content
-- Focuses on **technical organization**, not creative content
-- Uses **generic descriptions** of file purposes
-- Maintains **nominative use** for trademark references
+The tool reads and writes data files that you supply. This document lists the file layout and field values.
## Notes
-- All integers are little-endian
-- Text fields use WINDOWS-1250 encoding
-- The `game_tmp_blob_size` field in the header acts as a jump address; the reader seeks to this offset after parsing map
- sections
-- The `CharacterIdentity` struct only retains the trailing 35 bytes of the full identity block, skipping many runtime
- fields
-- Party member records have an optional combat snapshot that is conditionally present based on a marker value
-- Reserved runtime and header fields are preserved verbatim for round-trip fidelity.
-- The writer validates all fixed-size constraints before serialization to prevent corrupt output
+- All integers are little-endian.
+- Text fields use WINDOWS-1250 encoding.
+- The `game_tmp_blob_size` field holds a jump address. The reader seeks to this offset after it parses the map sections.
+- The `CharacterIdentity` struct retains the trailing 35 bytes of the identity block. It skips many runtime fields.
+- Party member records can include a combat snapshot. A marker value controls its presence.
+- The tool preserves reserved runtime and header fields for round-trip fidelity.
+- The writer validates all fixed-size constraints before it writes output.
diff --git a/docs/files/Sprites.spr.md b/docs/files/Sprites.spr.md
index 3d0bc8bb..7be8f3ae 100644
--- a/docs/files/Sprites.spr.md
+++ b/docs/files/Sprites.spr.md
@@ -1,12 +1,9 @@
-# *.spr — Sprite File Format
-
-> **DISPEL®** is a registered trademark. This project is not affiliated with,
-> endorsed by, or sponsored by the trademark owner.
+# *.spr: sprite file format
## Scope
-This document describes the `.spr` layout that this project reads and writes.
-All integer values use little-endian byte order.
+The tool reads and writes `.spr` files with this layout. All integer values use
+little-endian byte order.
## File Summary
diff --git a/docs/files/Wave.ini.md b/docs/files/Wave.ini.md
index 0db73cad..a68e6d84 100644
--- a/docs/files/Wave.ini.md
+++ b/docs/files/Wave.ini.md
@@ -1,13 +1,10 @@
# Wave.ini
-> **DISPEL®** is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark
-> owner.
-
## Purpose
`Wave.ini` maps a sound identifier to an SNF filename and a simultaneous-playback limit.
-## File Structure
+## File structure
- **Location**: `Wave.ini`
- **Encoding**: EUC-KR
@@ -25,18 +22,10 @@
| `snf_filename` | string or `null` | Referenced SNF filename. |
| `max_simultaneous_plays` | `i32` | Maximum concurrent instances of this sound. |
-## Runtime Behavior
-
-The loader creates `max_simultaneous_plays` audio-buffer copies for each entry. Playback uses a free copy.
-
-A limit of one prevents a sound from overlapping with itself. Larger limits allow concurrent playback.
+## Field values
-This value is not a priority, channel, or loop flag.
+A value of `1` records one concurrent instance. Larger values record more concurrent instances. The field is not a priority, channel or loop flag.
## Parser
-The Rust parser is in `src/references/wave_ini.rs` (`WaveIni` struct, `Extractor` trait).
-
-## Legal Notice
-
-This document describes a file format. It contains no game records, asset names, or other game-content data.
+The Rust parser is in `src/references/wave_ini.rs`. It defines the `WaveIni` struct and implements the `Extractor` trait.
From a98ad5a47b2b249a13100f85a7e5fb042f07d1d7 Mon Sep 17 00:00:00 2001
From: dimspell <141545384+dimspell@users.noreply.github.com>
Date: Wed, 25 Nov 2026 13:45:28 +0100
Subject: [PATCH 05/72] docs: rewrite fourteen format documents in plain
English
---
docs/files/CROSS_REFERENCES.md | 2 +-
docs/files/CharacterInGame/ChData.db.md | 29 ++++++--------
docs/files/CharacterInGame/EditItem.db.md | 13 +------
docs/files/CharacterInGame/EventItem.db.md | 18 ++++-----
docs/files/CharacterInGame/HealItem.db.md | 11 ++----
docs/files/CharacterInGame/MiscItem.db.md | 17 ++++----
docs/files/CharacterInGame/Monster.ini.md | 35 ++++++++---------
docs/files/CharacterInGame/Store.db.md | 41 +++++++++-----------
docs/files/CharacterInGame/WeaponItem.db.md | 11 +-----
docs/files/MagicInGame/Magic.db.md | 22 +++++------
docs/files/MonsterInGame/MondunMonmap.ref.md | 32 +++++++--------
docs/files/MonsterInGame/Monster.db.md | 38 ++++++++----------
docs/files/Ref/DrawItem.db.md | 5 ---
docs/files/Ref/Map.ini.md | 28 ++++++-------
docs/files/Ref/PartyRef.ref.md | 40 +++++++++----------
15 files changed, 138 insertions(+), 204 deletions(-)
diff --git a/docs/files/CROSS_REFERENCES.md b/docs/files/CROSS_REFERENCES.md
index 2a821570..4bbfd287 100644
--- a/docs/files/CROSS_REFERENCES.md
+++ b/docs/files/CROSS_REFERENCES.md
@@ -451,7 +451,7 @@ cargo run -- map render --map "file.map" --btl "file.btl" --gtl "file.gtl" --out
cargo run -- map sprites "path/to/file.map"
# Convert audio
-cargo run -- sound "path/to/file.snf" "output.wav"
+cargo run -- sound to-wav "path/to/file.snf" "output.wav"
# Import to SQLite database
cargo run -- database import "path/to/Dispel/" "database.sqlite"
diff --git a/docs/files/CharacterInGame/ChData.db.md b/docs/files/CharacterInGame/ChData.db.md
index 64ea3d15..236cbcb5 100644
--- a/docs/files/CharacterInGame/ChData.db.md
+++ b/docs/files/CharacterInGame/ChData.db.md
@@ -1,7 +1,4 @@
-# ChData.db - Character Initial Attributes
-
-> DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark
-> owner.
+# ChData.db: character initial attributes
## File Information
@@ -18,7 +15,7 @@
### Class Base Attributes (32 bytes)
-16 × `i16` — Base attributes (STR, CON, WIS, AGI) for each of 4 classes:
+The tool reads 16 `i16` base attributes: STR, CON, WIS and AGI for each of 4 classes.
| Offset | Class | Fields (each i16) |
|--------|---------|--------------------|
@@ -29,12 +26,11 @@
### Reserved (2 bytes)
-- `reserved_stat`: i16 — Separator between base stats and extra points (purpose unknown)
+- `reserved_stat`: i16 between the base stats and the extra points. Purpose unknown.
### Derived Stat Bonuses (20 bytes)
-5 × `i32` — per-class derived-stat bonuses applied at character creation. Only the low byte of each is significant
-(values are small, e.g. 5). Each bonus is added to a derived combat stat:
+The tool reads 5 `i32` derived-stat bonuses, one per class. Known files store small values such as 5. Only the low byte of each value carries meaning.
| Offset | Class | Field | Derived stat | Base attr |
|--------|---------|------------------------|--------------|-----------|
@@ -44,7 +40,7 @@
| 76 | Archer | archer_hit_bonus | hit_rate | CON |
| 80 | Mage | mage_magic_power_bonus | magic_power | WIS |
-> Points-per-level is hardcoded to 5 in the game and is NOT read from this file.
+> The tool does not read a points-per-level value from this file. The documented value is 5.
## Field Details
@@ -52,7 +48,7 @@
- 30-byte WINDOWS-1250 encoded string
- Starts with "Item" magic signature
-- Otherwise unused by the game
+- The tool treats this field as unused.
### Class Attributes (warrior_strength through mage_agility)
@@ -63,16 +59,15 @@
### reserved_stat
- i16 between class attributes and extra points
-- Value in the game appears to be ignored
+- Known files store zero at this offset.
### Derived Stat Bonuses (warrior_offense_bonus through mage_magic_power_bonus)
-- 5 × i32 — per-class derived-stat bonuses. Each is added to a derived combat stat (offense, defense, dodge_rate,
- hit_rate, magic_power) for the corresponding class.
+- The tool reads 5 `i32` derived-stat bonuses. Each maps to a derived combat stat: offense, defense, dodge_rate, hit_rate or magic_power.
### mage_magic_power_bonus
-- i32 — Mage class bonus added to magic_power (WIS-derived).
+- i32 value for the Mage bonus to magic_power, which uses WIS.
## Example Usage
@@ -139,10 +134,10 @@ Bytes 80-83: mage_magic_power_bonus (i32)
### Data Types
-- `unused_name`: [u8; 30] WINDOWS-1250
-- Class attributes: [i16; 16]
+- `unused_name`: `[u8; 30]` WINDOWS-1250
+- Class attributes: `[i16; 16]`
- `reserved_stat`: i16
-- Derived stat bonuses: [i32; 4]
+- Derived stat bonuses: `[i32; 4]`
- Mage magic power bonus: i32
### Endianness
diff --git a/docs/files/CharacterInGame/EditItem.db.md b/docs/files/CharacterInGame/EditItem.db.md
index 8f7da5d7..3f67359c 100644
--- a/docs/files/CharacterInGame/EditItem.db.md
+++ b/docs/files/CharacterInGame/EditItem.db.md
@@ -1,10 +1,6 @@
# EditItem.db
-> DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark
-> owner.
-
-`CharacterInGame/EditItem.db` defines consumable item-modification materials. It is a little-endian binary file with a
-four-byte record count followed by fixed-size 268-byte records. Text is encoded as WINDOWS-1250.
+`CharacterInGame/EditItem.db` holds consumable item-modification materials. The file is little-endian. It has a four-byte record count followed by fixed-size 268-byte records. Text uses WINDOWS-1250.
## Record layout
@@ -32,12 +28,7 @@ four-byte record count followed by fixed-size 268-byte records. Text is encoded
## Runtime item ID
-The four bytes at byte offset 236 are not two independent padding fields. The on-disk database stores zero there, then
-the game loader overwrites the word with the zero-based record index. Inventory and ground-item records preserve that
-value as `edit_item_id` to link an instance back to its database definition.
-
-When writing the original database, retain the stored value (normally zero). The game will assign the runtime ID when it
-loads the file.
+Known files store zero at byte offset 236. The tool reads those four bytes as `runtime_item_id` and writes them back unchanged. Other records keep the same value in `edit_item_id`. Keep the stored value when you write the database.
## Notes
diff --git a/docs/files/CharacterInGame/EventItem.db.md b/docs/files/CharacterInGame/EventItem.db.md
index a69bef0a..d8cae94b 100644
--- a/docs/files/CharacterInGame/EventItem.db.md
+++ b/docs/files/CharacterInGame/EventItem.db.md
@@ -1,21 +1,19 @@
# EventItem.db
-> DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark
-> owner.
-
## File Information
### Overview
-Binary database file that defines quest and event items with names and descriptions for the game's quest progression and
-event triggering system.
+The tool reads `EventItem.db` as name and description records for quest and event items.
### File Structure
-**Location**: `CharacterInGame/EventItem.db`
-**Encoding**: Binary (Little-Endian)
-**Text Encoding**: WINDOWS-1250 (Central European)
-**Header**: 4-byte record count **Record Size**: 240 bytes **Total Records**: Variable (determined by header)
+- **Location**: `CharacterInGame/EventItem.db`
+- **Encoding**: Binary (Little-Endian)
+- **Text Encoding**: WINDOWS-1250 (Central European)
+- **Header**: 4-byte record count
+- **Record Size**: 240 bytes
+- **Total Records**: Variable (determined by header)
### Binary Format
@@ -91,7 +89,7 @@ Offset | Size | Field | Description
- File uses binary format with WINDOWS-1250 text encoding
- Simple name/description/price structure for quest items
- Fixed record size enables efficient parsing
-- Integrated with quest progression systems
+- Other files reference these item IDs.
## Extractor
diff --git a/docs/files/CharacterInGame/HealItem.db.md b/docs/files/CharacterInGame/HealItem.db.md
index cc7319ac..387115a0 100644
--- a/docs/files/CharacterInGame/HealItem.db.md
+++ b/docs/files/CharacterInGame/HealItem.db.md
@@ -1,11 +1,8 @@
# HealItem.db
-> DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark
-> owner.
-
## Purpose
-`HealItem.db` stores fixed-size definitions for consumable items that restore health or mana and cure status effects.
+The tool reads `HealItem.db` as fixed-size definitions for items that restore health or mana and cure status effects.
## File Structure
@@ -31,9 +28,9 @@
| 248 | 1 | `cures_polymorph` | flag | Polymorph cure. |
| 249 | 3 | `reserved_trailer` | bytes | Preserved opaque data. Unused. |
-## Runtime Behavior
+## Field values
-The loader replaces `runtime_item_index_slot` with the sequential record index. Do not use this field as item data.
+Known files store zero in `runtime_item_index_slot`. The tool reads the word and writes it back unchanged. Do not use this field as item data.
Each effect flag uses `HealItemFlag`. `0` disables the effect. `1` enables the effect.
@@ -41,6 +38,4 @@ Each effect flag uses `HealItemFlag`. `0` disables the effect. `1` enables the e
The Rust parser is [heal_item_db.rs](../../../src/references/heal_item_db.rs).
-## Legal Notice
-This document describes a file format. It contains no game records, asset names, or other game-content data.
diff --git a/docs/files/CharacterInGame/MiscItem.db.md b/docs/files/CharacterInGame/MiscItem.db.md
index 4857f0ad..703980c2 100644
--- a/docs/files/CharacterInGame/MiscItem.db.md
+++ b/docs/files/CharacterInGame/MiscItem.db.md
@@ -1,22 +1,19 @@
# MiscItem.db
-> DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark
-> owner.
-
## File Information
### Overview
-Binary database file that defines generic miscellaneous items with names, descriptions, and economic values for the
-game's crafting, inventory, and utility systems.
+The tool reads `MiscItem.db` as name, description and price records for miscellaneous items.
### File Structure
-**Location**: `CharacterInGame/MiscItem.db`
-**Encoding**: Binary (Little-Endian)
-**Text Encodings**: Mixed (WINDOWS-1250 and EUC-KR)
-**Header**: 4-byte record count **Record Size**: 256 bytes (64 × 4-byte fields)
-**Total Records**: Variable (determined by header)
+- **Location**: `CharacterInGame/MiscItem.db`
+- **Encoding**: Binary (Little-Endian)
+- **Text Encodings**: Mixed (WINDOWS-1250 and EUC-KR)
+- **Header**: 4-byte record count
+- **Record Size**: 256 bytes (64 × 4-byte fields)
+- **Total Records**: Variable (determined by header)
### Binary Format
diff --git a/docs/files/CharacterInGame/Monster.ini.md b/docs/files/CharacterInGame/Monster.ini.md
index 3ce0545d..e5dab941 100644
--- a/docs/files/CharacterInGame/Monster.ini.md
+++ b/docs/files/CharacterInGame/Monster.ini.md
@@ -1,13 +1,10 @@
# Monster.ini
-> DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark
-> owner.
-
## File Information
### Overview
-Text file that defines monster visual appearances and animation sequences for the game's monster rendering system.
+The tool reads `Monster.ini` as a CSV file with comments. Each row holds a visual type ID, a name, a sprite filename and five animation sequence IDs.
### File Structure
@@ -67,21 +64,21 @@ The file organizes monsters into logical groups based on the comment header:
**Combat Animations:**
-- `attack_seq`: Attacking/offensive animations
+- `attack_seq`: attack animations
- `hit_seq`: Damage/taking hit animations
- `death_seq`: Death/dying animations
**Movement Animations:**
-- `walk_seq`: Walking/movement animations
-- `cast_seq`: Spellcasting/magic animations
+- `walk_seq`: movement animations
+- `cast_seq`: magic animations
### Special Values
- **"null"**: Literal string indicating no name or sprite
- **0**: Unused animation sequence (no animation)
- **-1**: Special or alternative animation sequence
-- **;**: Lines starting with semicolon are comments
+- **`;`**: Lines starting with this mark are comments.
- **Empty lines**: Ignored during processing
### Example Format
@@ -107,8 +104,8 @@ The file organizes monsters into logical groups based on the comment header:
**File Processing**:
-- Comments (lines starting with ";") are ignored
-- Empty lines are skipped
+- The parser ignores comments that start with `;`.
+- The parser skips empty lines.
- CSV format with comma delimiter
- "null" literal used for missing name/sprite fields
@@ -116,8 +113,8 @@ The file organizes monsters into logical groups based on the comment header:
- Processed by `MonsterIni` struct in the codebase
- Stored in database with all field mappings
-- Linked to monster placement files (mondun*.ref, monmap*.ref)
-- Referenced by combat and rendering systems
+- Monster placement files (`mondun*.ref`, `monmap*.ref`) use these IDs.
+- Other file formats reference these IDs.
### Animation Sequence System
@@ -136,20 +133,20 @@ pub struct MonsterIni {
}
```
-### Usage in Game
+### File use
-1. **Monster Rendering**: Game loads visual definitions from Monster.ini
-2. **Animation Mapping**: Links monster IDs to animation sequences
-3. **Combat System**: Uses attack/hit/death animations during battles
-4. **Movement System**: Applies walking animations during navigation
-5. **Magic System**: Triggers casting animations for spellcasters
+1. The tool reads visual definitions from `Monster.ini`.
+2. It links monster IDs to animation sequence IDs.
+3. It stores the attack, hit and death sequence IDs.
+4. It stores the walking sequence ID.
+5. It stores the casting sequence ID.
### Notes
- File uses Windows-style line endings (\r\n)
- Comments are in Polish (WINDOWS-1250 encoding)
- Animation sequences link to SPR file frame indices
-- Integrated with monster placement and combat systems
+- Other file formats link to these IDs.
## Extractor
diff --git a/docs/files/CharacterInGame/Store.db.md b/docs/files/CharacterInGame/Store.db.md
index 26b74a51..814cc842 100644
--- a/docs/files/CharacterInGame/Store.db.md
+++ b/docs/files/CharacterInGame/Store.db.md
@@ -1,21 +1,19 @@
# Store.db
-> DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark
-> owner.
-
## File Information
### Overview
-Binary database file that defines shops and inns with inventories, prices, merchant dialogue, and economic behavior for
-the game's commerce system.
+The tool reads `Store.db` as shop and inn records. Each record holds a name, a cost, product slots and text fields.
### File Structure
-**Location**: `CharacterInGame/STORE.DB`
-**Encoding**: Binary (Little-Endian)
-**Text Encoding**: WINDOWS-1250 **Header**: 4-byte record count **Record Size**: 948 bytes **Total Records**: Variable
-(determined by header)
+- **Location**: `CharacterInGame/STORE.DB`
+- **Encoding**: Binary (Little-Endian)
+- **Text Encoding**: WINDOWS-1250
+- **Header**: 4-byte record count
+- **Record Size**: 948 bytes
+- **Total Records**: Variable (determined by header)
### Binary Format
@@ -55,24 +53,22 @@ the game's commerce system.
**Inn (inn_night_cost > 0):**
-- No products (144 bytes padding)
-- Provides rest/healing services
-- Nightly accommodation cost
-- Dialogue for innkeeper
+- No products, 144 bytes of padding
+- A nightly cost value
+- Text fields
**Shop (inn_night_cost = 0):**
-- Product inventory (up to 15 items)
-- Sells goods and equipment
-- Price modifier affects economy
-- Merchant dialogue and haggling
+- Up to 15 product slots
+- A price modifier
+- Text fields
### Product Structure
**ProductType Enum:**
- **1**: Weapon - Weapons and armor
-- **2**: Healing - Healing items (potions, etc.)
+- **2**: potions and other healing items
- **3**: EditItem - Editable/modifiable equipment
- **4**: MiscItem - Miscellaneous items
@@ -85,17 +81,16 @@ the game's commerce system.
### Price Modifier & Pricing Formulas
-The `price_modifier` field is a signed percentage applied to an item's base price:
+The tool reads `price_modifier` as a signed percentage. The documented pricing equations are:
```
buy_price = base_price + (price_modifier * base_price) / 100
sell_price = base_price/2 + (price_modifier * (base_price/2)) / 100
```
-- **Buy price**: the player pays `base_price * (1 + price_modifier/100)`.
-- **Sell price**: the shop pays the player `(base_price/2) * (1 + price_modifier/100)`
- (items sell at half their base price, then the modifier is applied).
-- A positive modifier raises prices (e.g. `10` → +10%); a negative modifier lowers them.
+- Buy price: `base_price * (1 + price_modifier/100)`.
+- Sell price: `(base_price/2) * (1 + price_modifier/100)`. The tool halves the base price before it applies the modifier.
+- A positive modifier raises prices, for example `10` for +10%. A negative modifier lowers them.
- A value of `0` means the shop sells at the item's unmodified base price.
### Data Structure
diff --git a/docs/files/CharacterInGame/WeaponItem.db.md b/docs/files/CharacterInGame/WeaponItem.db.md
index d5e92caa..f64b0e9a 100644
--- a/docs/files/CharacterInGame/WeaponItem.db.md
+++ b/docs/files/CharacterInGame/WeaponItem.db.md
@@ -1,8 +1,5 @@
# WeaponItem.db
-> DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark
-> owner.
-
`CharacterInGame/WeaponItem.db` defines weapons and armour.
## Format
@@ -11,9 +8,7 @@
- Records: `record_count` fixed-size records of 284 bytes.
- Text: `name` and `description` are null-padded WINDOWS-1250 strings.
-The game loader reads the complete record block, then overwrites each record's
-`weapon_item_id` word with its zero-based record index. The file's stored value at that offset is therefore not a stable
-persistent ID.
+Known files store zero at offset 236. The tool reads this word as `weapon_item_id` and writes it back unchanged. The stored value is not a stable ID.
| Offset | Size | Type | Field | Meaning |
|-------:|-----:|--------|--------------------|------------------------------------------------|
@@ -44,6 +39,4 @@ persistent ID.
| 280 | 2 | i16 | `reserved_0x118` | Reserved; zero by default |
| 282 | 2 | i16 | `reserved_0x11a` | Reserved; zero by default |
-The seven reserved words are serialized and copied into save-game inventory records. No observed reader touches
-them, and all known records contain zero at those offsets. Preserve their values when editing; their purpose is
-unknown.
+The tool writes the seven reserved words into save-game inventory records. All known records contain zero at those offsets. Keep their values when you edit them. Their purpose is unknown.
diff --git a/docs/files/MagicInGame/Magic.db.md b/docs/files/MagicInGame/Magic.db.md
index 0889dbd7..5707d26b 100644
--- a/docs/files/MagicInGame/Magic.db.md
+++ b/docs/files/MagicInGame/Magic.db.md
@@ -1,7 +1,4 @@
-# Magic.db — Spell Database
-
-> DISPEL® is a registered trademark. This project is not affiliated with,
-> endorsed by, or sponsored by the trademark owner.
+# Magic.db: spell database
## File Information
@@ -12,7 +9,7 @@
## Record Structure (88 bytes)
-All fields are little-endian `u32`; the record ID is its zero-based position.
+All fields are little-endian `u32` values. The record ID is its zero-based position.
| Offset | Field | Meaning |
|-------:|--------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------|
@@ -38,25 +35,24 @@ All fields are little-endian `u32`; the record ID is its zero-based position.
## Field semantics
-- Effective mana cost is derived from `mana_cost` and the caster's magic type skill, clamped to a minimum of 5.
-- Effective success chance is derived from `base_success_rate` and that same skill category.
+- The documented mana cost combines `mana_cost` with the magic type skill. The minimum is 5.
+- The documented success chance combines `base_success_rate` with the same skill category.
- `cast_duration` controls the progress limit used by the casting/action state.
- `effect_visual_id` selects the mapping used to create the spell visual or projectile.
-- The flags at offsets 4 and 68 select the renderer's palette-blending path; clear values use direct pixel copies.
+- The flags at offsets 4 and 68 select the renderer's palette-blending path. Clear values use direct pixel copies.
- `effect_animation_repeats` keeps the target-effect animation alive after its last frame.
-- `animation_data_index` (offset 44) is resolved to a pointer after the file is loaded.
+- `animation_data_index` at offset 44 is an index into the animation data table.
## File Purpose
-Defines spell combat parameters, cast timing, and visual configuration. Effect-configuration words at offsets 48–56
-retain offset-based names because their purpose has not been established.
+The file holds spell parameters, cast timing and visual fields. The tool keeps offset-based names for the words at offsets 48 to 56.
## Implementation
- **Rust Module**: `src/references/magic_db.rs`
- **Extractor**: `MagicSpell` struct implementing `Extractor` trait
-- **Data Structure**: `MagicSpell` with comprehensive spell attributes
-- **Database**: Saved to SQLite via `save_magic_spells` function
+- **Data Structure**: `MagicSpell` with spell attributes
+- **Database**: saved to SQLite by the `save_magic_spells` function
## Example Usage
diff --git a/docs/files/MonsterInGame/MondunMonmap.ref.md b/docs/files/MonsterInGame/MondunMonmap.ref.md
index 952a0473..32756d43 100644
--- a/docs/files/MonsterInGame/MondunMonmap.ref.md
+++ b/docs/files/MonsterInGame/MondunMonmap.ref.md
@@ -1,7 +1,4 @@
-# Mondun/Monmap Files - Monster Placement References
-
-> DISPEL® is a registered trademark. This project is not affiliated with,
-> endorsed by, or sponsored by the trademark owner.
+# Mondun and Monmap files: monster placement references
## File Information
@@ -9,7 +6,7 @@
- **Encoding**: Binary (Little-Endian)
- **Record Size**: 56 bytes per monster entry
-Binary files that define monster placements, coordinates, event triggers, and loot configurations for game maps.
+The tool reads these files as monster placements. Each record holds coordinates, an event ID and loot slots.
## File Types
@@ -56,7 +53,7 @@ Binary files that define monster placements, coordinates, event triggers, and lo
## Map.ini Integration
-These files are referenced in `Ref/Map.ini` to associate monster placements with specific maps:
+`Ref/Map.ini` names these files for each map:
```
; Map ID, X, Y, Width, Height, MonsterFile, NPCFile, ExitFile, MapType
@@ -68,14 +65,13 @@ These files are referenced in `Ref/Map.ini` to associate monster placements with
## Field Details
-**monster_db_id**: Links to monster definitions in `Monster.db`. Determines monster type, stats, and appearance.
+**monster_db_id**: refers to a record in `Monster.db`.
**map_x, map_y**: Tile coordinates where the monster spawns on the map.
**event_id_on_kill**: Links to the event triggered when the monster dies.
-**loot_item_1..3**: Packed 32-bit `InventoryItem` values. The low bytes contain the item ID and type; the upper bits are
-preserved when writing.
+**loot_item_1..3**: packed 32-bit `InventoryItem` values. The low bytes hold the item ID and type. The tool preserves the upper bits.
## Loot System
@@ -83,7 +79,7 @@ preserved when writing.
- 3 loot slots per monster
- Each slot has item ID and type
-- Items dropped when monster is defeated
+- The slots hold item IDs and types.
### Item Types
@@ -92,7 +88,7 @@ preserved when writing.
- `Edit` (3): Modifiable equipment
- `Event` (4): Quest-related objects
- `Misc` (5): Various utility items
-- `NoItem` (-1, `0xFF` on disk; SQL/GUI numeric keys use 255): No item
+- `NoItem` (-1, `0xFF` on disk. SQL and GUI numeric keys use 255): No item
## Related Files
@@ -108,7 +104,7 @@ preserved when writing.
- **Editor**: `src/references/monster_ref_editor.rs` (EditableRecord impl)
- **Extractor**: `MonsterRef` struct implementing `Extractor` trait
- **Data Structure**: `MonsterRef` with position, event, and loot data
-- **Database**: Saved to SQLite via `save_monster_refs` function
+- **Database**: saved to SQLite by the `save_monster_refs` function
## Example Usage
@@ -137,10 +133,10 @@ cargo run -- database import "fixtures/Dispel/"
## Technical Notes
-- Both file types use identical binary format
+- Both file types use the same binary format.
- Distinction is organizational (dungeon vs overworld)
-- Padding fields have constrained value ranges (see Binary Format above)
-- Files are processed by `MonsterRef` struct in the codebase
+- The padding fields use constrained value ranges. See Binary Format above.
+- The `MonsterRef` struct processes these files.
## Extractor
@@ -163,8 +159,8 @@ cargo run -- validate -i monsteref.json --type monster_ref
The MonsterRef editor provides a 3-panel interface:
-1. **File list** — discovered Mondun*/Monmap*.ref files
-2. **Record list** — monster placements in the selected file
-3. **Record editor** — editable fields with monster name dropdown (loaded from Monster.ini)
+1. File list: Mondun* and Monmap* `.ref` files found by the tool
+2. Record list: monster placements in the selected file
+3. Record editor: editable fields with a monster name dropdown loaded from `Monster.ini`
All saves create a timestamped `.bak` backup automatically.
diff --git a/docs/files/MonsterInGame/Monster.db.md b/docs/files/MonsterInGame/Monster.db.md
index 24fea0fd..bc44cf55 100644
--- a/docs/files/MonsterInGame/Monster.db.md
+++ b/docs/files/MonsterInGame/Monster.db.md
@@ -1,22 +1,19 @@
# Monster.db Documentation
-> DISPEL® is a registered trademark. This project is not affiliated with,
-> endorsed by, or sponsored by the trademark owner.
-
## File Information
### Overview
-Binary database file that defines all monster types with complete combat statistics, behavior patterns, and reward
-systems for the game's monster spawning and combat AI.
+The tool reads `Monster.db` as fixed-size monster records. Each record holds a name and 34 numeric fields.
### File Structure
-**Location**: `MonsterInGame/Monster.db`
-**Encoding**: Binary (Little-Endian)
-**Text Encoding**: EUC-KR **Record Size**: 160 bytes (24-byte name + 34 × i32 fields)
-**Header**: None (count derived from file size)
-**Total Records**: Variable (file_size / 160)
+- **Location**: `MonsterInGame/Monster.db`
+- **Encoding**: Binary (Little-Endian)
+- **Text Encoding**: EUC-KR
+- **Record Size**: 160 bytes (24-byte name + 34 × i32 fields)
+- **Header**: None (count derived from file size)
+- **Total Records**: Variable (file_size / 160)
### Binary Format
@@ -111,13 +108,13 @@ systems for the game's monster spawning and combat AI.
**MonsterAiType (ai_type):**
-- **0**: Aggressor — Actively seeks and engages the player
-- **1**: HitAndFlee — Attacks then retreats (hit-and-run)
-- **2**: FleeWhenApproached — Runs away when player approaches
-- **3**: AttackWhenOutnumbered — Engages only when it has numerical advantage
-- **4**: TeleportTactic — Uses teleportation during combat
-- **5**: AttackWhenProvoked — Only attacks when attacked first
-- **6**: RunAwayWhenAttacked — Flees upon taking damage
+- **0**: Aggressor
+- **1**: HitAndFlee
+- **2**: FleeWhenApproached
+- **3**: AttackWhenOutnumbered
+- **4**: TeleportTactic
+- **5**: AttackWhenProvoked
+- **6**: RunAwayWhenAttacked
### Data Structure
@@ -214,14 +211,11 @@ Offset | Size | Field | Description
- **is_undead = 1**: Holy weakness, no bleed
- **has_blood = 0**: No blood effects (golems)
- **is_oversize = 1**: Large monsters (dragons, etc.)
-- **special_attack != 0**: The attack carries a poison (1) or paralysis (2)
- status rider — see the *Special-attack rider* section under Field
- Definitions. `special_attack_chance` is a percent roll against the victim,
- `special_attack_duration` counts 55 ms scheduler ticks.
+- **special_attack != 0**: the record carries a poison (1) or paralysis (2) status rider. See the *Special-attack rider* section under Field Definitions. `special_attack_chance` is a percentage value. `special_attack_duration` counts 55 ms scheduler ticks.
### File Purpose
-Defines all monster types with combat statistics, AI behavior patterns, and reward systems.
+The file holds 160-byte records with the fields listed above.
## Extractor
diff --git a/docs/files/Ref/DrawItem.db.md b/docs/files/Ref/DrawItem.db.md
index 89fae264..104764cb 100644
--- a/docs/files/Ref/DrawItem.db.md
+++ b/docs/files/Ref/DrawItem.db.md
@@ -1,8 +1,5 @@
# DRAWITEM.ref
-> DISPEL® is a registered trademark. This project is not affiliated with,
-> endorsed by, or sponsored by the trademark owner.
-
## Purpose
`DRAWITEM.ref` stores item placements for maps.
@@ -45,6 +42,4 @@ normalized CRLF line endings.
The Rust parser is [draw_item.rs](../../../src/references/draw_item.rs).
-## Legal Notice
-This document describes a file format. It contains no game records, asset names, or other game-content data.
diff --git a/docs/files/Ref/Map.ini.md b/docs/files/Ref/Map.ini.md
index e51e33f9..f16a945e 100644
--- a/docs/files/Ref/Map.ini.md
+++ b/docs/files/Ref/Map.ini.md
@@ -1,17 +1,13 @@
# Map.ini Documentation
-> DISPEL® is a registered trademark. This project is not affiliated with,
-> endorsed by, or sponsored by the trademark owner.
-
## File Information
- **Location**: `Dispel/Ref/Map.ini` (relative to game installation directory)
- **Encoding**: EUC-KR
- **Format**: CSV (Comma-Separated Values)
-- **Comment lines**: Lines starting with `;` are ignored
+- **Comment lines**: The parser ignores lines starting with `;`.
-`Map.ini` is a map initialization data file used by the game engine to configure individual map properties, starting
-positions, and associated resources.
+The tool reads `Map.ini` as a map initialization list. Each row holds a map ID, coordinates, an event ID and resource file names.
## Structure
@@ -51,7 +47,7 @@ id,camera_event,start_x,start_y,map_id,monsters,npcs,extras,cd_track
## Special Values
- **"null"**: Used for `monsters`, `npcs`, and `extras` fields when the file is absent
-- **Comments**: Lines starting with `;` are ignored
+- **Comments**: The parser ignores lines starting with `;`.
- **Coordinates**: Use isometric tile coordinate system
- **Event IDs**: Special event numbers that trigger when camera moves
@@ -59,24 +55,24 @@ id,camera_event,start_x,start_y,map_id,monsters,npcs,extras,cd_track
This file defines initialization parameters for each map including:
-1. Starting player positions (X,Y coordinates)
+1. Start positions (X,Y coordinates)
2. Linked resource files (monsters, NPCs, extra objects)
3. Background music track selection
4. Map transition and linking information
5. Camera movement event triggers
-The game engine uses this data during map loading to:
+The tool stores these values:
-- Position the player correctly
-- Load appropriate monster/NPC placements
-- Set up interactive objects
-- Play the correct background music
-- Handle map transitions and camera events
+- Start coordinates
+- Monster and NPC placement file names
+- Extra object file names
+- Music track number
+- Camera event and target map IDs
## Notes
-- The file is parsed by the `MapIni` struct in `src/references/map_ini.rs`
-- Map initialization records are stored in a database using the `save_map_inis` function
+- The `MapIni` struct in `src/references/map_ini.rs` parses the file.
+- The `save_map_inis` function stores the records in a database.
- The file format uses EUC-KR encoding
- Coordinate system uses isometric tiles, not pixel coordinates
diff --git a/docs/files/Ref/PartyRef.ref.md b/docs/files/Ref/PartyRef.ref.md
index 9c9b6104..f0639b39 100644
--- a/docs/files/Ref/PartyRef.ref.md
+++ b/docs/files/Ref/PartyRef.ref.md
@@ -1,7 +1,4 @@
-# PartyRef.ref — Party Characters
-
-> DISPEL® is a registered trademark. This project is not affiliated with,
-> endorsed by, or sponsored by the trademark owner.
+# PartyRef.ref: party characters
## File Information
@@ -16,7 +13,7 @@
- Lines starting with `;` are comments
- CSV format with comma delimiter
-- Empty lines are ignored
+- The parser ignores empty lines.
### Record Structure
@@ -35,7 +32,7 @@
- Unique character identifier
- Party member index
-- Used for character selection and management
+- The tool uses this ID for character selection.
### name
@@ -49,7 +46,7 @@
- Origin map identifier
- Where character is initially found
- Links to map files and locations
-- Determines recruitment location
+- Records the origin map ID.
### npc_id
@@ -61,21 +58,21 @@
### dlg_out
- Dialog ID when not in party
-- Conversation when character is roaming
+- Conversation text outside the party
- Recruitment dialogue
- Initial interaction text
### dlg_in
- Dialog ID when in party
-- Conversation when character is recruited
+- Conversation text inside the party
- Party member dialogue
-- Ongoing interaction text
+- Later interaction text
### in_party
- Boolean flag (0/1) marking the character as currently in the party
-- A single byte; non-zero marks the character's name as highlighted in the party member list
+- A single byte. Non-zero marks the name as highlighted in the party member list.
- `0`: character not in the party (default)
- `1`: character is in the party (name shown highlighted)
@@ -88,21 +85,20 @@
## File Purpose
-Defines all party characters with their names, classes, origin locations, dialog references, and visual representations.
-Used for:
+The tool reads each row as a character record with a name, a job, an origin map and dialogue IDs. The data supports:
-- Party management system
-- Character recruitment
-- Dialogue interactions
-- UI display and portraits
-- Character progression tracking
+- Party membership flags
+- Character origin records
+- Dialogue references
+- UI text and portraits
+- Character progression records
## Implementation
- **Rust Module**: `src/references/party_ref.rs`
- **Extractor**: `PartyRef` struct implementing `Extractor` trait
- **Data Structure**: `PartyRef` with character attributes
-- **Database**: Saved to SQLite via `save_party_refs` function
+- **Database**: saved to SQLite by the `save_party_refs` function
## Example Usage
@@ -125,9 +121,9 @@ cargo run -- extract -i "fixtures/Dispel/Ref/PartyRef.ref"
## Related Files
-- `Npc.ini` — NPC definitions
-- `PrtIni.db` — Party initialization data
-- `PrtLevel.db` — Character progression data
+- `Npc.ini`: NPC definitions
+- `PrtIni.db`: party initialization data
+- `PrtLevel.db`: character progression data
- Dialogue files (`.dlg`)
- Map files (`.map`)
From a9b493cb4941199a6ece7f35c4ebdd74a9ba0f4b Mon Sep 17 00:00:00 2001
From: dimspell <141545384+dimspell@users.noreply.github.com>
Date: Wed, 25 Nov 2026 13:51:36 +0100
Subject: [PATCH 06/72] docs: rewrite fourteen map and entity format documents
---
docs/files/ExtraInGame/Extra.ref.md | 42 +++++---------
docs/files/ExtraInGame/Message.scr.md | 13 ++---
docs/files/ExtraInGame/Quest.scr.md | 13 ++---
docs/files/ExtraInGame/fogdata.dat.md | 46 +++++----------
docs/files/Map/Map.btl.md | 24 +++-----
docs/files/Map/Map.gtl.md | 13 +----
docs/files/Map/Map.map.md | 74 ++++++++-----------------
docs/files/Map/MapModule.md | 53 ++++++++----------
docs/files/NpcInGame/DlgMapFiles.dlg.md | 17 +++---
docs/files/NpcInGame/Eventnpc.ref.md | 20 ++-----
docs/files/NpcInGame/NpcMapFiles.ref.md | 9 +--
docs/files/NpcInGame/PgpMapFiles.pgp.md | 16 ++----
docs/files/NpcInGame/PrtIni.db.md | 10 +---
docs/files/NpcInGame/PrtLevel.db.md | 15 ++---
14 files changed, 124 insertions(+), 241 deletions(-)
diff --git a/docs/files/ExtraInGame/Extra.ref.md b/docs/files/ExtraInGame/Extra.ref.md
index 45b4b2a9..a8f53723 100644
--- a/docs/files/ExtraInGame/Extra.ref.md
+++ b/docs/files/ExtraInGame/Extra.ref.md
@@ -1,8 +1,5 @@
# ExtraInGame/Ext*.ref Documentation
-> DISPEL® is a registered trademark. This project is not affiliated with,
-> endorsed by, or sponsored by the trademark owner.
-
## File Information
### Overview
@@ -87,18 +84,13 @@ items) on specific maps. Each map has its own `Ext*.ref` file containing all int
### Field semantics
-- `map_object_id` is exposed to the tile/object system as `700 + map_object_id`.
-- `interaction_state` is preserved across reloads; it selects the closed/open sprite sequence for chest-type objects.
-- `requires_key` enables validation of the three inclusive requirement ranges. A range starting with `9999` is disabled.
-- `gold_amount` awards gold, and three `(item, count)` loot pairs are processed: `loot_item`/`loot_item_count`, then the
- two
- `additional_loot_*` pairs.
-- `footprint_width`, `footprint_height`, and `footprint_orientation` determine which map cells the object occupies.
- `interaction_range` limits activation distance.
+- The tool exposes `map_object_id` to the tile and object system as `700 + map_object_id`.
+- The tool preserves `interaction_state` across reloads. It selects the closed or open sprite sequence for chest-type objects.
+- `requires_key` enables validation of three inclusive requirement ranges. The tool disables a range that starts with `9999`.
+- `gold_amount` holds the gold value. The tool reads three `(item, count)` loot pairs: `loot_item` with `loot_item_count`, then the two `additional_loot_*` pairs.
+- `footprint_width`, `footprint_height` and `footprint_orientation` describe the map cells the object occupies. `interaction_range` limits activation distance.
-The seven words from `additional_loot_2_count` through `use_counter` were formerly exported as one opaque
-28-byte `additional_loot_2_count_and_config` BLOB. Two of those words are the trap flag and trap spell
-index; both are zero in every shipped placement. They are **not** the same as `open_sfx_id`.
+The seven words from `additional_loot_2_count` through `use_counter` hold the trap flag, trap spell index and related configuration. Both trap fields are zero in every sample placement. They are separate from `open_sfx_id`.
#### Core Identification
@@ -185,13 +177,9 @@ index; both are zero in every shipped placement. They are **not** the same as `o
#### Trap fields and open sound
-`is_trapped` and `trap_spell_id` are the trap arming flag and `Magic.db` spell index. All 1,039
-shipped placements carry zero in both, so no shipped placement uses a trap.
+`is_trapped` and `trap_spell_id` hold the trap arming flag and `Magic.db` spell index. The 1,039 sample placements carry zero in both fields.
-`open_sfx_id` is a **Wave.ini sound index** played when a door, lever, chest, key, or subtype-8 object
-is activated successfully. It was previously exported as `activation_effect_id` with the bogus values
-`None`/`Effect10`; that mapping also rewrote any index other than 0 or 10 to 255 on save. It is a
-plain `u8` now.
+`open_sfx_id` holds a `Wave.ini` sound index for a door, lever, chest, key or subtype-8 object. Zero means no sound. The field is a `u8`.
#### Item Type ID (required_item_type_id, loot_item_type_id)
@@ -218,9 +206,7 @@ SQL columns and GUI numeric keys keep the on-disk byte value, so no item reads a
### File Purpose
-These files define interactive object placements with exact coordinates, requirements, contents, and behaviors. Used for
-populating maps with chests, doors, signs, and other interactive elements. Each map in the game has a corresponding
-`Ext*.ref` file.
+The tool reads these files as interactive object placements. Each placement holds coordinates, requirements, contents and state values. Each map has its own `Ext*.ref` file.
### Cross-References
@@ -234,10 +220,12 @@ populating maps with chests, doors, signs, and other interactive elements. Each
### Technical Details
-**Endianness**: Little-Endian throughout **Record Count**: Stored as first 4 bytes (i32)
-**Record Size**: Fixed 184 bytes (46 × i32 equivalent)
-**File Size**: 4 + (record_count × 184) bytes **Text Encoding**: WINDOWS-1250 for name fields **Padding**: Extensive
-padding with known patterns (zeros, 205 bytes)
+- **Endianness**: little-endian throughout
+- **Record count**: the first 4 bytes, as i32
+- **Record size**: 184 bytes, or 46 i32 words
+- **File size**: 4 + (record_count × 184) bytes
+- **Text encoding**: WINDOWS-1250 for name fields
+- **Padding**: zeros and 205 bytes
### File Processing
diff --git a/docs/files/ExtraInGame/Message.scr.md b/docs/files/ExtraInGame/Message.scr.md
index f84d493a..2d40034b 100644
--- a/docs/files/ExtraInGame/Message.scr.md
+++ b/docs/files/ExtraInGame/Message.scr.md
@@ -1,7 +1,4 @@
-# Message.scr — UI Text Messages
-
-> DISPEL® is a registered trademark. This project is not affiliated with,
-> endorsed by, or sponsored by the trademark owner.
+# Message.scr: UI text messages
## File Information
@@ -16,7 +13,7 @@
- Lines starting with `;` are comments
- Pipe-delimited format: `field1|field2|field3|field4`
-- Empty lines are ignored
+- The parser ignores empty lines.
### Record Structure
@@ -37,7 +34,7 @@
- Three lines of text for UI display
- Each line can be up to 255 characters
-- Lines are displayed vertically stacked
+- The three lines appear in vertical order.
- Empty lines use "null" literal
## Special Values
@@ -69,7 +66,7 @@ Stores multi-line text messages for UI elements such as:
- **Rust Module**: `src/references/message_scr.rs`
- **Extractor**: `Message` struct implementing `Extractor` trait
- **Data Structure**: `Message` with ID and three text lines
-- **Database**: Saved to SQLite via `save_messages` function
+- **Database**: saved to SQLite by the `save_messages` function
## Example Usage
@@ -94,7 +91,7 @@ cargo run -- extract -i "Dispel/ExtraInGame/Message.scr"
## Display System
-- Messages are displayed in UI panels
+- The tool shows messages in UI panels.
- Three-line vertical layout
- Centered or aligned based on context
- WINDOWS-1250 character encoding support
diff --git a/docs/files/ExtraInGame/Quest.scr.md b/docs/files/ExtraInGame/Quest.scr.md
index b5e7ede1..bf62860f 100644
--- a/docs/files/ExtraInGame/Quest.scr.md
+++ b/docs/files/ExtraInGame/Quest.scr.md
@@ -1,7 +1,4 @@
-# Quest.scr — Quest Journal Entries
-
-> DISPEL® is a registered trademark. This project is not affiliated with,
-> endorsed by, or sponsored by the trademark owner.
+# Quest.scr: quest journal entries
## File Information
@@ -16,7 +13,7 @@
- Lines starting with `;` are comments
- Pipe-delimited format: `field1|field2|field3|field4`
-- Empty lines are ignored
+- The parser ignores empty lines.
### Record Structure
@@ -76,7 +73,7 @@
### Traders Journal (type=2)
- Commerce-related quests
-- Trading missions
+- Trade missions
- Economic activities
- Merchant interactions
- Supply chain quests
@@ -97,14 +94,14 @@ Defines all quests with categories, titles, and descriptions. Used for:
- Player objectives
- Story advancement
- Reward distribution
-- Linked to event system for completion
+- Event IDs link to the event system.
## Implementation
- **Rust Module**: `src/references/quest_scr.rs`
- **Extractor**: `Quest` struct implementing `Extractor` trait
- **Data Structure**: `Quest` with ID, type, title, and description
-- **Database**: Saved to SQLite via `save_quests` function
+- **Database**: saved to SQLite by the `save_quests` function
## Example Usage
diff --git a/docs/files/ExtraInGame/fogdata.dat.md b/docs/files/ExtraInGame/fogdata.dat.md
index b1002bcf..44fa5e70 100644
--- a/docs/files/ExtraInGame/fogdata.dat.md
+++ b/docs/files/ExtraInGame/fogdata.dat.md
@@ -1,19 +1,12 @@
# ExtraInGame/fogdata.dat Documentation
-> DISPEL® is a registered trademark. This project is not affiliated with,
-> endorsed by, or sponsored by the trademark owner.
-
## File Information
### Overview
-Map-lighting fade tables. The file is a flat array of brightness factors used
-to shade tiles that carry a shadow (darkness) level. Each row of the table is one
-animated flicker pattern for a single light level; the renderer walks the row per rendered frame
-to make torch-lit darkness shimmer.
+The file holds brightness factors in a flat array. Each row covers one light level and has 512 bytes. The renderer reads a row for each shadowed tile.
-This file feeds the map lighting pass, which only runs on maps flagged **Dark** in `AllMap.ini`
-(see `docs/rendering.md` and `src/map/render.rs::plot_shadows`).
+The map lighting pass reads this file on maps flagged **Dark** in `AllMap.ini` (see `docs/rendering.md` and `src/map/render.rs::plot_shadows`).
### File Structure
@@ -49,38 +42,28 @@ Row `L-1` serves light level `L`. A consumer indexes the file as:
byte[(level - 1) * 512 + pair]
```
-where `pair` is the pixel-pair index (`0..512`) within a shadowed tile — each factor byte covers
-two horizontally adjacent pixels.
+Here `pair` is the pixel-pair index (`0..512`) within a shadowed tile. Each factor byte covers two horizontally adjacent pixels.
-**Range nuance:** light levels `1..=199` occur in the map's access-ref grid (levels ≥ 200 are
-skipped by the lighting pass entirely), but the file only covers levels `1..=123`.
-Levels above 123 would read past the table; tooling must clamp or skip.
+**Range:** light levels `1..=199` occur in the map's access-ref grid. The lighting pass skips levels of 200 or more. The file covers levels `1..=123`. Levels above 123 read past the table. Tooling must clamp or skip them.
### Factor Semantics
-Each byte is a brightness factor `f` in `0..=31` — a 5-bit fixed-point value:
+Each byte is a brightness factor `f` in `0..=31`. This is a 5-bit fixed-point value:
- Effective multiplier on shadowed pixels: `f / 32`.
- Applied to **all three colour channels**.
-- `f = 0` → pixel pair blacked out; `f = 31` → nearly full brightness.
-- Values are **not monotonic in level**: each row is an animated flicker pattern, so adjacent
- levels can have very different brightness at the same pair index.
+- `f = 0` blacks out the pixel pair. `f = 31` gives nearly full brightness.
+- Values do not rise with level. Adjacent levels can have very different brightness at the same pair index.
### File Purpose
-Provides the per-level darkness fade/flicker patterns that the map lighting pass applies to
-shadowed tiles on Dark maps, producing an animated torch-light falloff.
+The tool reads per-level brightness patterns. It applies them to shadowed tiles on Dark maps.
### Rendering Dark Maps
-The `.map` file's own light-level bits (access-ref word bits 15–29) are not used for
-rendering: a fixed 500-byte viewport template is applied per visible slot instead. A
-static render that uses the file's bits therefore shows every dark map as pitch black.
+The tool does not use the `.map` light-level bits (access-ref word bits 15 to 29) for rendering. It applies a fixed 500-byte viewport template per visible slot. A static render that uses the file's bits shows every dark map as black.
-`map render --light-template [--camera x,y]` applies that template before the fog
-pass and reproduces the lighting the game draws (the template is the 500×1 grayscale PNG the
-Godot remake's `tools/convert_lighting.py` writes). `make map-render-lit map_id=dun01`
-wraps it.
+`map render --light-template [--camera x,y]` applies that template before the fog pass. The template is a 500×1 grayscale PNG. `tools/convert_lighting.py` writes it. `make map-render-lit map_id=dun01` wraps the command.
### Cross-References
@@ -95,8 +78,8 @@ See also `docs/rendering.md` (isometric rendering pipeline) and
### Technical Details
-- No header, no padding — exactly 62,976 raw bytes.
-- Byte order is irrelevant (single-byte fields).
+- No header and no padding. The file holds exactly 62,976 raw bytes.
+- Byte order does not apply because fields are single bytes.
- Parsed by `dispel_core::map::fogdata::FogData` (re-exported as
`dispel_core::map::render::FogData`), which validates the length and provides
bounds-checked accessors plus an editor-safe `set_factor` that rejects values > 31
@@ -104,6 +87,5 @@ See also `docs/rendering.md` (isometric rendering pipeline) and
### Notes
-- Level 0 tiles are not looked up here: on Dark maps they are blacked out outright.
-- When editing, keep every byte in `0..=31`; larger values are invalid in this table even though
- they wrap silently when consumed.
+- The tool does not look up level 0 tiles. It draws them black on Dark maps.
+- When you edit the file, keep every byte in `0..=31`. Larger values are invalid in this table.
diff --git a/docs/files/Map/Map.btl.md b/docs/files/Map/Map.btl.md
index 04af760c..6f2d0870 100644
--- a/docs/files/Map/Map.btl.md
+++ b/docs/files/Map/Map.btl.md
@@ -1,10 +1,6 @@
# DISPEL® Building Tile Layer (`.btl`)
-Raw tileset binary used for structures, roofs, and architectural elements. The format is identical to `.gtl`; only the
-semantic role differs.
-
-> DISPEL® is a registered trademark. This project is not affiliated with,
-> endorsed by, or sponsored by the trademark owner.
+The tool reads `.btl` files as raw tilesets for structures and roofs. The binary format matches `.gtl`.
## Quick Facts
@@ -47,24 +43,20 @@ blue = bits 0–4 of pixel → scale 0–31 to 0–255
## Isometric Rendering
-Tiles are projected as isometric diamonds (62×32 px). A diamond-shaped mask clips each tile so that corners blend
-seamlessly.
+The renderer projects tiles as isometric diamonds of 62×32 pixels. A diamond-shaped mask clips each tile.
+
+The renderer picks a blit mode from the building overlay entry. Transparency 0 selects an opaque copy. A non-zero value selects a skip-zero blit, which copies only non-zero pixels. The draw-enable byte must be set before the renderer draws the cell. Only shadowed cells use this pass.
-The blit mode is chosen **per ref**, from the transparency and draw-enable bytes of the
-building overlay's map entry: transparency 0 means opaque copy, non-zero means a skip-zero blit
-that copies only the non-zero source pixels; the draw-enable byte must be set for the cell to be
-drawn at all. Only the shadowed cells are drawn by this pass. An atlas therefore bakes in one mode —
-`map atlas` uses the skip-zero blit for `.BTL` files, which matches the shadow art but drops the
-black pixels of the opaque-mode refs (764 of 1419 in `dun01`).
+An atlas bakes in one mode. `map atlas` uses the skip-zero blit for `.btl` files. In `dun01`, 764 of 1419 references use opaque mode.
## Relationship to `.map` Files
A `.map` file references BTL tile IDs in two places:
-- **Tiled Objects block** — building stacks drawn from anchor points
-- **Access-Ref block** — occlusion/access lookup per tile
+- **Tiled Objects block**: building stacks drawn from anchor points
+- **Access-Ref block**: occlusion and access lookup per tile
-BTL tile IDs inside the Tiled Objects block are stacked bottom-to-top; negative IDs are skipped during rendering.
+The tool stacks BTL tile IDs bottom-to-top. It skips negative IDs when rendering.
## Related Files
diff --git a/docs/files/Map/Map.gtl.md b/docs/files/Map/Map.gtl.md
index 1ceed937..40d7131a 100644
--- a/docs/files/Map/Map.gtl.md
+++ b/docs/files/Map/Map.gtl.md
@@ -1,10 +1,6 @@
# DISPEL® Ground Tile Layer (`.gtl`)
-Raw tileset binary used for terrain, paths, and natural features. The format is identical to `.btl`; only the semantic
-role differs.
-
-> DISPEL® is a registered trademark. This project is not affiliated with,
-> endorsed by, or sponsored by the trademark owner.
+The tool reads `.gtl` files as raw tilesets for terrain, paths and natural features. The binary format matches `.btl`.
## Quick Facts
@@ -47,12 +43,9 @@ blue = bits 0–4 of pixel → scale 0–31 to 0–255
## Isometric Rendering
-Tiles are projected as isometric diamonds (62×32 px). A diamond-shaped mask clips each tile so that corners blend
-seamlessly.
+The renderer projects tiles as isometric diamonds of 62×32 pixels. A diamond-shaped mask clips each tile.
-**The ground pass is an opaque row-copy**: the 32 rows are copied verbatim, so the
-tile's RGB(0,0,0) pixels are drawn like any other. An atlas that treats black as transparent punches holes in the
-floor — `map atlas` therefore defaults to the opaque mode for `.GTL` files.
+The ground pass copies 32 rows without filtering. The tool draws RGB(0,0,0) pixels like any other pixel. `map atlas` defaults to opaque mode for `.gtl` files.
## Relationship to `.map` Files
diff --git a/docs/files/Map/Map.map.md b/docs/files/Map/Map.map.md
index 4eff1f71..be5cbdb0 100644
--- a/docs/files/Map/Map.map.md
+++ b/docs/files/Map/Map.map.md
@@ -1,12 +1,6 @@
# DISPEL® Map File Format (`.map`)
-All game maps — overworld (`map1.map`…), catacombs (`cat1.map`…, `catp.map`), and dungeons (`dun01.map`…, `final.map`) —
-share this binary format. A `.map`
-file contains everything needed to render a map: dimensions, embedded sprites (thrones, statues, decor), building
-stacks, and three per-tile grids (events, ground tiles, occlusion).
-
-> DISPEL® is a registered trademark. This project is not affiliated with,
-> endorsed by, or sponsored by the trademark owner.
+The tool reads overworld, catacomb and dungeon maps with one binary format. Sample names include `map1.map`, `cat1.map`, `catp.map`, `dun01.map` and `final.map`. A `.map` file holds dimensions, embedded sprites, building stacks and three per-tile grids for events, ground tiles and occlusion.
## Quick Facts
@@ -59,9 +53,7 @@ count: i32
records: (count − 1) × 8 bytes -- each record: word0: i32, word1: i32
```
-Skipping `(count − 1) × 8` lands exactly on the next block's size field, verified against the cat1/cat3/dun01/map1/catp
-fixtures. Both words are **constant across all shipped maps** — `word0 == 0` and `word1 == 1` in all 99,104 records
-probed — so their purpose is unknown. The earlier "linear tile index into the end grids" interpretation was wrong.
+The tool skips `(count − 1) × 8` bytes and lands on the next block's size field. The cat1, cat3, dun01, map1 and catp samples contain 99,104 records. In those records `word0 == 0` and `word1 == 1`. The supplied data shows no use for these fields.
### Second Block *(u16 lookup table)*
@@ -87,8 +79,7 @@ for each sprite:
6 → 1904 bytes, 9 → 2996 bytes
```
-Any other `image_stamp` is a parse error. Sprites here are thrones, statues, decor — anything placed by pixel coordinate
-rather than tile grid.
+Any other `image_stamp` is a parse error. These sprites use pixel coordinates rather than tile grid coordinates.
### Sprite Info Block *(placements)*
@@ -105,16 +96,11 @@ for each placement:
frame_skip: (frame_count − 1) × 6 × 4 bytes
```
-The seven i32s after `sprite_id` are actually **frame 0 of a per-frame record**
-(24 bytes each: `{left, top, right, bottom}` box + duplicated `{x, y}` anchor;
-the game stores them in separate per-frame arrays so they can diverge).
-Verified against cat1/map1: `right − left` and `bottom − top` equal the frame's
-pixel `width × height` exactly. Placements Y-sort by `bottom`.
+The seven i32 values after `sprite_id` hold frame 0 of a per-frame record. Each record has 24 bytes: a `{left, top, right, bottom}` box and a duplicated `{x, y}` anchor. The format stores these values in separate per-frame arrays. In the cat1 and map1 samples, `right − left` and `bottom − top` equal the frame pixel `width × height`. Placements sort by `bottom` on the Y axis.
-### Tiled Objects Block *(buildings)* — fully typed
+### Tiled Objects Block *(buildings)*: fully typed
-This block is a three-level tree: bundle, record, item, and entry. The
-structure below is based on the on-disk data.
+This block is a three-level tree: bundle, record, item and entry. The structure below follows the on-disk data.
```
bundle_count: i32
@@ -148,26 +134,16 @@ for each bundle:
-- stack level; their meaning is unknown
```
-There is **no end-of-block sentinel**: the three end grids follow the last
-bundle's level flags immediately. The previously described "empirically fitted"
-layout (`264-byte blob`, `control words`, `84-byte trailer`,
-`sentinel alignment scan`) was an approximation that happened to consume the
-same byte stream; it has been deleted.
-
-Discovered semantics (verified over all 33 fixture maps, 43,554 entries):
-- `anchor_x`/`anchor_y` are the stack anchor `(x, y)` in map-local pixels;
- the entry's `ids` u16 array is its BTL tile stack. The renderer-facing
- `TiledObjectInfo` is derived from the bundle's *first* entry
- (first record → first item → first entry).
-- The bbox relations above hold exactly on every shipped entry.
+There is no end-of-block sentinel. The three end grids follow the last bundle's level flags immediately.
+
+The 33 sample maps contain 43,554 entries. Those entries use this layout:
+- `anchor_x` and `anchor_y` give the stack anchor `(x, y)` in map-local pixels. The entry's `ids` u16 array is its BTL tile stack. The renderer-facing `TiledObjectInfo` comes from the bundle's first entry (first record, first item, first entry).
+- The 43,554 entries follow the bounding-box relations above.
- An entry's `grid_height` sizes the per-bundle flag arrays that follow.
-Shipped data is degenerate: exactly one record per bundle, eight items per
-record, at most one entry per item; `type_flag ≡ 0` and `field_14 ≡ 0`
-everywhere.
+The sample maps contain one record per bundle, eight items per record and at most one entry per item. `type_flag` and `field_14` are zero in those files.
-Each bundle's first-entry tile stack is drawn downward from the anchor, one 62×32 diamond per id.
-Negative ids occur and are skipped when drawing.
+The tool draws each bundle's first-entry tile stack downward from the anchor. It draws one 62×32 diamond per id. Negative ids occur. The tool skips them when it draws.
### Event Block
@@ -182,7 +158,7 @@ flags: i16 -- high half: parameter/flag bits
In the packed u32, bit 22 sets `EventBlock::is_tile_marked`.
-Two game systems use the following exact event-word predicate:
+Two documented checks use this exact event-word predicate:
```text
(word & 0x0FC00000) == 0x00400000
@@ -198,7 +174,7 @@ remaining high bits have no documented meaning.
### Tile & Access Block
-One packed u32 per tile, row-major (bit layout verified against shipped map data):
+One packed u32 per tile, row-major:
| Bits | Meaning |
|-------|--------------------------------------------------------------|
@@ -211,8 +187,7 @@ The index points straight into the `.gtl` pixel data: the renderer blits from
`gtl_base + index × 2048` (one 32×32 RGB565 tile). Across observed maps the maximum index matches the `.gtl` tile
capacity minus one.
-Bits 0–9 together form one access field that can be rewritten without touching the tile index. Maps only ever
-use bit 0; bits 1–9 are written at runtime.
+Bits 0 to 9 form one access field. The tool can rewrite that field without changing the tile index. The sample maps use bit 0 only. No sample value sets bits 1 to 9.
### Access-Ref Block *(a.k.a. "roof" block)*
@@ -226,12 +201,10 @@ shadow_and_flags: i16 -- bits 15–29 of the u32: shadow level 0–19
This grid packs **two layers** in one u32:
-1. **BTL overlay ref** (bits 0–14): when the referenced Second Block entry has
- its *high* byte set, the game blits BTL pixels from
+1. BTL overlay ref (bits 0 to 14): when the referenced Second Block entry has its high byte set, the renderer blits BTL pixels from
`btl_base + ref_id × 2048` (entry *low* byte selects transparent vs opaque
blit). So the Second Block is `{transparency, draw_enable}` per overlay id.
-2. **Shadow/fog level** (bits 15–29): 0–199 darkness applied per tile via a
- fade table; entities carrying light raise the value (max wins).
+2. Shadow and fog level (bits 15 to 29): the value spans 0 to 199. The documented rule raises the value for light sources. The highest value wins.
On a dark map, a BTL overlay must have a non-zero reference and at least one
bit in positions 15–31. The extractor exposes this condition as
@@ -239,8 +212,7 @@ bit in positions 15–31. The extractor exposes this condition as
the referenced Second Block entry must also have its draw-enable byte set.
Light maps use a different roof pass and do not apply this extra condition.
-Bit 15 overlaps the signed-i16 view of `ref_id`; readers must mask the low 15
-bits instead of treating a negative i16 value as an absent reference.
+Bit 15 overlaps the signed-i16 view of `ref_id`. Readers must mask the low 15 bits. A negative i16 value does not mean the reference is absent.
---
@@ -253,11 +225,9 @@ pixel_x = (x + y) × 32
pixel_y = (y − x) × 16 + (map_diagonal / 2) × 16
```
-where `map_diagonal = tiled_width + tiled_height`. Moving `+1` in `x` steps up-left on screen (−32, −16); moving `+1` in
-`y` steps down-right (+32, +16).
+Here `map_diagonal = tiled_width + tiled_height`. A step of +1 in `x` moves the tile by (−32, −16) on screen. A step of +1 in `y` moves it by (+32, +16).
-Sprite and building placements inside the file are **map-local**: subtract
-`map_non_occluded_start_x/y` (computed in `src/map/model.rs`) to convert to world pixels.
+Sprite and building placements in the file use map-local coordinates. Subtract `map_non_occluded_start_x/y`, computed in `src/map/model.rs`, to convert them to world pixels.
## File Size Calculation
@@ -278,7 +248,7 @@ total = header + variable blocks + fixed_tail
## Implementation & Usage
- Parser: `read_map_data()` in `src/map/mod.rs`, block readers in `src/map/reader.rs`
-- Renderer: `render_map()` in `src/map/render.rs`; GUI canvas in
+- Renderer: `render_map()` in `src/map/render.rs`. The GUI canvas is in
`dispel-gui/src/components/map_render/`
```bash
diff --git a/docs/files/Map/MapModule.md b/docs/files/Map/MapModule.md
index 21f441ff..cfd04d2d 100644
--- a/docs/files/Map/MapModule.md
+++ b/docs/files/Map/MapModule.md
@@ -1,19 +1,15 @@
# Map Module Specification
-> DISPEL® is a registered trademark. This project is not affiliated with,
-> endorsed by, or sponsored by the trademark owner.
-
---
## Overview
-The `src/map/` module handles parsing, rendering, and database operations for the Dispel game's `.MAP`, `.GTL`, and
-`.BTL` binary file formats. It provides:
+The `src/map/` module parses and renders `.MAP`, `.GTL` and `.BTL` files. It also writes data to SQLite. It provides:
- **Binary parsing** of `.MAP` files (geometry, sprites, tiles, events, collisions)
- **Tileset extraction** from `.GTL` (ground) and `.BTL` (building) files
- **Isometric rendering** to PNG images
-- **Database import/export** via SQLite
+- **Database import and export** with SQLite
- **Sprite loading** from `.SPR` files for entity rendering
### Module Files
@@ -36,10 +32,9 @@ The `src/map/` module handles parsing, rendering, and database operations for th
## File Formats
-### `.MAP` — Map File
+### `.MAP`: map file
-Binary file containing the complete map definition: geometry, embedded sprites, tiled objects, event triggers, ground
-tiles, collision data, and optional roof tiles.
+The file holds geometry, embedded sprites, tiled objects, event triggers, ground tiles, collision data and optional roof tiles.
#### Structure
@@ -162,7 +157,7 @@ start_y = (-x + y) × 16 + (diagonal / 2 × 16)
#### Event Block Location
-The event block and tile blocks are located at the **end of the file**. The parser seeks backwards from EOF:
+The event block and tile blocks sit at the end of the file. The parser seeks backwards from EOF:
```
seek_offset = -(tiled_map_width × tiled_map_height × 4 × 3)
@@ -173,9 +168,9 @@ bytes/tile).
---
-### `.GTL` / `.BTL` — Tileset Files
+### `.GTL` and `.BTL`: tileset files
-Simple binary format with **no header**. Direct sequence of 32×32 pixel tiles in RGB565.
+The format has no header. It holds a sequence of 32×32 RGB565 tiles.
#### Structure
@@ -213,14 +208,14 @@ blue = bits 0–4 of pixel → scale 0-31 to 0-255
**File types:**
-- `.GTL` — Ground Tile Layer (terrain, paths, natural features)
-- `.BTL` — Building Tile Layer (structures, roofs, man-made objects)
+- `.GTL`: ground tile layer for terrain, paths and natural features
+- `.BTL`: building tile layer for structures, roofs and man-made objects
---
-### `.SPR` — Sprite Files (referenced, not owned by map module)
+### `.SPR`: sprite files (referenced, not owned by map module)
-Sprite files are parsed by the parent `sprite` module but loaded by `sprite_loader.rs` for entity rendering.
+The parent `sprite` module parses `.spr` files. `sprite_loader.rs` loads them for entity rendering.
#### Structure (per sequence)
@@ -345,8 +340,7 @@ struct LoadedSpriteFrame {
### Database
-Owned by `src/database/map_persistence.rs`; re-exported from `map` so existing
-`dispel_core::map::save_to_db` paths keep working.
+These functions live in `src/database/map_persistence.rs`. The `map` module re-exports them. Existing `dispel_core::map::save_to_db` paths keep working.
| Function | Description |
|-------------------------------------------------|------------------------------------|
@@ -378,12 +372,12 @@ Owned by `src/database/map_persistence.rs`; re-exported from `map` so existing
### Depth Sorting
-Sprites and tiled objects are sorted by `ground_y` before rendering:
+The renderer sorts sprites and tiled objects by `ground_y`.
- **Sprites**: `ground_y = sprite_y + frame_height`
- **Tiled objects**: `ground_y = tile_y + (stack_height × 32)`
-This ensures proper isometric depth ordering (painter's algorithm).
+This gives isometric depth order through the painter's algorithm.
---
@@ -415,7 +409,7 @@ This ensures proper isometric depth ordering (painter's algorithm).
## JSON Schema for Map Data Export
-The following JSON schema describes the structure for exporting `.MAP` file data:
+This JSON schema describes exported `.MAP` data:
```json
{
@@ -865,7 +859,7 @@ Where `w = tiled_map_width`, `h = tiled_map_height`.
## External Entity Rendering Colors
-When `game_path` is not provided or sprite files are missing, entities are rendered as colored diamond markers:
+The tool draws entities as colored diamond markers when `game_path` is absent or sprite files are missing.
| Entity Type | Color (RGBA) | Sprite Directory |
|-------------|----------------------------------|------------------|
@@ -877,11 +871,10 @@ When `game_path` is not provided or sprite files are missing, entities are rende
## Notes
-1. **Two unknown blocks** at the start of `.MAP` files are skipped — their purpose is not yet understood
-2. **Image stamps** (6 or 9) determine the padding size after sprite sequence data (1904 or 2996 bytes respectively)
-3. **Tiled object sentinel** — the end of the tiled objects block is detected by scanning 20 bytes backwards for the
- byte value 1
-4. **Roof block is optional** — only parsed if remaining file size is sufficient
-5. **Collision flag** is extracted from bit 0 of the packed tile value; tile index is bits 10–24
-6. **All integers are little-endian**
-7. **Sprite sequences** in the map file are self-contained — pixel data is embedded directly, not referenced externally
+1. The tool skips the first two blocks. The supplied data shows no use for these fields.
+2. Image stamp 6 uses 1904 bytes of padding after sprite sequence data. Image stamp 9 uses 2996 bytes.
+3. The tool finds the end of the tiled objects block with a 20-byte backwards scan for byte value 1.
+4. The tool parses the roof block only when enough bytes remain.
+5. The collision flag comes from bit 0 of the packed tile value. The tile index uses bits 10 to 24.
+6. All integers are little-endian.
+7. Sprite sequences in the map file hold embedded pixel data. The file does not reference external sprite data.
diff --git a/docs/files/NpcInGame/DlgMapFiles.dlg.md b/docs/files/NpcInGame/DlgMapFiles.dlg.md
index 0aa804b6..5b80d794 100644
--- a/docs/files/NpcInGame/DlgMapFiles.dlg.md
+++ b/docs/files/NpcInGame/DlgMapFiles.dlg.md
@@ -1,7 +1,4 @@
-# Dlgcat1.dlg - Dialogue/Conversation Scripts
-
-> DISPEL® is a registered trademark. This project is not affiliated with,
-> endorsed by, or sponsored by the trademark owner.
+# Dlgcat1.dlg: dialogue scripts
## File Information
@@ -16,7 +13,7 @@
- Lines starting with `;` are comments
- CSV format with comma delimiter
-- Empty lines are ignored
+- The parser ignores empty lines.
### Record Structure
@@ -29,8 +26,8 @@ Each line has exactly 10 comma-separated fields:
- `owner`: i32 - 0=player, 1=NPC
- `dlg_id`: i32 - Reference to PGP text content
- `opt0`: i32 - Next dialogue option 1 (choice dialogs) or next dialog in linear type
-- `opt1`: i32 - Next dialogue option 2 (choice dialogs); 0 = absent
-- `opt2`: i32 - Next dialogue option 3 (choice dialogs); 0 = absent
+- `opt1`: i32 - next dialogue option 2 for choice dialogs. Zero means absent.
+- `opt2`: i32 - next dialogue option 3 for choice dialogs. Zero means absent.
- `event_id`: i32 - Event triggered by dialogue
## Field Definitions
@@ -41,7 +38,7 @@ Each line has exactly 10 comma-separated fields:
- `type`: 0=normal, 1=choice dialog
- `owner`: 0=player, 1=NPC
- `dlg_id`: Reference to PGP text content
-- `opt0`–`opt2`: Choice-dialog branching targets; unused options are 0
+- `opt0` to `opt2`: choice-dialog targets. Unused options are 0.
- `event_id`: Event triggered by dialogue
## Dialogue Types
@@ -59,7 +56,7 @@ Each line has exactly 10 comma-separated fields:
- Optional fields are `0` when absent (not `"null"`)
- Lines starting with `;` are comments
- CSV format with comma delimiter
-- Empty lines are ignored
+- The parser ignores empty lines.
## File Purpose
@@ -77,7 +74,7 @@ quest dialogues, and story progression systems.
- **Rust Module**: `src/references/dialogue_script.rs`
- **Extractor**: `DialogueScript` struct implementing `Extractor` trait
-- **Database**: Saved to SQLite via `save_dialogs` function
+- **Database**: saved to SQLite by the `save_dialogs` function
## Extractor
diff --git a/docs/files/NpcInGame/Eventnpc.ref.md b/docs/files/NpcInGame/Eventnpc.ref.md
index 198d8cdb..b8df7f9c 100644
--- a/docs/files/NpcInGame/Eventnpc.ref.md
+++ b/docs/files/NpcInGame/Eventnpc.ref.md
@@ -1,7 +1,4 @@
-# Eventnpc.ref - Event NPC Definitions
-
-> DISPEL® is a registered trademark. This project is not affiliated with,
-> endorsed by, or sponsored by the trademark owner.
+# Eventnpc.ref: event NPC definitions
## File Information
@@ -17,8 +14,8 @@
- Lines starting with `;` are comments
- Rows are comma-separated, 40 columns each
-- Rows are terminated by CRLF
-- Empty lines are ignored
+- Each row ends with CRLF
+- The parser ignores empty lines.
### Record Structure
@@ -124,22 +121,17 @@ id, the high 16 bits the parameter - the same split the `Npccat*.ref` records us
- Lines starting with `;` are comments
- Empty lines ignored
-- The `id` column is the row index. The game itself ignores the value and
- selects rows by position.
+- The `id` column holds the row index. The tool selects rows by position.
## Known Data Defect
-The shipped `Eventnpc.ref` holds one row whose comma between the
-`npc_ini_id` and the `name` column is missing:
+The sample `Eventnpc.ref` holds one row with a missing comma between the `npc_ini_id` and `name` columns:
```text
2,69Character Name,guard,0,0,1,1,301,251,0,4,0,...,0,6
```
-The row therefore carries 39 columns. The game reads the leading digits of
-`69Character Name` as the archetype id and loses the name. The extractor splits
-the glued column back apart, so the record keeps the id `69` and the name
-`Character Name`. Saving the file writes the repaired 40-column row.
+That row carries 39 columns. The tool splits the glued column apart. The record keeps id `69` and name `Character Name`. When you save the file, the tool writes a repaired 40-column row.
## Extractor
diff --git a/docs/files/NpcInGame/NpcMapFiles.ref.md b/docs/files/NpcInGame/NpcMapFiles.ref.md
index 61cfde5c..30f04097 100644
--- a/docs/files/NpcInGame/NpcMapFiles.ref.md
+++ b/docs/files/NpcInGame/NpcMapFiles.ref.md
@@ -1,7 +1,4 @@
-# Npccat1.ref - NPC Placement Data
-
-> DISPEL® is a registered trademark. This project is not affiliated with,
-> endorsed by, or sponsored by the trademark owner.
+# Npccat1.ref: NPC placement data
## File Information
@@ -41,7 +38,7 @@
| 664 | dialog_id | Dialogue node ID. |
| 668 | dialogue_face_sprite_id | Face sprite ID. |
-## Looking Directions
+## Direction values
- `0`: Up (North)
- `1`: Up-Right (Northeast)
@@ -82,7 +79,7 @@ characters.
- **Rust Module**: `src/references/npc_ref.rs`
- **Extractor**: `NPC` struct implementing `Extractor` trait
-- **Database**: Saved to SQLite via `save_npc_refs` function
+- **Database**: saved to SQLite by the `save_npc_refs` function
## Extractor
diff --git a/docs/files/NpcInGame/PgpMapFiles.pgp.md b/docs/files/NpcInGame/PgpMapFiles.pgp.md
index 2db957cb..a52cc18b 100644
--- a/docs/files/NpcInGame/PgpMapFiles.pgp.md
+++ b/docs/files/NpcInGame/PgpMapFiles.pgp.md
@@ -1,7 +1,4 @@
-# Pgpcat1.pgp - Dialogue Text
-
-> DISPEL® is a registered trademark. This project is not affiliated with,
-> endorsed by, or sponsored by the trademark owner.
+# Pgpcat1.pgp: dialogue text
## File Information
@@ -16,7 +13,7 @@
- Lines starting with `;` are comments
- Pipe-delimited format
-- Empty lines are ignored
+- The parser ignores empty lines.
### Record Structure
@@ -37,14 +34,14 @@
## Parameter Usage
- `param1`: Dialogue branch conditions
-- `wave_ini_entry_id`: Sound effect played at dialogue start; 0 = none
+- `wave_ini_entry_id`: sound effect at dialogue start. Zero means none.
## Text Formatting
- "null" literal for empty text
- "$" literal interpreted as a line-break in game
- Pipe (|) delimiter between fields
-- Semicolon (;) for comment lines
+- Semicolon (`;`) for comment lines
- Multi-line comments supported
## Special Values
@@ -56,8 +53,7 @@
## File Purpose
-Stores dialogue text content with developer comments and logical parameters. Used for displaying conversation text,
-branching dialogue, and triggering game events.
+The tool stores dialogue text with developer comments and parameters. Each row holds an ID, text and a sound reference.
## Related Files
@@ -70,7 +66,7 @@ branching dialogue, and triggering game events.
- **Rust Module**: `src/references/dialogue_paragraph.rs`
- **Extractor**: `DialogueParagraph` struct implementing `Extractor` trait
-- **Database**: Saved to SQLite via `save_dialogue_paragraphs` function
+- **Database**: saved to SQLite by the `save_dialogue_paragraphs` function
## Extractor
diff --git a/docs/files/NpcInGame/PrtIni.db.md b/docs/files/NpcInGame/PrtIni.db.md
index e6f09570..8a7b1ef0 100644
--- a/docs/files/NpcInGame/PrtIni.db.md
+++ b/docs/files/NpcInGame/PrtIni.db.md
@@ -6,7 +6,7 @@
- No header.
- Exactly eight 28-byte records.
-- Records are addressed as `party_slot * 28`.
+- The parser addresses records as `party_slot * 28`.
- `name` is a 20-byte, null-padded string. Names are ASCII-compatible.
| Offset | Size | Type | Field | Meaning |
@@ -18,10 +18,6 @@
| `23` | 1 | u8 | `pathfinding_mode` | Map/path-query mode; observed value 7 |
| `24` | 4 | u32 | `character_variant` | Variant selector; observed values 0 and 1 |
-The loader copies `class_id`, `starting_level`, `pathfinding_mode`, and
-`character_variant` into runtime character state. It uses `class_id` for class-specific behavior and titles, and uses
-`character_variant` to choose one of two class variants. The binary does not establish whether that variant is a gender,
-portrait, or another presentation choice, so the parser uses the neutral name `character_variant`.
+The tool reads `class_id`, `starting_level`, `pathfinding_mode` and `character_variant` into character state. The supplied data does not establish what `character_variant` represents. The parser uses that neutral name.
+
-DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark
-owner.
diff --git a/docs/files/NpcInGame/PrtLevel.db.md b/docs/files/NpcInGame/PrtLevel.db.md
index b3f48685..56a4adcb 100644
--- a/docs/files/NpcInGame/PrtLevel.db.md
+++ b/docs/files/NpcInGame/PrtLevel.db.md
@@ -1,8 +1,6 @@
# PrtLevel.db
-`NpcInGame/PrtLevel.db` contains eight party-member progression tables, each with 20 levels. It has no header: the game
-reads level `n` of party slot `s`
-at `s * 720 + (n - 1) * 36`.
+`NpcInGame/PrtLevel.db` contains eight party-member progression tables, each with 20 levels. It has no header. The tool reads level `n` of party slot `s` at `s * 720 + (n - 1) * 36`.
Each entry is 36 bytes.
@@ -24,13 +22,8 @@ Each entry is 36 bytes.
| `28` | 4 | u32 | `weapon_skill_level` | Party member's shared weapon proficiency |
| `32` | 4 | u32 | `tactical_action_chance` | Percentage threshold for a level-10+ tactical action |
-The first three bytes were previously misidentified as a sentinel. They are magic-spell references copied into runtime
-state. All reserved bytes are preserved verbatim by the parser.
+The first three bytes hold magic-spell IDs. The tool preserves all reserved bytes.
+
+`weapon_skill_level` holds a shared weapon proficiency value. `tactical_action_chance` holds a percentage threshold from 0 to 99.
-`weapon_skill_level` is not MP recharge: the game uses it in the same generic weapon calculations that select one of the
-player's weapon-skill levels.
-`tactical_action_chance` is not defence: it is compared to a random value from 0 to 99 before changing the party
-member's tactical action state.
-DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark
-owner.
From 348da02dfb6c55bbfe882e04d15ebaf561badfb1 Mon Sep 17 00:00:00 2001
From: dimspell <141545384+dimspell@users.noreply.github.com>
Date: Wed, 25 Nov 2026 13:57:50 +0100
Subject: [PATCH 07/72] docs: rewrite AGENTS.md in plain English
---
AGENTS.md | 226 +++++++++++++++++++++++++++---------------------------
1 file changed, 112 insertions(+), 114 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
index 3b7872c6..e1f909f7 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,12 +1,12 @@
-# AGENTS.md — Dispel Game File Extractor
+# AGENTS.md: Dispel Game File Extractor
-**A game modding toolkit for Dispel RPG.** Reads/writes game files in native binary, INI, and DB formats — including save games. All edits are persisted directly — no intermediate database. Includes a full desktop GUI for editing game data with undo/redo, mod packaging, and a hex editor.
+This toolkit reads and writes game files in binary, INI and DB formats. It also handles save games. Edits go directly into game files. The repository includes a desktop GUI, a hex editor and a mod packaging pipeline.
---
## Project Overview
-This workspace is a **6-crate Cargo workspace** (Rust edition 2024) versioned `0.9.3`:
+The workspace is a **6-crate Cargo workspace** with Rust edition 2024 and version `0.9.3`.
| Crate | Type | Role |
|---|---|---|
@@ -17,7 +17,7 @@ This workspace is a **6-crate Cargo workspace** (Rust edition 2024) versioned `0
| `gui-widgets` | lib | Reusable custom Iced widgets (ContextMenu, modal, popover, toast, ParagraphCache…). |
| `hexedit` | lib + bin | Full hex editor — used by `dispel-gui` as a tab type. Single binary: `hexedit`. |
-**Separation of concerns:**
+Separation of concerns:
- `dispel-core` + `dispel-macros` + `dispel-encodings`: game logic only. Zero GUI/presentation code.
- `dispel-gui` + `gui-widgets` + `hexedit`: UI only. Zero game logic (they consume `dispel-core`).
- `dispel-extractor` (root `main.rs`): thin CLI wrapper around the library.
@@ -53,7 +53,7 @@ dispel-extractor/
│ ├── app.rs # App (transient UI state; embeds AppState)
│ ├── state.rs # AppState (persistent model) + RecordingSession
│ ├── workspace.rs # Tabs; re-exports EditorType from editor_catalog/
-│ ├── editor_catalog/ # define_editor_catalog! — 45 named variants + Unknown (EDITOR_COUNT = 46)
+│ ├── editor_catalog/ # define_editor_catalog! — 45 named variants + `Unknown` (EDITOR_COUNT = 46)
│ ├── editor_registry.rs # All 47 editor state fields
│ ├── platform.rs # OS-specific ops
│ ├── style.rs + style/ # Iced style functions ("Medieval" theme), split per component
@@ -96,7 +96,7 @@ dispel-extractor/
| `.snf` | Audio | PCM | Sound effects |
| `.ifo` / save file | Save game | Binary | Player saves (`Save.ifo`, parsed by `save_ifo` / `save_file`) |
-**Encoding is critical:** `Event.ini`, `Npc.ini`, `Monster.db` (desc) → **EUC-KR**. `Monster.ini`, `Store.db`, `WeaponItem.db` → **WINDOWS-1250**. Per-file encoding documented in `docs/files/CROSS_REFERENCES.md`.
+Check the encoding before you read a file. `Event.ini`, `Npc.ini` and `Monster.db` descriptions use EUC-KR. `Monster.ini`, `Store.db` and `WeaponItem.db` use WINDOWS-1250. `docs/files/CROSS_REFERENCES.md` lists the encoding of each file.
### Item Type Enum
| Value | Type | Database |
@@ -131,16 +131,18 @@ dispel-extractor/
## Binary Format Essentials
-- **All integers**: little-endian
-- **Colors**: RGB 565 (16-bit). Helpers: `sprite::Color::from_rgb565()` / `to_rgb565()`
-- **Map tiles**: seeked from EOF (event/GTL/BTL layers)
-- **Sprites**: start at byte 268; validation: `ints[11] * ints[12] == ints[13]`
-- **Tilesets**: contiguous 32×32 tiles, RGB 565 (2 bytes/pixel)
-- **Map rendering**: isometric projection, 62×32 display size; Y-sorted draw order for walls/objects. **Warning:** full map ≈ 300MB; GUI uses viewport + LRU cache (≤50MB via `lru` 0.12).
-- **TMX export**: `map::tmx::export_tmx()` converts `.map` + tilesets to Tiled TMX XML (isometric, CSV tile data)
-- **SNF audio**: custom PCM header; prepend RIFF WAVE header for conversion (`SnfFile::to_wav_bytes()`)
-- **DB record sizes** (all fixed): WeaponItem 284B, Monster 160B, Magic 88B, HealItem 252B, EditItem 268B, EventItem 240B, MiscItem 256B, ChData 84B, Store 948B (variable product list), PartyIniNpc 28B, PartyLevelNpc 5760B (8×20 grid), NPC 672B, MonsterRef 56B, ExtraRef 184B. Save records (`SaveFile`, `SaveIfo`) are variable-layout — see `docs/files/`.
-- **Static layout metadata**: `references/layout.rs` defines `FieldDef` / `FixedRecordLayout` and the `RecordLayout` derive trait — generated byte-offset metadata for fixed-size records.
+- All integers use little-endian byte order.
+- Colors use 16-bit RGB 565. Helpers: `sprite::Color::from_rgb565()` and `to_rgb565()`.
+- The parser seeks map tiles from EOF for the event, GTL and BTL layers.
+- Sprite data starts at byte 268. Validation uses `ints[11] * ints[12] == ints[13]`.
+- Tilesets hold contiguous 32×32 tiles in RGB 565, with 2 bytes per pixel.
+- Map rendering uses an isometric projection at 62×32 pixels. The tool draws walls and objects in Y-sorted order. A full map takes about 300MB. The GUI uses a viewport and an LRU cache of at most 50MB from `lru` 0.12.
+- `map::tmx::export_tmx()` converts a `.map` file and tilesets to Tiled TMX XML. The XML uses isometric projection and CSV tile data.
+- SNF audio has a custom PCM header. `SnfFile::to_wav_bytes()` prepends a RIFF WAVE header.
+- Fixed DB record sizes: WeaponItem 284B, Monster 160B, Magic 88B, HealItem 252B, EditItem 268B, EventItem 240B, MiscItem 256B, ChData 84B and Store 948B with a variable product list.
+- Other fixed sizes: PartyIniNpc 28B, PartyLevelNpc 5760B for an 8×20 grid, NPC 672B, MonsterRef 56B and ExtraRef 184B.
+- `SaveFile` and `SaveIfo` use variable layouts. See `docs/files/`.
+- `references/layout.rs` defines `FieldDef`, `FixedRecordLayout` and the `RecordLayout` derive trait. They generate byte-offset metadata for fixed-size records.
See `docs/file_formats.md` and per-file `docs/files/*.md` for detailed specs.
@@ -158,7 +160,7 @@ See `docs/file_formats.md` and per-file `docs/files/*.md` for detailed specs.
| `RecordPatcher` | `modding/patcher.rs` | Applies mod patches to individual records. Two derive variants (binary + text). |
| `Command` | `commands/mod.rs` | CLI command trait: `fn execute(&self) -> Result<(), Box>` |
-### Modding pipeline (`src/modding/`)
+### Mod pipeline (`src/modding/`)
Core modules: `apply`, `bsdiff`, `change`, `changelog`, `conflicts`, `manifest`, `package`, `patcher`, `registry`, `resolution`, `value`, `vanilla`, `workspace` (+ `error.rs`). Per-format record patchers live in `modding/patchers/`: `derived`, `dialogue`, `draw_item`, `event_script`, `misc_item`, `party_level`, `quest`, `save_ifo`, `store`.
@@ -167,21 +169,21 @@ Core modules: `apply`, `bsdiff`, `change`, `changelog`, `conflicts`, `manifest`,
- Other modules use `std::io::Result` / `rusqlite::Result` directly (plus thiserror errors in `dispel-gui`'s indexation/file-tree modules).
### Encoding helpers
-- `dispel-encodings` crate — single source of truth for accepted spellings (`WINDOWS-1250`/`WINDOWS_1250`, `EUC-KR`/`EUC_KR`, `UTF-8`/`UTF_8`, case-insensitive), CSV/PO labels and the `encoding_rs` mapping. Both `dispel-macros` (compile time) and `dispel-core` (runtime) consume it.
-- `TextEncoding` — re-exported from `localization.rs` (defined in `dispel-encodings`); `encoding_rs_for()`, `encoded_len()` in `localization.rs`
-- `read_null_terminated(bytes, &TextEncoding)` — in `references/extractor.rs`; `read_null_terminated_windows_1250()` is its backward-compatible wrapper
-- `WINDOWS_1250` / `EUC_KR` still used directly in a few hand-written parsers/patchers (not yet routed through the registry)
-- Enum wire-value fallback (`from_X(v).unwrap_or_default()`) lives once in `references/enums.rs::WireValue::from_wire`; the derive macros call it so parse and patch agree
+- The `dispel-encodings` crate holds accepted spellings (`WINDOWS-1250`/`WINDOWS_1250`, `EUC-KR`/`EUC_KR`, `UTF-8`/`UTF_8`, case-insensitive). It also holds CSV/PO labels and the `encoding_rs` mapping. `dispel-macros` reads it at compile time. `dispel-core` reads it at runtime.
+- `localization.rs` re-exports `TextEncoding` from `dispel-encodings`. The same file defines `encoding_rs_for()` and `encoded_len()`.
+- `references/extractor.rs` defines `read_null_terminated(bytes, &TextEncoding)`. It also defines the wrapper `read_null_terminated_windows_1250()`.
+- A few hand-written parsers and patchers use `WINDOWS_1250` and `EUC_KR` directly.
+- `references/enums.rs::WireValue::from_wire` holds the enum wire-value fallback `from_X(v).unwrap_or_default()`. The derive macros call it. Parse and patch then agree.
### SQLite schema (`src/queries/`)
-118 SQL files: 59 `create_table_*.sql` (schema DDL) + 59 parameterized `insert_*.sql`. Run by `database.rs` to drop and recreate the schema. **No foreign keys** — relationships are enforced in code, not SQL constraints.
+The directory holds 118 SQL files: 59 `create_table_*.sql` files for schema DDL and 59 parameterized `insert_*.sql` files. `database.rs` runs them to drop and recreate the schema. The schema has no foreign keys. Code enforces relationships.
### Tests
-**95 `#[cfg(test)]` blocks across 87 `.rs` files** in the root crate. Parsers have hardcoded-byte-slice unit tests; save-file round-trip checking lives in `examples/check_save_roundtrip.rs`.
+The root crate has **95 `#[cfg(test)]` blocks across 87 `.rs` files**. Parsers use hardcoded byte-slice unit tests. Save-file round-trip checking lives in `examples/check_save_roundtrip.rs`.
---
-## dispel-macros — Proc-Macro Crate
+## dispel-macros: proc-macro crate
7 derive macros using `syn 2` + `quote 1`:
@@ -195,13 +197,13 @@ Core modules: `apply`, `bsdiff`, `change`, `changelog`, `conflicts`, `manifest`,
| `#[derive(TextRecordPatcher)]` | `RecordPatcher` impl (text) + unit struct | Modding for text formats |
| `#[derive(Localizable)]` | `Localizable` impl | Translation extraction |
-**Attributes:** `#[extractor(id, string, primitive, enum_from_*, padding, array, skip, ...)]` on binary; `#[extractor(field=N, parse_null, enum_from_i32)]` + struct-level `encoding, delimiter, comment_char` on text; `#[patcher(filename=...)]` or `#[patcher(extension=..., stem_prefix=...)]`; `#[translatable(encoding=..., max_bytes=N)]`.
+Attributes: `#[extractor(id, string, primitive, enum_from_*, padding, array, skip, ...)]` on binary records. Text records use `#[extractor(field=N, parse_null, enum_from_i32)]` and struct-level `encoding, delimiter, comment_char`. Patchers use `#[patcher(filename=...)]` or `#[patcher(extension=..., stem_prefix=...)]`. Translatable fields use `#[translatable(encoding=..., max_bytes=N)]`.
-**Used by 26+ structs in `src/references/`.** No direct unit tests — verified indirectly via dependent crate's tests.
+26+ structs in `src/references/` use these macros. There are no direct unit tests. Dependent crates test them indirectly.
---
-## gui-widgets — Reusable Iced Widgets
+## gui-widgets: reusable Iced widgets
| Widget | Location | Purpose |
|---|---|---|
@@ -220,24 +222,24 @@ Also: `sweeten/` (builder-style helpers) and `lucide.rs` (icon set).
---
-## hexedit — Hex Editor Crate
+## hexedit: hex editor crate
Standalone library + single binary (`hexedit`, `src/main.rs`). Rust edition 2024. Iced (fork) with no features of its own.
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 (**26 `.rs` files with `#[cfg(test)]` total**)
+- `domain/` holds about 16 files: edit, goto, pattern, provider, search, selection and vanilla_diff.
+- `ui/` holds the inspector, update, view/, theme and colouring modules.
+- `tests/` holds 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`.
+`dispel-gui` stores hexedit state as `HashMap` in `EditorRegistry`. Tabs render it. `hex_save.rs` wires saves to the mod packager through the domain-level `SavePort` (`SaveRequest` → `SaveOutcome`).
---
## dispel-gui Architecture
### Tech Stack
-- **UI**: Iced from git fork `dimspell/iced` (rev `c0ffdd8`; GPU via wgpu, Elm/MVU, advanced + lazy features)
+- UI: Iced from the git fork `dimspell/iced`, rev `c0ffdd8`. It uses wgpu, Elm/MVU, advanced and lazy features.
- **Async**: Tokio multi-thread runtime + `iced::Task::perform`
- **Core**: `dispel_core` (sibling crate)
- **Search**: nucleo-matcher 0.3 (fuzzy full-text)
@@ -245,8 +247,11 @@ Structure:
- **File dialogs**: rfd 0.16
- **Window**: 1100×800, custom "Medieval" theme (dark leather/gold)
- **macOS native**: objc2 + objc2-app-kit + objc2-foundation (context menus, file manager reveal)
-- **Accessibility**: forked iced `accessibility` feature with vendored accesskit; enabled on `dispel-gui` only. The workspace `[patch.crates-io]` pins `winit` to an iced-rs fork for version alignment. Only `table_widget` implements full accesskit nodes (`accessibility()` + `accessibility_action()`). Custom widgets (context menu, modal, hex matrix) use the default no-op methods.
-- **Tests**: `iced_test` (same git fork, optional feature), `proptest`, `syn`
+- Accessibility: the forked iced `accessibility` feature uses vendored accesskit. Only `dispel-gui` enables it.
+- The workspace `[patch.crates-io]` pins `winit` to an iced-rs fork for version alignment.
+- Only `table_widget` implements full accesskit nodes with `accessibility()` and `accessibility_action()`.
+- Custom widgets such as the context menu, modal and hex matrix use the default no-op methods.
+- Tests: `iced_test` from the same fork as an optional feature, `proptest` and `syn`.
### Flow
`user action → Message → update/ handler (mutates App + AppState) → view/ (pure render)`
@@ -281,27 +286,27 @@ Top-level `Message` enum (`message/mod.rs`) has 5 variants:
**`MessageExt` trait** (`message/ext.rs`, generated by `define_message_ext!` macro) provides shorthand constructors like `Message::weapon(WeaponEditorMessage::LoadCatalog)`.
-### Editor System — 46 editor types / 47 registry state fields
+### Editor system: 46 editor types and 47 registry state fields
-`EditorType` is generated by `define_editor_catalog!` in `editor_catalog/mod.rs` (re-exported from `workspace.rs`); it has 45 named variants + `Unknown` (with `#[serde(other)]`), and `EDITOR_COUNT` is 46. Variants are suffixed `Editor` (e.g. `WeaponEditor`, `SaveIfoEditor`); new since v0.7: `SaveFileViewer`, `SaveIfoEditor`, `HexEditor`, `DialogueTextEditor`, `AudioViewer`, `BmpViewer`.
+`editor_catalog/mod.rs` defines `EditorType` through `define_editor_catalog!`. `workspace.rs` re-exports the type. It has 45 named variants plus `Unknown`, which uses `#[serde(other)]`. `EDITOR_COUNT` is 46. Variants end in `Editor`, for example `WeaponEditor` and `SaveIfoEditor`. Version 0.7 added `SaveFileViewer`, `SaveIfoEditor`, `HexEditor`, `DialogueTextEditor`, `AudioViewer` and `BmpViewer`.
-**Standard editors (20)** — macro-generated via `define_standard_editor!`, invoked in each editor's own `editors//mod.rs`:
+Twenty standard editors use `define_standard_editor!` in their own `editors//mod.rs`:
`weapon`, `monster`, `heal_item`, `misc_item`, `edit_item`, `event_item`, `party_ref`, `all_map_ini`, `event_ini`, `draw_item`, `chdata`, `event_npc_ref`, `map_ini`, `npc_ini`, `message_scr`, `extra_ini`, `magic`, `quest_scr`, `monster_ini`, `party_ini`
-**Custom boxed editors** — custom state in `Box<...>` (all listed in `EditorRegistry`):
+Custom boxed editors keep state in `Box<...>`. All appear in `EditorRegistry`:
`save_ifo_editor`, `event_scr`, `wave_ini`, `store`, `party_level_db`, `localization_manager`, …
-**Tabbed editors (5)** — `TabbedEditor` (HashMap>):
+Five tabbed editors use `TabbedEditor`, a HashMap from tab IDs to `MultiFileEditorState`:
`monster_ref`, `dialogue_script`, `dialogue_paragraph`, `extra_ref`, `npc_ref`
**Single-instance special editors:** mod_packager_editor (ModPackagerState)
-**Per-tab HashMap editors (8)** — one state per open tab:
+Eight per-tab HashMap editors keep one state per open tab:
`sprite_viewers`, `map_editors`, `tileset_editors`, `snf_editors`, `audio_viewers`, `bmp_viewers`, `hex_editors`, `save_file_viewers`
### `define_standard_editor!` macro
-Generates from a single declaration (now placed in each editor's `editors//mod.rs`):
+The macro generates code from one declaration in each `editors//mod.rs`:
```rust
define_standard_editor! {
name: weapon,
@@ -317,7 +322,7 @@ Produces: `pub type WeaponEditorState = StandardEditor`, `pub type W
### `EditorRegistry` (`editor_registry.rs`)
-Aggregates all editor state fields. Provides consolidated lifecycle:
+This struct holds all editor state fields and provides the lifecycle methods:
| Method | Role |
|---|---|
@@ -331,7 +336,7 @@ Aggregates all editor state fields. Provides consolidated lifecycle:
| `stop_snf_playback()` | Stops any playing SNF audio |
| `stop_audio_playback()` | Stops any playing audio-viewer audio |
-**Principle:** `AppState` exposes only pass-through methods — all real work lives in `EditorRegistry`.
+Principle: `AppState` exposes pass-through methods only. `EditorRegistry` does the work.
### Workspace & Tab Management (`workspace.rs`)
@@ -352,8 +357,8 @@ pub struct Workspace {
3-pane layout (sidebar | main content | history panel) using `pane_grid::State`. `PaneContent` enum: `Sidebar | MainContent | HistoryPanel`. `PaneState` tracks focus and maximized.
### Subscriptions (`subscriptions.rs`)
-- Keyboard handling via a single `keyboard::listen()` filter (shortcuts live in the filter logic, not a literal key list)
-- Separate global-search subscription; Event Script Editor ESC-shortcut subscription
+- Keyboard handling uses one `keyboard::listen()` filter. Shortcuts live in the filter logic, not a literal key list.
+- A separate subscription handles global search. Another handles the Event Script Editor ESC shortcut.
- Sprite animation tick (16ms)
- SNF and audio-viewer playback poll (250ms)
- Event script indexing poll (100ms)
@@ -373,30 +378,30 @@ pub struct Workspace {
### Mod Recording
-`RecordingSession` is defined in `state.rs`. Every `FieldChanged` handler calls `observe_field_change()` in `editors/mod_packager/recording.rs`. Records are debounced via `PendingEdit` / `RecordingKey` per field edit, then flushed to the mod changelog on save. 38 integration tests in `recording_tests.rs` cover macro-generated, custom-wrapper, fully-custom, and tab-based editor types.
+`state.rs` defines `RecordingSession`. Each `FieldChanged` handler calls `observe_field_change()` in `editors/mod_packager/recording.rs`. The tool debounces records through `PendingEdit` and `RecordingKey` for each field edit. It flushes them to the mod changelog on save. `recording_tests.rs` holds 38 integration tests. They cover macro-generated, custom-wrapper, fully custom and tab-based editor types.
### Indexation & Search
`indexation/` module:
-- `file_index_cache.rs` — `FileIndexCache` + `FileIndexCacheManager` (persistent bincode on disk)
-- `indexation_service.rs` — `IndexationService` background file scanning
-- `search_index.rs` — `SearchIndex` nucleo-matcher full-text search with persistence
-- `tests.rs` — Indexation tests
+- `file_index_cache.rs`: `FileIndexCache` and `FileIndexCacheManager`, stored as bincode on disk
+- `indexation_service.rs`: `IndexationService` scans files in the background
+- `search_index.rs`: `SearchIndex` uses nucleo-matcher and persists its index
+- `tests.rs`: indexation tests
-### Adding a New Editor
+### Add a new editor
-1. Implement `Extractor` (derive via `dispel-macros`) in `dispel-core/src/references/`
+1. Implement `Extractor` with `dispel-macros` in `dispel-core/src/references/`
2. If single-file spreadsheet: invoke `define_standard_editor!` in `dispel-gui/src/editors//mod.rs`
3. Otherwise: create `editors/my_editor/{mod,state,message,update,view}.rs`
-4. Add field to `EditorRegistry` (not `AppState` — editors are consolidated)
+4. Add a field to `EditorRegistry`, not `AppState`. The registry holds all editor state.
5. Add `EditorMessage` variant in `message/editor/mod.rs` (use `define_message_ext!` macro for shorthand)
-6. Add handler in `update/editor/` and route via `dispatch_table.rs` / `update/editor/mod.rs`
+6. Add a handler in `update/editor/`. Route it through `dispatch_table.rs` and `update/editor/mod.rs`.
7. Wire `EditorType::from_path()` for file extension detection (in `workspace.rs`)
8. Wire `view/mod.rs` dispatch (the `view_editor` match)
9. Wire `EditorRegistry` lifecycle methods (`remove_tab`, `undo_active`, etc.)
-10. Delete old editor code — never keep both
+10. Delete old editor code. Never keep both.
-### Naming Glossary
+### Glossary
| Term | Meaning |
|------|---------|
@@ -414,7 +419,7 @@ pub struct Workspace {
- **State mutation**: `update/` only. Views are pure.
- **Views**: defined as `impl App` blocks in `view/*.rs`, not `app.rs`.
- **Messages**: use `define_message_ext!` macro for shorthand constructors.
-- **Scan vs Browse**: "Scan" = load from `shared_game_path`; "Browse" = file picker.
+- Scan and Browse: Scan loads from `shared_game_path`. Browse opens a file picker.
- **Game files**: editors read/write game files directly.
- **Enums over booleans**: e.g. `LoadingState { Idle, Loading, Loaded(T), Failed(String) }`
- **Editor state lives on `EditorRegistry`, not `AppState`**.
@@ -433,34 +438,41 @@ pub struct Workspace {
| `docs/iced-fork-config.md` | Single iced fork pin set, feature matrix, headless test backend, consistency check |
| `docs/files/*.md` | **36 per-format docs** (in subdirectories `CharacterInGame/`, `MonsterInGame/`, `NpcInGame/`, `Ref/`, `Map/`, `ExtraInGame/`, `MagicInGame/` and at the top level) + `CROSS_REFERENCES.md` — 37 files total |
-Always read the relevant `docs/files/*.md` before modifying a parser.
+Read the relevant `docs/files/*.md` before you change a parser.
## Build System & CI
### Makefile targets (95 total)
- Basic dev: `fmt`, `check`, `build`, `cargo_test`, `clippy`, `run`, `help`, `check_iced_config`, `check_metadata`, `check_metadata_test`
-- Build, fmt, clippy and test recipes delegate to **`scripts/ci-commands.sh`** — the one canonical command set shared with CI. Set `ICED_TEST_BACKEND=software` where Iced simulations need the CPU renderer.
-- `iced_test`, `hexedit_test` — headless GUI/hexedit test suites
-- `hexedit` — launch the hex editor
-- Extraction/render: `sound`, `sprite-*`, `map-render` (+ 13 `map-render-*` flavors), `map-atlas-gtl/btl`, `map-to-db` / `map-from-db`
- - Every `map-render*` flavor is generated from **one** recipe plus a flag table (`MAP_RENDER_ARGS`, per-flavor `MAP_RENDER_EXTRA`) and the `MAP_RENDER_TARGETS` list. A common flag change touches `MAP_RENDER_ARGS` only.
- - `light_template` is configurable (`make map-render-lit light_template=/path/to/light_template.png`); the default is `$(game_path)/Map/light_template.png` and assumes no sibling repo.
-- `extract-*` (~24 targets) — extract individual game files to JSON
-- `database-*` — SQLite import (maps, databases, refs, rest, dialog-texts)
-- `template*`, `patch-*`, `list-json`, `sprite-info`, `mod-pack-*` — misc pipelines
-
-`make help` lists CLI subcommands; the Makefile's `.PHONY` list is kept in sync with real recipes by `scripts/check-project-metadata.sh`.
+- Build, fmt, clippy and test recipes call `scripts/ci-commands.sh`. This is the single canonical command set shared with CI. Set `ICED_TEST_BACKEND=software` where Iced simulations need the CPU renderer.
+- `iced_test` and `hexedit_test` run headless GUI and hexedit suites.
+- `hexedit` launches the hex editor.
+- Extraction and render targets: `sound`, `sprite-*`, `map-render` plus 13 `map-render-*` flavors, `map-atlas-gtl/btl`, `map-to-db` and `map-from-db`.
+ - One recipe and a flag table generate every `map-render*` flavor. The table holds `MAP_RENDER_ARGS` and per-flavor `MAP_RENDER_EXTRA`. The `MAP_RENDER_TARGETS` list names the flavors. A common flag change touches `MAP_RENDER_ARGS` only.
+ - `light_template` is configurable with `make map-render-lit light_template=/path/to/light_template.png`. The default is `$(game_path)/Map/light_template.png`. It assumes no sibling repo.
+- `extract-*` has about 24 targets. They extract individual game files to JSON.
+- `database-*` imports maps, databases, refs, rest and dialog texts to SQLite.
+- `template*`, `patch-*`, `list-json`, `sprite-info` and `mod-pack-*` run miscellaneous pipelines.
+
+`make help` lists CLI subcommands. `scripts/check-project-metadata.sh` keeps the Makefile `.PHONY` list in sync with real recipes.
### GitHub Actions
-- `.github/workflows/test.yml` — CI on push to `master`: fmt, iced-config + metadata checks, clippy, full test suite, build on ubuntu-latest
-- `.github/workflows/pr.yml` — same verify job, then a 5-build release-binary matrix
-- `.github/workflows/release.yml` — Release on tag `v*.*.*`: the same 5 builds, archives with SHA256, uploads to GitHub release (draft)
-- Both matrix workflows read the **single** matrix definition in `.github/build-matrix.json` via a `build-matrix` job and `fromJSON(needs.build-matrix.outputs.matrix)` — target lists cannot drift between PR and release.
-- All three workflows use `dtolnay/rust-toolchain@stable`. The test.yml and pr.yml verify jobs call `scripts/ci-commands.sh` for fmt/clippy/test; test.yml also routes its workspace build through the script. Release matrix builds invoke Cargo directly with each target's flags.
-- `scripts/check-project-metadata.sh` (also run by the Makefile) validates AGENTS.md counts, `.PHONY` ↔ recipe parity, canonical command parity, and matrix parity. `scripts/test-check-project-metadata.sh` injects eight independent drifts into a scratch tree to test that validator; both run in `test.yml` and `pr.yml`.
+- `.github/workflows/test.yml`: CI on push to `master` runs fmt, iced-config and metadata checks, clippy, the full test suite and a build on ubuntu-latest.
+- `.github/workflows/pr.yml`: the same `verify` job, then a 5-build release-binary matrix.
+- `.github/workflows/release.yml`: Release on tag `v*.*.*` runs the same 5 builds. It archives with SHA256 and uploads to a draft GitHub release.
+- Both matrix workflows read one definition in `.github/build-matrix.json`. A `build-matrix` job reads it with `fromJSON(needs.build-matrix.outputs.matrix)`. Target lists cannot drift between PR and release.
+- All three workflows use `dtolnay/rust-toolchain@stable`. The `verify` jobs in test.yml and pr.yml call `scripts/ci-commands.sh` for fmt, clippy and test. test.yml also routes its workspace build through the script. Release matrix builds invoke Cargo directly with each target's flags.
+- `scripts/check-project-metadata.sh` (also run by the Makefile) validates AGENTS.md counts, `.PHONY` ↔ recipe parity, canonical command parity, and matrix parity. `scripts/test-check-project-metadata.sh` injects eight independent drifts into a scratch tree to test that validator. Both scripts run in `test.yml` and `pr.yml`.
### Release script
-`scripts/release.sh` automates: validate semver → `bash scripts/ci-commands.sh fmt-check` + `bash scripts/ci-commands.sh test` → bump version in all workspace `Cargo.toml` (discovered via `cargo metadata`) → regen `Cargo.lock` via `bash scripts/ci-commands.sh check` → commit + tag `v{major}.{minor}.{patch}` → print push instructions.
+`scripts/release.sh` automates these steps:
+
+1. Validate the semver value.
+2. Run `bash scripts/ci-commands.sh fmt-check` and `bash scripts/ci-commands.sh test`.
+3. Bump the version in every workspace `Cargo.toml` found through `cargo metadata`.
+4. Regenerate `Cargo.lock` with `bash scripts/ci-commands.sh check`.
+5. Commit and tag `v{major}.{minor}.{patch}`.
+6. Print push instructions.
---
@@ -469,22 +481,22 @@ Always read the relevant `docs/files/*.md` before modifying a parser.
### Error Handling
- `dispel-core`: `thiserror` for enumerable error types (see `ModdingError`)
- GUI/CLI: `anyhow` for contextual bubbling
-- Never `.unwrap()` on file I/O — show errors in `status_msg`
-- **Never swallow I/O or serialization errors** with `let _ =` or `.unwrap_or_default()` — log them via `eprintln!` or propagate with `?`
+- Never call `.unwrap()` on file I/O. Show errors in `status_msg`.
+- Never swallow I/O or serialization errors with `let _ =` or `.unwrap_or_default()`. Log them with `eprintln!` or propagate them with `?`.
### State & Async
- Use **enums over booleans**: `LoadingState { Idle, Loading, Loaded(T), Failed(String) }`
-- Always use `Task::perform` for async work — never block
+- Always use `Task::perform` for async work. Never block.
### Code Quality
-- Clippy: zero warnings; format before commit; validate all binary bounds before indexing
-- Compiler warnings: use the `cargo test … --no-run` command in [Quick Commands](#quick-commands) to compile all crates (including tests) and surface compiler warnings without waiting for tests to execute — useful as a fast pre-commit check
+- Clippy: keep zero warnings. Format code before you commit. Validate binary bounds before you index data.
+- Compiler warnings: run the `cargo test … --no-run` command in [Quick Commands](#quick-commands). It compiles all crates and their tests. It surfaces compiler warnings without running the tests. Use it as a fast pre-commit check.
### Testing
-**Writing effective tests:** The goal is finding real bugs, not just confirming compilation. Prefer integration tests (iced_test) that simulate real user flows — they catch behavioral regressions, state corruption, and edge cases that unit tests miss.
+Effective tests: find real bugs. Compilation alone is not enough. Prefer `iced_test` integration tests that simulate user flows. They catch behavioural regressions, state corruption and edge cases.
- **dispel-core**: unit test every new parser with hardcoded byte slices (95 `#[cfg(test)]` blocks across 87 `.rs` files)
-- **dispel-gui**: write iced_test integration tests that simulate real user flows (open tabs, edit data, undo/redo, save). Test state transitions and behaviors, not visuals. Dedicated suite in `dispel-gui/src/tests/` (28 files) plus co-located `#[cfg(test)]` blocks.
+- dispel-gui: write iced_test integration tests that simulate user flows, such as tab opens, data edits, undo, redo and saves. Test state transitions and behaviour, not visuals. The dedicated suite is in `dispel-gui/src/tests/` (30 files), with co-located `#[cfg(test)]` blocks.
- **Round-trip checks**: `examples/check_save_roundtrip.rs` (parse → write → compare)
- **Test naming**: `test_${scenario}_${condition}` e.g. `test_undo_weapon_editor_empty_history`
- **Test helpers**: tests in `$module/tests.rs` (co-located), separate `recording_tests.rs` for recording
@@ -528,33 +540,20 @@ Subcommands defined in `src/cli.rs`: extract, patch, validate, list, schema, tem
---
-## Legal Compliance
-
-**✅ Permitted:**
-- Analyzing file formats, documenting specs
-- Creating modding/interoperability tools
-- Using "Dispel" for identification only
-
-**❌ Prohibited:**
-- Extracting/distributing copyrighted content
-- Bypassing copy protection
-- Commercial exploitation
-- Using DISPEL® trademark beyond identification
-
-**When mentioning Dispel:** Use **DISPEL®** with ® symbol on first mention. Include disclaimer: "not affiliated with, endorsed by, or sponsored by the trademark owner."
+Scope and legal notice: see README.md.
---
## Common Pitfalls
-- **Circular imports**: GUI ↔ core must never share presentation code
-- **Blocking UI**: All file I/O is async via Task
-- **Unsafe parsing**: Validate all bounds before indexing
+- Circular imports: GUI and core must never share presentation code.
+- UI blocking: run all file I/O asynchronously through Task.
+- Unsafe parsing: validate all bounds before you index data.
- **Hardcoded paths**: Use `dirs` crate for config/cache (`~/.config/dispel-gui/`)
-- **Text encoding**: Check encoding table before reading — wrong codec = corruption
-- **Map memory**: Never load full rendered map (~300MB); use viewport + LRU cache
-- **Macros have no unit tests**: `dispel-macros` is verified only via dependent crate's tests
-- **Editor count drifts**: Verify editor count against `EditorRegistry` and `EditorType` if unsure
+- Text encoding: check the encoding table before you read. The wrong codec corrupts text.
+- Map memory: never load a full rendered map of about 300MB. Use a viewport and an LRU cache.
+- Macro tests: `dispel-macros` has no direct unit tests. Dependent crates test it.
+- Editor count drift: check the count against `EditorRegistry` and `EditorType` when unsure.
---
@@ -576,14 +575,14 @@ make iced_test # Iced UI simulation tests
`make build`, `make fmt`, `make clippy`, `make cargo_test`, `make check`,
`make iced_test` and `make hexedit_test` are thin wrappers around
-`scripts/ci-commands.sh`; CI calls the same subcommands. Never introduce a
+`scripts/ci-commands.sh`. CI calls the same subcommands. Never introduce a
second inline spelling of these commands.
### rtk (Rust Token Killer)
-**Always use `rtk` instead of the bare command** when running these operations. It compresses output by 60-90%, saving significant context window for real work.
+Always use `rtk` instead of the bare command for these operations. It compresses output by 60 to 90%. This saves context for real work.
-Note: the rtk hook only applies to Bash tool calls — built-in tools like `Read`, `Grep`, and `Glob` bypass it. For token-efficient file access, prefer shell commands through `rtk read`, `rtk grep`, `rtk ls` instead of the built-in tools.
+The rtk hook applies only to Bash tool calls. Built-in tools such as `Read`, `Grep` and `Glob` bypass it. For token-efficient file access, use `rtk read`, `rtk grep` and `rtk ls`.
```bash
rtk cargo test -v [cargo test args...] # Tests with compact output (failures only, ~-90%)
@@ -599,15 +598,15 @@ rtk read file.rs # Smart file reading
## iced GUI patterns
-This project uses iced from a git fork: `https://github.com/dimspell/iced` (pinned rev `c0ffdd8`). It is a nightly version (v0.15-dev) with modifications to handle accessibility features (like a VoiceOver screen reader). A local clone may exist at `../iced` for development.
+The project uses iced from a git fork at `https://github.com/dimspell/iced`, pinned at rev `c0ffdd8`. The fork is a nightly version, v0.15-dev. It includes accessibility changes such as VoiceOver support. A local clone may exist at `../iced` for development.
### Custom patterns
-Custom patterns are in the `gui-widgets` crate - `./gui-widgets/src`.
+Custom patterns are in the `gui-widgets` crate at `./gui-widgets/src`.
### `min` and `max` methods for `Length`
-There are `min` and `max` methods to the `Length` type, allowing to define minimum and maximum constraints for any widget:
+The `Length` type has `min` and `max` methods. They set minimum and maximum constraints for any widget:
```rs
row![
@@ -618,10 +617,9 @@ row![
### Notification on `scale_factor` change
-`window::Event::Resized` is notified when `scale_factor` changes.
+The tool receives `window::Event::Resized` when `scale_factor` changes.
---
*Last updated: 2026-11-19*
-**DISPEL®** is a registered trademark. This project is **not affiliated with, endorsed by, or sponsored by** the trademark owner.
From dae2c4a79be8f8a71a9fe9a0c04e3cb2fc186a47 Mon Sep 17 00:00:00 2001
From: dimspell <141545384+dimspell@users.noreply.github.com>
Date: Wed, 25 Nov 2026 14:00:03 +0100
Subject: [PATCH 08/72] docs: align agent guide version and sound example
---
AGENTS.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
index e1f909f7..ef5086ac 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -6,7 +6,7 @@ This toolkit reads and writes game files in binary, INI and DB formats. It also
## Project Overview
-The workspace is a **6-crate Cargo workspace** with Rust edition 2024 and version `0.9.3`.
+The workspace is a **6-crate Cargo workspace** with Rust edition 2024 and version `0.9.5`.
| Crate | Type | Role |
|---|---|---|
@@ -527,7 +527,7 @@ cargo run -- map tiles "file.gtl" --output dir/
cargo run -- map render --map file.map --btl file.btl --gtl file.gtl --output out.png
# Audio
-cargo run -- sound "file.snf" output.wav
+cargo run -- sound to-wav "file.snf" output.wav
# SQLite (optional)
cargo run -- database import "path/to/Dispel/" db.sqlite
From 404c11e0bf58ac3db55cc48887959a85cd3b5bda Mon Sep 17 00:00:00 2001
From: dimspell <141545384+dimspell@users.noreply.github.com>
Date: Wed, 25 Nov 2026 14:05:13 +0100
Subject: [PATCH 09/72] docs: keep the shared notice unique in the root readme
---
README.md | 4 ++--
hexedit/README.md | 4 ----
2 files changed, 2 insertions(+), 6 deletions(-)
diff --git a/README.md b/README.md
index dfc95c9b..e50e6280 100644
--- a/README.md
+++ b/README.md
@@ -4,11 +4,11 @@ This toolkit reads and writes DISPEL® game files in binary, INI and DB formats.
## Scope and notice
-This project reads and writes data files for DISPEL®. It ships no game content. You provide the files you edit.
+This project reads and writes data files for DISPEL®. It ships no game content. You choose the files you edit.
DISPEL® is a registered trademark. This project is not affiliated with, endorsed by, or sponsored by the trademark owner.
-The source code is licensed under the MIT License (LICENSE). Game content is not covered by this license.
+The MIT License (LICENSE) covers the source code. It does not cover game content.
## What's in this repository
diff --git a/hexedit/README.md b/hexedit/README.md
index 71cd3322..6d697528 100644
--- a/hexedit/README.md
+++ b/hexedit/README.md
@@ -984,7 +984,3 @@ Keep these invariants when you change the code:
## Project context
hexedit is part of the [Dispel RPG modding toolkit](https://github.com/piotr/dispel-extractor), a 6-crate Rust workspace: root `dispel-extractor`, `dispel-encodings`, `dispel-gui`, `dispel-macros`, `gui-widgets` and `hexedit`. It powers the hex editor tab inside `dispel-gui`. You can also use it standalone for general binary editing.
-
-## License
-
-The MIT License (LICENSE) covers `hexedit`.
From 95a8df8de45541a198091211231b6612f7440e9a Mon Sep 17 00:00:00 2001
From: dimspell <141545384+dimspell@users.noreply.github.com>
Date: Wed, 25 Nov 2026 22:25:43 +0100
Subject: [PATCH 10/72] docs: correct file cross references from code
---
docs/files/CROSS_REFERENCES.md | 633 ++++++++++++++-------------------
1 file changed, 272 insertions(+), 361 deletions(-)
diff --git a/docs/files/CROSS_REFERENCES.md b/docs/files/CROSS_REFERENCES.md
index 4bbfd287..2c0544c4 100644
--- a/docs/files/CROSS_REFERENCES.md
+++ b/docs/files/CROSS_REFERENCES.md
@@ -1,406 +1,316 @@
-# Dispel game file system: cross references
+# Dispel game files: cross references
## Overview
-This document maps the cross references between game data files. The tool reads and writes data files that you supply. Each row below links a field in one file to a file name or a field in another file.
+This document lists the links between game data files. The tool reads and writes the files that you supply. Each link connects a field in one file with a field in another file. Some links point to a file name instead of a field.
-## File Dependency Map
+## File dependency map
-### Core Configuration Files (INI)
+This section groups files by role. A family name such as `DlgMapFiles.dlg` stands for a set of real files. A real file name such as `Dlgcat1.dlg` names one file on disk.
-- **AllMap.ini**: Master map index linking maps to resources
-- **Map.ini** (Ref/): Map initialization with positions and resource links
-- **Monster.ini** (CharacterInGame/): Monster visual definitions and animations
-- **Npc.ini**: NPC visual definitions and sprite references
-- **Extra.ini**: Interactive object definitions
-- **Event.ini**: Event scripts with conditions and triggers
-- **Wave.ini**: Sound effect mappings
+### Core configuration files (INI)
-### Database Files (DB)
+- `AllMap.ini`: Master map index. It lists each map and its resources.
+- `Ref/Map.ini`: Map setup with spawn coordinates and file links. Each row holds one entrance.
+- `CharacterInGame/Monster.ini`: Monster visuals and animation sequences.
+- `Npc.ini`: NPC visuals and sprite file names.
+- `Extra.ini`: Interactive object definitions.
+- `Event.ini`: Event conditions and script file names.
+- `Wave.ini`: Sound effect names that point to `.snf` files.
-- **Monster.db** (MonsterInGame/): Monster combat statistics and AI
-- **WeaponItem.db** (CharacterInGame/): Weapons and armor with stats
-- **HealItem.db** (CharacterInGame/): Consumable healing items
-- **MiscItem.db** (CharacterInGame/): Generic utility items
-- **EditItem.db** (CharacterInGame/): Modifiable equipment items
-- **EventItem.db** (CharacterInGame/): Quest and event items
-- **Store.db** (CharacterInGame/): Shops and inns with inventories
-- **ChData.db** (CharacterInGame/): Character statistics tracking
-- **PrtLevel.db** (NpcInGame/): Character progression (levels 1-20)
-- **Magic.db** (Ref/): Spell database with effects
-- **DrawItem.db** (Ref/): Object placements on maps
+### Database files (DB)
-### Reference Files (REF)
+- `CharacterInGame/WeaponItem.db`: Weapons and armor with combat stats.
+- `CharacterInGame/HealItem.db`: Consumable healing items.
+- `CharacterInGame/EditItem.db`: Editable items that the player can change.
+- `CharacterInGame/EventItem.db`: Quest and event items.
+- `CharacterInGame/MiscItem.db`: Utility items.
+- `CharacterInGame/STORE.DB`: Shops and inns with product lists.
+- `CharacterInGame/ChData.db`: One record of initial class statistics.
+- `MagicInGame/Magic.db`: Spell definitions and effects.
+- `NpcInGame/PrtLevel.db`: Party growth records for eight slots and twenty levels.
+- `MonsterInGame/Monster.db`: Monster combat statistics.
-- **PartyRef.ref** (Ref/): Party character definitions
-- **Eventnpc.ref** (NpcInGame/): Event-triggered NPC definitions
-- **NpcMapFiles.ref** (NpcInGame/): NPC placements with waypoints
-- **Extra.ref** (ExtraInGame/): Interactive object placements
-- **fogdata.dat** (ExtraInGame/): Map lighting fade tables, consumed by the map renderer/editor (see [ExtraInGame/fogdata.dat.md](ExtraInGame/fogdata.dat.md))
-- **MondunMonmap.ref** (MonsterInGame/): Monster placements on maps
+### Reference files (REF)
-### Script Files (SCR/DLG/PGP)
+- `Ref/PartyRef.ref`: Party member definitions and dialogue links.
+- `MonsterInGame/Mondun01.ref`: Monster placements. `MondunMonmap.ref` is the family name.
+- `NpcInGame/Npccat1.ref`: NPC placements. `NpcMapFiles.ref` is the family name.
+- `ExtraInGame/Extdun01.ref`: Interactive object placements. `Extra.ref` is the family name.
+- `NpcInGame/Eventnpc.ref`: NPCs that appear during events.
+- `Ref/DRAWITEM.ref`: Map item drops. This is a parenthesized CSV file with EUC-KR text.
+- `ExtraInGame/fogdata.dat`: Fade tables for map lighting. See [ExtraInGame/fogdata.dat.md](ExtraInGame/fogdata.dat.md).
-- **Message.scr** (ExtraInGame/): UI text messages
-- **Quest.scr** (ExtraInGame/): Quest journal entries
-- **DlgMapFiles.dlg** (NpcInGame/): Dialogue conversation scripts
-- **PgpMapFiles.pgp** (NpcInGame/): Dialogue text content
+### Script files (SCR/DLG/PGP)
-### Visual/Audio Assets
+- `ExtraInGame/Message.scr`: UI text messages.
+- `ExtraInGame/Quest.scr`: Quest journal entries.
+- `NpcInGame/Dlgcat1.dlg`: Dialogue scripts. `DlgMapFiles.dlg` is the family name.
+- `NpcInGame/Pgpcat1.pgp`: Dialogue text and parameters. `PgpMapFiles.pgp` is the family name.
-- **Sprites.spr** (Map/): Sprite files for characters, monsters, objects
-- **SNF files** (referenced by Wave.ini): Sound effect files
-- **Map.map** (Map/): Map geometry and tile data
-- **Map.gtl** (Map/): Ground tileset files
-- **Map.btl** (Map/): Building/roof tileset files
+### Visual, audio and map assets
-### Map Tileset Relationships
+- Map.map: Map geometry, tile layers and embedded sprites.
+- Tileset files: Ground and roof tiles. Each map stem names its own pair of `.gtl` and `.btl` files.
+- `.spr` files: Sprite art. File names come from `Monster.ini`, `Npc.ini` and `Extra.ini`.
+- `.snf` files: Audio data. `Wave.ini` names these files.
-```
-Map.map files
- ├── gtl_tile_id → Map.gtl (ground tiles)
- ├── btl_tile_id → Map.btl (building tiles)
- └── event_id → Event.ini (tile events)
-
-Map.gtl (ground tiles)
- └── Referenced by Map.map for terrain
-
-Map.btl (building tiles)
- └── Referenced by Map.map for structures
-```
-
-## Cross-Reference Relationships
+## Relationship diagrams
-### 1. Map System Relationships
+### 1. Map system
```
-AllMap.ini (master index)
- ├── map_file → Map.map files
- ├── pgp → PgpMapFiles.pgp (dialogue text)
- └── dlg → DlgMapFiles.dlg (dialogue scripts)
-
-Map.ini (Ref/)
- ├── id → AllMap.ini.id
- ├── monsters → MondunMonmap.ref (monster placements)
- ├── npcs → NpcMapFiles.ref (NPC placements)
- ├── extras → Extra.ref (object placements)
- ├── camera_event → Event.ini.event_id
- └── cd_track → Audio track number
-
-Map.map (map geometry)
- ├── gtl_tile_id → Map.gtl (ground tiles)
- ├── btl_tile_id → Map.btl (building tiles)
- ├── event_id → Event.ini (tile events)
- └── Contains embedded sprites
-
-Map.gtl (ground tiles)
- └── Referenced by Map.map for terrain
-
-Map.btl (building tiles)
- └── Referenced by Map.map for structures
+AllMap.ini
+ ├── id → row key
+ ├── map_filename → Map.map stem
+ ├── pgp_filename → Pgpcat1.pgp (dialogue text)
+ ├── dlg_filename → Dlgcat1.dlg (dialogue scripts)
+ └── lighting → MapLighting code
+
+Ref/Map.ini
+ ├── id → entrance row key
+ ├── map_id → AllMap.ini.id
+ ├── event_id_on_camera_move → event index
+ ├── start_pos_x / start_pos_y → spawn point
+ ├── monsters_filename → Mondun01.ref
+ ├── npc_filename → Npccat1.ref
+ ├── extra_filename → Extdun01.ref
+ └── cd_music_track_number → audio track
```
-### 2. Character System Relationships
+### 2. Map.map layers
```
-PartyRef.ref (Ref/)
- ├── npc_id → Npc.ini.id (visual appearance)
- ├── map_id → AllMap.ini.id (recruitment location)
- ├── dlg_out → DlgMapFiles.dlg.id (dialogue when not in party)
- └── dlg_in → DlgMapFiles.dlg.id (dialogue when in party)
-
-Npc.ini (visual definitions)
- └── sprite_filename → Sprites.spr files
-
-PrtLevel.db (character progression)
- └── 8 NPC slots × 20 levels = character stat growth
-
-ChData.db (character statistics)
- └── Tracks overall game/player statistics
-
-Character System Cross-References:
- ├── PartyRef.ref → PrtLevel.db (character progression)
- ├── PrtLevel.db → WeaponItem.db (equipment requirements)
- ├── PrtLevel.db → Magic.db (spell access)
- └── ChData.db → Overall game statistics
+Map.map
+ ├── ground GTL index = (word >> 10) & 0x7FFF (Tile and Access words)
+ ├── BTL IDs → u16 array in the Tiled Objects block
+ ├── roof BTL index → bits 0..14 of the Access-Ref grid
+ ├── event IDs → bits 0..13 of a u32 (resolved via Map.ini and AllMap.ini)
+ └── sprites → embedded sprite block
```
-### 3. Monster System Relationships
+### 3. Character data
```
-Monster.ini (visual definitions)
- ├── sprite_filename → Sprites.spr files
- ├── attack_seq → Sprite animation sequence
- ├── hit_seq → Sprite animation sequence
- ├── death_seq → Sprite animation sequence
- ├── walk_seq → Sprite animation sequence
- └── cast_seq → Sprite animation sequence
-
-Monster.db (combat statistics)
- ├── known_spell_slot1 → Magic.db.id
- ├── known_spell_slot2 → Magic.db.id
- ├── known_spell_slot3 → Magic.db.id
- └── AI type determines combat behavior
-
-MondunMonmap.ref (monster placements)
- ├── mon_id → Monster.db.id (monster type)
- ├── loot1/2/3_item_id → Item databases (loot drops)
- └── Places monsters from Monster.db/ini on specific maps
-```
+Ref/PartyRef.ref
+ ├── npc_id → Npc.ini.id (visual type)
+ ├── root_map_id → AllMap.ini.id
+ ├── dlg_when_not_in_party → PartyDlg.dlg paragraph
+ └── dlg_when_in_party → PartyDlg.dlg paragraph
-### 4. NPC System Relationships
+NpcInGame/PrtLevel.db
+ ├── 8 slots × 20 levels, with 36-byte records
+ ├── magic_spell_id_1 / 2 / 3 → spell indices
+ └── weapon_skill_level → skill level
-```
-NpcMapFiles.ref (NPC placements)
- ├── npc_id → Npc.ini.id (visual type)
- ├── dialog_id → DlgMapFiles.dlg.id (dialogue script)
- ├── show_on_event → Event.ini.event_id (visibility trigger)
- └── Waypoints for patrol routes
-
-Eventnpc.ref (event NPCs)
- ├── npc_ini_id → Npc.ini.id (visual type)
- ├── show_on_event → Event.ini.event_id (trigger condition)
- ├── dialog_id → DlgMapFiles.dlg.id (dialogue script)
- └── Temporary NPCs appearing during specific events
-
-DlgMapFiles.dlg (dialogue scripts)
- ├── prev_event → Event.ini.event_id (prerequisite)
- ├── next_dlg → DlgMapFiles.dlg.id (conversation chain)
- ├── dlg_id → PgpMapFiles.pgp.id (text content)
- ├── event_id → Event.ini.event_id (triggered by dialogue)
- └── Referenced by NpcMapFiles.ref and PartyRef.ref
-
-PgpMapFiles.pgp (dialogue text)
- └── Contains actual dialogue text and parameters
+CharacterInGame/ChData.db
+ └── one 84-byte record of initial class statistics
```
-### 5. Interactive Object System Relationships
+### 4. Monster data
```
-Extra.ini (object definitions)
- ├── sprite_filename → Sprites.spr files
- └── flag (0=standard, 1=special/quest)
-
-Extra.ref (object placements)
- ├── ext_id → Extra.ini.id (object type)
- ├── event_id → Event.ini.event_id (interaction trigger)
- ├── message_id → Message.scr.id (sign text)
- ├── required_item_id → Item database
- ├── required_item_type_id → Item type enum
- ├── item_id → Item database (contents)
- └── item_type_id → Item type enum
-
-DrawItem.db (object placements)
- ├── map_id → AllMap.ini.id
- └── item_id → Extra.ini.id or object database
-```
+CharacterInGame/Monster.ini
+ └── sprite_filename → .spr file under CharacterInGame/
-### 6. Event System Relationships
+MonsterInGame/Monster.db
+ ├── known_spell_slot1 / 2 / 3 → spell indices (-1 = SQL NULL)
+ └── combat statistics
-```
-Event.ini (event definitions)
- ├── required_event_id → Event.ini.id (prerequisite)
- ├── script_filename → Script files (.scr)
- └── event_type (0-8) determines execution logic
-
-Events are referenced by:
- ├── Map.ini.camera_event
- ├── NpcMapFiles.ref.show_on_event
- ├── DlgMapFiles.dlg.event_id
- ├── DlgMapFiles.dlg.prev_event
- ├── Extra.ref.event_id
- └── Eventnpc.ref.show_on_event
+MonsterInGame/Mondun01.ref
+ ├── monster_db_id → Monster.db.id
+ ├── loot_item_1 / 2 / 3 → items lookup (type:ID)
+ └── event_id_on_kill → event index
```
-### 7. Item/Equipment System Relationships
+### 5. NPC and dialogue data
```
-WeaponItem.db (weapons/armor)
- ├── Referenced by Store.db products (type=0,1)
- ├── Referenced by Extra.ref contents (item_type_id=0,1)
- └── Referenced by MondunMonmap.ref loot (loot*_item_type)
-
-HealItem.db (consumable healing)
- ├── Referenced by Store.db products (type=2)
- ├── Referenced by Extra.ref contents (item_type_id=2)
- └── Referenced by MondunMonmap.ref loot (loot*_item_type)
-
-MiscItem.db (generic utility items)
- ├── Referenced by Store.db products (type=3)
- ├── Referenced by Extra.ref contents (item_type_id=3)
- └── Referenced by MondunMonmap.ref loot (loot*_item_type)
-
-EditItem.db (modifiable equipment)
- ├── Referenced by Store.db products (type=4)
- ├── Referenced by Extra.ref contents (item_type_id=4)
- └── Referenced by MondunMonmap.ref loot (loot*_item_type)
-
-EventItem.db (quest items)
- ├── Referenced by Extra.ref contents (item_type_id=5)
- └── Quest progression tracking
-
-Store.db (shops/inns)
- ├── products reference item databases
- └── Commerce system with haggling and dialogue
-
-Item Type Enum (used in Extra.ref and Store.db):
- ├── 1: Weapon → WeaponItem.db
- ├── 2: Healing → HealItem.db
- ├── 3: Edit → EditItem.db
- ├── 4: Event → EventItem.db
- ├── 5: Misc → MiscItem.db
- └── -1: NoItem → no item (0xFF on disk; SQL/GUI keys use 255)
+NpcInGame/Npccat1.ref
+ ├── npc_ini_id → Npc.ini.id
+ ├── dialog_id → Dlgcat1.dlg script
+ └── show_on_event → event index
+
+NpcInGame/Eventnpc.ref
+ ├── npc_ini_id → Npc.ini.id
+ ├── show_on_event → event index
+ └── dialog_id → Dlgcat1.dlg script
+
+NpcInGame/Dlgcat1.dlg (on-disk labels in parentheses)
+ ├── required_event_id (prev_event) → event index
+ ├── next_dialog_to_check (next_dlg) → Dlg script
+ ├── dialog_id (dlg_id) → Pgpcat1.pgp paragraph
+ └── triggered_event_id (event_id) → event index
+
+NpcInGame/Pgpcat1.pgp
+ └── dialogue text and parameters
```
-### 8. Audio System Relationships
+### 6. Interactive object data
```
-Wave.ini (sound mappings)
- └── snf_filename → .snf audio files
-
-Sound IDs referenced by:
- ├── dialogue_paragraph.rs (wave_ini_entry_id)
- └── Game events and interactions
+ExtraInGame/Extra.ini
+ └── sprite_filename → .spr file under ExtraInGame/
+
+ExtraInGame/Extdun01.ref
+ ├── extra_definition_id → Extra.ini.id
+ ├── map_object_id → map object number
+ ├── interaction_event_id → event index
+ ├── interaction_message_id → Message.scr.id
+ ├── required_item / required_item2 → items lookup (type:ID)
+ ├── loot_item → items lookup (type:ID)
+ ├── additional_loot_1 / additional_loot_2 → item IDs
+ ├── trap_spell_id → spell index
+ └── open_sfx_id → Wave.ini index
+
+Ref/DRAWITEM.ref
+ ├── map_id → AllMap.ini.id
+ ├── x_coord / y_coord → map position
+ └── item → items lookup (type:ID)
```
-### 9. Quest System Relationships
+### 7. Events and audio
```
-Quest.scr (quest definitions)
- ├── type (0=main, 1=side, 2=traders journal)
- └── Referenced by event system
+Event.ini
+ ├── required_event_id → event prerequisite
+ ├── event_filename → event script file
+ └── event_type → 0, 2, 5 or 6
-Message.scr (UI messages)
- └── Referenced by Extra.ref.message_id for signs
-```
-
-## Complete Cross-Reference Table
-
-| Source File | Source Field | Target File | Target Field | Relationship |
-|------------------|-----------------------|------------------|--------------|--------------------|
-| AllMap.ini | map_file | Map.map | filename | Map geometry |
-| AllMap.ini | pgp | PgpMapFiles.pgp | filename | Dialogue text |
-| AllMap.ini | dlg | DlgMapFiles.dlg | filename | Dialogue scripts |
-| Map.ini | monsters | MondunMonmap.ref | filename | Monster placements |
-| Map.ini | npcs | NpcMapFiles.ref | filename | NPC placements |
-| Map.ini | extras | Extra.ref | filename | Object placements |
-| Map.ini | camera_event | Event.ini | event_id | Camera trigger |
-| Monster.ini | sprite_filename | Sprites.spr | filename | Visual assets |
-| Npc.ini | sprite_filename | Sprites.spr | filename | Visual assets |
-| Extra.ini | sprite_filename | Sprites.spr | filename | Visual assets |
-| PartyRef.ref | npc_id | Npc.ini | id | Visual appearance |
-| PartyRef.ref | map_id | AllMap.ini | id | Location |
-| PartyRef.ref | dlg_out | DlgMapFiles.dlg | id | Dialogue |
-| PartyRef.ref | dlg_in | DlgMapFiles.dlg | id | Dialogue |
-| NpcMapFiles.ref | npc_id | Npc.ini | id | NPC type |
-| NpcMapFiles.ref | dialog_id | DlgMapFiles.dlg | id | Dialogue |
-| NpcMapFiles.ref | show_on_event | Event.ini | event_id | Visibility |
-| Eventnpc.ref | show_on_event | Event.ini | event_id | Trigger |
-| Eventnpc.ref | npc_ini_id | Npc.ini | id | NPC type |
-| Eventnpc.ref | dialog_id | DlgMapFiles.dlg | id | Dialogue |
-| DlgMapFiles.dlg | prev_event | Event.ini | event_id | Prerequisite |
-| DlgMapFiles.dlg | next_dlg | DlgMapFiles.dlg | id | Chain |
-| DlgMapFiles.dlg | dlg_id | PgpMapFiles.pgp | id | Text |
-| DlgMapFiles.dlg | event_id | Event.ini | event_id | Trigger |
-| Extra.ref | ext_id | Extra.ini | id | Object type |
-| Extra.ref | event_id | Event.ini | event_id | Interaction |
-| Extra.ref | message_id | Message.scr | id | Sign text |
-| Extra.ref | required_item_type_id | Item type enum | - | Key type |
-| Extra.ref | item_type_id | Item type enum | - | Content type |
-| Monster.db | known_spell_slot1-3 | Magic.db | id | Spells |
-| DrawItem.db | map_id | AllMap.ini | id | Map location |
-| DrawItem.db | item_id | Extra.ini | id | Object type |
-| Map.map | gtl_tile_id | Map.gtl | id | Ground tiles |
-| Map.map | btl_tile_id | Map.btl | id | Building tiles |
-| Map.map | event_id | Event.ini | event_id | Tile events |
-| Store.db | products | Item databases | id | Inventory |
-| Store.db | products (type=0,1) | WeaponItem.db | id | Weapons/Armor |
-| Store.db | products (type=2) | HealItem.db | id | Healing items |
-| Store.db | products (type=3) | MiscItem.db | id | Misc items |
-| Store.db | products (type=4) | EditItem.db | id | Modifiable items |
-| Extra.ref | item_type_id=1 | WeaponItem.db | id | Weapons/Armor |
-| Extra.ref | item_type_id=2 | HealItem.db | id | Healing items |
-| Extra.ref | item_type_id=3 | EditItem.db | id | Modifiable items |
-| Extra.ref | item_type_id=4 | EventItem.db | id | Quest items |
-| Extra.ref | item_type_id=5 | MiscItem.db | id | Misc items |
-| MondunMonmap.ref | loot*_item_type=1 | WeaponItem.db | id | Weapon loot |
-| MondunMonmap.ref | loot*_item_type=2 | HealItem.db | id | Healing loot |
-| MondunMonmap.ref | loot*_item_type=3 | EditItem.db | id | Editable loot |
-| MondunMonmap.ref | loot*_item_type=4 | EventItem.db | id | Event loot |
-| MondunMonmap.ref | loot*_item_type=5 | MiscItem.db | id | Misc loot |
-| Wave.ini | snf_filename | .snf files | filename | Audio |
-
-## Data Flow Summary
-
-1. Map data: AllMap.ini → Map.ini → Map.map, MondunMonmap.ref, NpcMapFiles.ref and Extra.ref
-2. Map rendering: Map.map → Map.gtl (ground tiles), Map.btl (building tiles) and Sprites.spr (objects and NPCs)
-3. NPC data: NpcMapFiles.ref → Npc.ini → Sprites.spr, and DlgMapFiles.dlg → PgpMapFiles.pgp
-4. Monster data: MondunMonmap.ref → Monster.ini → Sprites.spr, and Monster.db → Magic.db
-5. Object data: Extra.ref → Extra.ini → Sprites.spr, Event.ini and Message.scr
-6. Quest data: Event.ini → script files → Quest.scr
-7. Character data: PartyRef.ref → PrtLevel.db → WeaponItem.db and Magic.db
-8. Commerce data: Store.db → item databases such as WeaponItem.db and HealItem.db
-9. Audio data: Wave.ini → .snf files
-10. Monster loot: MondunMonmap.ref → item databases
-
-## Item Database Relationships
-
-### Item Type Enum (ItemTypeId)
+Wave.ini
+ └── snf_filename → .snf audio file
-```
-1: Weapon → WeaponItem.db
-2: Healing → HealItem.db
-3: Edit → EditItem.db
-4: Event → EventItem.db
-5: Misc → MiscItem.db
--1: NoItem → no item (0xFF on disk; SQL/GUI numeric keys use 255)
+NpcInGame/Pgpcat1.pgp
+ └── wave_ini_entry_id (column 3) → Wave.ini index
```
-### Item Database Cross-References
+### 8. Item keys and store products
```
-WeaponItem.db (weapons/armor)
- ├── Referenced by Store.db products (type=1)
- ├── Referenced by Extra.ref contents (item_type_id=1)
- └── Referenced by MondunMonmap.ref loot (loot*_item_type=1)
-
-HealItem.db (consumable healing)
- ├── Referenced by Store.db products (type=2)
- ├── Referenced by Extra.ref contents (item_type_id=2)
- └── Referenced by MondunMonmap.ref loot (loot*_item_type=2)
-
-EditItem.db (modifiable equipment)
- ├── Referenced by Store.db products (type=4)
- ├── Referenced by Extra.ref contents (item_type_id=3)
- └── Referenced by MondunMonmap.ref loot (loot*_item_type=3)
-
-EventItem.db (quest items)
- ├── Referenced by Extra.ref contents (item_type_id=4)
- └── Quest progression tracking
-
-MiscItem.db (generic utility items)
- ├── Referenced by Store.db products (type=3)
- ├── Referenced by Extra.ref contents (item_type_id=5)
- └── Referenced by MondunMonmap.ref loot (loot*_item_type=5)
+ItemTypeId (composite key type:ID)
+ ├── 1 Weapon → WeaponItem.db
+ ├── 2 Healing → HealItem.db
+ ├── 3 Edit → EditItem.db
+ ├── 4 Event → EventItem.db
+ ├── 5 Misc → MiscItem.db
+ └── -1 NoItem → 0xFF on disk, 255 in SQL and GUI keys
+
+ProductType (Store.db slots)
+ ├── 1 Weapon → WeaponItem.db
+ ├── 2 Healing → HealItem.db
+ ├── 3 EditItem → EditItem.db
+ ├── 4 MiscItem → MiscItem.db
+ └── 0 ends the list, with at most 15 products
```
-## File Encoding Summary
-
-| Encoding | Files |
-|--------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| EUC-KR | Event.ini, Extra.ini, Npc.ini, Wave.ini, Map.ini, Monster.db, DlgMapFiles.dlg, HealItem.db (descriptions) |
-| WINDOWS-1250 | AllMap.ini, Monster.ini, Store.db, WeaponItem.db, HealItem.db (names), MiscItem.db, EditItem.db, EventItem.db, Message.scr, Quest.scr, PgpMapFiles.pgp, Extra.ref, NpcMapFiles.ref, PartyRef.ref, Eventnpc.ref |
-| Binary | Monster.db, WeaponItem.db, HealItem.db, MiscItem.db, EditItem.db, EventItem.db, Store.db, ChData.db, PrtLevel.db, Magic.db, DrawItem.db, Map.map, Map.gtl, Map.btl, Sprites.spr |
+## Complete cross-reference table
+
+| Source file | Source field | Target file | Target field | Relationship |
+|---|---|---|---|---|
+| AllMap.ini | map_filename | Map.map | stem | Map geometry |
+| AllMap.ini | pgp_filename | Pgpcat1.pgp | file name | Dialogue text |
+| AllMap.ini | dlg_filename | Dlgcat1.dlg | file name | Dialogue scripts |
+| Ref/Map.ini | map_id | AllMap.ini | id | Map link |
+| Ref/Map.ini | monsters_filename | Mondun01.ref | file name | Monster placements |
+| Ref/Map.ini | npc_filename | Npccat1.ref | file name | NPC placements |
+| Ref/Map.ini | extra_filename | Extdun01.ref | file name | Object placements |
+| Ref/Map.ini | cd_music_track_number | Wave.ini | index | Music track |
+| Mondun01.ref | monster_db_id | Monster.db | id | Monster type |
+| Mondun01.ref | loot_item_1 / 2 / 3 | items lookup | type:ID | Loot |
+| Mondun01.ref | event_id_on_kill | event index | - | Kill trigger |
+| Monster.db | known_spell_slot1 / 2 / 3 | spell index | - | Spells (NULL for -1) |
+| Npccat1.ref | npc_ini_id | Npc.ini | id | NPC type |
+| Npccat1.ref | dialog_id | Dlgcat1.dlg | id | Dialogue |
+| Npccat1.ref | show_on_event | event index | - | Visibility |
+| Eventnpc.ref | npc_ini_id | Npc.ini | id | NPC type |
+| Eventnpc.ref | show_on_event | event index | - | Trigger |
+| Eventnpc.ref | dialog_id | Dlgcat1.dlg | id | Dialogue |
+| Dlgcat1.dlg | required_event_id | event index | - | Prerequisite |
+| Dlgcat1.dlg | next_dialog_to_check | Dlgcat1.dlg | id | Chain |
+| Dlgcat1.dlg | dialog_id | Pgpcat1.pgp | paragraph | Text |
+| Dlgcat1.dlg | triggered_event_id | event index | - | Trigger |
+| Pgpcat1.pgp | wave_ini_entry_id | Wave.ini | index | Voice audio |
+| PartyRef.ref | npc_id | Npc.ini | id | Visual type |
+| PartyRef.ref | root_map_id | AllMap.ini | id | Location |
+| PartyRef.ref | dlg_when_not_in_party | PartyDlg.dlg | paragraph | Dialogue |
+| PartyRef.ref | dlg_when_in_party | PartyDlg.dlg | paragraph | Dialogue |
+| Extdun01.ref | extra_definition_id | Extra.ini | id | Object type |
+| Extdun01.ref | interaction_event_id | event index | - | Interaction |
+| Extdun01.ref | interaction_message_id | Message.scr | id | Sign text |
+| Extdun01.ref | required_item / required_item2 | items lookup | type:ID | Required item |
+| Extdun01.ref | loot_item | items lookup | type:ID | Loot |
+| Extdun01.ref | trap_spell_id | spell index | - | Trap spell |
+| Extdun01.ref | open_sfx_id | Wave.ini | index | Open sound |
+| DRAWITEM.ref | map_id | AllMap.ini | id | Map location |
+| DRAWITEM.ref | item | items lookup | type:ID | Dropped item |
+| Map.map | ground GTL index | Map.gtl | tile index | Ground tiles |
+| Map.map | BTL IDs | Map.btl | tile index | Roof tiles |
+| Map.map | event ID bits | event index | - | Tile event |
+| STORE.DB | product | items lookup | type:ID | Product |
+| PrtLevel.db | magic_spell_id_1 / 2 / 3 | spell index | - | Spells |
+| Monster.ini / Npc.ini / Extra.ini | sprite_filename | .spr | file name | Sprites |
+| Event.ini | event_filename | event script | file name | Event logic |
+| Wave.ini | snf_filename | .snf | file name | Audio |
+
+## Data flow summary
+
+1. Map data: `AllMap.ini` → `Ref/Map.ini` → `Map.map`, `Mondun01.ref`, `Npccat1.ref` and `Extdun01.ref`.
+2. Map rendering: `Map.map` → ground `.gtl` tiles, roof `.btl` tiles and the embedded sprite block.
+3. NPC data: `Npccat1.ref` → `Npc.ini` → `.spr` files, and `Dlgcat1.dlg` → `Pgpcat1.pgp`.
+4. Monster data: `Mondun01.ref` → `Monster.db` and `Monster.ini`, plus spell indices in `Monster.db`.
+5. Object data: `Extdun01.ref` → `Extra.ini`, `Event.ini` and `Message.scr`.
+6. Item drops: `DRAWITEM.ref` → item databases through the items lookup.
+7. Party data: `PartyRef.ref` → `Npc.ini` and `PartyDlg.dlg`, with growth in `PrtLevel.db`.
+8. Commerce data: `STORE.DB` → item databases through product types.
+9. Audio data: `Wave.ini` → `.snf` files, with indices from `Pgpcat1.pgp`.
+10. Event data: `Event.ini` → event scripts, with indices in placements and dialogue.
+
+## Item type section
+
+### Item type enum
+
+The tool uses `ItemTypeId` for composite item keys. A key holds a type code and an item ID.
+
+- 1 Weapon → `WeaponItem.db`
+- 2 Healing → `HealItem.db`
+- 3 Edit → `EditItem.db`
+- 4 Event → `EventItem.db`
+- 5 Misc → `MiscItem.db`
+- -1 NoItem → empty slot (`0xFF` on disk, `255` in SQL and GUI keys)
+
+There is no item type 0.
+
+### Product types in stores
+
+`STORE.DB` uses a different enum named `ProductType`. Each product slot holds a type code and an item ID.
+
+- 1 Weapon → `WeaponItem.db`
+- 2 Healing → `HealItem.db`
+- 3 EditItem → `EditItem.db`
+- 4 MiscItem → `MiscItem.db`
+- 0 ends the product list, with at most 15 products per store
+
+Unknown type codes fall back to MiscItem. EventItem has no product type. NoItem and 255 do not appear in `STORE.DB`.
+
+## File encoding summary
+
+Some files mix text and binary data. `Monster.db` is binary, and its 24-byte name field is EUC-KR. `MiscItem.db` has a WINDOWS-1250 name and an EUC-KR description.
+
+| Encoding | Files |
+|---|---|
+| EUC-KR | `Event.ini`, `Extra.ini`, `Npc.ini`, `Wave.ini`, `Map.ini`, DLG files, `HealItem.db` descriptions, `MiscItem.db` description, `Monster.db` name field, `DRAWITEM.ref` |
+| WINDOWS-1250 | `AllMap.ini`, `Monster.ini`, `WeaponItem.db`, `EditItem.db`, `EventItem.db`, `Message.scr`, `Quest.scr`, PGP files, `MiscItem.db` name, `STORE.DB` text fields, `Extra.ref` names, NPC refs, `PartyRef.ref`, `Eventnpc.ref` |
+| Binary | `WeaponItem.db`, `HealItem.db`, `MiscItem.db`, `EditItem.db`, `EventItem.db`, `STORE.DB`, `Monster.db`, `ChData.db`, `PrtLevel.db`, `Magic.db`, `Map.map`, `.gtl`, `.btl`, `.spr`, `.snf` |
## Scope
-The tool reads and writes data files that you supply. This document lists the field links between those files.
+The tool reads and writes the game files that you supply. This document lists the field links between those files. The extractor commands below use sample paths.
## Extractor commands
The tool in `src/` parses and extracts data from game files. Run these commands from the repository root.
-### Quick Reference
+### Quick reference
```bash
# Build the extractor
@@ -408,37 +318,38 @@ cargo build --release
# Extract INI files to JSON
cargo run -- extract -i "path/to/AllMap.ini"
+cargo run -- extract -i "path/to/Ref/Map.ini"
cargo run -- extract -i "path/to/Event.ini"
cargo run -- extract -i "path/to/Extra.ini"
-cargo run -- extract -i "path/to/Monster.ini"
+cargo run -- extract -i "path/to/CharacterInGame/Monster.ini"
cargo run -- extract -i "path/to/Npc.ini"
cargo run -- extract -i "path/to/Wave.ini"
-cargo run -- extract -i "path/to/Map.ini"
# Extract database files to JSON
-cargo run -- extract -i "path/to/weaponItem.db"
-cargo run -- extract -i "path/to/Monster.db"
-cargo run -- extract -i "path/to/HealItem.db"
-cargo run -- extract -i "path/to/MiscItem.db"
-cargo run -- extract -i "path/to/EditItem.db"
-cargo run -- extract -i "path/to/EventItem.db"
-cargo run -- extract -i "path/to/STORE.DB"
-cargo run -- extract -i "path/to/Magic.db"
-cargo run -- extract -i "path/to/PrtLevel.db"
-cargo run -- extract -i "path/to/ChData.db"
+cargo run -- extract -i "path/to/CharacterInGame/weaponItem.db"
+cargo run -- extract -i "path/to/MonsterInGame/Monster.db"
+cargo run -- extract -i "path/to/CharacterInGame/HealItem.db"
+cargo run -- extract -i "path/to/CharacterInGame/MiscItem.db"
+cargo run -- extract -i "path/to/CharacterInGame/EditItem.db"
+cargo run -- extract -i "path/to/CharacterInGame/EventItem.db"
+cargo run -- extract -i "path/to/CharacterInGame/STORE.DB"
+cargo run -- extract -i "path/to/MagicInGame/Magic.db"
+cargo run -- extract -i "path/to/NpcInGame/PrtLevel.db"
+cargo run -- extract -i "path/to/CharacterInGame/ChData.db"
# Extract reference files to JSON
-cargo run -- extract -i "path/to/PartyRef.ref"
-cargo run -- extract -i "path/to/DrawItem.ref"
-cargo run -- extract -i "path/to/Npccat1.ref"
-cargo run -- extract -i "path/to/Mondun01.ref"
-cargo run -- extract -i "path/to/Extdun01.ref"
-cargo run -- extract -i "path/to/Eventnpc.ref"
+cargo run -- extract -i "path/to/Ref/PartyRef.ref"
+cargo run -- extract -i "path/to/Ref/DRAWITEM.ref"
+cargo run -- extract -i "path/to/NpcInGame/Npccat1.ref"
+cargo run -- extract -i "path/to/MonsterInGame/Mondun01.ref"
+cargo run -- extract -i "path/to/ExtraInGame/Extdun01.ref"
+cargo run -- extract -i "path/to/NpcInGame/Eventnpc.ref"
# Extract script files to JSON
-cargo run -- extract -i "path/to/Dlgcat1.dlg"
-cargo run -- extract -i "path/to/Message.scr"
-cargo run -- extract -i "path/to/Quest.scr"
+cargo run -- extract -i "path/to/NpcInGame/Dlgcat1.dlg"
+cargo run -- extract -i "path/to/NpcInGame/Pgpcat1.pgp"
+cargo run -- extract -i "path/to/ExtraInGame/Message.scr"
+cargo run -- extract -i "path/to/ExtraInGame/Quest.scr"
# Extract sprites
cargo run -- sprite "path/to/file.spr" "output_name"
From 0a539df720b8d41141542af142974be8cfdce2b9 Mon Sep 17 00:00:00 2001
From: dimspell <141545384+dimspell@users.noreply.github.com>
Date: Wed, 25 Nov 2026 22:31:12 +0100
Subject: [PATCH 11/72] docs: fix five cross reference details
---
docs/files/CROSS_REFERENCES.md | 21 +++++++++++----------
1 file changed, 11 insertions(+), 10 deletions(-)
diff --git a/docs/files/CROSS_REFERENCES.md b/docs/files/CROSS_REFERENCES.md
index 2c0544c4..b1d668cc 100644
--- a/docs/files/CROSS_REFERENCES.md
+++ b/docs/files/CROSS_REFERENCES.md
@@ -12,7 +12,7 @@ This section groups files by role. A family name such as `DlgMapFiles.dlg` stand
- `AllMap.ini`: Master map index. It lists each map and its resources.
- `Ref/Map.ini`: Map setup with spawn coordinates and file links. Each row holds one entrance.
-- `CharacterInGame/Monster.ini`: Monster visuals and animation sequences.
+- `Monster.ini`: Monster visuals and animation sequences.
- `Npc.ini`: NPC visuals and sprite file names.
- `Extra.ini`: Interactive object definitions.
- `Event.ini`: Event conditions and script file names.
@@ -110,8 +110,8 @@ CharacterInGame/ChData.db
### 4. Monster data
```
-CharacterInGame/Monster.ini
- └── sprite_filename → .spr file under CharacterInGame/
+Monster.ini
+ └── sprite_filename → .spr file under MonsterInGame/
MonsterInGame/Monster.db
├── known_spell_slot1 / 2 / 3 → spell indices (-1 = SQL NULL)
@@ -199,8 +199,9 @@ ProductType (Store.db slots)
├── 1 Weapon → WeaponItem.db
├── 2 Healing → HealItem.db
├── 3 EditItem → EditItem.db
- ├── 4 MiscItem → MiscItem.db
- └── 0 ends the list, with at most 15 products
+ └── 4 MiscItem → MiscItem.db
+
+Note: 0 ends the list. A store holds at most 15 products.
```
## Complete cross-reference table
@@ -214,7 +215,7 @@ ProductType (Store.db slots)
| Ref/Map.ini | monsters_filename | Mondun01.ref | file name | Monster placements |
| Ref/Map.ini | npc_filename | Npccat1.ref | file name | NPC placements |
| Ref/Map.ini | extra_filename | Extdun01.ref | file name | Object placements |
-| Ref/Map.ini | cd_music_track_number | Wave.ini | index | Music track |
+| Ref/Map.ini | cd_music_track_number | CD audio track | number | Music track |
| Mondun01.ref | monster_db_id | Monster.db | id | Monster type |
| Mondun01.ref | loot_item_1 / 2 / 3 | items lookup | type:ID | Loot |
| Mondun01.ref | event_id_on_kill | event index | - | Kill trigger |
@@ -243,10 +244,10 @@ ProductType (Store.db slots)
| Extdun01.ref | open_sfx_id | Wave.ini | index | Open sound |
| DRAWITEM.ref | map_id | AllMap.ini | id | Map location |
| DRAWITEM.ref | item | items lookup | type:ID | Dropped item |
-| Map.map | ground GTL index | Map.gtl | tile index | Ground tiles |
-| Map.map | BTL IDs | Map.btl | tile index | Roof tiles |
+| Map.map | ground GTL index | per-map .gtl file | tile index | Ground tiles |
+| Map.map | BTL IDs | per-map .btl file | tile index | Roof tiles |
| Map.map | event ID bits | event index | - | Tile event |
-| STORE.DB | product | items lookup | type:ID | Product |
+| STORE.DB | product | item databases | product type:ID | Product |
| PrtLevel.db | magic_spell_id_1 / 2 / 3 | spell index | - | Spells |
| Monster.ini / Npc.ini / Extra.ini | sprite_filename | .spr | file name | Sprites |
| Event.ini | event_filename | event script | file name | Event logic |
@@ -321,7 +322,7 @@ cargo run -- extract -i "path/to/AllMap.ini"
cargo run -- extract -i "path/to/Ref/Map.ini"
cargo run -- extract -i "path/to/Event.ini"
cargo run -- extract -i "path/to/Extra.ini"
-cargo run -- extract -i "path/to/CharacterInGame/Monster.ini"
+cargo run -- extract -i "path/to/Monster.ini"
cargo run -- extract -i "path/to/Npc.ini"
cargo run -- extract -i "path/to/Wave.ini"
From 129ca2a8056b06634ba6ee4fcf430efd8011d186 Mon Sep 17 00:00:00 2001
From: dimspell <141545384+dimspell@users.noreply.github.com>
Date: Wed, 25 Nov 2026 22:48:51 +0100
Subject: [PATCH 12/72] refactor(gui): combine composite item selects with
search
---
dispel-gui/src/components/composite_item.rs | 453 ++++++++++--------
.../src/editors/map_editor/view/fields.rs | 26 +-
.../view/editor/spreadsheet/view/inspector.rs | 24 +-
3 files changed, 286 insertions(+), 217 deletions(-)
diff --git a/dispel-gui/src/components/composite_item.rs b/dispel-gui/src/components/composite_item.rs
index a459d688..82348483 100644
--- a/dispel-gui/src/components/composite_item.rs
+++ b/dispel-gui/src/components/composite_item.rs
@@ -1,9 +1,9 @@
use std::rc::Rc;
-use dispel_core::ItemTypeId;
use iced::widget::{column as col, pick_list, row, text, text_input};
use iced::{Element, Length};
+use crate::components::select::lookup_select;
use crate::message::Message;
use crate::style;
@@ -11,7 +11,6 @@ const LABEL_W: f32 = 140.0;
/// The empty-slot option shared with the item catalog.
const NO_ITEM_KEY: &str = "255:15";
-const NO_ITEM_LABEL: &str = "[-]";
/// Render a picker body, optionally prefixed with a fixed-width label column.
///
@@ -38,28 +37,36 @@ fn with_optional_label<'a>(
}
}
-/// Build a cascading item-type + item-id picker for `CompositeItem` fields.
+/// Build a searchable item picker for `CompositeItem` fields.
///
-/// Renders two pick-lists (type then item). Falls back to a plain `text_input`
-/// when `entries` is `None` (lookups unavailable). `show_label` controls whether
-/// the label column is drawn by this component or by the caller.
+/// All item files share one select: every entry carries its type in the
+/// display label (`[Weapon] Cap`, `[Healing] Herb`, …). A text input above the
+/// select filters those labels and composite keys. Falls back to a plain
+/// `text_input` when `entries` is `None` (lookups unavailable). `show_label`
+/// controls whether the label column is drawn by this component or the caller.
pub fn composite_item_picker(
label: &'static str,
value: &str,
entries: Option<&[(String, String)]>,
show_label: bool,
+ filter: &str,
+ on_filter: impl Fn(String) -> Message + 'static,
on_change: impl Fn(String) -> Message + 'static,
) -> Element<'static, Message> {
- let current_type_byte: u8 = value
- .split(':')
- .next()
- .and_then(|s| s.parse().ok())
- .unwrap_or(255);
- let current_type = ItemTypeId::from_u8(current_type_byte).unwrap_or(ItemTypeId::NoItem);
- let current_id = value.split(':').nth(1).unwrap_or("0").to_string();
-
+ let filter = filter.to_owned();
+ let on_filter: Rc Message> = Rc::new(on_filter);
let on_change: Rc Message> = Rc::new(on_change);
+ let search_input: Element<'static, Message> = {
+ let of = on_filter.clone();
+ text_input("Search items...", filter.clone())
+ .on_input(move |v| of(v))
+ .padding(4)
+ .size(11)
+ .width(Length::Fill)
+ .into()
+ };
+
let Some(entries) = entries else {
let oc = on_change;
let input: Element<'static, Message> = text_input("", value.to_owned())
@@ -68,148 +75,174 @@ pub fn composite_item_picker(
.size(11)
.width(Length::Fill)
.into();
- return with_optional_label(label, input, show_label);
+ let body: Element<'static, Message> = col![search_input, input].spacing(4).into();
+ return with_optional_label(label, body, show_label);
};
- // Parallel label/byte vectors, so a displayed type always maps back to the
- // byte the setter needs. Insert the current type when the lookup omits it.
- let mut type_labels: Vec = Vec::new();
- let mut type_bytes: Vec = Vec::new();
- for (key, _) in entries {
- let tb: u8 = key
- .split(':')
- .next()
- .and_then(|s| s.parse().ok())
- .unwrap_or(255);
- if !type_bytes.contains(&tb)
- && let Some(ty) = ItemTypeId::from_u8(tb)
- {
- type_bytes.push(tb);
- type_labels.push(ty.to_string());
+ // One option per item file. Every key with the no-item byte denotes the
+ // same empty slot, so only the canonical sentinel survives.
+ let mut collapsed: Vec<(String, String)> = Vec::with_capacity(entries.len());
+ for (key, display) in entries {
+ if key.starts_with("255:") {
+ if key == NO_ITEM_KEY && !collapsed.iter().any(|(k, _)| k == key) {
+ collapsed.push((key.clone(), display.clone()));
+ }
+ } else {
+ collapsed.push((key.clone(), display.clone()));
}
}
- let current_type_label = current_type.to_string();
- if !type_bytes.contains(¤t_type_byte) {
- type_bytes.push(current_type_byte);
- type_labels.push(current_type_label.clone());
+ if !collapsed.iter().any(|(key, _)| key == NO_ITEM_KEY) {
+ collapsed.push((NO_ITEM_KEY.to_string(), "[-]".to_string()));
}
- let mut filtered_items: Vec<(String, String)> = entries
+ let is_no_item = value.starts_with("255:");
+ let query = filter.to_lowercase();
+ let mut filtered_entries: Vec<(String, String)> = collapsed
.iter()
- .filter(|(key, _)| {
- key.split(':').next().and_then(|s| s.parse::().ok()) == Some(current_type_byte)
+ .filter(|(key, display)| {
+ display.to_lowercase().contains(&query) || key.to_lowercase().contains(&query)
})
.cloned()
.collect();
- // Every key with the no-item byte denotes the same empty slot, regardless
- // of its id. Resolve all of them to the shared sentinel option so the
- // selection is never blank.
- let is_no_item = current_type_byte == u8::from(ItemTypeId::NoItem);
- if is_no_item && !filtered_items.iter().any(|(key, _)| key == NO_ITEM_KEY) {
- filtered_items.push((NO_ITEM_KEY.to_string(), NO_ITEM_LABEL.to_string()));
+ // The current value must never vanish from the select while the user
+ // types. A no-item value also keeps the sentinel that stands in for it.
+ let mut required: Vec<&str> = vec![value];
+ if is_no_item {
+ required.push(NO_ITEM_KEY);
+ }
+ for key in required {
+ if !filtered_entries.iter().any(|(k, _)| k == key)
+ && let Some(entry) = collapsed.iter().find(|(k, _)| k == key)
+ {
+ filtered_entries.push(entry.clone());
+ }
}
- let lookup_key = if is_no_item { NO_ITEM_KEY } else { value };
-
- let mut selected_item = filtered_items
- .iter()
- .find(|(key, _)| *key == lookup_key)
- .map(|(_, name)| name.clone());
-
- let mut labelled_keys: Vec<(String, String)> = filtered_items
- .iter()
- .map(|(key, name)| (name.clone(), key.clone()))
- .collect();
- // A non-canonical no-item key still renders as the shared "[-]" option,
- // but re-selecting it must emit the exact stored key to keep the record
- // byte-for-byte intact.
+ // A non-canonical stored key (e.g. `255:255`) still renders as the shared
+ // empty-slot option, but re-selecting that option must emit the exact key
+ // so `InventoryItem::is_empty()` keeps working.
+ let effective_selected_id = if is_no_item { NO_ITEM_KEY } else { value };
+ let mut select = lookup_select(&filtered_entries, effective_selected_id);
if is_no_item && value != NO_ITEM_KEY {
- for (label, key) in &mut labelled_keys {
- if label == NO_ITEM_LABEL {
- *key = value.to_string();
+ for id in select.label_to_id.values_mut() {
+ if id == NO_ITEM_KEY {
+ *id = value.to_string();
}
}
}
- // An id that is gone from the lookup still gets a visible, selectable
- // label. The stored value is left untouched; choosing the fallback keeps
- // the original key.
- if selected_item.is_none() {
- let fallback_label = format!("Unknown ({})", current_id);
- labelled_keys.push((fallback_label.clone(), value.to_string()));
- selected_item = Some(fallback_label);
- }
-
- let item_options: Vec = labelled_keys
- .iter()
- .map(|(label, _)| label.clone())
- .collect();
-
- let type_picker: Element<'static, Message> = {
- let oc = on_change.clone();
- let current_id = current_id.clone();
- let labels = type_labels.clone();
- let bytes = type_bytes.clone();
- let entries_owned: Vec<(String, String)> = entries.to_vec();
- pick_list(Some(current_type_label), type_labels, |v| v.to_string())
- .on_select(move |selected_label| {
- let new_byte = labels
- .iter()
- .position(|l| l == &selected_label)
- .and_then(|i| bytes.get(i).copied())
- .unwrap_or_else(|| u8::from(ItemTypeId::NoItem));
- let ids: Vec = entries_owned
- .iter()
- .filter(|(key, _)| {
- key.split(':').next().and_then(|s| s.parse::().ok()) == Some(new_byte)
- })
- .map(|(key, _)| key.split(':').nth(1).unwrap_or("0").to_string())
- .collect();
- // Prefer the current id when the new type offers it, otherwise
- // use the first entry of that type, or the shared empty slot.
- let key = if ids.contains(¤t_id) {
- format!("{}:{}", new_byte, current_id)
- } else if let Some(id) = ids.first() {
- format!("{}:{}", new_byte, id)
- } else {
- NO_ITEM_KEY.to_string()
- };
- oc(key)
- })
- .width(Length::Fill)
- .into()
- };
-
- let item_picker: Element<'static, Message> = {
- let fallback_key = value.to_string();
- pick_list(selected_item, item_options, |v| v.to_string())
+ let picker: Element<'static, Message> = {
+ let ids = select.label_to_id;
+ let fallback_key = value.to_owned();
+ pick_list(select.selected, select.options, String::clone)
.on_select(move |selected_name| {
- let composite_key = labelled_keys
- .iter()
- .find(|(label, _)| *label == selected_name)
- .map(|(_, key)| key.clone())
+ let key = ids
+ .get(&selected_name)
+ .cloned()
.unwrap_or_else(|| fallback_key.clone());
- on_change(composite_key)
+ on_change(key)
})
.width(Length::Fill)
.into()
};
- let pickers: Element<'static, Message> = col![type_picker, item_picker].spacing(4).into();
- with_optional_label(label, pickers, show_label)
+ let body: Element<'static, Message> = col![search_input, picker].spacing(4).into();
+ with_optional_label(label, body, show_label)
}
#[cfg(all(test, feature = "iced_test"))]
mod tests {
use super::*;
+ use crate::editors::weapon::WeaponEditorMessage;
+ use crate::message::{EditorMessage, FileTreeMessage};
+ use dispel_core::ItemTypeId;
+ use iced_test::selector::{Candidate, Target};
use iced_test::simulator;
+ fn picker(
+ value: &str,
+ entries: Option<&[(String, String)]>,
+ filter: &str,
+ ) -> Element<'static, Message> {
+ composite_item_picker(
+ "Invented Item",
+ value,
+ entries,
+ false,
+ filter,
+ |v| Message::FileTree(FileTreeMessage::Search(v)),
+ |v| {
+ Message::Editor(EditorMessage::Weapon(WeaponEditorMessage::FieldChanged(
+ 0,
+ "item".to_string(),
+ v,
+ )))
+ },
+ )
+ }
+
+ fn emitted_keys(messages: Vec) -> Vec {
+ messages
+ .into_iter()
+ .filter_map(|m| match m {
+ Message::Editor(EditorMessage::Weapon(WeaponEditorMessage::FieldChanged(
+ _,
+ _,
+ value,
+ ))) => Some(value),
+ _ => None,
+ })
+ .collect()
+ }
+
+ /// Type into the search box and feed the emitted query back into a fresh
+ /// render, the way the real caller stores it in state.
+ fn typed_filter(element: Element<'static, Message>, query: &str) -> String {
+ let mut ui = simulator(element);
+ let mut search = |candidate: Candidate<'_>| match candidate {
+ Candidate::TextInput { state, .. }
+ if state.text().into_owned() == "Search items..." =>
+ {
+ Some(Target::from(candidate))
+ }
+ _ => None,
+ };
+ ui.click(&mut search)
+ .expect("search input must be rendered");
+ ui.typewrite(query);
+ ui.into_messages()
+ .filter_map(|m| match m {
+ Message::FileTree(FileTreeMessage::Search(v)) => Some(v),
+ _ => None,
+ })
+ .last()
+ .expect("search input must emit its query")
+ }
+
+ fn select_option(
+ value: &str,
+ entries: &[(String, String)],
+ filter: &str,
+ offset: isize,
+ ) -> Vec {
+ emitted_keys(crate::tests::common::activate_select_option(
+ picker(value, Some(entries), filter),
+ 0,
+ offset,
+ ))
+ }
+
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 element: Element<'_, Message> = composite_item_picker(
+ "Invented Item",
+ "1:0",
+ entries,
+ show_label,
+ "",
+ |_| Message::FileTree(FileTreeMessage::Search(String::new())),
+ |_| Message::FileTree(FileTreeMessage::Search(String::new())),
+ );
let mut ui = simulator(element);
ui.find("Invented Item").is_ok()
}
@@ -217,41 +250,97 @@ mod tests {
#[test]
fn test_unmapped_composite_keys_render_a_label_and_keep_value() {
let entries = [
- ("1:0".to_string(), "Invented Sword".to_string()),
+ ("1:0".to_string(), "[Weapon] Invented Sword".to_string()),
("255:15".to_string(), "[-]".to_string()),
];
- let element = |value: &'static str| {
- composite_item_picker("Invented Item", value, Some(&entries), false, |v| {
- Message::FileTree(crate::message::FileTreeMessage::Search(v))
- })
- };
for value in ["255:0", "255:255"] {
- let values = crate::tests::common::select_values(element(value));
+ let values = crate::tests::common::select_values(picker(value, Some(&entries), ""));
assert!(
values.iter().any(|v| v == "[-]"),
"{value} must resolve to the no-item sentinel label, got {values:?}"
);
}
- let values = crate::tests::common::select_values(element("1:999"));
+ let values = crate::tests::common::select_values(picker("1:999", Some(&entries), ""));
assert!(
- values.iter().any(|v| v.starts_with("Unknown (999)")),
- "an unmapped item id must render a visible fallback label, got {values:?}"
+ values.iter().any(|v| v == "Unknown (1:999)"),
+ "an unmapped composite key must render a visible fallback label, got {values:?}"
);
- let messages = crate::tests::common::activate_select_option(element("255:0"), 1, 0);
- let emitted: Vec = messages
- .into_iter()
- .filter_map(|m| match m {
- Message::FileTree(crate::message::FileTreeMessage::Search(v)) => Some(v),
- _ => None,
- })
- .collect();
+ let keys = select_option("255:0", &entries, "", 0);
+ assert_eq!(
+ keys,
+ vec!["255:0"],
+ "choosing the sentinel must keep the exact stored key"
+ );
+ }
+
+ #[test]
+ fn test_one_select_offers_items_from_every_type() {
+ let entries = [
+ ("1:0".to_string(), "[Weapon] Invented Sword".to_string()),
+ ("2:7".to_string(), "[Healing] Invented Herb".to_string()),
+ ("3:2".to_string(), "[Edit] Invented Charm".to_string()),
+ ("255:15".to_string(), "[-]".to_string()),
+ ];
+ let values = crate::tests::common::select_values(picker("1:0", Some(&entries), ""));
+ assert_eq!(
+ values.len(),
+ 1,
+ "there must be exactly one select, got {values:?}"
+ );
+
+ assert_eq!(select_option("1:0", &entries, "", 1), vec!["2:7"]);
+ assert_eq!(select_option("1:0", &entries, "", 2), vec!["3:2"]);
+ assert_eq!(select_option("1:0", &entries, "", 3), vec!["255:15"]);
+ }
+
+ #[test]
+ fn test_search_narrows_options_and_keeps_selection_visible() {
+ let entries = [
+ ("1:0".to_string(), "[Weapon] Invented Sword".to_string()),
+ ("2:7".to_string(), "[Healing] Invented Herb".to_string()),
+ ("3:2".to_string(), "[Edit] Invented Charm".to_string()),
+ ("255:15".to_string(), "[-]".to_string()),
+ ];
+ let query = typed_filter(picker("1:0", Some(&entries), ""), "herb");
+ assert_eq!(query, "herb");
+
+ let values = crate::tests::common::select_values(picker("1:0", Some(&entries), &query));
assert!(
- emitted.iter().any(|v| v == "255:0"),
- "choosing the sentinel must keep the exact stored key, got {emitted:?}"
+ values.iter().any(|v| v == "[Weapon] Invented Sword"),
+ "the current item must stay selected while filtering, got {values:?}"
+ );
+
+ assert_eq!(
+ select_option("1:0", &entries, &query, -1),
+ vec!["2:7"],
+ "the only other option must be the matching item"
);
+ let reachable: std::collections::HashSet = (-3..=3)
+ .flat_map(|offset| select_option("1:0", &entries, "charm", offset))
+ .collect();
+ assert_eq!(
+ reachable,
+ std::collections::HashSet::from(["1:0".to_string(), "3:2".to_string()]),
+ "non-matching items must be absent from the narrowed list"
+ );
+
+ // Filtering by the composite key works just like filtering by label.
+ let query = typed_filter(picker("1:0", Some(&entries), ""), "3:2");
+ assert_eq!(select_option("1:0", &entries, &query, -1), vec!["3:2"]);
+ }
+
+ #[test]
+ fn test_selected_label_emits_its_exact_composite_key() {
+ let entries = [
+ ("1:0".to_string(), "[Weapon] Invented Sword".to_string()),
+ ("2:7".to_string(), "[Healing] Invented Herb".to_string()),
+ ("255:15".to_string(), "[-]".to_string()),
+ ];
+ assert_eq!(select_option("2:7", &entries, "", 0), vec!["2:7"]);
+ assert_eq!(select_option("2:7", &entries, "", -1), vec!["1:0"]);
}
#[test]
@@ -259,43 +348,22 @@ mod tests {
use dispel_core::InventoryItem;
let entries = [
- ("1:0".to_string(), "Invented Sword".to_string()),
+ ("1:0".to_string(), "[Weapon] Invented Sword".to_string()),
("255:15".to_string(), "[-]".to_string()),
];
- let element = |value: &'static str| {
- composite_item_picker("Invented Item", value, Some(&entries), false, |v| {
- Message::FileTree(crate::message::FileTreeMessage::Search(v))
- })
- };
- let emitted_for = |value: &'static str| -> String {
- let messages = crate::tests::common::activate_select_option(element(value), 1, 0);
- messages
- .into_iter()
- .find_map(|m| match m {
- Message::FileTree(crate::message::FileTreeMessage::Search(v)) => Some(v),
- _ => None,
- })
- .unwrap_or_else(|| panic!("no value emitted for {value}"))
- };
for value in ["255:255", "255:5"] {
- let values = crate::tests::common::select_values(element(value));
- assert!(
- values.iter().any(|v| v == "[-]"),
- "{value} must render the shared no-item label, got {values:?}"
- );
+ assert_eq!(select_option(value, &entries, "", 0), vec![value]);
}
+ assert_eq!(select_option("255:15", &entries, "", 0), vec!["255:15"]);
- assert_eq!(emitted_for("255:255"), "255:255");
- assert_eq!(emitted_for("255:5"), "255:5");
- assert_eq!(emitted_for("255:15"), "255:15");
-
- let emitted = emitted_for("255:255");
- let parts: Vec<&str> = emitted.split(':').collect();
- let item = InventoryItem::new(
- ItemTypeId::from_u8(parts[0].parse().unwrap()).unwrap(),
- parts[1].parse().unwrap(),
+ // Filtering out "[-]" must not hide the empty slot either.
+ assert_eq!(
+ select_option("255:255", &entries, "sword", 0),
+ vec!["255:255"]
);
+
+ let item = InventoryItem::new(ItemTypeId::NoItem, 255);
assert!(
item.is_empty(),
"255:255 must decode to an empty inventory item"
@@ -303,39 +371,24 @@ mod tests {
}
#[test]
- fn test_composite_type_picker_keeps_current_type_and_selects_valid_id() {
- // The lookup knows only type 2; the record currently uses type 3.
- let entries = [("2:5".to_string(), "Invented Potion".to_string())];
- let element = || {
- composite_item_picker("Invented Item", "3:7", Some(&entries), false, |v| {
- Message::FileTree(crate::message::FileTreeMessage::Search(v))
- })
- };
-
- let values = crate::tests::common::select_values(element());
- assert!(
- values.first().is_some_and(|v| v == "Edit"),
- "the type picker must show the current type, got {values:?}"
- );
-
- // "Edit" is inserted after "Healing", so move the highlight up once.
- let messages = crate::tests::common::activate_select_option(element(), 0, -1);
- let emitted: Vec = messages
- .into_iter()
- .filter_map(|m| match m {
- Message::FileTree(crate::message::FileTreeMessage::Search(v)) => Some(v),
- _ => None,
- })
- .collect();
+ fn test_duplicate_display_names_stay_distinguishable() {
+ let entries = [
+ ("1:4".to_string(), "Invented Blade".to_string()),
+ ("2:4".to_string(), "Invented Blade".to_string()),
+ ("255:15".to_string(), "[-]".to_string()),
+ ];
+ let values = crate::tests::common::select_values(picker("2:4", Some(&entries), ""));
assert!(
- emitted.iter().any(|v| v == "2:5"),
- "switching type must choose an id present in the new type, got {emitted:?}"
+ values.iter().any(|v| v == "Invented Blade (2:4)"),
+ "duplicate labels must be qualified with their composite key, got {values:?}"
);
+ assert_eq!(select_option("2:4", &entries, "", -1), vec!["1:4"]);
+ assert_eq!(select_option("2:4", &entries, "", 0), vec!["2:4"]);
}
#[test]
fn test_composite_picker_label_follows_show_label() {
- let entries = [("1:0".to_string(), "Invented Sword".to_string())];
+ let entries = [("1:0".to_string(), "[Weapon] Invented Sword".to_string())];
for show_label in [true, false] {
assert_eq!(
label_rendered(None, show_label),
diff --git a/dispel-gui/src/editors/map_editor/view/fields.rs b/dispel-gui/src/editors/map_editor/view/fields.rs
index 04b162ce..74cf1869 100644
--- a/dispel-gui/src/editors/map_editor/view/fields.rs
+++ b/dispel-gui/src/editors/map_editor/view/fields.rs
@@ -2,7 +2,7 @@ use std::collections::HashMap;
use crate::components::composite_item::composite_item_picker;
use crate::components::editable::{EditableRecord, FieldKind};
-use crate::message::{Message, MessageExt};
+use crate::message::{Message, MessageExt, SystemMessage};
use crate::style;
use iced::widget::{column, pick_list, row, scrollable, text, text_input};
use iced::{Element, Fill};
@@ -151,14 +151,22 @@ 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, true, move |v| {
- Message::map_editor(MapEditorMessage::EntityFieldChanged(
- tab_id,
- sel,
- name.to_string(),
- v,
- ))
- })
+ composite_item_picker(
+ label,
+ value,
+ entries,
+ true,
+ "",
+ |_| Message::System(SystemMessage::DismissError),
+ move |v| {
+ Message::map_editor(MapEditorMessage::EntityFieldChanged(
+ tab_id,
+ sel,
+ name.to_string(),
+ v,
+ ))
+ },
+ )
}
}
}
diff --git a/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs b/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs
index 559ae3ca..70f1633c 100644
--- a/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs
+++ b/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs
@@ -12,7 +12,7 @@ use crate::components::composite_item::composite_item_picker;
use crate::components::editable::{EditableRecord, FieldDescriptor, FieldKind};
use crate::components::generic_editor::GenericEditorState;
use crate::components::utils::horizontal_space;
-use crate::message::Message;
+use crate::message::{Message, SystemMessage};
use crate::style;
use crate::view::editor::spreadsheet::message::SpreadsheetMessage;
use crate::view::editor::spreadsheet::state::SpreadsheetState;
@@ -161,13 +161,21 @@ pub(crate) 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, false, move |v| {
- spreadsheet_msg(SpreadsheetMessage::InspectorFieldChanged(
- orig_idx,
- field_name.clone(),
- v,
- ))
- })
+ composite_item_picker(
+ descriptor.label,
+ &value,
+ entries,
+ false,
+ "",
+ |_| Message::System(SystemMessage::DismissError),
+ move |v| {
+ spreadsheet_msg(SpreadsheetMessage::InspectorFieldChanged(
+ orig_idx,
+ field_name.clone(),
+ v,
+ ))
+ },
+ )
}
_ => {
let field_name = descriptor.name.to_string();
From 06bf6db8c90548cb8c0cc91e8e03ff5621606856 Mon Sep 17 00:00:00 2001
From: dimspell <141545384+dimspell@users.noreply.github.com>
Date: Wed, 25 Nov 2026 23:00:49 +0100
Subject: [PATCH 13/72] feat(gui): keep composite item search per field
---
.../src/components/map_render/view_state.rs | 6 +
dispel-gui/src/editors/map_editor/message.rs | 3 +
.../src/editors/map_editor/update/mod.rs | 6 +
.../src/editors/map_editor/view/fields.rs | 38 ++-
.../src/editors/map_editor/view/inspector.rs | 33 ++-
dispel-gui/src/tests/select_boxes.rs | 240 +++++++++++++++++-
dispel-gui/src/update/editor/common.rs | 3 +
.../src/view/editor/spreadsheet/message.rs | 3 +
.../src/view/editor/spreadsheet/state.rs | 4 +
.../view/editor/spreadsheet/view/inspector.rs | 36 ++-
.../src/view/editor/spreadsheet/view/mod.rs | 1 +
11 files changed, 350 insertions(+), 23 deletions(-)
diff --git a/dispel-gui/src/components/map_render/view_state.rs b/dispel-gui/src/components/map_render/view_state.rs
index 084f80bc..c9037b37 100644
--- a/dispel-gui/src/components/map_render/view_state.rs
+++ b/dispel-gui/src/components/map_render/view_state.rs
@@ -1,3 +1,5 @@
+use std::collections::HashMap;
+
use crate::editors::map_editor::message::{MapTool, MapViewMode, ObjectBrushMode, SelectedEntity};
use iced::widget::canvas;
@@ -53,6 +55,9 @@ pub struct MapViewState {
pub selected_sprite_sequence: Option,
/// Currently selected entity in the inspector panel.
pub selected_entity: Option,
+ /// Search text of the composite item picker, keyed by field name. Each map
+ /// editor is per-tab, so the field name alone identifies the input.
+ pub composite_item_filters: HashMap,
/// Cached tile-layer frame. Clear whenever pan, zoom, tiles, or entity
/// sprites change. Avoids redrawing the expensive tile layer on every
/// cursor-move event (which only affects the overlay canvas).
@@ -96,6 +101,7 @@ impl Default for MapViewState {
layers_popover_open: false,
selected_sprite_sequence: None,
selected_entity: None,
+ composite_item_filters: HashMap::new(),
tile_layer_cache: canvas::Cache::new(),
overlay_cache: canvas::Cache::new(),
}
diff --git a/dispel-gui/src/editors/map_editor/message.rs b/dispel-gui/src/editors/map_editor/message.rs
index 709a4395..d3b903fa 100644
--- a/dispel-gui/src/editors/map_editor/message.rs
+++ b/dispel-gui/src/editors/map_editor/message.rs
@@ -125,6 +125,9 @@ pub enum MapEditorMessage {
Deselect(usize),
/// Entity field edited in the inspector.
EntityFieldChanged(usize, SelectedEntity, String, String),
+ /// Search text typed into a composite item picker. State-only: the record
+ /// is untouched, so no cache refresh or history entry is needed.
+ CompositeItemFilterChanged(usize, String, String),
/// Save all modified entity .ref files.
SaveEntities(usize),
/// Async save completed. Ok carries a status message; Err the error text.
diff --git a/dispel-gui/src/editors/map_editor/update/mod.rs b/dispel-gui/src/editors/map_editor/update/mod.rs
index f37dc2ca..41b97ced 100644
--- a/dispel-gui/src/editors/map_editor/update/mod.rs
+++ b/dispel-gui/src/editors/map_editor/update/mod.rs
@@ -23,6 +23,12 @@ pub fn handle(message: MapEditorMessage, app: &mut App) -> Task {
MapEditorMessage::EntityFieldChanged(tab_id, entity, field, value) => {
entity::field_changed(app, tab_id, entity, field, value)
}
+ MapEditorMessage::CompositeItemFilterChanged(tab_id, field, query) => {
+ if let Some(editor) = app.state.editors.map_editors.get_mut(&tab_id) {
+ editor.view.composite_item_filters.insert(field, query);
+ }
+ Task::none()
+ }
MapEditorMessage::Undo(tab_id) => entity::undo(app, tab_id),
MapEditorMessage::Redo(tab_id) => entity::redo(app, tab_id),
MapEditorMessage::SaveEntities(tab_id) => persistence::save_entities(app, tab_id),
diff --git a/dispel-gui/src/editors/map_editor/view/fields.rs b/dispel-gui/src/editors/map_editor/view/fields.rs
index 74cf1869..06517ced 100644
--- a/dispel-gui/src/editors/map_editor/view/fields.rs
+++ b/dispel-gui/src/editors/map_editor/view/fields.rs
@@ -2,7 +2,7 @@ use std::collections::HashMap;
use crate::components::composite_item::composite_item_picker;
use crate::components::editable::{EditableRecord, FieldKind};
-use crate::message::{Message, MessageExt, SystemMessage};
+use crate::message::{Message, MessageExt};
use crate::style;
use iced::widget::{column, pick_list, row, scrollable, text, text_input};
use iced::{Element, Fill};
@@ -18,13 +18,21 @@ pub fn build_record_fields<'a, R: EditableRecord>(
tab_id: usize,
sel: SelectedEntity,
lookups: &'a HashMap>,
+ composite_filters: &'a HashMap,
) -> Element<'a, Message> {
let mut col = column![].spacing(5);
for desc in R::field_descriptors() {
let value = record.get_field(desc.name);
col = col.push(inspector_field_row(
- desc.label, desc.name, &desc.kind, &value, tab_id, sel, lookups,
+ desc.label,
+ desc.name,
+ &desc.kind,
+ &value,
+ tab_id,
+ sel,
+ lookups,
+ composite_filters,
));
}
scrollable(col).spacing(6).into()
@@ -35,6 +43,7 @@ pub fn build_record_fields<'a, R: EditableRecord>(
/// `label` and `name` are `&'static str` (from `FieldDescriptor`); `value` is a
/// short-lived borrow of a locally-computed `String`; text inputs clone it before
/// constructing their returned widgets.
+#[allow(clippy::too_many_arguments)]
pub fn inspector_field_row<'a>(
label: &'static str,
name: &'static str,
@@ -43,6 +52,7 @@ pub fn inspector_field_row<'a>(
tab_id: usize,
sel: SelectedEntity,
lookups: &'a HashMap>,
+ composite_filters: &'a HashMap,
) -> Element<'a, Message> {
const LABEL_W: f32 = 140.0;
match kind {
@@ -151,13 +161,23 @@ pub fn inspector_field_row<'a>(
FieldKind::CompositeItem { lookup_key } => {
let entries = lookups.get(*lookup_key).map(|v| v.as_slice());
+ let filter = composite_filters
+ .get(name)
+ .map(String::as_str)
+ .unwrap_or("");
composite_item_picker(
label,
value,
entries,
true,
- "",
- |_| Message::System(SystemMessage::DismissError),
+ filter,
+ move |text| {
+ Message::map_editor(MapEditorMessage::CompositeItemFilterChanged(
+ tab_id,
+ name.to_string(),
+ text,
+ ))
+ },
move |v| {
Message::map_editor(MapEditorMessage::EntityFieldChanged(
tab_id,
@@ -177,6 +197,9 @@ mod tests {
use iced_test::selector::{Candidate, Target};
use iced_test::simulator;
+ static EMPTY_FILTERS: std::sync::LazyLock> =
+ std::sync::LazyLock::new(HashMap::new);
+
fn count_label_text(element: Element<'_, Message>, label: &str) -> usize {
let mut ui = simulator(element);
let mut count = 0usize;
@@ -221,6 +244,7 @@ mod tests {
0,
SelectedEntity::Npc(0),
&lookups,
+ &EMPTY_FILTERS,
);
assert!(
crate::tests::common::select_shows(element, "Left"),
@@ -254,6 +278,7 @@ mod tests {
0,
SelectedEntity::DrawItem(0),
&lookups,
+ &EMPTY_FILTERS,
);
assert!(
crate::tests::common::select_shows(unknown, "Bogus"),
@@ -268,6 +293,7 @@ mod tests {
0,
SelectedEntity::DrawItem(0),
&lookups,
+ &EMPTY_FILTERS,
);
assert!(
crate::tests::common::select_shows(known, "Beta"),
@@ -294,6 +320,7 @@ mod tests {
0,
SelectedEntity::Monster(0),
&lookups,
+ &EMPTY_FILTERS,
);
assert!(
crate::tests::common::select_shows(missing, "Unknown (99)"),
@@ -308,6 +335,7 @@ mod tests {
0,
SelectedEntity::Monster(0),
&lookups,
+ &EMPTY_FILTERS,
);
assert!(
crate::tests::common::select_shows(duplicate, "Invented Creature (9)"),
@@ -322,6 +350,7 @@ mod tests {
0,
SelectedEntity::Monster(0),
&lookups,
+ &EMPTY_FILTERS,
);
let messages = crate::tests::common::activate_select_option(duplicate, 0, -1);
let emitted: Vec = messages
@@ -353,6 +382,7 @@ mod tests {
0,
SelectedEntity::DrawItem(0),
&lookups,
+ &EMPTY_FILTERS,
);
assert_eq!(
count_label_text(element, "Invented Item:"),
diff --git a/dispel-gui/src/editors/map_editor/view/inspector.rs b/dispel-gui/src/editors/map_editor/view/inspector.rs
index 1d50b100..a4f35b09 100644
--- a/dispel-gui/src/editors/map_editor/view/inspector.rs
+++ b/dispel-gui/src/editors/map_editor/view/inspector.rs
@@ -24,7 +24,13 @@ pub fn build_inspector<'a>(
let (title, width, body): (&'static str, f32, Element<'a, Message>) = match sel {
SelectedEntity::Monster(i) => {
let body = if let Some(record) = state.data.monsters.get(i) {
- fields::build_record_fields::(record, tab_id, sel, lookups)
+ fields::build_record_fields::(
+ record,
+ tab_id,
+ sel,
+ lookups,
+ &state.view.composite_item_filters,
+ )
} else {
text("Monster not found").size(12).into()
};
@@ -36,7 +42,14 @@ pub fn build_inspector<'a>(
for desc in NPC::field_descriptors() {
let value = record.get_field(desc.name);
els.push(fields::inspector_field_row(
- desc.label, desc.name, &desc.kind, &value, tab_id, sel, lookups,
+ desc.label,
+ desc.name,
+ &desc.kind,
+ &value,
+ tab_id,
+ sel,
+ lookups,
+ &state.view.composite_item_filters,
));
}
column(els).spacing(6).into()
@@ -47,7 +60,13 @@ pub fn build_inspector<'a>(
}
SelectedEntity::Extra(i) => {
let body = if let Some(record) = state.data.extra_refs.get(i) {
- fields::build_record_fields::(record, tab_id, sel, lookups)
+ fields::build_record_fields::(
+ record,
+ tab_id,
+ sel,
+ lookups,
+ &state.view.composite_item_filters,
+ )
} else {
text("Object not found").size(12).into()
};
@@ -55,7 +74,13 @@ pub fn build_inspector<'a>(
}
SelectedEntity::DrawItem(i) => {
let body = if let Some(record) = state.data.draw_items.get(i) {
- fields::build_record_fields::(record, tab_id, sel, lookups)
+ fields::build_record_fields::(
+ record,
+ tab_id,
+ sel,
+ lookups,
+ &state.view.composite_item_filters,
+ )
} else {
text("Draw item not found").size(12).into()
};
diff --git a/dispel-gui/src/tests/select_boxes.rs b/dispel-gui/src/tests/select_boxes.rs
index c7211567..d8311a73 100644
--- a/dispel-gui/src/tests/select_boxes.rs
+++ b/dispel-gui/src/tests/select_boxes.rs
@@ -5,12 +5,12 @@
//! contain and omit the displayed id. Each label must survive `set_field` /
//! `get_field` and be visible in the spreadsheet inspector and the map editor.
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use std::fmt::{Debug, Display};
use dispel_core::references::enums::WireValue;
use dispel_core::{
- BooleanFlag, DialogOwner, DialogType, DialogueScript, EditItem, EditItemEffect,
+ BooleanFlag, DialogOwner, DialogType, DialogueScript, DrawItem, EditItem, EditItemEffect,
EditItemModification, Event, EventNpcRef, EventType, ExtraObjectType, ExtraRef, HealItem,
HealItemFlag, MagicSpell, MagicSpellFlag, MagicType, Map, MapLighting, Monster, MonsterAiType,
MonsterRef, MonsterSpawn, NPC, NpcInteractionMode, NpcLookingDirection, NpcMovementMode,
@@ -18,13 +18,19 @@ use dispel_core::{
};
use crate::components::editable::{EditableRecord, FieldDescriptor, FieldKind};
+use crate::editors::map_editor::MapEditorMessage;
use crate::editors::map_editor::message::SelectedEntity;
use crate::editors::map_editor::view::fields;
-use crate::message::{EditorMessage, Message, SystemMessage};
+use crate::message::{EditorMessage, FileTreeMessage, Message, SystemMessage};
use crate::view::editor::spreadsheet::message::SpreadsheetMessage;
use crate::view::editor::spreadsheet::view::inspector::build_inspector_field;
+use iced_test::selector::{Candidate, Target};
+use iced_test::simulator;
-use super::common::{activate_select_option, select_shows};
+use super::common::{activate_select_option, select_shows, select_values};
+
+static EMPTY_FILTERS: std::sync::LazyLock> =
+ std::sync::LazyLock::new(HashMap::new);
/// The formatting protocol of a field's get path.
trait LabelFormat {
@@ -128,11 +134,18 @@ fn render_both(
None,
captured_field_changed,
&empty,
+ &EMPTY_FILTERS,
captured_spreadsheet,
);
+ let shown = select_values(inspector);
+ assert!(
+ shown.iter().any(|value| value == expected),
+ "inspector for {} must render {expected:?}, got {shown:?}",
+ desc.name
+ );
assert!(
- select_shows(inspector, expected),
- "inspector for {} must render {expected:?}",
+ shown.iter().all(|value| !value.trim().is_empty()),
+ "inspector for {} must never render a blank selection, got {shown:?}",
desc.name
);
@@ -144,10 +157,17 @@ fn render_both(
0,
SelectedEntity::Npc(0),
lookups,
+ &EMPTY_FILTERS,
);
+ let shown = select_values(row);
assert!(
- select_shows(row, expected),
- "map editor row for {} must render {expected:?}",
+ shown.iter().any(|value| value == expected),
+ "map editor row for {} must render {expected:?}, got {shown:?}",
+ desc.name
+ );
+ assert!(
+ shown.iter().all(|value| !value.trim().is_empty()),
+ "map editor row for {} must never render a blank selection, got {shown:?}",
desc.name
);
}
@@ -215,6 +235,7 @@ fn inspector_emissions(
None,
captured_field_changed,
&empty,
+ &EMPTY_FILTERS,
captured_spreadsheet,
);
activate_select_option(element, nth, 0)
@@ -241,6 +262,7 @@ fn map_emissions(
0,
SelectedEntity::Npc(0),
lookups,
+ &EMPTY_FILTERS,
);
activate_select_option(element, 0, 0)
.into_iter()
@@ -253,6 +275,31 @@ fn map_emissions(
.collect()
}
+/// Type into the composite search input of a rendered inspector and return the
+/// messages emitted while typing (one per keystroke).
+fn type_filter(element: iced::Element<'_, Message>, query: &str) -> Vec {
+ let mut ui = simulator(element);
+ let mut search = |candidate: Candidate<'_>| match candidate {
+ Candidate::TextInput { state, .. } if state.text().into_owned() == "Search items..." => {
+ Some(Target::from(candidate))
+ }
+ _ => None,
+ };
+ ui.click(&mut search)
+ .expect("composite search input must be rendered");
+ ui.typewrite(query);
+ ui.into_messages().collect()
+}
+
+fn filter_capturing_spreadsheet(msg: SpreadsheetMessage) -> Message {
+ match msg {
+ SpreadsheetMessage::CompositeItemFilterChanged(_, query) => {
+ Message::FileTree(FileTreeMessage::Search(query))
+ }
+ other => captured_spreadsheet(other),
+ }
+}
+
fn audit_lookup(field: &'static str) {
let desc = descriptor_of::(field);
let FieldKind::Lookup(key) = &desc.kind else {
@@ -307,10 +354,10 @@ fn audit_composite(field: &'static str) {
)]);
render_both(desc, "1:5", &present, "Invented Sword");
- render_both(desc, "1:5", &absent, "Unknown (5)");
- render_both(desc, "1:99", &present, "Unknown (99)");
+ render_both(desc, "1:5", &absent, "Unknown (1:5)");
+ render_both(desc, "1:99", &present, "Unknown (1:99)");
- for emitted in inspector_emissions(desc, "1:5", &present, 1)
+ for emitted in inspector_emissions(desc, "1:5", &present, 0)
.into_iter()
.chain(map_emissions(desc, "1:5", &present))
{
@@ -504,6 +551,176 @@ fn test_every_lookup_and_composite_field_round_trips_through_both_views() {
audit_composite::("interaction_result_item");
}
+#[test]
+fn test_composite_filter_narrows_spreadsheet_inspector_options() {
+ let desc = descriptor_of::("item");
+ let FieldKind::CompositeItem { lookup_key } = &desc.kind else {
+ panic!("item must be a composite field");
+ };
+ let lookups = HashMap::from([(
+ lookup_key.to_string(),
+ vec![
+ ("1:5".to_string(), "[Weapon] Invented Sword".to_string()),
+ ("2:7".to_string(), "[Healing] Invented Herb".to_string()),
+ ("255:15".to_string(), "[-]".to_string()),
+ ],
+ )]);
+ let contents = HashMap::new();
+
+ let unfiltered = build_inspector_field(
+ desc,
+ "1:5".into(),
+ 0,
+ &lookups,
+ None,
+ captured_field_changed,
+ &contents,
+ &EMPTY_FILTERS,
+ filter_capturing_spreadsheet,
+ );
+ let query = type_filter(unfiltered, "herb")
+ .into_iter()
+ .filter_map(|m| match m {
+ Message::FileTree(FileTreeMessage::Search(q)) => Some(q),
+ _ => None,
+ })
+ .last()
+ .expect("the search input must emit its query");
+ assert_eq!(query, "herb");
+
+ let filters = HashMap::from([("item".to_string(), query)]);
+ let filtered = build_inspector_field(
+ desc,
+ "1:5".into(),
+ 0,
+ &lookups,
+ None,
+ captured_field_changed,
+ &contents,
+ &filters,
+ captured_spreadsheet,
+ );
+ assert!(
+ select_values(filtered)
+ .iter()
+ .any(|value| value == "[Weapon] Invented Sword"),
+ "the current item must stay visible while its filter is active"
+ );
+
+ let reachable: HashSet = (-3..=3)
+ .flat_map(|offset| {
+ let element = build_inspector_field(
+ desc,
+ "1:5".into(),
+ 0,
+ &lookups,
+ None,
+ captured_field_changed,
+ &contents,
+ &filters,
+ captured_spreadsheet,
+ );
+ activate_select_option(element, 0, offset)
+ .into_iter()
+ .filter_map(|m| match m {
+ Message::Editor(EditorMessage::Weapon(
+ crate::editors::weapon::WeaponEditorMessage::FieldChanged(_, _, value),
+ )) => Some(value),
+ _ => None,
+ })
+ })
+ .collect();
+ assert_eq!(
+ reachable,
+ HashSet::from(["1:5".to_string(), "2:7".to_string()]),
+ "the filter must remove every non-matching option"
+ );
+}
+
+#[test]
+fn test_composite_filter_narrows_map_editor_options() {
+ let desc = descriptor_of::("item");
+ let FieldKind::CompositeItem { lookup_key } = &desc.kind else {
+ panic!("item must be a composite field");
+ };
+ let lookups = HashMap::from([(
+ lookup_key.to_string(),
+ vec![
+ ("1:5".to_string(), "[Weapon] Invented Sword".to_string()),
+ ("2:7".to_string(), "[Healing] Invented Herb".to_string()),
+ ("255:15".to_string(), "[-]".to_string()),
+ ],
+ )]);
+
+ let unfiltered = fields::inspector_field_row(
+ desc.label,
+ desc.name,
+ &desc.kind,
+ "1:5",
+ 0,
+ SelectedEntity::Npc(0),
+ &lookups,
+ &EMPTY_FILTERS,
+ );
+ let query = type_filter(unfiltered, "herb")
+ .into_iter()
+ .filter_map(|m| match m {
+ Message::Editor(EditorMessage::MapEditor(
+ MapEditorMessage::CompositeItemFilterChanged(_, _, query),
+ )) => Some(query),
+ _ => None,
+ })
+ .last()
+ .expect("the search input must emit its query");
+ assert_eq!(query, "herb");
+
+ let filters = HashMap::from([("item".to_string(), query)]);
+ let filtered = fields::inspector_field_row(
+ desc.label,
+ desc.name,
+ &desc.kind,
+ "1:5",
+ 0,
+ SelectedEntity::Npc(0),
+ &lookups,
+ &filters,
+ );
+ assert!(
+ select_values(filtered)
+ .iter()
+ .any(|value| value == "[Weapon] Invented Sword"),
+ "the current item must stay visible while its filter is active"
+ );
+
+ let reachable: HashSet = (-3..=3)
+ .flat_map(|offset| {
+ let element = fields::inspector_field_row(
+ desc.label,
+ desc.name,
+ &desc.kind,
+ "1:5",
+ 0,
+ SelectedEntity::Npc(0),
+ &lookups,
+ &filters,
+ );
+ activate_select_option(element, 0, offset)
+ .into_iter()
+ .filter_map(|m| match m {
+ Message::Editor(EditorMessage::MapEditor(
+ MapEditorMessage::EntityFieldChanged(_, _, _, value),
+ )) => Some(value),
+ _ => None,
+ })
+ })
+ .collect();
+ assert_eq!(
+ reachable,
+ HashSet::from(["1:5".to_string(), "2:7".to_string()]),
+ "the map editor filter must remove every non-matching option"
+ );
+}
+
#[test]
fn test_lookup_label_collision_emits_each_own_id() {
let desc = descriptor_of::("monster_db_id");
@@ -525,6 +742,7 @@ fn test_lookup_label_collision_emits_each_own_id() {
None,
captured_field_changed,
&empty,
+ &EMPTY_FILTERS,
captured_spreadsheet,
);
activate_select_option(element, 0, offset)
diff --git a/dispel-gui/src/update/editor/common.rs b/dispel-gui/src/update/editor/common.rs
index b59123c1..81ee9f6d 100644
--- a/dispel-gui/src/update/editor/common.rs
+++ b/dispel-gui/src/update/editor/common.rs
@@ -166,6 +166,9 @@ macro_rules! handle_spreadsheet_messages_inner {
$compute_caches
return task;
}
+ SM::CompositeItemFilterChanged(field, query) => {
+ $ss.composite_item_filters.insert(field, query);
+ }
SM::CachesComputed(data) => {
$ss.install_caches(data);
$ss.is_loading = false;
diff --git a/dispel-gui/src/view/editor/spreadsheet/message.rs b/dispel-gui/src/view/editor/spreadsheet/message.rs
index 7a73384c..488db432 100644
--- a/dispel-gui/src/view/editor/spreadsheet/message.rs
+++ b/dispel-gui/src/view/editor/spreadsheet/message.rs
@@ -63,6 +63,9 @@ pub enum SpreadsheetMessage {
/// Fired by `text_input` / `pick_list` widgets in the inspector panel.
/// Routes through the macro so that `compute_all_caches` is called after.
InspectorFieldChanged(usize, String, String),
+ /// Search text typed into a composite item picker. `(field_name, query)`
+ /// is stored on the spreadsheet state; no record is touched.
+ CompositeItemFilterChanged(String, String),
// ── Async cache loading ────────────────────────────────────────────────
/// Result of an off-thread `compute_caches` job. The handler installs the
diff --git a/dispel-gui/src/view/editor/spreadsheet/state.rs b/dispel-gui/src/view/editor/spreadsheet/state.rs
index a858fbd6..fdb4eddf 100644
--- a/dispel-gui/src/view/editor/spreadsheet/state.rs
+++ b/dispel-gui/src/view/editor/spreadsheet/state.rs
@@ -127,6 +127,9 @@ pub struct SpreadsheetState {
/// record, keyed by field name. Populated on `SelectRow`. Allows the
/// cursor / selection to survive re-renders.
pub inspector_textarea_contents: HashMap,
+ /// Search text of the composite item picker, keyed by field name. Kept per
+ /// field so switching rows does not lose an in-progress item search.
+ pub composite_item_filters: HashMap,
/// Process-wide cache of pre-shaped paragraphs. Shared by every cell
/// the table widget paints; cheap to clone (Arc).
@@ -165,6 +168,7 @@ impl Default for SpreadsheetState {
column_filter_options: Vec::new(),
column_filter_search: String::new(),
inspector_textarea_contents: HashMap::new(),
+ composite_item_filters: HashMap::new(),
paragraph_cache: ParagraphCache::default(),
}
}
diff --git a/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs b/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs
index 70f1633c..2bc78f5b 100644
--- a/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs
+++ b/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs
@@ -12,7 +12,7 @@ use crate::components::composite_item::composite_item_picker;
use crate::components::editable::{EditableRecord, FieldDescriptor, FieldKind};
use crate::components::generic_editor::GenericEditorState;
use crate::components::utils::horizontal_space;
-use crate::message::{Message, SystemMessage};
+use crate::message::Message;
use crate::style;
use crate::view::editor::spreadsheet::message::SpreadsheetMessage;
use crate::view::editor::spreadsheet::state::SpreadsheetState;
@@ -24,6 +24,7 @@ pub fn build_inspector_panel<'a, R: EditableRecord>(
editor: &'a GenericEditorState,
spreadsheet: &'a SpreadsheetState,
lookups: &'a HashMap>,
+ composite_filters: &'a HashMap,
field_changed_msg: fn(usize, String, String) -> Message,
spreadsheet_msg: fn(SpreadsheetMessage) -> Message,
) -> Element<'a, Message> {
@@ -59,6 +60,7 @@ pub fn build_inspector_panel<'a, R: EditableRecord>(
validation_error,
field_changed_msg,
&spreadsheet.inspector_textarea_contents,
+ composite_filters,
spreadsheet_msg,
));
}
@@ -89,6 +91,7 @@ pub(crate) fn build_inspector_field<'a>(
validation_error: Option,
field_changed_msg: fn(usize, String, String) -> Message,
textarea_contents: &'a HashMap,
+ composite_filters: &'a HashMap,
spreadsheet_msg: fn(SpreadsheetMessage) -> Message,
) -> Element<'a, Message> {
let label = text(descriptor.label).size(11).style(style::subtle_text);
@@ -161,13 +164,23 @@ pub(crate) 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();
+ let filter_name = descriptor.name.to_string();
+ let filter = composite_filters
+ .get(descriptor.name)
+ .map(String::as_str)
+ .unwrap_or("");
composite_item_picker(
descriptor.label,
&value,
entries,
false,
- "",
- |_| Message::System(SystemMessage::DismissError),
+ filter,
+ move |text| {
+ spreadsheet_msg(SpreadsheetMessage::CompositeItemFilterChanged(
+ filter_name.clone(),
+ text,
+ ))
+ },
move |v| {
spreadsheet_msg(SpreadsheetMessage::InspectorFieldChanged(
orig_idx,
@@ -214,6 +227,9 @@ mod tests {
use iced_test::selector::{Candidate, Target};
use iced_test::simulator;
+ static EMPTY_FILTERS: std::sync::LazyLock> =
+ std::sync::LazyLock::new(HashMap::new);
+
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),
@@ -269,6 +285,7 @@ mod tests {
None,
field_changed,
&contents,
+ &EMPTY_FILTERS,
spreadsheet_msg,
);
assert_eq!(
@@ -290,6 +307,7 @@ mod tests {
None,
field_changed,
&contents,
+ &EMPTY_FILTERS,
spreadsheet_msg,
);
assert_eq!(
@@ -336,6 +354,7 @@ mod tests {
None,
field_changed,
&contents,
+ &EMPTY_FILTERS,
spreadsheet_msg,
);
assert!(
@@ -382,6 +401,7 @@ mod tests {
None,
field_changed,
&contents,
+ &EMPTY_FILTERS,
spreadsheet_msg,
);
assert!(
@@ -415,6 +435,7 @@ mod tests {
None,
field_changed,
&contents,
+ &EMPTY_FILTERS,
spreadsheet_msg,
);
assert!(
@@ -430,6 +451,7 @@ mod tests {
None,
field_changed,
&contents,
+ &EMPTY_FILTERS,
spreadsheet_msg,
);
assert!(
@@ -445,6 +467,7 @@ mod tests {
None,
field_changed,
&contents,
+ &EMPTY_FILTERS,
field_changed_spreadsheet_msg,
);
let messages = crate::tests::common::activate_select_option(duplicate, 0, -1);
@@ -480,11 +503,16 @@ mod tests {
None,
field_changed,
&contents,
+ &EMPTY_FILTERS,
spreadsheet_msg,
);
let mut ui = simulator(element);
+ // Select by placeholder: a composite picker would render its search
+ // input first, and clicking that would not edit the field value.
let mut pick_input = |candidate: Candidate<'_>| match candidate {
- Candidate::TextInput { .. } => Some(Target::from(candidate)),
+ Candidate::TextInput { state, .. } if state.text().into_owned().is_empty() => {
+ Some(Target::from(candidate))
+ }
_ => None,
};
ui.click(&mut pick_input)
diff --git a/dispel-gui/src/view/editor/spreadsheet/view/mod.rs b/dispel-gui/src/view/editor/spreadsheet/view/mod.rs
index d36f6cdb..01fc6b45 100644
--- a/dispel-gui/src/view/editor/spreadsheet/view/mod.rs
+++ b/dispel-gui/src/view/editor/spreadsheet/view/mod.rs
@@ -73,6 +73,7 @@ pub fn view_spreadsheet<'a, R: EditableRecord>(
editor,
spreadsheet,
lookups,
+ &spreadsheet.composite_item_filters,
field_changed_msg,
spreadsheet_msg,
),
From 4b697d4de456ec0bb0c1f2d816aa6a28c0f87697 Mon Sep 17 00:00:00 2001
From: dimspell <141545384+dimspell@users.noreply.github.com>
Date: Thu, 26 Nov 2026 17:14:29 +0100
Subject: [PATCH 14/72] refactor(gui): use iced combo box for composite items
---
dispel-gui/src/components/composite_item.rs | 478 +++++++-----------
.../src/components/map_render/view_state.rs | 6 -
dispel-gui/src/components/standard/macros.rs | 1 +
.../src/editors/dialogue_paragraph/view.rs | 1 +
.../src/editors/dialogue_script/view.rs | 1 +
dispel-gui/src/editors/extra_ref/view.rs | 1 +
dispel-gui/src/editors/map_editor/message.rs | 3 -
.../src/editors/map_editor/update/mod.rs | 6 -
.../src/editors/map_editor/view/fields.rs | 65 +--
.../src/editors/map_editor/view/inspector.rs | 30 +-
dispel-gui/src/editors/map_editor/view/mod.rs | 9 +-
dispel-gui/src/editors/monster_ref/view.rs | 1 +
dispel-gui/src/editors/npc_ref/view.rs | 1 +
dispel-gui/src/editors/party_level_db/view.rs | 1 +
dispel-gui/src/state.rs | 4 +
dispel-gui/src/tests/common.rs | 78 ++-
dispel-gui/src/tests/select_boxes.rs | 321 ++++++------
dispel-gui/src/update/editor/common.rs | 3 -
dispel-gui/src/update/mod.rs | 6 +-
.../src/view/editor/spreadsheet/message.rs | 3 -
.../src/view/editor/spreadsheet/state.rs | 4 -
.../view/editor/spreadsheet/view/inspector.rs | 69 +--
.../src/view/editor/spreadsheet/view/mod.rs | 5 +-
23 files changed, 491 insertions(+), 606 deletions(-)
diff --git a/dispel-gui/src/components/composite_item.rs b/dispel-gui/src/components/composite_item.rs
index 82348483..f4f9c8ed 100644
--- a/dispel-gui/src/components/composite_item.rs
+++ b/dispel-gui/src/components/composite_item.rs
@@ -1,9 +1,11 @@
-use std::rc::Rc;
+use std::collections::hash_map::DefaultHasher;
+use std::fmt;
+use std::hash::Hasher;
-use iced::widget::{column as col, pick_list, row, text, text_input};
+use iced::widget::combo_box::{self, ComboBox};
+use iced::widget::{row, text, text_input};
use iced::{Element, Length};
-use crate::components::select::lookup_select;
use crate::message::Message;
use crate::style;
@@ -11,6 +13,73 @@ const LABEL_W: f32 = 140.0;
/// The empty-slot option shared with the item catalog.
const NO_ITEM_KEY: &str = "255:15";
+const NO_ITEM_LABEL: &str = "[-]";
+
+/// One item in the shared composite item catalog.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ItemOption {
+ pub key: String,
+ pub label: String,
+}
+
+impl fmt::Display for ItemOption {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(&self.label)
+ }
+}
+
+/// A single app-level option list shared by every composite item field.
+#[derive(Default)]
+pub struct CompositeItemOptions {
+ pub state: combo_box::State,
+ pub fingerprint: u64,
+}
+
+fn fingerprint_options(entries: Option<&[(String, String)]>) -> u64 {
+ let mut hasher = DefaultHasher::new();
+ hasher.write_u8(u8::from(entries.is_some()));
+ if let Some(entries) = entries {
+ for (key, label) in entries {
+ hasher.write(key.as_bytes());
+ hasher.write_u8(0);
+ hasher.write(label.as_bytes());
+ hasher.write_u8(1);
+ }
+ }
+ hasher.finish()
+}
+
+/// Rebuild the shared option list whenever the `"items"` lookup changes.
+pub fn refresh_composite_item_options(state: &mut crate::state::AppState) {
+ let entries = state.lookups.get("items").map(Vec::as_slice);
+ let fingerprint = fingerprint_options(entries);
+ if fingerprint == state.composite_item_options.fingerprint {
+ return;
+ }
+
+ let options = match entries {
+ Some(entries) => {
+ let mut options: Vec = entries
+ .iter()
+ .map(|(key, label)| ItemOption {
+ key: key.clone(),
+ label: label.clone(),
+ })
+ .collect();
+ if !options.iter().any(|option| option.key == NO_ITEM_KEY) {
+ options.push(ItemOption {
+ key: NO_ITEM_KEY.to_string(),
+ label: NO_ITEM_LABEL.to_string(),
+ });
+ }
+ options
+ }
+ None => Vec::new(),
+ };
+
+ state.composite_item_options.state = combo_box::State::new(options);
+ state.composite_item_options.fingerprint = fingerprint;
+}
/// Render a picker body, optionally prefixed with a fixed-width label column.
///
@@ -39,149 +108,100 @@ fn with_optional_label<'a>(
/// Build a searchable item picker for `CompositeItem` fields.
///
-/// All item files share one select: every entry carries its type in the
-/// display label (`[Weapon] Cap`, `[Healing] Herb`, …). A text input above the
-/// select filters those labels and composite keys. Falls back to a plain
-/// `text_input` when `entries` is `None` (lookups unavailable). `show_label`
-/// controls whether the label column is drawn by this component or the caller.
-pub fn composite_item_picker(
+/// Every item file shares the one app-level option list, so all fields get the
+/// same built-in fuzzy search. Falls back to a plain `text_input` before the
+/// item catalog has been loaded. `show_label` controls whether the label
+/// column is drawn by this component or the caller.
+pub fn composite_item_picker<'a>(
label: &'static str,
value: &str,
- entries: Option<&[(String, String)]>,
+ combo_state: &'a combo_box::State,
show_label: bool,
- filter: &str,
- on_filter: impl Fn(String) -> Message + 'static,
- on_change: impl Fn(String) -> Message + 'static,
-) -> Element<'static, Message> {
- let filter = filter.to_owned();
- let on_filter: Rc Message> = Rc::new(on_filter);
- let on_change: Rc Message> = Rc::new(on_change);
-
- let search_input: Element<'static, Message> = {
- let of = on_filter.clone();
- text_input("Search items...", filter.clone())
- .on_input(move |v| of(v))
- .padding(4)
- .size(11)
- .width(Length::Fill)
- .into()
- };
-
- let Some(entries) = entries else {
- let oc = on_change;
- let input: Element<'static, Message> = text_input("", value.to_owned())
- .on_input(move |v| oc(v))
+ on_change: impl Fn(String) -> Message + 'a,
+) -> Element<'a, Message> {
+ // Without lookups there is nothing to search: keep the raw key editable.
+ if combo_state.options().is_empty() {
+ let input: Element<'a, Message> = text_input("", value.to_owned())
+ .on_input(on_change)
.padding(4)
.size(11)
.width(Length::Fill)
.into();
- let body: Element<'static, Message> = col![search_input, input].spacing(4).into();
- return with_optional_label(label, body, show_label);
- };
-
- // One option per item file. Every key with the no-item byte denotes the
- // same empty slot, so only the canonical sentinel survives.
- let mut collapsed: Vec<(String, String)> = Vec::with_capacity(entries.len());
- for (key, display) in entries {
- if key.starts_with("255:") {
- if key == NO_ITEM_KEY && !collapsed.iter().any(|(k, _)| k == key) {
- collapsed.push((key.clone(), display.clone()));
- }
- } else {
- collapsed.push((key.clone(), display.clone()));
- }
- }
- if !collapsed.iter().any(|(key, _)| key == NO_ITEM_KEY) {
- collapsed.push((NO_ITEM_KEY.to_string(), "[-]".to_string()));
+ return with_optional_label(label, input, show_label);
}
- let is_no_item = value.starts_with("255:");
- let query = filter.to_lowercase();
- let mut filtered_entries: Vec<(String, String)> = collapsed
+ // ComboBox copies the selection into a String, so a locally-built option
+ // is enough. Only the label must match; the closure owns the exact key.
+ let selected = combo_state
+ .options()
.iter()
- .filter(|(key, display)| {
- display.to_lowercase().contains(&query) || key.to_lowercase().contains(&query)
- })
+ .find(|option| option.key == value)
.cloned()
- .collect();
-
- // The current value must never vanish from the select while the user
- // types. A no-item value also keeps the sentinel that stands in for it.
- let mut required: Vec<&str> = vec![value];
- if is_no_item {
- required.push(NO_ITEM_KEY);
- }
- for key in required {
- if !filtered_entries.iter().any(|(k, _)| k == key)
- && let Some(entry) = collapsed.iter().find(|(k, _)| k == key)
- {
- filtered_entries.push(entry.clone());
- }
- }
-
- // A non-canonical stored key (e.g. `255:255`) still renders as the shared
- // empty-slot option, but re-selecting that option must emit the exact key
- // so `InventoryItem::is_empty()` keeps working.
- let effective_selected_id = if is_no_item { NO_ITEM_KEY } else { value };
- let mut select = lookup_select(&filtered_entries, effective_selected_id);
- if is_no_item && value != NO_ITEM_KEY {
- for id in select.label_to_id.values_mut() {
- if id == NO_ITEM_KEY {
- *id = value.to_string();
- }
- }
- }
-
- let picker: Element<'static, Message> = {
- let ids = select.label_to_id;
- let fallback_key = value.to_owned();
- pick_list(select.selected, select.options, String::clone)
- .on_select(move |selected_name| {
- let key = ids
- .get(&selected_name)
- .cloned()
- .unwrap_or_else(|| fallback_key.clone());
- on_change(key)
- })
- .width(Length::Fill)
- .into()
- };
-
- let body: Element<'static, Message> = col![search_input, picker].spacing(4).into();
- with_optional_label(label, body, show_label)
+ .unwrap_or_else(|| ItemOption {
+ key: value.to_owned(),
+ label: if value.starts_with("255:") {
+ NO_ITEM_LABEL.to_string()
+ } else {
+ format!("Unknown ({value})")
+ },
+ });
+
+ // A non-canonical stored key (e.g. `255:255`) renders as the shared empty
+ // slot. Re-selecting that option must still emit the exact stored key so
+ // `InventoryItem::is_empty()` keeps working.
+ let stored_key = value.to_owned();
+ let picker: Element<'a, Message> = ComboBox::new(
+ combo_state,
+ "Search items...",
+ Some(&selected),
+ move |option: ItemOption| {
+ let key = if option.key == NO_ITEM_KEY && stored_key.starts_with("255:") {
+ stored_key.clone()
+ } else {
+ option.key
+ };
+ on_change(key)
+ },
+ )
+ .padding(4)
+ .size(11)
+ .width(Length::Fill)
+ .menu_height(240.0)
+ .into();
+
+ with_optional_label(label, picker, show_label)
}
#[cfg(all(test, feature = "iced_test"))]
mod tests {
use super::*;
use crate::editors::weapon::WeaponEditorMessage;
- use crate::message::{EditorMessage, FileTreeMessage};
- use dispel_core::ItemTypeId;
+ use crate::message::EditorMessage;
use iced_test::selector::{Candidate, Target};
use iced_test::simulator;
- fn picker(
- value: &str,
- entries: Option<&[(String, String)]>,
- filter: &str,
- ) -> Element<'static, Message> {
- composite_item_picker(
- "Invented Item",
- value,
- entries,
- false,
- filter,
- |v| Message::FileTree(FileTreeMessage::Search(v)),
- |v| {
- Message::Editor(EditorMessage::Weapon(WeaponEditorMessage::FieldChanged(
- 0,
- "item".to_string(),
- v,
- )))
- },
+ fn options(entries: &[(&str, &str)]) -> combo_box::State {
+ combo_box::State::new(
+ entries
+ .iter()
+ .map(|(key, label)| ItemOption {
+ key: (*key).to_string(),
+ label: (*label).to_string(),
+ })
+ .collect(),
)
}
+ fn picker<'a>(value: &str, state: &'a combo_box::State) -> Element<'a, Message> {
+ composite_item_picker("Invented Item", value, state, false, |v| {
+ Message::Editor(EditorMessage::Weapon(WeaponEditorMessage::FieldChanged(
+ 0,
+ "item".to_string(),
+ v,
+ )))
+ })
+ }
+
fn emitted_keys(messages: Vec) -> Vec {
messages
.into_iter()
@@ -196,199 +216,75 @@ mod tests {
.collect()
}
- /// Type into the search box and feed the emitted query back into a fresh
- /// render, the way the real caller stores it in state.
- fn typed_filter(element: Element<'static, Message>, query: &str) -> String {
- let mut ui = simulator(element);
- let mut search = |candidate: Candidate<'_>| match candidate {
- Candidate::TextInput { state, .. }
- if state.text().into_owned() == "Search items..." =>
- {
- Some(Target::from(candidate))
- }
- _ => None,
- };
- ui.click(&mut search)
- .expect("search input must be rendered");
- ui.typewrite(query);
- ui.into_messages()
- .filter_map(|m| match m {
- Message::FileTree(FileTreeMessage::Search(v)) => Some(v),
- _ => None,
- })
- .last()
- .expect("search input must emit its query")
- }
-
fn select_option(
value: &str,
- entries: &[(String, String)],
- filter: &str,
+ state: &combo_box::State,
offset: isize,
) -> Vec {
emitted_keys(crate::tests::common::activate_select_option(
- picker(value, Some(entries), filter),
+ picker(value, state),
0,
offset,
))
}
- fn label_rendered(entries: Option<&[(String, String)]>, show_label: bool) -> bool {
- let element: Element<'_, Message> = composite_item_picker(
+ fn label_rendered(state: Option<&combo_box::State>, show_label: bool) -> bool {
+ let empty = options(&[]);
+ let state = state.unwrap_or(&empty);
+ let mut ui = simulator(composite_item_picker(
"Invented Item",
"1:0",
- entries,
+ state,
show_label,
- "",
- |_| Message::FileTree(FileTreeMessage::Search(String::new())),
- |_| Message::FileTree(FileTreeMessage::Search(String::new())),
- );
- let mut ui = simulator(element);
+ |_| {
+ Message::Editor(EditorMessage::Weapon(WeaponEditorMessage::FieldChanged(
+ 0,
+ "item".to_string(),
+ String::new(),
+ )))
+ },
+ ));
ui.find("Invented Item").is_ok()
}
#[test]
- fn test_unmapped_composite_keys_render_a_label_and_keep_value() {
- let entries = [
- ("1:0".to_string(), "[Weapon] Invented Sword".to_string()),
- ("255:15".to_string(), "[-]".to_string()),
- ];
-
- for value in ["255:0", "255:255"] {
- let values = crate::tests::common::select_values(picker(value, Some(&entries), ""));
- assert!(
- values.iter().any(|v| v == "[-]"),
- "{value} must resolve to the no-item sentinel label, got {values:?}"
- );
- }
-
- let values = crate::tests::common::select_values(picker("1:999", Some(&entries), ""));
- assert!(
- values.iter().any(|v| v == "Unknown (1:999)"),
- "an unmapped composite key must render a visible fallback label, got {values:?}"
- );
-
- let keys = select_option("255:0", &entries, "", 0);
- assert_eq!(
- keys,
- vec!["255:0"],
- "choosing the sentinel must keep the exact stored key"
- );
- }
-
- #[test]
- fn test_one_select_offers_items_from_every_type() {
- let entries = [
- ("1:0".to_string(), "[Weapon] Invented Sword".to_string()),
- ("2:7".to_string(), "[Healing] Invented Herb".to_string()),
- ("3:2".to_string(), "[Edit] Invented Charm".to_string()),
- ("255:15".to_string(), "[-]".to_string()),
- ];
- let values = crate::tests::common::select_values(picker("1:0", Some(&entries), ""));
- assert_eq!(
- values.len(),
- 1,
- "there must be exactly one select, got {values:?}"
- );
-
- assert_eq!(select_option("1:0", &entries, "", 1), vec!["2:7"]);
- assert_eq!(select_option("1:0", &entries, "", 2), vec!["3:2"]);
- assert_eq!(select_option("1:0", &entries, "", 3), vec!["255:15"]);
- }
-
- #[test]
- fn test_search_narrows_options_and_keeps_selection_visible() {
- let entries = [
- ("1:0".to_string(), "[Weapon] Invented Sword".to_string()),
- ("2:7".to_string(), "[Healing] Invented Herb".to_string()),
- ("3:2".to_string(), "[Edit] Invented Charm".to_string()),
- ("255:15".to_string(), "[-]".to_string()),
- ];
- let query = typed_filter(picker("1:0", Some(&entries), ""), "herb");
- assert_eq!(query, "herb");
-
- let values = crate::tests::common::select_values(picker("1:0", Some(&entries), &query));
- assert!(
- values.iter().any(|v| v == "[Weapon] Invented Sword"),
- "the current item must stay selected while filtering, got {values:?}"
- );
-
- assert_eq!(
- select_option("1:0", &entries, &query, -1),
- vec!["2:7"],
- "the only other option must be the matching item"
- );
- let reachable: std::collections::HashSet = (-3..=3)
- .flat_map(|offset| select_option("1:0", &entries, "charm", offset))
- .collect();
- assert_eq!(
- reachable,
- std::collections::HashSet::from(["1:0".to_string(), "3:2".to_string()]),
- "non-matching items must be absent from the narrowed list"
- );
-
- // Filtering by the composite key works just like filtering by label.
- let query = typed_filter(picker("1:0", Some(&entries), ""), "3:2");
- assert_eq!(select_option("1:0", &entries, &query, -1), vec!["3:2"]);
- }
-
- #[test]
- fn test_selected_label_emits_its_exact_composite_key() {
- let entries = [
- ("1:0".to_string(), "[Weapon] Invented Sword".to_string()),
- ("2:7".to_string(), "[Healing] Invented Herb".to_string()),
- ("255:15".to_string(), "[-]".to_string()),
- ];
- assert_eq!(select_option("2:7", &entries, "", 0), vec!["2:7"]);
- assert_eq!(select_option("2:7", &entries, "", -1), vec!["1:0"]);
+ fn test_selected_option_emits_its_composite_key() {
+ let state = options(&[
+ ("1:0", "[Weapon] Invented Sword"),
+ ("2:7", "[Healing] Invented Herb"),
+ ("255:15", NO_ITEM_LABEL),
+ ]);
+ assert_eq!(select_option("1:0", &state, 1), vec!["2:7"]);
}
#[test]
- fn test_no_item_selection_preserves_exact_key() {
- use dispel_core::InventoryItem;
-
- let entries = [
- ("1:0".to_string(), "[Weapon] Invented Sword".to_string()),
- ("255:15".to_string(), "[-]".to_string()),
- ];
-
- for value in ["255:255", "255:5"] {
- assert_eq!(select_option(value, &entries, "", 0), vec![value]);
- }
- assert_eq!(select_option("255:15", &entries, "", 0), vec!["255:15"]);
-
- // Filtering out "[-]" must not hide the empty slot either.
- assert_eq!(
- select_option("255:255", &entries, "sword", 0),
- vec!["255:255"]
- );
-
- let item = InventoryItem::new(ItemTypeId::NoItem, 255);
- assert!(
- item.is_empty(),
- "255:255 must decode to an empty inventory item"
- );
+ fn test_non_canonical_no_item_key_is_preserved() {
+ let state = options(&[
+ ("1:0", "[Weapon] Invented Sword"),
+ ("255:15", NO_ITEM_LABEL),
+ ]);
+ assert_eq!(select_option("255:255", &state, -1), vec!["255:255"]);
}
#[test]
- fn test_duplicate_display_names_stay_distinguishable() {
- let entries = [
- ("1:4".to_string(), "Invented Blade".to_string()),
- ("2:4".to_string(), "Invented Blade".to_string()),
- ("255:15".to_string(), "[-]".to_string()),
- ];
- let values = crate::tests::common::select_values(picker("2:4", Some(&entries), ""));
- assert!(
- values.iter().any(|v| v == "Invented Blade (2:4)"),
- "duplicate labels must be qualified with their composite key, got {values:?}"
- );
- assert_eq!(select_option("2:4", &entries, "", -1), vec!["1:4"]);
- assert_eq!(select_option("2:4", &entries, "", 0), vec!["2:4"]);
+ fn test_fallback_text_input_edits_the_raw_value() {
+ let state = options(&[]);
+ let mut ui = simulator(picker("255:255", &state));
+ let mut input = |candidate: Candidate<'_>| match candidate {
+ Candidate::TextInput { state, .. } if state.text().into_owned() == "255:255" => {
+ Some(Target::from(candidate))
+ }
+ _ => None,
+ };
+ ui.click(&mut input)
+ .expect("raw value input must be rendered");
+ ui.typewrite("5");
+ assert_eq!(emitted_keys(ui.into_messages().collect()), vec!["255:2555"]);
}
#[test]
fn test_composite_picker_label_follows_show_label() {
- let entries = [("1:0".to_string(), "[Weapon] Invented Sword".to_string())];
+ let state = options(&[("1:0", "[Weapon] Invented Sword")]);
for show_label in [true, false] {
assert_eq!(
label_rendered(None, show_label),
@@ -396,9 +292,9 @@ mod tests {
"fallback picker label must follow show_label"
);
assert_eq!(
- label_rendered(Some(&entries), show_label),
+ label_rendered(Some(&state), show_label),
show_label,
- "lookup picker label must follow show_label"
+ "combo box label must follow show_label"
);
}
}
diff --git a/dispel-gui/src/components/map_render/view_state.rs b/dispel-gui/src/components/map_render/view_state.rs
index c9037b37..084f80bc 100644
--- a/dispel-gui/src/components/map_render/view_state.rs
+++ b/dispel-gui/src/components/map_render/view_state.rs
@@ -1,5 +1,3 @@
-use std::collections::HashMap;
-
use crate::editors::map_editor::message::{MapTool, MapViewMode, ObjectBrushMode, SelectedEntity};
use iced::widget::canvas;
@@ -55,9 +53,6 @@ pub struct MapViewState {
pub selected_sprite_sequence: Option,
/// Currently selected entity in the inspector panel.
pub selected_entity: Option,
- /// Search text of the composite item picker, keyed by field name. Each map
- /// editor is per-tab, so the field name alone identifies the input.
- pub composite_item_filters: HashMap,
/// Cached tile-layer frame. Clear whenever pan, zoom, tiles, or entity
/// sprites change. Avoids redrawing the expensive tile layer on every
/// cursor-move event (which only affects the overlay canvas).
@@ -101,7 +96,6 @@ impl Default for MapViewState {
layers_popover_open: false,
selected_sprite_sequence: None,
selected_entity: None,
- composite_item_filters: HashMap::new(),
tile_layer_cache: canvas::Cache::new(),
overlay_cache: canvas::Cache::new(),
}
diff --git a/dispel-gui/src/components/standard/macros.rs b/dispel-gui/src/components/standard/macros.rs
index bf64da7a..7b8fc5ea 100644
--- a/dispel-gui/src/components/standard/macros.rs
+++ b/dispel-gui/src/components/standard/macros.rs
@@ -35,6 +35,7 @@ macro_rules! define_standard_view {
},
|msg| $crate::message::Message::$name(<$Msg>::Spreadsheet(msg)),
&app.state.lookups,
+ &app.state.composite_item_options.state,
|event| $crate::message::Message::$name(<$Msg>::PaneResized(event)),
|pane| $crate::message::Message::$name(<$Msg>::PaneClicked(pane)),
None,
diff --git a/dispel-gui/src/editors/dialogue_paragraph/view.rs b/dispel-gui/src/editors/dialogue_paragraph/view.rs
index 63a6067f..bf2d1c62 100644
--- a/dispel-gui/src/editors/dialogue_paragraph/view.rs
+++ b/dispel-gui/src/editors/dialogue_paragraph/view.rs
@@ -50,6 +50,7 @@ pub fn view(app: &App) -> Element<'_, Message> {
},
|msg| Message::dialogue_paragraph(DialogueParagraphEditorMessage::Spreadsheet(msg)),
&app.state.lookups,
+ &app.state.composite_item_options.state,
|event| Message::dialogue_paragraph(DialogueParagraphEditorMessage::PaneResized(event)),
|pane| Message::dialogue_paragraph(DialogueParagraphEditorMessage::PaneClicked(pane)),
None,
diff --git a/dispel-gui/src/editors/dialogue_script/view.rs b/dispel-gui/src/editors/dialogue_script/view.rs
index 2218ef5e..c7e6b9d4 100644
--- a/dispel-gui/src/editors/dialogue_script/view.rs
+++ b/dispel-gui/src/editors/dialogue_script/view.rs
@@ -46,6 +46,7 @@ pub fn view(app: &App) -> Element<'_, Message> {
},
|msg| Message::dialogue_script(DialogueScriptEditorMessage::Spreadsheet(msg)),
&app.state.lookups,
+ &app.state.composite_item_options.state,
|event| Message::dialogue_script(DialogueScriptEditorMessage::PaneResized(event)),
|pane| Message::dialogue_script(DialogueScriptEditorMessage::PaneClicked(pane)),
None,
diff --git a/dispel-gui/src/editors/extra_ref/view.rs b/dispel-gui/src/editors/extra_ref/view.rs
index a69dd482..22055183 100644
--- a/dispel-gui/src/editors/extra_ref/view.rs
+++ b/dispel-gui/src/editors/extra_ref/view.rs
@@ -36,6 +36,7 @@ pub fn view(app: &App) -> Element<'_, Message> {
|idx, field, val| Message::extra_ref(ExtraRefEditorMessage::FieldChanged(idx, field, val)),
|msg| Message::extra_ref(ExtraRefEditorMessage::Spreadsheet(msg)),
&app.state.lookups,
+ &app.state.composite_item_options.state,
|event| Message::extra_ref(ExtraRefEditorMessage::PaneResized(event)),
|pane| Message::extra_ref(ExtraRefEditorMessage::PaneClicked(pane)),
Some(Message::extra_ref(ExtraRefEditorMessage::AddEntry)),
diff --git a/dispel-gui/src/editors/map_editor/message.rs b/dispel-gui/src/editors/map_editor/message.rs
index d3b903fa..709a4395 100644
--- a/dispel-gui/src/editors/map_editor/message.rs
+++ b/dispel-gui/src/editors/map_editor/message.rs
@@ -125,9 +125,6 @@ pub enum MapEditorMessage {
Deselect(usize),
/// Entity field edited in the inspector.
EntityFieldChanged(usize, SelectedEntity, String, String),
- /// Search text typed into a composite item picker. State-only: the record
- /// is untouched, so no cache refresh or history entry is needed.
- CompositeItemFilterChanged(usize, String, String),
/// Save all modified entity .ref files.
SaveEntities(usize),
/// Async save completed. Ok carries a status message; Err the error text.
diff --git a/dispel-gui/src/editors/map_editor/update/mod.rs b/dispel-gui/src/editors/map_editor/update/mod.rs
index 41b97ced..f37dc2ca 100644
--- a/dispel-gui/src/editors/map_editor/update/mod.rs
+++ b/dispel-gui/src/editors/map_editor/update/mod.rs
@@ -23,12 +23,6 @@ pub fn handle(message: MapEditorMessage, app: &mut App) -> Task {
MapEditorMessage::EntityFieldChanged(tab_id, entity, field, value) => {
entity::field_changed(app, tab_id, entity, field, value)
}
- MapEditorMessage::CompositeItemFilterChanged(tab_id, field, query) => {
- if let Some(editor) = app.state.editors.map_editors.get_mut(&tab_id) {
- editor.view.composite_item_filters.insert(field, query);
- }
- Task::none()
- }
MapEditorMessage::Undo(tab_id) => entity::undo(app, tab_id),
MapEditorMessage::Redo(tab_id) => entity::redo(app, tab_id),
MapEditorMessage::SaveEntities(tab_id) => persistence::save_entities(app, tab_id),
diff --git a/dispel-gui/src/editors/map_editor/view/fields.rs b/dispel-gui/src/editors/map_editor/view/fields.rs
index 06517ced..3b205ac9 100644
--- a/dispel-gui/src/editors/map_editor/view/fields.rs
+++ b/dispel-gui/src/editors/map_editor/view/fields.rs
@@ -1,10 +1,10 @@
use std::collections::HashMap;
-use crate::components::composite_item::composite_item_picker;
+use crate::components::composite_item::{ItemOption, composite_item_picker};
use crate::components::editable::{EditableRecord, FieldKind};
use crate::message::{Message, MessageExt};
use crate::style;
-use iced::widget::{column, pick_list, row, scrollable, text, text_input};
+use iced::widget::{column, combo_box, pick_list, row, scrollable, text, text_input};
use iced::{Element, Fill};
use super::super::message::{MapEditorMessage, SelectedEntity};
@@ -18,7 +18,7 @@ pub fn build_record_fields<'a, R: EditableRecord>(
tab_id: usize,
sel: SelectedEntity,
lookups: &'a HashMap>,
- composite_filters: &'a HashMap,
+ combo_state: &'a combo_box::State,
) -> Element<'a, Message> {
let mut col = column![].spacing(5);
@@ -32,7 +32,7 @@ pub fn build_record_fields<'a, R: EditableRecord>(
tab_id,
sel,
lookups,
- composite_filters,
+ combo_state,
));
}
scrollable(col).spacing(6).into()
@@ -52,7 +52,7 @@ pub fn inspector_field_row<'a>(
tab_id: usize,
sel: SelectedEntity,
lookups: &'a HashMap>,
- composite_filters: &'a HashMap,
+ combo_state: &'a combo_box::State,
) -> Element<'a, Message> {
const LABEL_W: f32 = 140.0;
match kind {
@@ -159,34 +159,15 @@ pub fn inspector_field_row<'a>(
.into()
}
- FieldKind::CompositeItem { lookup_key } => {
- let entries = lookups.get(*lookup_key).map(|v| v.as_slice());
- let filter = composite_filters
- .get(name)
- .map(String::as_str)
- .unwrap_or("");
- composite_item_picker(
- label,
- value,
- entries,
- true,
- filter,
- move |text| {
- Message::map_editor(MapEditorMessage::CompositeItemFilterChanged(
- tab_id,
- name.to_string(),
- text,
- ))
- },
- move |v| {
- Message::map_editor(MapEditorMessage::EntityFieldChanged(
- tab_id,
- sel,
- name.to_string(),
- v,
- ))
- },
- )
+ FieldKind::CompositeItem { lookup_key: _ } => {
+ composite_item_picker(label, value, combo_state, true, move |v| {
+ Message::map_editor(MapEditorMessage::EntityFieldChanged(
+ tab_id,
+ sel,
+ name.to_string(),
+ v,
+ ))
+ })
}
}
}
@@ -197,8 +178,8 @@ mod tests {
use iced_test::selector::{Candidate, Target};
use iced_test::simulator;
- static EMPTY_FILTERS: std::sync::LazyLock> =
- std::sync::LazyLock::new(HashMap::new);
+ static EMPTY_COMBO: std::sync::LazyLock> =
+ std::sync::LazyLock::new(|| combo_box::State::new(Vec::new()));
fn count_label_text(element: Element<'_, Message>, label: &str) -> usize {
let mut ui = simulator(element);
@@ -244,7 +225,7 @@ mod tests {
0,
SelectedEntity::Npc(0),
&lookups,
- &EMPTY_FILTERS,
+ &EMPTY_COMBO,
);
assert!(
crate::tests::common::select_shows(element, "Left"),
@@ -278,7 +259,7 @@ mod tests {
0,
SelectedEntity::DrawItem(0),
&lookups,
- &EMPTY_FILTERS,
+ &EMPTY_COMBO,
);
assert!(
crate::tests::common::select_shows(unknown, "Bogus"),
@@ -293,7 +274,7 @@ mod tests {
0,
SelectedEntity::DrawItem(0),
&lookups,
- &EMPTY_FILTERS,
+ &EMPTY_COMBO,
);
assert!(
crate::tests::common::select_shows(known, "Beta"),
@@ -320,7 +301,7 @@ mod tests {
0,
SelectedEntity::Monster(0),
&lookups,
- &EMPTY_FILTERS,
+ &EMPTY_COMBO,
);
assert!(
crate::tests::common::select_shows(missing, "Unknown (99)"),
@@ -335,7 +316,7 @@ mod tests {
0,
SelectedEntity::Monster(0),
&lookups,
- &EMPTY_FILTERS,
+ &EMPTY_COMBO,
);
assert!(
crate::tests::common::select_shows(duplicate, "Invented Creature (9)"),
@@ -350,7 +331,7 @@ mod tests {
0,
SelectedEntity::Monster(0),
&lookups,
- &EMPTY_FILTERS,
+ &EMPTY_COMBO,
);
let messages = crate::tests::common::activate_select_option(duplicate, 0, -1);
let emitted: Vec = messages
@@ -382,7 +363,7 @@ mod tests {
0,
SelectedEntity::DrawItem(0),
&lookups,
- &EMPTY_FILTERS,
+ &EMPTY_COMBO,
);
assert_eq!(
count_label_text(element, "Invented Item:"),
diff --git a/dispel-gui/src/editors/map_editor/view/inspector.rs b/dispel-gui/src/editors/map_editor/view/inspector.rs
index a4f35b09..de32b47c 100644
--- a/dispel-gui/src/editors/map_editor/view/inspector.rs
+++ b/dispel-gui/src/editors/map_editor/view/inspector.rs
@@ -1,11 +1,12 @@
use std::collections::HashMap;
+use crate::components::composite_item::ItemOption;
use crate::components::editable::EditableRecord;
use crate::components::utils::{horizontal_rule, horizontal_space};
use crate::message::{Message, MessageExt};
use crate::style;
use dispel_core::{DrawItem, ExtraRef, MonsterRef, NPC};
-use iced::widget::{button, column, container, row, scrollable, text, text_input};
+use iced::widget::{button, column, combo_box, container, row, scrollable, text, text_input};
use iced::{Element, Fill, Font};
use super::super::message::{MapEditorMessage, SelectedEntity};
@@ -18,19 +19,14 @@ pub fn build_inspector<'a>(
tab_id: usize,
sel: SelectedEntity,
lookups: &'a HashMap>,
+ combo_state: &'a combo_box::State,
) -> Element<'a, Message> {
let close_msg = Message::map_editor(MapEditorMessage::Deselect(tab_id));
let (title, width, body): (&'static str, f32, Element<'a, Message>) = match sel {
SelectedEntity::Monster(i) => {
let body = if let Some(record) = state.data.monsters.get(i) {
- fields::build_record_fields::(
- record,
- tab_id,
- sel,
- lookups,
- &state.view.composite_item_filters,
- )
+ fields::build_record_fields::(record, tab_id, sel, lookups, combo_state)
} else {
text("Monster not found").size(12).into()
};
@@ -49,7 +45,7 @@ pub fn build_inspector<'a>(
tab_id,
sel,
lookups,
- &state.view.composite_item_filters,
+ combo_state,
));
}
column(els).spacing(6).into()
@@ -60,13 +56,7 @@ pub fn build_inspector<'a>(
}
SelectedEntity::Extra(i) => {
let body = if let Some(record) = state.data.extra_refs.get(i) {
- fields::build_record_fields::(
- record,
- tab_id,
- sel,
- lookups,
- &state.view.composite_item_filters,
- )
+ fields::build_record_fields::(record, tab_id, sel, lookups, combo_state)
} else {
text("Object not found").size(12).into()
};
@@ -74,13 +64,7 @@ pub fn build_inspector<'a>(
}
SelectedEntity::DrawItem(i) => {
let body = if let Some(record) = state.data.draw_items.get(i) {
- fields::build_record_fields::(
- record,
- tab_id,
- sel,
- lookups,
- &state.view.composite_item_filters,
- )
+ fields::build_record_fields::(record, tab_id, sel, lookups, combo_state)
} else {
text("Draw item not found").size(12).into()
};
diff --git a/dispel-gui/src/editors/map_editor/view/mod.rs b/dispel-gui/src/editors/map_editor/view/mod.rs
index 33471925..2651d4de 100644
--- a/dispel-gui/src/editors/map_editor/view/mod.rs
+++ b/dispel-gui/src/editors/map_editor/view/mod.rs
@@ -557,8 +557,13 @@ pub fn view(app: &App) -> Element<'_, Message> {
let body: Element<'_, Message> = match state.view.view_mode {
MapViewMode::Map => match state.view.selected_entity {
Some(sel) => {
- let inspector =
- inspector::build_inspector(state, tab_id, sel, &app.state.lookups);
+ let inspector = inspector::build_inspector(
+ state,
+ tab_id,
+ sel,
+ &app.state.lookups,
+ &app.state.composite_item_options.state,
+ );
row![canvas_with_overlay, inspector]
.width(Fill)
.height(Fill)
diff --git a/dispel-gui/src/editors/monster_ref/view.rs b/dispel-gui/src/editors/monster_ref/view.rs
index a1e7a877..26741557 100644
--- a/dispel-gui/src/editors/monster_ref/view.rs
+++ b/dispel-gui/src/editors/monster_ref/view.rs
@@ -42,6 +42,7 @@ pub fn view(app: &App) -> Element<'_, Message> {
},
|msg| Message::monster_ref(MonsterRefEditorMessage::Spreadsheet(msg)),
&app.state.lookups,
+ &app.state.composite_item_options.state,
|event| Message::monster_ref(MonsterRefEditorMessage::PaneResized(event)),
|pane| Message::monster_ref(MonsterRefEditorMessage::PaneClicked(pane)),
Some(Message::monster_ref(MonsterRefEditorMessage::AddEntry)),
diff --git a/dispel-gui/src/editors/npc_ref/view.rs b/dispel-gui/src/editors/npc_ref/view.rs
index ec9102ff..158ea24b 100644
--- a/dispel-gui/src/editors/npc_ref/view.rs
+++ b/dispel-gui/src/editors/npc_ref/view.rs
@@ -36,6 +36,7 @@ pub fn view(app: &App) -> Element<'_, Message> {
|idx, field, val| Message::npc_ref(NpcRefEditorMessage::FieldChanged(idx, field, val)),
|msg| Message::npc_ref(NpcRefEditorMessage::Spreadsheet(msg)),
&app.state.lookups,
+ &app.state.composite_item_options.state,
|event| Message::npc_ref(NpcRefEditorMessage::PaneResized(event)),
|pane| Message::npc_ref(NpcRefEditorMessage::PaneClicked(pane)),
Some(Message::npc_ref(NpcRefEditorMessage::AddEntry)),
diff --git a/dispel-gui/src/editors/party_level_db/view.rs b/dispel-gui/src/editors/party_level_db/view.rs
index 4f5bd81f..6024bb08 100644
--- a/dispel-gui/src/editors/party_level_db/view.rs
+++ b/dispel-gui/src/editors/party_level_db/view.rs
@@ -57,6 +57,7 @@ pub fn view(app: &App) -> Element<'_, Message> {
},
|msg| Message::party_level_db(PartyLevelDbEditorMessage::Spreadsheet(msg)),
&app.state.lookups,
+ &app.state.composite_item_options.state,
|msg| Message::party_level_db(PartyLevelDbEditorMessage::PaneResized(msg)),
|pane| Message::party_level_db(PartyLevelDbEditorMessage::PaneClicked(pane)),
None,
diff --git a/dispel-gui/src/state.rs b/dispel-gui/src/state.rs
index ce2ea82d..3c24a91b 100644
--- a/dispel-gui/src/state.rs
+++ b/dispel-gui/src/state.rs
@@ -1,3 +1,4 @@
+use crate::components::composite_item::CompositeItemOptions;
use crate::editor_registry::EditorRegistry;
use crate::indexation::file_index_cache::{FileIndexCache, FileIndexCacheManager};
use crate::message::{Message, system::SystemMessage};
@@ -20,6 +21,8 @@ pub struct AppState {
pub shared_game_path: String,
pub editors: EditorRegistry,
pub lookups: HashMap>,
+ /// Shared searchable options for every composite item field.
+ pub composite_item_options: CompositeItemOptions,
pub workspace: Workspace,
pub pane_state: PaneState,
pub file_index_cache_manager: Option,
@@ -258,6 +261,7 @@ impl Default for AppState {
status_msg: String::new(),
editors: EditorRegistry::default(),
lookups: HashMap::new(),
+ composite_item_options: CompositeItemOptions::default(),
workspace: Workspace::new(),
pane_state: PaneState::default(),
file_index_cache_manager: None,
diff --git a/dispel-gui/src/tests/common.rs b/dispel-gui/src/tests/common.rs
index 8f01027c..324a2e76 100644
--- a/dispel-gui/src/tests/common.rs
+++ b/dispel-gui/src/tests/common.rs
@@ -54,6 +54,7 @@ pub(crate) fn activate_select_option(
) -> Vec {
use iced_test::core::accessibility::accesskit;
use iced_test::instruction::Key;
+ use iced_test::selector::{Candidate, Target};
let mut ui = iced_test::simulator(element);
let tree = ui.accessibility_tree();
@@ -61,16 +62,40 @@ pub(crate) fn activate_select_option(
.nodes
.iter()
.filter(|(_, node)| node.role() == accesskit::Role::ComboBox)
- .map(|(id, _)| *id)
+ .map(|(id, node)| (*id, node.child_supports_action(accesskit::Action::Click)))
.collect();
- let target = targets[nth];
- ui.accessibility_action(&accesskit::ActionRequest {
- action: accesskit::Action::Focus,
- target_tree: tree.tree_id,
- target_node: target,
- data: None,
- });
- ui.tap_key(Key::Enter);
+ let (target, is_combo_box) = targets[nth];
+ if is_combo_box {
+ // A ComboBox initially filters its options by the current selection.
+ // Open it with a click, then erase that text to expose the full list.
+ let mut seen = 0;
+ let mut text_len = 0;
+ let mut select = |candidate: Candidate<'_>| match candidate {
+ Candidate::TextInput { state, .. } if seen == nth => {
+ seen += 1;
+ text_len = state.text().chars().count();
+ Some(Target::from(candidate))
+ }
+ Candidate::TextInput { .. } => {
+ seen += 1;
+ None
+ }
+ _ => None,
+ };
+ ui.click(&mut select).expect("combo box must be clickable");
+ for _ in 0..text_len {
+ ui.tap_key(Key::Backspace);
+ }
+ } else {
+ ui.accessibility_action(&accesskit::ActionRequest {
+ action: accesskit::Action::Focus,
+ target_tree: tree.tree_id,
+ target_node: target,
+ data: None,
+ });
+ // A pick_list opens on Enter; a ComboBox is already open once clicked.
+ ui.tap_key(Key::Enter);
+ }
let named = if offset < 0 {
iced::keyboard::key::Named::ArrowUp
@@ -94,3 +119,38 @@ pub(crate) fn activate_select_option(
ui.tap_key(Key::Enter);
ui.into_messages().collect()
}
+
+/// Focus the `nth` combo box, type a filter query, and activate the highlighted
+/// option. Returns the messages produced by the interaction.
+#[cfg(feature = "iced_test")]
+pub(crate) fn filter_select(
+ element: iced::Element<'_, M>,
+ nth: usize,
+ query: &str,
+) -> Vec {
+ use iced_test::instruction::Key;
+ use iced_test::selector::{Candidate, Target};
+
+ let mut ui = iced_test::simulator(element);
+ let mut seen = 0;
+ let mut text_len = 0;
+ let mut select = |candidate: Candidate<'_>| match candidate {
+ Candidate::TextInput { state, .. } if seen == nth => {
+ seen += 1;
+ text_len = state.text().chars().count();
+ Some(Target::from(candidate))
+ }
+ Candidate::TextInput { .. } => {
+ seen += 1;
+ None
+ }
+ _ => None,
+ };
+ ui.click(&mut select).expect("combo box must be clickable");
+ for _ in 0..text_len {
+ ui.tap_key(Key::Backspace);
+ }
+ ui.typewrite(query);
+ ui.tap_key(Key::Enter);
+ ui.into_messages().collect()
+}
diff --git a/dispel-gui/src/tests/select_boxes.rs b/dispel-gui/src/tests/select_boxes.rs
index d8311a73..fc11921d 100644
--- a/dispel-gui/src/tests/select_boxes.rs
+++ b/dispel-gui/src/tests/select_boxes.rs
@@ -5,9 +5,11 @@
//! contain and omit the displayed id. Each label must survive `set_field` /
//! `get_field` and be visible in the spreadsheet inspector and the map editor.
-use std::collections::{HashMap, HashSet};
+use std::collections::HashMap;
use std::fmt::{Debug, Display};
+use iced::widget::combo_box;
+
use dispel_core::references::enums::WireValue;
use dispel_core::{
BooleanFlag, DialogOwner, DialogType, DialogueScript, DrawItem, EditItem, EditItemEffect,
@@ -17,20 +19,30 @@ use dispel_core::{
NpcRoleResult, SmallRange0to3, SpellTargetType,
};
+use super::common::{activate_select_option, filter_select, select_shows, select_values};
+use crate::components::composite_item::ItemOption;
use crate::components::editable::{EditableRecord, FieldDescriptor, FieldKind};
use crate::editors::map_editor::MapEditorMessage;
use crate::editors::map_editor::message::SelectedEntity;
use crate::editors::map_editor::view::fields;
-use crate::message::{EditorMessage, FileTreeMessage, Message, SystemMessage};
+use crate::message::{EditorMessage, Message, SystemMessage};
use crate::view::editor::spreadsheet::message::SpreadsheetMessage;
use crate::view::editor::spreadsheet::view::inspector::build_inspector_field;
-use iced_test::selector::{Candidate, Target};
-use iced_test::simulator;
-use super::common::{activate_select_option, select_shows, select_values};
+static EMPTY_COMBO: std::sync::LazyLock> =
+ std::sync::LazyLock::new(|| combo_box::State::new(Vec::new()));
-static EMPTY_FILTERS: std::sync::LazyLock> =
- std::sync::LazyLock::new(HashMap::new);
+fn combo_options(entries: &[(String, String)]) -> combo_box::State {
+ combo_box::State::new(
+ entries
+ .iter()
+ .map(|(key, label)| ItemOption {
+ key: key.clone(),
+ label: label.clone(),
+ })
+ .collect(),
+ )
+}
/// The formatting protocol of a field's get path.
trait LabelFormat {
@@ -123,6 +135,7 @@ fn render_both(
desc: &FieldDescriptor,
value: &str,
lookups: &HashMap>,
+ combo_state: &combo_box::State,
expected: &str,
) {
let empty = HashMap::new();
@@ -134,7 +147,7 @@ fn render_both(
None,
captured_field_changed,
&empty,
- &EMPTY_FILTERS,
+ combo_state,
captured_spreadsheet,
);
let shown = select_values(inspector);
@@ -157,7 +170,7 @@ fn render_both(
0,
SelectedEntity::Npc(0),
lookups,
- &EMPTY_FILTERS,
+ combo_state,
);
let shown = select_values(row);
assert!(
@@ -201,7 +214,7 @@ where
label,
"{field}: get_field disagrees with the rendered label"
);
- render_both(desc, &label, &lookups, &label);
+ render_both(desc, &label, &lookups, &EMPTY_COMBO, &label);
}
// Walk the options themselves so a variant the setter cannot accept, or
@@ -224,6 +237,7 @@ fn inspector_emissions(
desc: &FieldDescriptor,
value: &str,
lookups: &HashMap>,
+ combo_state: &combo_box::State,
nth: usize,
) -> Vec {
let empty = HashMap::new();
@@ -235,7 +249,7 @@ fn inspector_emissions(
None,
captured_field_changed,
&empty,
- &EMPTY_FILTERS,
+ combo_state,
captured_spreadsheet,
);
activate_select_option(element, nth, 0)
@@ -253,6 +267,7 @@ fn map_emissions(
desc: &FieldDescriptor,
value: &str,
lookups: &HashMap>,
+ combo_state: &combo_box::State,
) -> Vec {
let element = fields::inspector_field_row(
desc.label,
@@ -262,7 +277,7 @@ fn map_emissions(
0,
SelectedEntity::Npc(0),
lookups,
- &EMPTY_FILTERS,
+ combo_state,
);
activate_select_option(element, 0, 0)
.into_iter()
@@ -275,31 +290,6 @@ fn map_emissions(
.collect()
}
-/// Type into the composite search input of a rendered inspector and return the
-/// messages emitted while typing (one per keystroke).
-fn type_filter(element: iced::Element<'_, Message>, query: &str) -> Vec {
- let mut ui = simulator(element);
- let mut search = |candidate: Candidate<'_>| match candidate {
- Candidate::TextInput { state, .. } if state.text().into_owned() == "Search items..." => {
- Some(Target::from(candidate))
- }
- _ => None,
- };
- ui.click(&mut search)
- .expect("composite search input must be rendered");
- ui.typewrite(query);
- ui.into_messages().collect()
-}
-
-fn filter_capturing_spreadsheet(msg: SpreadsheetMessage) -> Message {
- match msg {
- SpreadsheetMessage::CompositeItemFilterChanged(_, query) => {
- Message::FileTree(FileTreeMessage::Search(query))
- }
- other => captured_spreadsheet(other),
- }
-}
-
fn audit_lookup(field: &'static str) {
let desc = descriptor_of::(field);
let FieldKind::Lookup(key) = &desc.kind else {
@@ -315,12 +305,12 @@ fn audit_lookup(field: &'static str) {
vec![("7".to_string(), "Invented 7".to_string())],
)]);
- render_both(desc, "9", &present, "Invented 9");
- render_both(desc, "9", &absent, "Unknown (9)");
+ render_both(desc, "9", &present, &EMPTY_COMBO, "Invented 9");
+ render_both(desc, "9", &absent, &EMPTY_COMBO, "Unknown (9)");
- for emitted in inspector_emissions(desc, "9", &present, 0)
+ for emitted in inspector_emissions(desc, "9", &present, &EMPTY_COMBO, 0)
.into_iter()
- .chain(map_emissions(desc, "9", &present))
+ .chain(map_emissions(desc, "9", &present, &EMPTY_COMBO))
{
let mut record = R::default();
assert!(
@@ -329,7 +319,13 @@ fn audit_lookup(field: &'static str) {
);
let stored = record.get_field(field);
assert_eq!(stored, emitted, "{field}: emitted id did not round-trip");
- render_both(desc, &stored, &present, &format!("Invented {stored}"));
+ render_both(
+ desc,
+ &stored,
+ &present,
+ &EMPTY_COMBO,
+ &format!("Invented {stored}"),
+ );
}
}
@@ -353,13 +349,16 @@ fn audit_composite(field: &'static str) {
],
)]);
- render_both(desc, "1:5", &present, "Invented Sword");
- render_both(desc, "1:5", &absent, "Unknown (1:5)");
- render_both(desc, "1:99", &present, "Unknown (1:99)");
+ let present_combo = combo_options(present.get(*lookup_key).expect("present items"));
+ let absent_combo = combo_options(absent.get(*lookup_key).expect("absent items"));
+
+ render_both(desc, "1:5", &present, &present_combo, "Invented Sword");
+ render_both(desc, "1:5", &absent, &absent_combo, "Unknown (1:5)");
+ render_both(desc, "1:99", &present, &present_combo, "Unknown (1:99)");
- for emitted in inspector_emissions(desc, "1:5", &present, 0)
+ for emitted in inspector_emissions(desc, "1:5", &present, &present_combo, 0)
.into_iter()
- .chain(map_emissions(desc, "1:5", &present))
+ .chain(map_emissions(desc, "1:5", &present, &present_combo))
{
let mut record = R::default();
assert!(
@@ -368,7 +367,7 @@ fn audit_composite(field: &'static str) {
);
let stored = record.get_field(field);
assert_eq!(stored, emitted, "{field}: emitted key did not round-trip");
- render_both(desc, &stored, &present, "Invented Sword");
+ render_both(desc, &stored, &present, &present_combo, "Invented Sword");
}
}
@@ -551,45 +550,83 @@ fn test_every_lookup_and_composite_field_round_trips_through_both_views() {
audit_composite::("interaction_result_item");
}
-#[test]
-fn test_composite_filter_narrows_spreadsheet_inspector_options() {
- let desc = descriptor_of::("item");
- let FieldKind::CompositeItem { lookup_key } = &desc.kind else {
- panic!("item must be a composite field");
- };
- let lookups = HashMap::from([(
- lookup_key.to_string(),
- vec![
- ("1:5".to_string(), "[Weapon] Invented Sword".to_string()),
- ("2:7".to_string(), "[Healing] Invented Herb".to_string()),
- ("255:15".to_string(), "[-]".to_string()),
- ],
- )]);
- let contents = HashMap::new();
-
- let unfiltered = build_inspector_field(
+fn inspector_combo_emissions(
+ desc: &FieldDescriptor,
+ value: &str,
+ lookups: &HashMap>,
+ combo_state: &combo_box::State,
+ query: &str,
+) -> Vec {
+ let empty = HashMap::new();
+ let element = build_inspector_field(
desc,
- "1:5".into(),
+ value.to_string(),
0,
- &lookups,
+ lookups,
None,
captured_field_changed,
- &contents,
- &EMPTY_FILTERS,
- filter_capturing_spreadsheet,
+ &empty,
+ combo_state,
+ captured_spreadsheet,
+ );
+ filter_select(element, 0, query)
+ .into_iter()
+ .filter_map(|message| match message {
+ Message::Editor(EditorMessage::Weapon(
+ crate::editors::weapon::WeaponEditorMessage::FieldChanged(_, _, value),
+ )) => Some(value),
+ _ => None,
+ })
+ .collect()
+}
+
+fn map_combo_emissions(
+ desc: &FieldDescriptor,
+ value: &str,
+ lookups: &HashMap>,
+ combo_state: &combo_box::State,
+ query: &str,
+) -> Vec {
+ let element = fields::inspector_field_row(
+ desc.label,
+ desc.name,
+ &desc.kind,
+ value,
+ 0,
+ SelectedEntity::Npc(0),
+ lookups,
+ combo_state,
);
- let query = type_filter(unfiltered, "herb")
+ filter_select(element, 0, query)
.into_iter()
- .filter_map(|m| match m {
- Message::FileTree(FileTreeMessage::Search(q)) => Some(q),
+ .filter_map(|message| match message {
+ Message::Editor(EditorMessage::MapEditor(MapEditorMessage::EntityFieldChanged(
+ _,
+ _,
+ _,
+ value,
+ ))) => Some(value),
_ => None,
})
- .last()
- .expect("the search input must emit its query");
- assert_eq!(query, "herb");
+ .collect()
+}
+
+#[test]
+fn test_combo_box_filter_narrows_spreadsheet_inspector_options() {
+ let desc = descriptor_of::("item");
+ let FieldKind::CompositeItem { lookup_key } = &desc.kind else {
+ panic!("item must be a composite field");
+ };
+ let entries = vec![
+ ("1:5".to_string(), "[Weapon] Invented Sword".to_string()),
+ ("2:7".to_string(), "[Healing] Invented Herb".to_string()),
+ ("255:15".to_string(), "[-]".to_string()),
+ ];
+ let lookups = HashMap::from([(lookup_key.to_string(), entries.clone())]);
+ let combo = combo_options(&entries);
+ let contents = HashMap::new();
- let filters = HashMap::from([("item".to_string(), query)]);
- let filtered = build_inspector_field(
+ let element = build_inspector_field(
desc,
"1:5".into(),
0,
@@ -597,85 +634,48 @@ fn test_composite_filter_narrows_spreadsheet_inspector_options() {
None,
captured_field_changed,
&contents,
- &filters,
+ &combo,
captured_spreadsheet,
);
assert!(
- select_values(filtered)
+ select_values(element)
.iter()
.any(|value| value == "[Weapon] Invented Sword"),
- "the current item must stay visible while its filter is active"
+ "the current item must stay visible before filtering"
);
- let reachable: HashSet = (-3..=3)
- .flat_map(|offset| {
- let element = build_inspector_field(
- desc,
- "1:5".into(),
- 0,
- &lookups,
- None,
- captured_field_changed,
- &contents,
- &filters,
- captured_spreadsheet,
- );
- activate_select_option(element, 0, offset)
- .into_iter()
- .filter_map(|m| match m {
- Message::Editor(EditorMessage::Weapon(
- crate::editors::weapon::WeaponEditorMessage::FieldChanged(_, _, value),
- )) => Some(value),
- _ => None,
- })
- })
- .collect();
assert_eq!(
- reachable,
- HashSet::from(["1:5".to_string(), "2:7".to_string()]),
- "the filter must remove every non-matching option"
+ inspector_combo_emissions(desc, "1:5", &lookups, &combo, "herb"),
+ vec!["2:7"],
+ "typing a label fragment must leave only the matching option"
+ );
+ assert_eq!(
+ inspector_combo_emissions(desc, "1:5", &lookups, &combo, "sword"),
+ vec!["1:5"],
+ "typing the current label must leave only the current option"
+ );
+ assert_eq!(
+ inspector_combo_emissions(desc, "1:5", &lookups, &combo, "nomatch"),
+ Vec::::new(),
+ "a query with no matching label must offer nothing to select"
);
}
#[test]
-fn test_composite_filter_narrows_map_editor_options() {
+fn test_combo_box_filter_narrows_map_editor_options() {
let desc = descriptor_of::("item");
let FieldKind::CompositeItem { lookup_key } = &desc.kind else {
panic!("item must be a composite field");
};
- let lookups = HashMap::from([(
- lookup_key.to_string(),
- vec![
- ("1:5".to_string(), "[Weapon] Invented Sword".to_string()),
- ("2:7".to_string(), "[Healing] Invented Herb".to_string()),
- ("255:15".to_string(), "[-]".to_string()),
- ],
- )]);
-
- let unfiltered = fields::inspector_field_row(
- desc.label,
- desc.name,
- &desc.kind,
- "1:5",
- 0,
- SelectedEntity::Npc(0),
- &lookups,
- &EMPTY_FILTERS,
- );
- let query = type_filter(unfiltered, "herb")
- .into_iter()
- .filter_map(|m| match m {
- Message::Editor(EditorMessage::MapEditor(
- MapEditorMessage::CompositeItemFilterChanged(_, _, query),
- )) => Some(query),
- _ => None,
- })
- .last()
- .expect("the search input must emit its query");
- assert_eq!(query, "herb");
+ let entries = vec![
+ ("1:5".to_string(), "[Weapon] Invented Sword".to_string()),
+ ("2:7".to_string(), "[Healing] Invented Herb".to_string()),
+ ("255:15".to_string(), "[-]".to_string()),
+ ];
+ let lookups = HashMap::from([(lookup_key.to_string(), entries.clone())]);
+ let combo = combo_options(&entries);
- let filters = HashMap::from([("item".to_string(), query)]);
- let filtered = fields::inspector_field_row(
+ let element = fields::inspector_field_row(
desc.label,
desc.name,
&desc.kind,
@@ -683,41 +683,24 @@ fn test_composite_filter_narrows_map_editor_options() {
0,
SelectedEntity::Npc(0),
&lookups,
- &filters,
+ &combo,
);
assert!(
- select_values(filtered)
+ select_values(element)
.iter()
.any(|value| value == "[Weapon] Invented Sword"),
- "the current item must stay visible while its filter is active"
+ "the current item must stay visible before filtering"
);
- let reachable: HashSet = (-3..=3)
- .flat_map(|offset| {
- let element = fields::inspector_field_row(
- desc.label,
- desc.name,
- &desc.kind,
- "1:5",
- 0,
- SelectedEntity::Npc(0),
- &lookups,
- &filters,
- );
- activate_select_option(element, 0, offset)
- .into_iter()
- .filter_map(|m| match m {
- Message::Editor(EditorMessage::MapEditor(
- MapEditorMessage::EntityFieldChanged(_, _, _, value),
- )) => Some(value),
- _ => None,
- })
- })
- .collect();
assert_eq!(
- reachable,
- HashSet::from(["1:5".to_string(), "2:7".to_string()]),
- "the map editor filter must remove every non-matching option"
+ map_combo_emissions(desc, "1:5", &lookups, &combo, "herb"),
+ vec!["2:7"],
+ "the map editor combo box must filter on label text"
+ );
+ assert_eq!(
+ map_combo_emissions(desc, "1:5", &lookups, &combo, "sword"),
+ vec!["1:5"],
+ "filtering to the current label must emit its exact key"
);
}
@@ -742,7 +725,7 @@ fn test_lookup_label_collision_emits_each_own_id() {
None,
captured_field_changed,
&empty,
- &EMPTY_FILTERS,
+ &EMPTY_COMBO,
captured_spreadsheet,
);
activate_select_option(element, 0, offset)
diff --git a/dispel-gui/src/update/editor/common.rs b/dispel-gui/src/update/editor/common.rs
index 81ee9f6d..b59123c1 100644
--- a/dispel-gui/src/update/editor/common.rs
+++ b/dispel-gui/src/update/editor/common.rs
@@ -166,9 +166,6 @@ macro_rules! handle_spreadsheet_messages_inner {
$compute_caches
return task;
}
- SM::CompositeItemFilterChanged(field, query) => {
- $ss.composite_item_filters.insert(field, query);
- }
SM::CachesComputed(data) => {
$ss.install_caches(data);
$ss.is_loading = false;
diff --git a/dispel-gui/src/update/mod.rs b/dispel-gui/src/update/mod.rs
index 163459ac..b8831a58 100644
--- a/dispel-gui/src/update/mod.rs
+++ b/dispel-gui/src/update/mod.rs
@@ -4,13 +4,15 @@ use iced::Task;
impl App {
pub fn update(&mut self, message: crate::message::Message) -> Task {
- match message {
+ let task = match message {
crate::message::Message::Workspace(msg) => workspace::handle(msg, self),
crate::message::Message::Editor(msg) => editor::handle(msg, self),
crate::message::Message::FileTree(msg) => file_tree::handle(msg, self),
crate::message::Message::System(msg) => system::handle(msg, self),
crate::message::Message::StartPage(msg) => startpage::handle(msg, self),
- }
+ };
+ crate::components::composite_item::refresh_composite_item_options(&mut self.state);
+ task
}
}
diff --git a/dispel-gui/src/view/editor/spreadsheet/message.rs b/dispel-gui/src/view/editor/spreadsheet/message.rs
index 488db432..7a73384c 100644
--- a/dispel-gui/src/view/editor/spreadsheet/message.rs
+++ b/dispel-gui/src/view/editor/spreadsheet/message.rs
@@ -63,9 +63,6 @@ pub enum SpreadsheetMessage {
/// Fired by `text_input` / `pick_list` widgets in the inspector panel.
/// Routes through the macro so that `compute_all_caches` is called after.
InspectorFieldChanged(usize, String, String),
- /// Search text typed into a composite item picker. `(field_name, query)`
- /// is stored on the spreadsheet state; no record is touched.
- CompositeItemFilterChanged(String, String),
// ── Async cache loading ────────────────────────────────────────────────
/// Result of an off-thread `compute_caches` job. The handler installs the
diff --git a/dispel-gui/src/view/editor/spreadsheet/state.rs b/dispel-gui/src/view/editor/spreadsheet/state.rs
index fdb4eddf..a858fbd6 100644
--- a/dispel-gui/src/view/editor/spreadsheet/state.rs
+++ b/dispel-gui/src/view/editor/spreadsheet/state.rs
@@ -127,9 +127,6 @@ pub struct SpreadsheetState {
/// record, keyed by field name. Populated on `SelectRow`. Allows the
/// cursor / selection to survive re-renders.
pub inspector_textarea_contents: HashMap,
- /// Search text of the composite item picker, keyed by field name. Kept per
- /// field so switching rows does not lose an in-progress item search.
- pub composite_item_filters: HashMap,
/// Process-wide cache of pre-shaped paragraphs. Shared by every cell
/// the table widget paints; cheap to clone (Arc).
@@ -168,7 +165,6 @@ impl Default for SpreadsheetState {
column_filter_options: Vec::new(),
column_filter_search: String::new(),
inspector_textarea_contents: HashMap::new(),
- composite_item_filters: HashMap::new(),
paragraph_cache: ParagraphCache::default(),
}
}
diff --git a/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs b/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs
index 2bc78f5b..6d882809 100644
--- a/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs
+++ b/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs
@@ -4,11 +4,11 @@
use std::collections::HashMap;
use iced::widget::{
- Column, button, column, container, pick_list, row, scrollable, text, text_input,
+ Column, button, column, combo_box, container, pick_list, row, scrollable, text, text_input,
};
use iced::{Element, Fill, Length};
-use crate::components::composite_item::composite_item_picker;
+use crate::components::composite_item::{ItemOption, composite_item_picker};
use crate::components::editable::{EditableRecord, FieldDescriptor, FieldKind};
use crate::components::generic_editor::GenericEditorState;
use crate::components::utils::horizontal_space;
@@ -24,7 +24,7 @@ pub fn build_inspector_panel<'a, R: EditableRecord>(
editor: &'a GenericEditorState,
spreadsheet: &'a SpreadsheetState,
lookups: &'a HashMap>,
- composite_filters: &'a HashMap,
+ combo_state: &'a combo_box::State,
field_changed_msg: fn(usize, String, String) -> Message,
spreadsheet_msg: fn(SpreadsheetMessage) -> Message,
) -> Element<'a, Message> {
@@ -60,7 +60,7 @@ pub fn build_inspector_panel<'a, R: EditableRecord>(
validation_error,
field_changed_msg,
&spreadsheet.inspector_textarea_contents,
- composite_filters,
+ combo_state,
spreadsheet_msg,
));
}
@@ -91,7 +91,7 @@ pub(crate) fn build_inspector_field<'a>(
validation_error: Option,
field_changed_msg: fn(usize, String, String) -> Message,
textarea_contents: &'a HashMap,
- composite_filters: &'a HashMap,
+ combo_state: &'a combo_box::State,
spreadsheet_msg: fn(SpreadsheetMessage) -> Message,
) -> Element<'a, Message> {
let label = text(descriptor.label).size(11).style(style::subtle_text);
@@ -161,34 +161,15 @@ pub(crate) fn build_inspector_field<'a>(
.width(Length::Fill)
.into()
}
- FieldKind::CompositeItem { lookup_key } => {
- let entries = lookups.get(*lookup_key).map(|v| v.as_slice());
+ FieldKind::CompositeItem { lookup_key: _ } => {
let field_name = descriptor.name.to_string();
- let filter_name = descriptor.name.to_string();
- let filter = composite_filters
- .get(descriptor.name)
- .map(String::as_str)
- .unwrap_or("");
- composite_item_picker(
- descriptor.label,
- &value,
- entries,
- false,
- filter,
- move |text| {
- spreadsheet_msg(SpreadsheetMessage::CompositeItemFilterChanged(
- filter_name.clone(),
- text,
- ))
- },
- move |v| {
- spreadsheet_msg(SpreadsheetMessage::InspectorFieldChanged(
- orig_idx,
- field_name.clone(),
- v,
- ))
- },
- )
+ composite_item_picker(descriptor.label, &value, combo_state, false, move |v| {
+ spreadsheet_msg(SpreadsheetMessage::InspectorFieldChanged(
+ orig_idx,
+ field_name.clone(),
+ v,
+ ))
+ })
}
_ => {
let field_name = descriptor.name.to_string();
@@ -227,8 +208,8 @@ mod tests {
use iced_test::selector::{Candidate, Target};
use iced_test::simulator;
- static EMPTY_FILTERS: std::sync::LazyLock> =
- std::sync::LazyLock::new(HashMap::new);
+ static EMPTY_COMBO: std::sync::LazyLock> =
+ std::sync::LazyLock::new(|| combo_box::State::new(Vec::new()));
fn field_changed(idx: usize, name: String, value: String) -> Message {
Message::Editor(crate::message::editor::EditorMessage::Weapon(
@@ -285,7 +266,7 @@ mod tests {
None,
field_changed,
&contents,
- &EMPTY_FILTERS,
+ &EMPTY_COMBO,
spreadsheet_msg,
);
assert_eq!(
@@ -299,6 +280,10 @@ mod tests {
"invented_items".to_string(),
vec![("1:0".to_string(), "Invented Sword".to_string())],
)]);
+ let combo = combo_box::State::new(vec![ItemOption {
+ key: "1:0".to_string(),
+ label: "Invented Sword".to_string(),
+ }]);
let element = build_inspector_field(
&descriptor,
"1:0".into(),
@@ -307,7 +292,7 @@ mod tests {
None,
field_changed,
&contents,
- &EMPTY_FILTERS,
+ &combo,
spreadsheet_msg,
);
assert_eq!(
@@ -354,7 +339,7 @@ mod tests {
None,
field_changed,
&contents,
- &EMPTY_FILTERS,
+ &EMPTY_COMBO,
spreadsheet_msg,
);
assert!(
@@ -401,7 +386,7 @@ mod tests {
None,
field_changed,
&contents,
- &EMPTY_FILTERS,
+ &EMPTY_COMBO,
spreadsheet_msg,
);
assert!(
@@ -435,7 +420,7 @@ mod tests {
None,
field_changed,
&contents,
- &EMPTY_FILTERS,
+ &EMPTY_COMBO,
spreadsheet_msg,
);
assert!(
@@ -451,7 +436,7 @@ mod tests {
None,
field_changed,
&contents,
- &EMPTY_FILTERS,
+ &EMPTY_COMBO,
spreadsheet_msg,
);
assert!(
@@ -467,7 +452,7 @@ mod tests {
None,
field_changed,
&contents,
- &EMPTY_FILTERS,
+ &EMPTY_COMBO,
field_changed_spreadsheet_msg,
);
let messages = crate::tests::common::activate_select_option(duplicate, 0, -1);
@@ -503,7 +488,7 @@ mod tests {
None,
field_changed,
&contents,
- &EMPTY_FILTERS,
+ &EMPTY_COMBO,
spreadsheet_msg,
);
let mut ui = simulator(element);
diff --git a/dispel-gui/src/view/editor/spreadsheet/view/mod.rs b/dispel-gui/src/view/editor/spreadsheet/view/mod.rs
index 01fc6b45..679c839c 100644
--- a/dispel-gui/src/view/editor/spreadsheet/view/mod.rs
+++ b/dispel-gui/src/view/editor/spreadsheet/view/mod.rs
@@ -7,6 +7,7 @@ pub mod table;
use super::message::SpreadsheetMessage;
use super::state::{SpreadsheetPaneContent, SpreadsheetState};
+use crate::components::composite_item::ItemOption;
use crate::components::editable::EditableRecord;
use crate::components::filter::{self, FilterBarExtras};
use crate::components::generic_editor::GenericEditorState;
@@ -14,6 +15,7 @@ use crate::components::utils::horizontal_rule;
use crate::message::Message;
use gui_widgets::components::modal;
use iced::widget::column;
+use iced::widget::combo_box;
use iced::widget::pane_grid::{self, Pane};
use iced::{Element, Fill, Length};
use std::collections::HashMap;
@@ -28,6 +30,7 @@ pub fn view_spreadsheet<'a, R: EditableRecord>(
field_changed_msg: fn(usize, String, String) -> Message,
spreadsheet_msg: fn(SpreadsheetMessage) -> Message,
lookups: &'a HashMap>,
+ combo_state: &'a combo_box::State,
pane_resized_msg: fn(pane_grid::ResizeEvent) -> Message,
pane_clicked_msg: fn(Pane) -> Message,
add_msg: Option,
@@ -73,7 +76,7 @@ pub fn view_spreadsheet<'a, R: EditableRecord>(
editor,
spreadsheet,
lookups,
- &spreadsheet.composite_item_filters,
+ combo_state,
field_changed_msg,
spreadsheet_msg,
),
From b67b08b30239be93f2a6e4fe611e1505ea780003 Mon Sep 17 00:00:00 2001
From: dimspell <141545384+dimspell@users.noreply.github.com>
Date: Thu, 26 Nov 2026 17:20:38 +0100
Subject: [PATCH 15/72] test(gui): verify composite combo box behaviour
---
dispel-gui/src/components/composite_item.rs | 184 +++++++++++++++++-
.../src/editors/map_editor/view/fields.rs | 64 ++++++
dispel-gui/src/tests/select_boxes.rs | 31 ++-
.../view/editor/spreadsheet/view/inspector.rs | 71 +++++++
4 files changed, 341 insertions(+), 9 deletions(-)
diff --git a/dispel-gui/src/components/composite_item.rs b/dispel-gui/src/components/composite_item.rs
index f4f9c8ed..1e36d8e0 100644
--- a/dispel-gui/src/components/composite_item.rs
+++ b/dispel-gui/src/components/composite_item.rs
@@ -177,6 +177,8 @@ mod tests {
use super::*;
use crate::editors::weapon::WeaponEditorMessage;
use crate::message::EditorMessage;
+ use iced_test::core::accessibility::accesskit;
+ use iced_test::instruction::Key;
use iced_test::selector::{Candidate, Target};
use iced_test::simulator;
@@ -228,6 +230,36 @@ mod tests {
))
}
+ /// Labels of the options shown by the open combo box. The current
+ /// selection is erased first so the widget filters by an empty query.
+ fn visible_options(state: &combo_box::State) -> Vec {
+ let mut ui = simulator(picker("1:0", state));
+ let mut seen = 0;
+ let mut text_len = 0;
+ let mut select = |candidate: Candidate<'_>| match candidate {
+ Candidate::TextInput { state, .. } if seen == 0 => {
+ seen += 1;
+ text_len = state.text().chars().count();
+ Some(Target::from(candidate))
+ }
+ Candidate::TextInput { .. } => {
+ seen += 1;
+ None
+ }
+ _ => None,
+ };
+ ui.click(&mut select).expect("combo box must be clickable");
+ for _ in 0..text_len {
+ ui.tap_key(Key::Backspace);
+ }
+ ui.accessibility_tree()
+ .nodes
+ .into_iter()
+ .filter(|(_, node)| node.role() == accesskit::Role::MenuListOption)
+ .filter_map(|(_, node)| node.label().map(str::to_owned))
+ .collect()
+ }
+
fn label_rendered(state: Option<&combo_box::State>, show_label: bool) -> bool {
let empty = options(&[]);
let state = state.unwrap_or(&empty);
@@ -248,13 +280,49 @@ mod tests {
}
#[test]
- fn test_selected_option_emits_its_composite_key() {
+ fn test_one_combo_box_lists_labels_from_every_item_type() {
+ let state = options(&[
+ ("1:0", "[Weapon] Invented Sword"),
+ ("2:7", "[Healing] Invented Herb"),
+ ("3:2", "[Edit] Invented Charm"),
+ ("4:1", "[Event] Invented Scroll"),
+ ("5:3", "[Misc] Invented Stone"),
+ ("255:15", NO_ITEM_LABEL),
+ ]);
+
+ assert_eq!(
+ crate::tests::common::select_values(picker("1:0", &state)),
+ vec!["[Weapon] Invented Sword"],
+ "one item field must render exactly one combo box"
+ );
+ let labels = visible_options(&state);
+ for label in [
+ "[Weapon] Invented Sword",
+ "[Healing] Invented Herb",
+ "[Edit] Invented Charm",
+ "[Event] Invented Scroll",
+ "[Misc] Invented Stone",
+ NO_ITEM_LABEL,
+ ] {
+ assert!(
+ labels.iter().any(|shown| shown == label),
+ "the shared option list must offer {label:?}, got {labels:?}"
+ );
+ }
+ assert_eq!(select_option("1:0", &state, 3), vec!["4:1"]);
+ assert_eq!(select_option("1:0", &state, 5), vec!["255:15"]);
+ }
+
+ #[test]
+ fn test_selected_option_emits_its_exact_composite_key() {
let state = options(&[
("1:0", "[Weapon] Invented Sword"),
("2:7", "[Healing] Invented Herb"),
("255:15", NO_ITEM_LABEL),
]);
assert_eq!(select_option("1:0", &state, 1), vec!["2:7"]);
+ assert_eq!(select_option("1:0", &state, 2), vec!["255:15"]);
+ assert_eq!(select_option("2:7", &state, 0), vec!["1:0"]);
}
#[test]
@@ -263,12 +331,67 @@ mod tests {
("1:0", "[Weapon] Invented Sword"),
("255:15", NO_ITEM_LABEL),
]);
- assert_eq!(select_option("255:255", &state, -1), vec!["255:255"]);
+ for value in ["255:255", "255:5"] {
+ assert_eq!(
+ crate::tests::common::select_values(picker(value, &state)),
+ vec![NO_ITEM_LABEL],
+ "{value} must display the shared empty-slot label"
+ );
+ assert_eq!(
+ select_option(value, &state, -1),
+ vec![value],
+ "reselecting the empty slot must keep the exact stored key"
+ );
+ }
+ assert_eq!(select_option("255:15", &state, -1), vec!["255:15"]);
+ }
+
+ #[test]
+ fn test_duplicate_display_names_remain_distinct() {
+ let state = options(&[
+ ("1:4", "Invented Blade"),
+ ("2:4", "Invented Blade"),
+ ("255:15", NO_ITEM_LABEL),
+ ]);
+ let labels = visible_options(&state);
+ assert_eq!(
+ labels,
+ vec!["Invented Blade", "Invented Blade", NO_ITEM_LABEL],
+ "both duplicate rows must stay in the one option list"
+ );
+ assert_eq!(select_option("2:4", &state, 0), vec!["1:4"]);
+ assert_eq!(select_option("2:4", &state, 1), vec!["2:4"]);
+ }
+
+ #[test]
+ fn test_unmapped_key_shows_visible_fallback() {
+ let state = options(&[
+ ("1:0", "[Weapon] Invented Sword"),
+ ("255:15", NO_ITEM_LABEL),
+ ]);
+ assert_eq!(
+ crate::tests::common::select_values(picker("1:999", &state)),
+ vec!["Unknown (1:999)"]
+ );
+ assert_eq!(
+ crate::tests::common::select_values(picker("255:0", &state)),
+ vec![NO_ITEM_LABEL]
+ );
}
#[test]
fn test_fallback_text_input_edits_the_raw_value() {
let state = options(&[]);
+ let no_combo = simulator(picker("255:255", &state))
+ .accessibility_tree()
+ .nodes
+ .into_iter()
+ .any(|(_, node)| node.role() == accesskit::Role::ComboBox);
+ assert!(
+ !no_combo,
+ "without a loaded catalog there must be no combo box"
+ );
+
let mut ui = simulator(picker("255:255", &state));
let mut input = |candidate: Candidate<'_>| match candidate {
Candidate::TextInput { state, .. } if state.text().into_owned() == "255:255" => {
@@ -299,3 +422,60 @@ mod tests {
}
}
}
+
+#[cfg(test)]
+mod refresh_tests {
+ use super::*;
+ use crate::state::AppState;
+
+ #[test]
+ fn test_refresh_builds_one_option_list_and_adds_the_sentinel() {
+ let mut app = AppState::default();
+ app.lookups.insert(
+ "items".to_string(),
+ vec![
+ ("1:5".to_string(), "[Weapon] Invented Sword".to_string()),
+ ("2:7".to_string(), "[Healing] Invented Herb".to_string()),
+ ],
+ );
+
+ refresh_composite_item_options(&mut app);
+ let options = app.composite_item_options.state.options();
+ assert_eq!(
+ options
+ .iter()
+ .map(|option| option.key.as_str())
+ .collect::>(),
+ vec!["1:5", "2:7", NO_ITEM_KEY]
+ );
+ assert_eq!(options.last().unwrap().label, NO_ITEM_LABEL);
+ let fingerprint = app.composite_item_options.fingerprint;
+ let pointer = options.as_ptr();
+
+ refresh_composite_item_options(&mut app);
+ assert_eq!(
+ app.composite_item_options.fingerprint, fingerprint,
+ "an unchanged lookup must not rebuild the options"
+ );
+ assert_eq!(
+ app.composite_item_options.state.options().as_ptr(),
+ pointer,
+ "the same option list must be reused"
+ );
+
+ app.lookups
+ .get_mut("items")
+ .unwrap()
+ .push(("3:2".to_string(), "[Edit] Invented Charm".to_string()));
+ refresh_composite_item_options(&mut app);
+ assert_ne!(app.composite_item_options.fingerprint, fingerprint);
+ assert_eq!(app.composite_item_options.state.options().len(), 4);
+ }
+
+ #[test]
+ fn test_refresh_without_lookups_keeps_the_fallback_empty() {
+ let mut app = AppState::default();
+ refresh_composite_item_options(&mut app);
+ assert!(app.composite_item_options.state.options().is_empty());
+ }
+}
diff --git a/dispel-gui/src/editors/map_editor/view/fields.rs b/dispel-gui/src/editors/map_editor/view/fields.rs
index 3b205ac9..df7ffd81 100644
--- a/dispel-gui/src/editors/map_editor/view/fields.rs
+++ b/dispel-gui/src/editors/map_editor/view/fields.rs
@@ -196,6 +196,70 @@ mod tests {
count
}
+ #[test]
+ fn test_map_editor_composite_combo_emits_exact_key() {
+ let kind = FieldKind::CompositeItem {
+ lookup_key: "invented_items",
+ };
+ let lookups = HashMap::from([(
+ "invented_items".to_string(),
+ vec![
+ ("1:0".to_string(), "[Weapon] Invented Sword".to_string()),
+ ("2:7".to_string(), "[Healing] Invented Herb".to_string()),
+ ],
+ )]);
+ let combo = combo_box::State::new(vec![
+ ItemOption {
+ key: "1:0".to_string(),
+ label: "[Weapon] Invented Sword".to_string(),
+ },
+ ItemOption {
+ key: "2:7".to_string(),
+ label: "[Healing] Invented Herb".to_string(),
+ },
+ ]);
+
+ let element = inspector_field_row(
+ "Invented Item:",
+ "item_type",
+ &kind,
+ "1:0",
+ 0,
+ SelectedEntity::DrawItem(0),
+ &lookups,
+ &combo,
+ );
+ assert!(
+ crate::tests::common::select_shows(element, "[Weapon] Invented Sword"),
+ "the map editor combo must show the selected item label"
+ );
+
+ let element = inspector_field_row(
+ "Invented Item:",
+ "item_type",
+ &kind,
+ "1:0",
+ 0,
+ SelectedEntity::DrawItem(0),
+ &lookups,
+ &combo,
+ );
+ let emitted: Vec = crate::tests::common::activate_select_option(element, 0, 1)
+ .into_iter()
+ .filter_map(|message| match message {
+ Message::Editor(crate::message::editor::EditorMessage::MapEditor(
+ MapEditorMessage::EntityFieldChanged(_, _, _, value),
+ )) => Some(value),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(
+ emitted,
+ vec!["2:7"],
+ "the map editor must emit the selected composite key"
+ );
+ }
+
#[test]
fn test_npc_facing_directions_offer_left_in_map_editor() {
use crate::components::editable::EditableRecord;
diff --git a/dispel-gui/src/tests/select_boxes.rs b/dispel-gui/src/tests/select_boxes.rs
index fc11921d..f13c83b0 100644
--- a/dispel-gui/src/tests/select_boxes.rs
+++ b/dispel-gui/src/tests/select_boxes.rs
@@ -239,6 +239,7 @@ fn inspector_emissions(
lookups: &HashMap>,
combo_state: &combo_box::State,
nth: usize,
+ offset: isize,
) -> Vec {
let empty = HashMap::new();
let element = build_inspector_field(
@@ -252,7 +253,7 @@ fn inspector_emissions(
combo_state,
captured_spreadsheet,
);
- activate_select_option(element, nth, 0)
+ activate_select_option(element, nth, offset)
.into_iter()
.filter_map(|message| match message {
Message::Editor(EditorMessage::Weapon(
@@ -268,6 +269,7 @@ fn map_emissions(
value: &str,
lookups: &HashMap>,
combo_state: &combo_box::State,
+ offset: isize,
) -> Vec {
let element = fields::inspector_field_row(
desc.label,
@@ -279,7 +281,7 @@ fn map_emissions(
lookups,
combo_state,
);
- activate_select_option(element, 0, 0)
+ activate_select_option(element, 0, offset)
.into_iter()
.filter_map(|message| match message {
Message::Editor(EditorMessage::MapEditor(
@@ -308,9 +310,9 @@ fn audit_lookup(field: &'static str) {
render_both(desc, "9", &present, &EMPTY_COMBO, "Invented 9");
render_both(desc, "9", &absent, &EMPTY_COMBO, "Unknown (9)");
- for emitted in inspector_emissions(desc, "9", &present, &EMPTY_COMBO, 0)
+ for emitted in inspector_emissions(desc, "9", &present, &EMPTY_COMBO, 0, 0)
.into_iter()
- .chain(map_emissions(desc, "9", &present, &EMPTY_COMBO))
+ .chain(map_emissions(desc, "9", &present, &EMPTY_COMBO, 0))
{
let mut record = R::default();
assert!(
@@ -355,10 +357,20 @@ fn audit_composite(field: &'static str) {
render_both(desc, "1:5", &present, &present_combo, "Invented Sword");
render_both(desc, "1:5", &absent, &absent_combo, "Unknown (1:5)");
render_both(desc, "1:99", &present, &present_combo, "Unknown (1:99)");
+ render_both(desc, "255:255", &present, &present_combo, "[-]");
- for emitted in inspector_emissions(desc, "1:5", &present, &present_combo, 0)
+ for emitted in inspector_emissions(desc, "1:5", &present, &present_combo, 0, 0)
.into_iter()
- .chain(map_emissions(desc, "1:5", &present, &present_combo))
+ .chain(map_emissions(desc, "1:5", &present, &present_combo, 0))
+ .chain(inspector_emissions(
+ desc,
+ "255:255",
+ &present,
+ &present_combo,
+ 0,
+ -1,
+ ))
+ .chain(map_emissions(desc, "255:255", &present, &present_combo, -1))
{
let mut record = R::default();
assert!(
@@ -367,7 +379,12 @@ fn audit_composite(field: &'static str) {
);
let stored = record.get_field(field);
assert_eq!(stored, emitted, "{field}: emitted key did not round-trip");
- render_both(desc, &stored, &present, &present_combo, "Invented Sword");
+ let expected = if emitted.starts_with("255:") {
+ "[-]"
+ } else {
+ "Invented Sword"
+ };
+ render_both(desc, &stored, &present, &present_combo, expected);
}
}
diff --git a/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs b/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs
index 6d882809..b27149ce 100644
--- a/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs
+++ b/dispel-gui/src/view/editor/spreadsheet/view/inspector.rs
@@ -302,6 +302,77 @@ mod tests {
);
}
+ #[test]
+ fn test_composite_field_combo_emits_exact_key() {
+ let descriptor = FieldDescriptor {
+ name: "item_type",
+ label: "Invented Item:",
+ kind: FieldKind::CompositeItem {
+ lookup_key: "invented_items",
+ },
+ };
+ let lookups = HashMap::from([(
+ "invented_items".to_string(),
+ vec![
+ ("1:0".to_string(), "[Weapon] Invented Sword".to_string()),
+ ("2:7".to_string(), "[Healing] Invented Herb".to_string()),
+ ],
+ )]);
+ let combo = combo_box::State::new(vec![
+ ItemOption {
+ key: "1:0".to_string(),
+ label: "[Weapon] Invented Sword".to_string(),
+ },
+ ItemOption {
+ key: "2:7".to_string(),
+ label: "[Healing] Invented Herb".to_string(),
+ },
+ ]);
+ let contents = HashMap::new();
+
+ let element = build_inspector_field(
+ &descriptor,
+ "1:0".into(),
+ 0,
+ &lookups,
+ None,
+ field_changed,
+ &contents,
+ &combo,
+ field_changed_spreadsheet_msg,
+ );
+ assert!(
+ crate::tests::common::select_shows(element, "[Weapon] Invented Sword"),
+ "the inspector combo must show the selected item label"
+ );
+
+ let element = build_inspector_field(
+ &descriptor,
+ "1:0".into(),
+ 0,
+ &lookups,
+ None,
+ field_changed,
+ &contents,
+ &combo,
+ field_changed_spreadsheet_msg,
+ );
+ let emitted: Vec = crate::tests::common::activate_select_option(element, 0, 1)
+ .into_iter()
+ .filter_map(|message| match message {
+ Message::Editor(crate::message::editor::EditorMessage::Weapon(
+ crate::editors::weapon::WeaponEditorMessage::FieldChanged(_, _, value),
+ )) => Some(value),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(
+ emitted,
+ vec!["2:7"],
+ "choosing an item must emit its composite key, not its label"
+ );
+ }
+
#[test]
fn test_npc_facing_directions_offer_left_in_inspector() {
use crate::components::editable::EditableRecord;
From d146a1b55b16e25d8a66c23ac66d05b569a0d213 Mon Sep 17 00:00:00 2001
From: dimspell <141545384+dimspell@users.noreply.github.com>
Date: Thu, 26 Nov 2026 17:31:01 +0100
Subject: [PATCH 16/72] fix(gui): disambiguate duplicate item labels and cover
update hook
---
dispel-gui/src/components/composite_item.rs | 130 +++++++++++++++++---
dispel-gui/src/tests/common.rs | 8 +-
dispel-gui/src/update/mod.rs | 41 ++++++
3 files changed, 161 insertions(+), 18 deletions(-)
diff --git a/dispel-gui/src/components/composite_item.rs b/dispel-gui/src/components/composite_item.rs
index 1e36d8e0..acc510f3 100644
--- a/dispel-gui/src/components/composite_item.rs
+++ b/dispel-gui/src/components/composite_item.rs
@@ -1,3 +1,4 @@
+use std::collections::HashMap;
use std::collections::hash_map::DefaultHasher;
use std::fmt;
use std::hash::Hasher;
@@ -59,14 +60,34 @@ pub fn refresh_composite_item_options(state: &mut crate::state::AppState) {
let options = match entries {
Some(entries) => {
+ // Count the original labels before adding the sentinel. The
+ // fingerprint above also comes from these unmodified pairs.
+ let mut label_counts: HashMap<&str, usize> = HashMap::new();
+ for (_, label) in entries {
+ *label_counts.entry(label.as_str()).or_default() += 1;
+ }
+ let needs_sentinel = !entries.iter().any(|(key, _)| key == NO_ITEM_KEY);
+ if needs_sentinel {
+ *label_counts.entry(NO_ITEM_LABEL).or_default() += 1;
+ }
+
let mut options: Vec = entries
.iter()
- .map(|(key, label)| ItemOption {
- key: key.clone(),
- label: label.clone(),
+ .map(|(key, label)| {
+ let display = if key != NO_ITEM_KEY
+ && label_counts.get(label.as_str()).copied().unwrap_or(0) > 1
+ {
+ format!("{label} ({key})")
+ } else {
+ label.clone()
+ };
+ ItemOption {
+ key: key.clone(),
+ label: display,
+ }
})
.collect();
- if !options.iter().any(|option| option.key == NO_ITEM_KEY) {
+ if needs_sentinel {
options.push(ItemOption {
key: NO_ITEM_KEY.to_string(),
label: NO_ITEM_LABEL.to_string(),
@@ -230,8 +251,10 @@ mod tests {
))
}
- /// Labels of the options shown by the open combo box. The current
- /// selection is erased first so the widget filters by an empty query.
+ /// Labels of the options shown by the open combo box. Clicking opens the
+ /// dropdown; the widget clears its seeded selection on focus, but the
+ /// simulated click can leave that text in the input. The backspaces keep
+ /// the query empty so the whole option list stays visible.
fn visible_options(state: &combo_box::State) -> Vec {
let mut ui = simulator(picker("1:0", state));
let mut seen = 0;
@@ -348,19 +371,55 @@ mod tests {
#[test]
fn test_duplicate_display_names_remain_distinct() {
- let state = options(&[
- ("1:4", "Invented Blade"),
- ("2:4", "Invented Blade"),
- ("255:15", NO_ITEM_LABEL),
- ]);
- let labels = visible_options(&state);
+ let mut app = crate::state::AppState::default();
+ app.lookups.insert(
+ "items".to_string(),
+ vec![
+ ("1:4".to_string(), "Invented Blade".to_string()),
+ ("2:4".to_string(), "Invented Blade".to_string()),
+ ("255:15".to_string(), NO_ITEM_LABEL.to_string()),
+ ],
+ );
+ refresh_composite_item_options(&mut app);
+ let state = &app.composite_item_options.state;
+
+ let labels = visible_options(state);
assert_eq!(
labels,
- vec!["Invented Blade", "Invented Blade", NO_ITEM_LABEL],
- "both duplicate rows must stay in the one option list"
+ vec![
+ "Invented Blade (1:4)",
+ "Invented Blade (2:4)",
+ NO_ITEM_LABEL
+ ],
+ "both duplicate rows must stay distinct in the one option list"
+ );
+ assert_eq!(select_option("2:4", state, 0), vec!["1:4"]);
+ assert_eq!(select_option("2:4", state, 1), vec!["2:4"]);
+ }
+
+ #[test]
+ fn test_duplicate_selected_value_shows_qualified_label() {
+ let mut app = crate::state::AppState::default();
+ app.lookups.insert(
+ "items".to_string(),
+ vec![
+ ("1:4".to_string(), "Cap".to_string()),
+ ("2:4".to_string(), "Cap".to_string()),
+ ],
+ );
+ refresh_composite_item_options(&mut app);
+ let state = &app.composite_item_options.state;
+
+ assert_eq!(
+ crate::tests::common::select_values(picker("2:4", state)),
+ vec!["Cap (2:4)"],
+ "a field holding 2:4 must not show the same label as 1:4"
+ );
+ assert_eq!(
+ select_option("2:4", state, 1),
+ vec!["2:4"],
+ "the qualified label must still emit the exact key"
);
- assert_eq!(select_option("2:4", &state, 0), vec!["1:4"]);
- assert_eq!(select_option("2:4", &state, 1), vec!["2:4"]);
}
#[test]
@@ -472,6 +531,45 @@ mod refresh_tests {
assert_eq!(app.composite_item_options.state.options().len(), 4);
}
+ #[test]
+ fn test_refresh_fingerprints_original_entries_and_qualifies_duplicates() {
+ let mut app = AppState::default();
+ let entries = vec![
+ ("1:4".to_string(), "Cap".to_string()),
+ ("2:4".to_string(), "Cap".to_string()),
+ (NO_ITEM_KEY.to_string(), NO_ITEM_LABEL.to_string()),
+ ];
+ app.lookups.insert("items".to_string(), entries.clone());
+
+ refresh_composite_item_options(&mut app);
+ assert_eq!(
+ app.composite_item_options.fingerprint,
+ fingerprint_options(Some(&entries)),
+ "the fingerprint must come from the raw key/label pairs"
+ );
+ let labels: Vec<&str> = app
+ .composite_item_options
+ .state
+ .options()
+ .iter()
+ .map(|option| option.label.as_str())
+ .collect();
+ assert_eq!(
+ labels,
+ vec!["Cap (1:4)", "Cap (2:4)", NO_ITEM_LABEL],
+ "only repeated labels are qualified, and the sentinel stays as-is"
+ );
+
+ let fingerprint = app.composite_item_options.fingerprint;
+ app.lookups.get_mut("items").unwrap()[1].0 = "2:5".to_string();
+ refresh_composite_item_options(&mut app);
+ assert_ne!(fingerprint, app.composite_item_options.fingerprint);
+ assert_eq!(
+ app.composite_item_options.state.options()[1].label,
+ "Cap (2:5)"
+ );
+ }
+
#[test]
fn test_refresh_without_lookups_keeps_the_fallback_empty() {
let mut app = AppState::default();
diff --git a/dispel-gui/src/tests/common.rs b/dispel-gui/src/tests/common.rs
index 324a2e76..6b4fd5a2 100644
--- a/dispel-gui/src/tests/common.rs
+++ b/dispel-gui/src/tests/common.rs
@@ -66,8 +66,9 @@ pub(crate) fn activate_select_option(
.collect();
let (target, is_combo_box) = targets[nth];
if is_combo_box {
- // A ComboBox initially filters its options by the current selection.
- // Open it with a click, then erase that text to expose the full list.
+ // Click to open the dropdown. The widget clears its seeded selection
+ // on focus; the extra Backspaces keep the simulated input's query
+ // empty so arrow navigation starts from the full option list.
let mut seen = 0;
let mut text_len = 0;
let mut select = |candidate: Candidate<'_>| match candidate {
@@ -146,6 +147,9 @@ pub(crate) fn filter_select(
}
_ => None,
};
+ // Click to open the combo. The widget clears its seeded selection on
+ // focus; the Backspaces keep the simulated query empty before typing so
+ // filtering starts from every option.
ui.click(&mut select).expect("combo box must be clickable");
for _ in 0..text_len {
ui.tap_key(Key::Backspace);
diff --git a/dispel-gui/src/update/mod.rs b/dispel-gui/src/update/mod.rs
index b8831a58..6dad4796 100644
--- a/dispel-gui/src/update/mod.rs
+++ b/dispel-gui/src/update/mod.rs
@@ -22,3 +22,44 @@ mod file_tree;
mod startpage;
mod system;
mod workspace;
+
+#[cfg(test)]
+mod tests {
+ use crate::app::App;
+ use crate::components::composite_item::ItemOption;
+ use crate::components::composite_item::refresh_composite_item_options;
+ use crate::message::{Message, SystemMessage};
+ use crate::workspace::Workspace;
+
+ /// The refresh hook must run after routing, so a handler that empties the
+ /// item lookup also empties the shared combo box options.
+ #[test]
+ fn test_update_refreshes_options_after_workspace_clear() {
+ let mut app = App::test_new(Workspace::new());
+ app.state.lookups.insert(
+ "items".to_string(),
+ vec![
+ ("1:5".to_string(), "Invented Sword".to_string()),
+ ("2:7".to_string(), "Invented Herb".to_string()),
+ ],
+ );
+ refresh_composite_item_options(&mut app.state);
+ assert_eq!(
+ app.state.composite_item_options.state.options().len(),
+ 3,
+ "the item catalog and the no-item sentinel must be loaded"
+ );
+
+ let _ = app.update(Message::System(SystemMessage::ClearWorkspace));
+
+ assert!(
+ app.state.lookups.is_empty(),
+ "ClearWorkspace must empty the lookups"
+ );
+ let options: &[ItemOption] = app.state.composite_item_options.state.options();
+ assert!(
+ options.is_empty(),
+ "App::update must rebuild the options after the handler, got {options:?}"
+ );
+ }
+}
From 4799519cef0717582d5da40c3c4e4afa05f55d1b Mon Sep 17 00:00:00 2001
From: dimspell <141545384+dimspell@users.noreply.github.com>
Date: Sat, 28 Nov 2026 11:10:27 +0100
Subject: [PATCH 17/72] fix(gui): clear editor state when entering a new game
---
dispel-gui/src/tests/start_page.rs | 34 ++++++++++++++++++++++++++++++
dispel-gui/src/update/startpage.rs | 8 +++++++
2 files changed, 42 insertions(+)
diff --git a/dispel-gui/src/tests/start_page.rs b/dispel-gui/src/tests/start_page.rs
index e3bbb77f..7ed19d10 100644
--- a/dispel-gui/src/tests/start_page.rs
+++ b/dispel-gui/src/tests/start_page.rs
@@ -54,3 +54,37 @@ fn test_back_to_start_no_game_path_does_not_change_input() {
assert_eq!(app.start_page_input, "existing");
assert_eq!(task.units(), 0);
}
+
+#[test]
+fn test_enter_editor_mode_new_game_path_clears_editors_and_tabs() {
+ use dispel_core::WeaponItem;
+
+ let previous_game = tempfile::tempdir().expect("temp dir");
+ let next_game = tempfile::tempdir().expect("temp dir");
+
+ let mut app = App::test_new(Workspace::new());
+ app.state.workspace.game_path = Some(previous_game.path().to_path_buf());
+ app.state.editors.weapon_editor.catalog = Some(vec![WeaponItem {
+ name: "Gloomvale Sabre".into(),
+ ..Default::default()
+ }]);
+ app.state.workspace.open(
+ "Gloomvale Sabre".to_string(),
+ Some(previous_game.path().join("GloomvaleWeaponItem.db")),
+ );
+
+ assert!(app.state.editors.weapon_editor.catalog.is_some());
+ assert_eq!(app.state.workspace.tabs.len(), 1);
+
+ app.start_page_input = next_game.path().to_string_lossy().to_string();
+ let _task = app.update(Message::StartPage(StartPageMessage::Continue));
+
+ assert!(
+ app.state.editors.weapon_editor.catalog.is_none(),
+ "catalog from the previous game must not survive a game switch"
+ );
+ assert!(
+ app.state.workspace.tabs.is_empty(),
+ "tabs from the previous game must not survive a game switch"
+ );
+}
diff --git a/dispel-gui/src/update/startpage.rs b/dispel-gui/src/update/startpage.rs
index 0dbead3b..7cc89a73 100644
--- a/dispel-gui/src/update/startpage.rs
+++ b/dispel-gui/src/update/startpage.rs
@@ -37,6 +37,14 @@ pub fn handle(message: StartPageMessage, app: &mut App) -> Task {
}
pub fn enter_editor_mode(app: &mut App, path: PathBuf) -> Task {
+ // A different game path invalidates every loaded catalog and open tab.
+ // Continuing with the same path keeps the current editor session intact.
+ let path_changed = app.state.workspace.game_path.as_ref() != Some(&path);
+ if path_changed {
+ app.state.clear_editor_states();
+ app.state.workspace.clear_all_tabs();
+ }
+
// Update recent game paths (max 5)
let recent = &mut app.state.workspace.recent_game_paths;
recent.retain(|p| p != &path);
From 3b8aca35860c65d47a7b8504e4ae6d3e7f30ecbd Mon Sep 17 00:00:00 2001
From: dimspell <141545384+dimspell@users.noreply.github.com>
Date: Sat, 28 Nov 2026 11:12:44 +0100
Subject: [PATCH 18/72] fix(gui): stop recording when the game path changes
---
dispel-gui/src/recording_tests.rs | 20 ++++++++++++++
dispel-gui/src/update/startpage.rs | 42 ++++++++++++++++--------------
dispel-gui/src/update/system.rs | 9 ++++++-
3 files changed, 51 insertions(+), 20 deletions(-)
diff --git a/dispel-gui/src/recording_tests.rs b/dispel-gui/src/recording_tests.rs
index 9d236d3b..cc0a309e 100644
--- a/dispel-gui/src/recording_tests.rs
+++ b/dispel-gui/src/recording_tests.rs
@@ -1422,3 +1422,23 @@ fn fog_data_editor_save_without_session_writes_file_only() {
"edited table persisted to disk"
);
}
+
+#[test]
+fn test_switch_game_path_stops_recording() {
+ use crate::message::Message;
+ use crate::message::startpage::StartPageMessage;
+
+ let previous_game = tempfile::tempdir().expect("temp dir");
+ let next_game = tempfile::tempdir().expect("temp dir");
+
+ let mut app = app_with_recording();
+ app.state.workspace.game_path = Some(previous_game.path().to_path_buf());
+ app.start_page_input = next_game.path().to_string_lossy().to_string();
+
+ let _task = app.update(Message::StartPage(StartPageMessage::Continue));
+
+ assert!(
+ app.state.recording.is_none(),
+ "a session tied to the old game path must not survive a game switch"
+ );
+}
diff --git a/dispel-gui/src/update/startpage.rs b/dispel-gui/src/update/startpage.rs
index 7cc89a73..0eb1cbed 100644
--- a/dispel-gui/src/update/startpage.rs
+++ b/dispel-gui/src/update/startpage.rs
@@ -40,10 +40,18 @@ pub fn enter_editor_mode(app: &mut App, path: PathBuf) -> Task {
// A different game path invalidates every loaded catalog and open tab.
// Continuing with the same path keeps the current editor session intact.
let path_changed = app.state.workspace.game_path.as_ref() != Some(&path);
- if path_changed {
+ let stop_recording_task = if path_changed {
app.state.clear_editor_states();
app.state.workspace.clear_all_tabs();
- }
+ // Stop through the mod packager so pending edits are flushed to the
+ // old workspace instead of being dropped with the session.
+ crate::editors::mod_packager::handle(
+ crate::editors::mod_packager::ModPackagerMessage::StopRecording,
+ app,
+ )
+ } else {
+ Task::none()
+ };
// Update recent game paths (max 5)
let recent = &mut app.state.workspace.recent_game_paths;
@@ -83,24 +91,20 @@ pub fn enter_editor_mode(app: &mut App, path: PathBuf) -> Task {
|index| Message::System(SystemMessage::IndexLoaded(Ok(index))),
);
+ let mut tasks = vec![stop_recording_task, search_task];
if let Some(ref cache_manager) = app.state.file_index_cache_manager {
let cache_manager = cache_manager.clone();
- Task::batch([
- search_task,
- Task::perform(
- async move {
- let svc = crate::indexation::indexation_service::IndexationService::new(
- cache_manager,
- );
- svc.start_indexation_with_fallback(gp_cache).await
- },
- |result| match result {
- Ok(cache) => Message::System(SystemMessage::CacheIndexationComplete(cache)),
- Err(_) => Message::System(SystemMessage::CacheIndexationFailed),
- },
- ),
- ])
- } else {
- search_task
+ tasks.push(Task::perform(
+ async move {
+ let svc =
+ crate::indexation::indexation_service::IndexationService::new(cache_manager);
+ svc.start_indexation_with_fallback(gp_cache).await
+ },
+ |result| match result {
+ Ok(cache) => Message::System(SystemMessage::CacheIndexationComplete(cache)),
+ Err(_) => Message::System(SystemMessage::CacheIndexationFailed),
+ },
+ ));
}
+ Task::batch(tasks)
}
diff --git a/dispel-gui/src/update/system.rs b/dispel-gui/src/update/system.rs
index 916d5273..be8cb37f 100644
--- a/dispel-gui/src/update/system.rs
+++ b/dispel-gui/src/update/system.rs
@@ -151,6 +151,13 @@ pub fn handle(message: SystemMessage, app: &mut App) -> Task Task {}
}
From 74ec28135b9e57df919dd8477dfe5bffd0d37da1 Mon Sep 17 00:00:00 2001
From: dimspell <141545384+dimspell@users.noreply.github.com>
Date: Sat, 28 Nov 2026 11:21:20 +0100
Subject: [PATCH 19/72] fix(gui): route completion messages to their tab
---
dispel-gui/src/app.rs | 4 +-
.../src/editors/save_file_viewer/message.rs | 4 +-
.../editors/save_file_viewer/update/mod.rs | 13 +-
.../src/editors/sprite_editor/message.rs | 4 +-
.../src/editors/sprite_editor/update.rs | 13 +-
dispel-gui/src/editors/tileset/message.rs | 6 +-
dispel-gui/src/editors/tileset/update.rs | 21 ++-
dispel-gui/src/tests/common.rs | 37 +++++
dispel-gui/src/tests/tabbed_editor.rs | 139 ++++++++++++++++++
9 files changed, 219 insertions(+), 22 deletions(-)
diff --git a/dispel-gui/src/app.rs b/dispel-gui/src/app.rs
index 1052eb96..08d536f1 100644
--- a/dispel-gui/src/app.rs
+++ b/dispel-gui/src/app.rs
@@ -410,7 +410,9 @@ impl App {
},
move |result| {
crate::message::Message::save_file_viewer(
- crate::editors::save_file_viewer::SaveFileViewerMessage::Loaded(result),
+ crate::editors::save_file_viewer::SaveFileViewerMessage::Loaded(
+ tab_id, result,
+ ),
)
},
)
diff --git a/dispel-gui/src/editors/save_file_viewer/message.rs b/dispel-gui/src/editors/save_file_viewer/message.rs
index 098f2c99..1c7386cf 100644
--- a/dispel-gui/src/editors/save_file_viewer/message.rs
+++ b/dispel-gui/src/editors/save_file_viewer/message.rs
@@ -13,8 +13,8 @@ use crate::editors::save_file_viewer::state::{
pub enum SaveFileViewerMessage {
/// Load a save file from disk.
Load(PathBuf),
- /// Result of loading a save file.
- Loaded(Result),
+ /// Result of loading a save file, tagged with the tab that issued the load.
+ Loaded(usize, Result),
/// Switch to a different section.
SelectSection(SaveFileSection),
/// Select an inventory category to view.
diff --git a/dispel-gui/src/editors/save_file_viewer/update/mod.rs b/dispel-gui/src/editors/save_file_viewer/update/mod.rs
index 15172a15..421c6475 100644
--- a/dispel-gui/src/editors/save_file_viewer/update/mod.rs
+++ b/dispel-gui/src/editors/save_file_viewer/update/mod.rs
@@ -234,9 +234,14 @@ fn apply_column_width(state: &mut SaveFileViewerState, key: TableKey, col: usize
}
pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task {
- let tab_id = match app.state.workspace.active() {
- Some(t) => t.id,
- None => return Task::none(),
+ // A load result carries its tab id so it still reaches the originating
+ // viewer if another tab became active while the async read was running.
+ let tab_id = match &msg {
+ SaveFileViewerMessage::Loaded(id, _) => *id,
+ _ => match app.state.workspace.active() {
+ Some(t) => t.id,
+ None => return Task::none(),
+ },
};
let state = match app.state.editors.save_file_viewers.get_mut(&tab_id) {
@@ -1012,7 +1017,7 @@ pub fn handle(msg: SaveFileViewerMessage, app: &mut App) -> Task {
SaveFileViewerMessage::TableFilter { key, action } => {
handle_table_filter(state, key, action)
}
- SaveFileViewerMessage::Loaded(result) => {
+ SaveFileViewerMessage::Loaded(_, result) => {
state.loading = false;
match result {
Ok(loaded) => {
diff --git a/dispel-gui/src/editors/sprite_editor/message.rs b/dispel-gui/src/editors/sprite_editor/message.rs
index dd6cfda7..7d068df5 100644
--- a/dispel-gui/src/editors/sprite_editor/message.rs
+++ b/dispel-gui/src/editors/sprite_editor/message.rs
@@ -52,8 +52,8 @@ pub enum SpriteViewerMessage {
// ── Editing ──────────────────────────────────────────────────────────────
/// Save the current sprite file to disk.
Save,
- /// Save completed (async result).
- SaveComplete(Result),
+ /// Save completed (async result), tagged with the tab that issued the save.
+ SaveComplete(usize, Result),
/// Undo last edit.
Undo,
/// Redo last undone edit.
diff --git a/dispel-gui/src/editors/sprite_editor/update.rs b/dispel-gui/src/editors/sprite_editor/update.rs
index 125b0e3e..b6b0aab1 100644
--- a/dispel-gui/src/editors/sprite_editor/update.rs
+++ b/dispel-gui/src/editors/sprite_editor/update.rs
@@ -13,7 +13,12 @@ use iced::Task;
const TICK_MS: f32 = 16.0;
pub fn handle(message: SpriteViewerMessage, app: &mut App) -> Task {
- let tab_id = app.state.workspace.active_tab_id().as_usize();
+ // Async results carry their tab id so a save that resolves after a tab
+ // switch still reaches the editor that issued it.
+ let tab_id = match &message {
+ SpriteViewerMessage::SaveComplete(id, _) => *id,
+ _ => app.state.workspace.active_tab_id().as_usize(),
+ };
let Some(viewer) = app.state.editors.sprite_viewers.get_mut(&tab_id) else {
return Task::none();
@@ -84,14 +89,14 @@ pub fn handle(message: SpriteViewerMessage, app: &mut App) -> Task {
+ SpriteViewerMessage::SaveComplete(_, result) => {
match result {
Ok(_msg) => {
viewer.mark_clean();
diff --git a/dispel-gui/src/editors/tileset/message.rs b/dispel-gui/src/editors/tileset/message.rs
index a3135e37..d3428091 100644
--- a/dispel-gui/src/editors/tileset/message.rs
+++ b/dispel-gui/src/editors/tileset/message.rs
@@ -17,7 +17,9 @@ pub enum TilesetEditorMessage {
CloseExportDialog,
SetExportFormat(TileExportFormat),
ChooseExportDir,
- ExportDirChosen(Option),
+ /// Folder selection result, tagged with the tab that opened the dialog.
+ ExportDirChosen(usize, Option),
ExportConfirm,
- ExportDone(Result),
+ /// Export result, tagged with the tab that issued the export.
+ ExportDone(usize, Result),
}
diff --git a/dispel-gui/src/editors/tileset/update.rs b/dispel-gui/src/editors/tileset/update.rs
index f882155a..3d0b6d55 100644
--- a/dispel-gui/src/editors/tileset/update.rs
+++ b/dispel-gui/src/editors/tileset/update.rs
@@ -6,7 +6,14 @@ use iced::Task;
use std::path::PathBuf;
pub fn handle(message: TilesetEditorMessage, app: &mut App) -> Task {
- let tab_id = app.state.workspace.active_tab_id().as_usize();
+ // Async results carry their tab id so a result that resolves after a tab
+ // switch still reaches the editor that issued it.
+ let tab_id = match &message {
+ TilesetEditorMessage::ExportDirChosen(id, _) | TilesetEditorMessage::ExportDone(id, _) => {
+ *id
+ }
+ _ => app.state.workspace.active_tab_id().as_usize(),
+ };
let Some(editor) = app.state.editors.tileset_editors.get_mut(&tab_id) else {
return Task::none();
@@ -38,14 +45,14 @@ pub fn handle(message: TilesetEditorMessage, app: &mut App) -> Task {
+ TilesetEditorMessage::ExportDirChosen(_, path) => {
if let Some(ref mut dlg) = editor.export_dialog {
dlg.export_dir = path;
dlg.status = ExportStatus::Idle;
@@ -70,14 +77,14 @@ pub fn handle(message: TilesetEditorMessage, app: &mut App) -> Task {
+ TilesetEditorMessage::ExportDone(_, result) => {
if let Some(ref mut dlg) = editor.export_dialog {
dlg.status = match result {
Ok(msg) => ExportStatus::Done(msg),
diff --git a/dispel-gui/src/tests/common.rs b/dispel-gui/src/tests/common.rs
index 6b4fd5a2..0ac40e19 100644
--- a/dispel-gui/src/tests/common.rs
+++ b/dispel-gui/src/tests/common.rs
@@ -21,6 +21,43 @@ pub(crate) fn app_without_recording() -> App {
App::test_new(Workspace::new())
}
+/// Drain the output messages of a `Task` without an iced runtime.
+/// Async operations made of immediately-ready futures resolve on the first poll.
+#[cfg(feature = "iced_test")]
+pub(crate) fn task_outputs(
+ task: iced::Task