From a970c36c574af66e9ddfac4c0f1e8e2b1e08739f Mon Sep 17 00:00:00 2001 From: crashbashash <109347317+crashbashash@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:26:57 +0000 Subject: [PATCH 1/5] Add a Windows 7 terminal front end - New dw4vhp-tui crate (ratatui/crossterm, ASCII-only, 16 colours): disc check, options, settings files, output path and progress - Move the settings-file format, default output naming and disc refusal notices into core so the desktop app and TUI share them - tools/build-win7-tui.sh cross-builds x86_64-win7-windows-msvc with a static CRT, rejects Windows 8+ imports and zips the exe --- Cargo.lock | 537 ++++++++++++++++++++++++++- Cargo.toml | 2 +- crates/dw4vhp-core/src/error.rs | 13 + crates/dw4vhp-core/src/lib.rs | 2 + crates/dw4vhp-core/src/naming.rs | 76 ++++ crates/dw4vhp-core/src/settings.rs | 137 +++++++ crates/dw4vhp-tauri/src/commands.rs | 65 +--- crates/dw4vhp-tauri/src/settings.rs | 136 +------ crates/dw4vhp-tui/Cargo.toml | 17 + crates/dw4vhp-tui/README.txt | 27 ++ crates/dw4vhp-tui/src/app.rs | 545 ++++++++++++++++++++++++++++ crates/dw4vhp-tui/src/main.rs | 102 ++++++ crates/dw4vhp-tui/src/ui.rs | 294 +++++++++++++++ tools/build-win7-tui.sh | 44 +++ 14 files changed, 1793 insertions(+), 204 deletions(-) create mode 100644 crates/dw4vhp-core/src/naming.rs create mode 100644 crates/dw4vhp-core/src/settings.rs create mode 100644 crates/dw4vhp-tui/Cargo.toml create mode 100644 crates/dw4vhp-tui/README.txt create mode 100644 crates/dw4vhp-tui/src/app.rs create mode 100644 crates/dw4vhp-tui/src/main.rs create mode 100644 crates/dw4vhp-tui/src/ui.rs create mode 100755 tools/build-win7-tui.sh diff --git a/Cargo.lock b/Cargo.lock index c962b85..c57d5af 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + [[package]] name = "bitflags" version = "2.13.2" @@ -17,6 +23,21 @@ dependencies = [ "generic-array", ] +[[package]] +name = "cassowary" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" + +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + [[package]] name = "cc" version = "1.8.0" @@ -35,6 +56,20 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "compact_str" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd622ebbb56a5b2ccb651b32b911cdeb2a9b4b11776b2473bf26a26a286244e" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "static_assertions", +] + [[package]] name = "cpufeatures" version = "0.2.17" @@ -44,6 +79,31 @@ dependencies = [ "libc", ] +[[package]] +name = "crossterm" +version = "0.28.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" +dependencies = [ + "bitflags", + "crossterm_winapi", + "mio", + "parking_lot", + "rustix 0.38.44", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -54,6 +114,40 @@ dependencies = [ "typenum", ] +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.6", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.6", +] + [[package]] name = "digest" version = "0.10.7" @@ -81,6 +175,27 @@ dependencies = [ "zstd", ] +[[package]] +name = "dw4vhp-tui" +version = "0.20.0" +dependencies = [ + "dw4vhp-core", + "getrandom", + "ratatui", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + [[package]] name = "errno" version = "0.3.14" @@ -88,7 +203,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -103,14 +218,20 @@ version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + [[package]] name = "fs4" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e72ed92b67c146290f88e9c89d60ca163ea417a446f61ffd7b72df3e7f1dfd5" dependencies = [ - "rustix", - "windows-sys", + "rustix 1.1.5", + "windows-sys 0.61.2", ] [[package]] @@ -134,6 +255,60 @@ dependencies = [ "r-efi", ] +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "indoc" +version = "2.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a37b2691796cffeb8a8cd305ac66e65841559f147f4e63231d0eafa4db5384d1" +dependencies = [ + "rustversion", +] + +[[package]] +name = "instability" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3b5acc1e2fd9375041a388da33d1eb8aed5f7a8c0dd3543e3ea2805adfbe20" +dependencies = [ + "darling", + "indoc", + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.18" @@ -156,12 +331,42 @@ version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + [[package]] name = "linux-raw-sys" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lru" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" +dependencies = [ + "hashbrown", +] + [[package]] name = "md-5" version = "0.10.6" @@ -187,12 +392,53 @@ dependencies = [ "libc", ] +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + [[package]] name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + [[package]] name = "pkg-config" version = "0.3.34" @@ -223,6 +469,49 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "ratatui" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eabd94c2f37801c20583fc49dd5cd6b0ba68c716787c2dd6ed18571e1e63117b" +dependencies = [ + "bitflags", + "cassowary", + "compact_str", + "crossterm", + "indoc", + "instability", + "itertools", + "lru", + "paste", + "strum", + "unicode-segmentation", + "unicode-truncate", + "unicode-width 0.2.0", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + [[package]] name = "rustix" version = "1.1.5" @@ -232,10 +521,28 @@ dependencies = [ "bitflags", "errno", "libc", - "linux-raw-sys", - "windows-sys", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", ] +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + [[package]] name = "serde" version = "1.0.229" @@ -263,7 +570,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.6", ] [[package]] @@ -296,6 +603,88 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "3.0.6" @@ -316,8 +705,8 @@ dependencies = [ "fastrand", "getrandom", "once_cell", - "rustix", - "windows-sys", + "rustix 1.1.5", + "windows-sys 0.61.2", ] [[package]] @@ -337,7 +726,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.6", ] [[package]] @@ -352,18 +741,84 @@ version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-truncate" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3644627a5af5fa321c95b9b235a72fd24cd29c648c2c379431e6628655627bf" +dependencies = [ + "itertools", + "unicode-segmentation", + "unicode-width 0.1.14", +] + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "unicode-width" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" + [[package]] name = "version_check" version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -373,6 +828,70 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index 520938f..3ee3e1e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "2" -members = ["crates/dw4vhp-core"] +members = ["crates/dw4vhp-core", "crates/dw4vhp-tui"] # webkit2gtk-4.1 is not available in every build environment, and a member that # cannot compile would break the whole workspace gate. CI (or a developer host) # builds this crate in a job that installs the system dependencies. diff --git a/crates/dw4vhp-core/src/error.rs b/crates/dw4vhp-core/src/error.rs index 733afdc..25c7c36 100644 --- a/crates/dw4vhp-core/src/error.rs +++ b/crates/dw4vhp-core/src/error.rs @@ -90,3 +90,16 @@ pub enum Error { } pub type Result = std::result::Result; + +impl Error { + /// The player-facing notice when a chosen disc image is refused. + pub fn disc_notice(&self) -> String { + match self { + Error::AlreadyModded { .. } => "This disc is already modded. Choose a clean, original disc image.".into(), + Error::AlreadyCrownMod { version } => format!("This disc is already Crown Mod v{version}. Choose a clean, original disc image."), + Error::NotThisDisc | Error::FileNotFound { .. } | Error::ElfNotFound => "This file is not a supported disc image, or it is incomplete. Choose a clean Digimon World 4 or Digimon World X disc from a supported release.".into(), + Error::WrongRevision { .. } | Error::CrownData(_) => "This disc image is not a supported original revision. Choose a clean, original copy of a supported release.".into(), + _ => self.to_string(), + } + } +} diff --git a/crates/dw4vhp-core/src/lib.rs b/crates/dw4vhp-core/src/lib.rs index aec7725..49b60c2 100644 --- a/crates/dw4vhp-core/src/lib.rs +++ b/crates/dw4vhp-core/src/lib.rs @@ -11,6 +11,7 @@ mod gc_memory; pub mod gcm; pub mod iso9660; pub mod layout; +pub mod naming; pub mod options; pub mod patch; pub mod plan; @@ -21,6 +22,7 @@ pub mod region; pub mod release; pub mod rowgroup; pub mod serial; +pub mod settings; pub mod signature; pub mod table; pub mod testkit; diff --git a/crates/dw4vhp-core/src/naming.rs b/crates/dw4vhp-core/src/naming.rs new file mode 100644 index 0000000..feccfaa --- /dev/null +++ b/crates/dw4vhp-core/src/naming.rs @@ -0,0 +1,76 @@ +//! The output name a disc image suggests. +use crate::container::{detect, Format}; +use std::path::{Path, PathBuf}; + +/// The marker a patched image's name carries. +pub const OUTPUT_MARKER: &str = " [CrownMod]"; + +/// Same directory, stem plus the marker and optional enemy seed +/// (`game [CrownMod] [Seed 1234].iso`), so the default never targets the input. +/// Compressed containers keep their format; plain GameCube .gcm keeps its suffix too. +pub fn default_output(input: &Path, seed: Option) -> PathBuf { + let mut name = input + .file_stem() + .map(|s| s.to_os_string()) + .unwrap_or_default(); + name.push(OUTPUT_MARKER); + if let Some(seed) = seed { + name.push(format!(" [Seed {seed}]")); + } + let format = detect(input).unwrap_or(Format::Raw); + let extension = match format { + Format::Raw + if input + .extension() + .is_some_and(|ext| ext.eq_ignore_ascii_case("gcm")) => + { + "gcm" + } + _ => format.extension(), + }; + name.push(format!(".{extension}")); + input.with_file_name(name) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn suggested_output_preserves_the_source_container_and_plain_gcm_suffix() { + let dir = tempfile::tempdir().unwrap(); + for (name, magic, suffix) in [ + ("game.iso", b"raw!", "iso"), + ("game.gcm", b"raw!", "gcm"), + ("game.GCM", b"raw!", "gcm"), + ("game.ciso", b"CISO", "ciso"), + ("game.rvz", b"RVZ\x01", "rvz"), + // The output suffix follows the bytes when an input is misnamed. + ("compressed.iso", b"RVZ\x01", "rvz"), + ] { + let input = dir.path().join(name); + std::fs::write(&input, magic).unwrap(); + let output = default_output(&input, None); + assert_eq!(output.parent(), Some(dir.path())); + assert_eq!(output.extension().unwrap(), suffix); + assert!(output + .file_stem() + .unwrap() + .to_str() + .unwrap() + .ends_with(OUTPUT_MARKER)); + assert_ne!(output, input); + } + } + + #[test] + fn suggested_output_names_the_enemy_seed_after_the_marker() { + let dir = tempfile::tempdir().unwrap(); + let input = dir.path().join("game.iso"); + std::fs::write(&input, b"raw!").unwrap(); + assert_eq!( + default_output(&input, Some(1234)), + dir.path().join("game [CrownMod] [Seed 1234].iso") + ); + } +} diff --git a/crates/dw4vhp-core/src/settings.rs b/crates/dw4vhp-core/src/settings.rs new file mode 100644 index 0000000..0dc5fd2 --- /dev/null +++ b/crates/dw4vhp-core/src/settings.rs @@ -0,0 +1,137 @@ +//! Portable settings files: patch options only, never disc or output paths. +use crate::options::PatchSelection; +use serde::{Deserialize, Serialize}; +use std::io::Read; +use std::path::Path; + +const FORMAT: &str = "dw4-crown-mod-settings"; +const VERSION: u32 = 1; +const MAX_BYTES: u64 = 64 * 1024; + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct SettingsFile { + format: String, + version: u32, + settings: PatchSelection, +} + +fn validate(settings: PatchSelection) -> Result { + if settings.crown_drops && !settings.crown_mod { + return Err("Match drops to crowns requires Crown Mod.".into()); + } + if settings.random_bosses && !settings.random_enemies { + return Err("Random bosses requires Random enemies.".into()); + } + if settings.random_enemies && settings.enemy_seed.is_none() { + return Err("Random enemies requires a valid seed.".into()); + } + Ok(settings) +} + +/// The settings file text for `settings`, refusing dependent options without their parent. +pub fn encode(settings: PatchSelection) -> Result { + let file = SettingsFile { + format: FORMAT.into(), + version: VERSION, + settings: validate(settings)?, + }; + serde_json::to_string_pretty(&file) + .map(|json| json + "\n") + .map_err(|error| format!("Unable to encode settings: {error}")) +} + +/// Reads and validates a settings file, with player-facing error messages. +pub fn read(path: &Path) -> Result { + let mut bytes = Vec::new(); + std::fs::File::open(path) + .and_then(|file| file.take(MAX_BYTES + 1).read_to_end(&mut bytes)) + .map_err(|_| "Unable to read the settings file.".to_string())?; + if bytes.len() as u64 > MAX_BYTES { + return Err("The settings file is too large.".into()); + } + let file: SettingsFile = serde_json::from_slice(&bytes) + .map_err(|_| "Invalid settings file. Choose a Crown Mod settings JSON file.".to_string())?; + if file.format != FORMAT { + return Err("This is not a Crown Mod settings file.".into()); + } + if file.version != VERSION { + return Err( + "This settings file uses an unsupported version. Update Crown Mod and try again." + .into(), + ); + } + validate(file.settings) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn settings_round_trip_preserves_all_options_and_seed_without_paths() { + let selection = PatchSelection { + crown_mod: true, + crown_drops: true, + four_player_spawns: true, + random_crown_colours: true, + random_enemies: true, + random_bosses: true, + enemy_seed: Some(u32::MAX), + solo_buttons: true, + fix_death_softlock: true, + }; + let encoded = encode(selection).unwrap(); + let value: serde_json::Value = serde_json::from_str(&encoded).unwrap(); + assert_eq!( + value, + json!({"format": FORMAT, "version": VERSION, "settings": selection}) + ); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("settings.json"); + std::fs::write(&path, encoded).unwrap(); + assert_eq!(read(&path).unwrap(), selection); + assert!(encode(PatchSelection::default()).is_ok()); + } + + #[test] + fn bad_imports_are_rejected_including_paths_and_invalid_dependencies() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("settings.json"); + for value in [ + json!({"format": FORMAT, "version": 2, "settings": {}}), + json!({"format": "another-app", "version": 1, "settings": {}}), + json!({"format": FORMAT, "version": 1, "settings": {"crownMod": "true"}}), + json!({"format": FORMAT, "version": 1, "settings": {"enemySeed": 4294967296u64}}), + json!({"format": FORMAT, "version": 1, "settings": {"randomEnemies": true}}), + json!({"format": FORMAT, "version": 1, "settings": {"randomBosses": true}}), + json!({"format": FORMAT, "version": 1, "settings": {"crownDrops": true}}), + json!({"format": FORMAT, "version": 1, "settings": {"inputPath": "game.iso"}}), + json!({"format": FORMAT, "version": 1, "settings": {}, "outputPath": "out.iso"}), + ] { + std::fs::write(&path, value.to_string()).unwrap(); + assert!(read(&path).is_err(), "{value}"); + } + std::fs::write(&path, "not json").unwrap(); + assert!(read(&path).is_err()); + std::fs::write(&path, vec![b' '; MAX_BYTES as usize + 1]).unwrap(); + assert!(read(&path).unwrap_err().contains("too large")); + } + + #[test] + fn older_settings_leave_bosses_disabled() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("settings.json"); + std::fs::write( + &path, + json!({"format": FORMAT, "version": 1, + "settings": {"randomEnemies": true, "enemySeed": 1520}}) + .to_string(), + ) + .unwrap(); + let settings = read(&path).unwrap(); + assert!(settings.random_enemies); + assert!(!settings.random_bosses); + } +} diff --git a/crates/dw4vhp-tauri/src/commands.rs b/crates/dw4vhp-tauri/src/commands.rs index 8068a18..df2278a 100644 --- a/crates/dw4vhp-tauri/src/commands.rs +++ b/crates/dw4vhp-tauri/src/commands.rs @@ -19,9 +19,6 @@ use serde::Serialize; use std::sync::atomic::Ordering; use tauri::{AppHandle, Emitter, Manager}; -/// The marker a patched image's name carries (old `form::OUTPUT_SUFFIX`). -const OUTPUT_MARKER: &str = " [CrownMod]"; - #[derive(Serialize, Clone)] #[serde(rename_all = "camelCase")] pub struct DiscStatusPayload { @@ -200,31 +197,12 @@ pub async fn choose_output(window: tauri::Window, default_name: String) -> Optio .flatten() } -/// The output name an input suggests: same directory, stem plus the marker -/// (old `form::default_output_path`), so the default never targets the input. +/// The output name an input suggests; see [`dw4vhp_core::naming::default_output`]. #[tauri::command] pub fn default_output(input: String) -> String { - let input = std::path::Path::new(&input); - let mut name = input - .file_stem() - .map(|s| s.to_os_string()) - .unwrap_or_default(); - name.push(OUTPUT_MARKER); - // Compressed containers keep their format; plain GameCube .gcm keeps its suffix too. - let format = - dw4vhp_core::container::detect(input).unwrap_or(dw4vhp_core::container::Format::Raw); - let extension = match format { - dw4vhp_core::container::Format::Raw - if input - .extension() - .is_some_and(|ext| ext.eq_ignore_ascii_case("gcm")) => - { - "gcm" - } - _ => format.extension(), - }; - name.push(format!(".{extension}")); - input.with_file_name(name).display().to_string() + dw4vhp_core::naming::default_output(std::path::Path::new(&input), None) + .display() + .to_string() } /// Checks whether patching needs the user's overwrite confirmation. @@ -266,13 +244,7 @@ fn verdict(result: &Result) -> DiscStatusPayload { _ => "unknown", }, reason: matches!(error, Error::AlreadyModded { .. } | Error::AlreadyCrownMod { .. }).then_some("already-modded"), - text: match error { - Error::AlreadyModded { .. } => "This disc is already modded. Choose a clean, original disc image.".into(), - Error::AlreadyCrownMod { version } => format!("This disc is already Crown Mod v{version}. Choose a clean, original disc image."), - Error::NotThisDisc | Error::FileNotFound { .. } | Error::ElfNotFound => "This file is not a supported disc image, or it is incomplete. Choose a clean Digimon World 4 or Digimon World X disc from a supported release.".into(), - Error::WrongRevision { .. } | Error::CrownData(_) => "This disc image is not a supported original revision. Choose a clean, original copy of a supported release.".into(), - _ => error.to_string(), - }, + text: error.disc_notice(), mod_metadata: None, disc_info: None, size: 0, @@ -561,33 +533,6 @@ fn phase_name(phase: dw4vhp_core::writer::Phase) -> &'static str { #[cfg(test)] mod tests { use super::*; - #[test] - fn suggested_output_preserves_the_source_container_and_plain_gcm_suffix() { - let dir = tempfile::tempdir().unwrap(); - for (name, magic, suffix) in [ - ("game.iso", b"raw!", "iso"), - ("game.gcm", b"raw!", "gcm"), - ("game.GCM", b"raw!", "gcm"), - ("game.ciso", b"CISO", "ciso"), - ("game.rvz", b"RVZ\x01", "rvz"), - // The output suffix follows the bytes when an input is misnamed. - ("compressed.iso", b"RVZ\x01", "rvz"), - ] { - let input = dir.path().join(name); - std::fs::write(&input, magic).unwrap(); - let output = std::path::PathBuf::from(default_output(input.display().to_string())); - assert_eq!(output.parent(), Some(dir.path())); - assert_eq!(output.extension().unwrap(), suffix); - assert!(output - .file_stem() - .unwrap() - .to_str() - .unwrap() - .ends_with(OUTPUT_MARKER)); - assert_ne!(output, input); - } - } - #[test] fn an_updated_image_name_follows_its_new_seed() { use std::path::{Path, PathBuf}; diff --git a/crates/dw4vhp-tauri/src/settings.rs b/crates/dw4vhp-tauri/src/settings.rs index b639cf2..60a053e 100644 --- a/crates/dw4vhp-tauri/src/settings.rs +++ b/crates/dw4vhp-tauri/src/settings.rs @@ -1,68 +1,8 @@ -//! Portable settings contain patch options only, never disc or output paths. +//! Settings file dialogs; the file format lives in `dw4vhp_core::settings`. use dw4vhp_core::options::PatchSelection; -use serde::{Deserialize, Serialize}; -use std::io::Read; -use std::path::Path; +use dw4vhp_core::settings::{encode, read}; use tauri_plugin_dialog::DialogExt; -const FORMAT: &str = "dw4-crown-mod-settings"; -const VERSION: u32 = 1; -const MAX_BYTES: u64 = 64 * 1024; - -#[derive(Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct SettingsFile { - format: String, - version: u32, - settings: PatchSelection, -} - -fn validate(settings: PatchSelection) -> Result { - if settings.crown_drops && !settings.crown_mod { - return Err("Match drops to crowns requires Crown Mod.".into()); - } - if settings.random_bosses && !settings.random_enemies { - return Err("Random bosses requires Random enemies.".into()); - } - if settings.random_enemies && settings.enemy_seed.is_none() { - return Err("Random enemies requires a valid seed.".into()); - } - Ok(settings) -} - -fn encode(settings: PatchSelection) -> Result { - let file = SettingsFile { - format: FORMAT.into(), - version: VERSION, - settings: validate(settings)?, - }; - serde_json::to_string_pretty(&file) - .map(|json| json + "\n") - .map_err(|error| format!("Unable to encode settings: {error}")) -} - -fn read(path: &Path) -> Result { - let mut bytes = Vec::new(); - std::fs::File::open(path) - .and_then(|file| file.take(MAX_BYTES + 1).read_to_end(&mut bytes)) - .map_err(|_| "Unable to read the settings file.".to_string())?; - if bytes.len() as u64 > MAX_BYTES { - return Err("The settings file is too large.".into()); - } - let file: SettingsFile = serde_json::from_slice(&bytes) - .map_err(|_| "Invalid settings file. Choose a Crown Mod settings JSON file.".to_string())?; - if file.format != FORMAT { - return Err("This is not a Crown Mod settings file.".into()); - } - if file.version != VERSION { - return Err( - "This settings file uses an unsupported version. Update Crown Mod and try again." - .into(), - ); - } - validate(file.settings) -} - #[tauri::command] pub async fn import_settings(window: tauri::Window) -> Result, String> { tauri::async_runtime::spawn_blocking(move || { @@ -116,75 +56,3 @@ pub async fn export_settings( .await .map_err(|_| "Unable to open the settings dialog.".to_string())? } - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn settings_round_trip_preserves_all_options_and_seed_without_paths() { - let selection = PatchSelection { - crown_mod: true, - crown_drops: true, - four_player_spawns: true, - random_crown_colours: true, - random_enemies: true, - random_bosses: true, - enemy_seed: Some(u32::MAX), - solo_buttons: true, - fix_death_softlock: true, - }; - let encoded = encode(selection).unwrap(); - let value: serde_json::Value = serde_json::from_str(&encoded).unwrap(); - assert_eq!( - value, - json!({"format": FORMAT, "version": VERSION, "settings": selection}) - ); - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("settings.json"); - std::fs::write(&path, encoded).unwrap(); - assert_eq!(read(&path).unwrap(), selection); - assert!(encode(PatchSelection::default()).is_ok()); - } - - #[test] - fn bad_imports_are_rejected_including_paths_and_invalid_dependencies() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("settings.json"); - for value in [ - json!({"format": FORMAT, "version": 2, "settings": {}}), - json!({"format": "another-app", "version": 1, "settings": {}}), - json!({"format": FORMAT, "version": 1, "settings": {"crownMod": "true"}}), - json!({"format": FORMAT, "version": 1, "settings": {"enemySeed": 4294967296u64}}), - json!({"format": FORMAT, "version": 1, "settings": {"randomEnemies": true}}), - json!({"format": FORMAT, "version": 1, "settings": {"randomBosses": true}}), - json!({"format": FORMAT, "version": 1, "settings": {"crownDrops": true}}), - json!({"format": FORMAT, "version": 1, "settings": {"inputPath": "game.iso"}}), - json!({"format": FORMAT, "version": 1, "settings": {}, "outputPath": "out.iso"}), - ] { - std::fs::write(&path, value.to_string()).unwrap(); - assert!(read(&path).is_err(), "{value}"); - } - std::fs::write(&path, "not json").unwrap(); - assert!(read(&path).is_err()); - std::fs::write(&path, vec![b' '; MAX_BYTES as usize + 1]).unwrap(); - assert!(read(&path).unwrap_err().contains("too large")); - } - - #[test] - fn older_settings_leave_bosses_disabled() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("settings.json"); - std::fs::write( - &path, - json!({"format": FORMAT, "version": 1, - "settings": {"randomEnemies": true, "enemySeed": 1520}}) - .to_string(), - ) - .unwrap(); - let settings = read(&path).unwrap(); - assert!(settings.random_enemies); - assert!(!settings.random_bosses); - } -} diff --git a/crates/dw4vhp-tui/Cargo.toml b/crates/dw4vhp-tui/Cargo.toml new file mode 100644 index 0000000..98c3650 --- /dev/null +++ b/crates/dw4vhp-tui/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "dw4vhp-tui" +version = "0.20.0" +edition = "2021" +license = "GPL-3.0-or-later" +description = "Terminal front end for the Digimon World 4 Crown Mod ISO patcher" + +[[bin]] +name = "dw4-crown-mod-tui" +path = "src/main.rs" + +[dependencies] +dw4vhp-core = { path = "../dw4vhp-core" } +getrandom = "0.4" +# The legacy Windows console (Windows 7) has no ANSI support; crossterm falls back +# to the console API there, which cannot set underline colours. +ratatui = { version = "0.29", default-features = false, features = ["crossterm"] } diff --git a/crates/dw4vhp-tui/README.txt b/crates/dw4vhp-tui/README.txt new file mode 100644 index 0000000..b59203c --- /dev/null +++ b/crates/dw4vhp-tui/README.txt @@ -0,0 +1,27 @@ +DW4 Crown Mod - terminal version for Windows 7 and later +========================================================= + +This is the same patcher as the desktop app, in a console window. It runs on +Windows 7 SP1 64-bit and later and needs nothing else installed. + +Starting + - Double-click dw4-crown-mod-tui.exe, or + - drag your disc image onto dw4-crown-mod-tui.exe to start with it chosen. + +Choosing your disc + Type the path to your clean, original disc image (.iso, .gcm, .ciso or .rvz) + and press Enter. You can also drag the file onto the console window, or + right-click in the window and choose Paste. + +Keys + Up/Down move between options + Space turn the highlighted option on or off + Enter continue + Esc go back + L / S load or save a settings file (shared with the desktop app) + R new enemy seed (when the seed is highlighted) + Ctrl+U clear a text field + +Your original disc image is never changed. The patched game is written next to +it unless you choose another path. Random enemies can take several minutes; +keep the window open until it says Done. diff --git a/crates/dw4vhp-tui/src/app.rs b/crates/dw4vhp-tui/src/app.rs new file mode 100644 index 0000000..2976c2f --- /dev/null +++ b/crates/dw4vhp-tui/src/app.rs @@ -0,0 +1,545 @@ +//! Screen state and key handling. The main loop performs the returned [`Action`]s. +use dw4vhp_core::options::PatchSelection; +use dw4vhp_core::patch::PatchOutcome; +use dw4vhp_core::writer::{Phase, Progress}; +use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; +use std::path::{Path, PathBuf}; +use std::time::Instant; + +/// Results from worker threads. +pub enum Msg { + /// The disc label, or the notice explaining why it was refused. + Checked(Result), + Progress(Progress), + Finished(Result), +} + +/// Work for the main loop. +pub enum Action { + None, + Quit, + Check(PathBuf), + Patch { + input: PathBuf, + output: PathBuf, + selection: PatchSelection, + overwrite: bool, + }, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Screen { + Disc, + Options, + Output, + Patching, + Done, + Failed, +} + +/// A question that takes over the keyboard until answered. +pub enum Prompt { + Load(String), + Save(String), + Overwrite, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Opt { + FourPlayerSpawns, + RandomEnemies, + RandomBosses, + EnemySeed, + SoloButtons, + CrownMod, + CrownDrops, + RandomCrownColours, + FixDeathSoftlock, +} + +impl Opt { + pub fn title(self) -> &'static str { + match self { + Opt::FourPlayerSpawns => "4-player enemy spawns", + Opt::RandomEnemies => "Random enemies (experimental)", + Opt::RandomBosses => "Random bosses", + Opt::EnemySeed => "Enemy seed", + Opt::SoloButtons => "Solo co-op buttons", + Opt::CrownMod => "Crown Mod", + Opt::CrownDrops => "Match drops to crowns", + Opt::RandomCrownColours => "Random crown colours", + Opt::FixDeathSoftlock => "Fix death softlock", + } + } + + pub fn description(self) -> &'static str { + match self { + Opt::FourPlayerSpawns => "Spawn the same number of enemies as four-player mode.", + Opt::RandomEnemies => "Different regular enemies on each difficulty, with matching stats. Protected encounters stay intact.", + Opt::RandomBosses => "Shuffle every boss except the four world bosses.", + Opt::EnemySeed => "The same seed on the same version gives the same game. Type digits, or press R for a new seed.", + Opt::SoloButtons => "In single player, a pressed two-player button stays down until you press its partner.", + Opt::CrownMod => "Stronger enemies, increased EXP rewards and crowns for every enemy.", + Opt::CrownDrops => "Improve enemy drops for the increased difficulty.", + Opt::RandomCrownColours => "Give every enemy and boss a random crown colour.", + Opt::FixDeathSoftlock => "Dying before your first death tutorial has played (for example after entering Goblin Fortress early) no longer freezes the game.", + } + } + + /// Sub-options are indented under their parent. + pub fn nested(self) -> bool { + matches!(self, Opt::RandomBosses | Opt::EnemySeed | Opt::CrownDrops) + } +} + +pub enum Row { + Header(&'static str), + Item(Opt), +} + +/// The largest seed the desktop app accepts. +const SEED_DIGITS: usize = 10; + +pub struct App { + pub screen: Screen, + pub disc_field: String, + /// The checked disc and its label. + pub disc: Option<(PathBuf, String)>, + pub checking: bool, + pub selection: PatchSelection, + pub seed_text: String, + pub cursor: usize, + pub output_field: String, + /// The output name last suggested, replaced on return unless the player edited it. + suggested: String, + pub prompt: Option, + /// A one-line message for the current screen; `true` marks an error. + pub notice: Option<(String, bool)>, + pub progress: Option, + pub started: Instant, + pub outcome: Option<(PathBuf, PatchOutcome, Option)>, + pub failure: String, + pending_output: PathBuf, +} + +impl App { + pub fn new() -> Self { + Self { + screen: Screen::Disc, + disc_field: String::new(), + disc: None, + checking: false, + selection: PatchSelection::default(), + seed_text: String::new(), + cursor: 0, + output_field: String::new(), + suggested: String::new(), + prompt: None, + notice: None, + progress: None, + started: Instant::now(), + outcome: None, + failure: String::new(), + pending_output: PathBuf::new(), + } + } + + /// Starts checking `path` as if it had been typed on the disc screen. + pub fn open(&mut self, path: &Path) -> Action { + self.disc_field = path.display().to_string(); + self.check() + } + + pub fn rows(&self) -> Vec { + let s = &self.selection; + let mut rows = vec![Row::Header("Gameplay"), Row::Item(Opt::FourPlayerSpawns)]; + rows.push(Row::Item(Opt::RandomEnemies)); + if s.random_enemies { + rows.extend([Row::Item(Opt::RandomBosses), Row::Item(Opt::EnemySeed)]); + } + rows.extend([ + Row::Item(Opt::SoloButtons), + Row::Header("Balance"), + Row::Item(Opt::CrownMod), + ]); + if s.crown_mod { + rows.push(Row::Item(Opt::CrownDrops)); + } + rows.extend([ + Row::Header("Cosmetics"), + Row::Item(Opt::RandomCrownColours), + Row::Header("Bugfixes"), + Row::Item(Opt::FixDeathSoftlock), + ]); + rows + } + + pub fn items(&self) -> Vec { + self.rows() + .into_iter() + .filter_map(|row| match row { + Row::Item(opt) => Some(opt), + Row::Header(_) => None, + }) + .collect() + } + + pub fn current(&self) -> Opt { + let items = self.items(); + items[self.cursor.min(items.len() - 1)] + } + + pub fn enabled(&self, opt: Opt) -> bool { + let s = &self.selection; + match opt { + Opt::FourPlayerSpawns => s.four_player_spawns, + Opt::RandomEnemies => s.random_enemies, + Opt::RandomBosses => s.random_bosses, + Opt::EnemySeed => true, + Opt::SoloButtons => s.solo_buttons, + Opt::CrownMod => s.crown_mod, + Opt::CrownDrops => s.crown_drops, + Opt::RandomCrownColours => s.random_crown_colours, + Opt::FixDeathSoftlock => s.fix_death_softlock, + } + } + + fn toggle(&mut self, opt: Opt) { + let s = &mut self.selection; + match opt { + Opt::FourPlayerSpawns => s.four_player_spawns ^= true, + Opt::RandomEnemies => { + s.random_enemies ^= true; + if !s.random_enemies { + s.random_bosses = false; + } else if parse_seed(&self.seed_text).is_none() { + self.seed_text = new_seed(); + } + } + Opt::RandomBosses => s.random_bosses ^= true, + Opt::EnemySeed => {} + Opt::SoloButtons => s.solo_buttons ^= true, + Opt::CrownMod => { + s.crown_mod ^= true; + if !s.crown_mod { + s.crown_drops = false; + } + } + Opt::CrownDrops => s.crown_drops ^= true, + Opt::RandomCrownColours => s.random_crown_colours ^= true, + Opt::FixDeathSoftlock => s.fix_death_softlock ^= true, + } + self.cursor = self.cursor.min(self.items().len() - 1); + } + + /// The selection the patch will use, with the typed seed when enemies are random. + pub fn patch_selection(&self) -> PatchSelection { + PatchSelection { + enemy_seed: parse_seed(&self.seed_text).filter(|_| self.selection.random_enemies), + ..self.selection + } + } + + fn settings_path(&self) -> String { + let dir = self + .disc + .as_ref() + .and_then(|(path, _)| path.parent()) + .map(Path::to_path_buf) + .unwrap_or_default(); + dir.join("crown-mod-settings.json").display().to_string() + } + + pub fn receive(&mut self, msg: Msg) { + match msg { + Msg::Checked(result) => { + self.checking = false; + match result { + Ok(label) => { + let path = PathBuf::from(clean_path(&self.disc_field)); + self.disc = Some((path, label)); + self.notice = None; + self.screen = Screen::Options; + } + Err(notice) => self.notice = Some((notice, true)), + } + } + Msg::Progress(progress) => self.progress = Some(progress), + Msg::Finished(Ok(outcome)) => { + let seed = self.patch_selection().enemy_seed; + self.outcome = Some((std::mem::take(&mut self.pending_output), outcome, seed)); + self.screen = Screen::Done; + } + Msg::Finished(Err(error)) => { + self.failure = error; + self.screen = Screen::Failed; + } + } + } + + pub fn key(&mut self, key: KeyEvent) -> Action { + let ctrl = key.modifiers.contains(KeyModifiers::CONTROL); + if ctrl && key.code == KeyCode::Char('c') && self.screen != Screen::Patching { + return Action::Quit; + } + if let Some(prompt) = self.prompt.take() { + return self.prompt_key(prompt, key); + } + match self.screen { + Screen::Disc => self.disc_key(key), + Screen::Options => self.options_key(key), + Screen::Output => self.output_key(key), + Screen::Patching => Action::None, + Screen::Done => match key.code { + KeyCode::Enter | KeyCode::Esc => Action::Quit, + _ => Action::None, + }, + Screen::Failed => { + if matches!(key.code, KeyCode::Enter | KeyCode::Esc) { + self.screen = Screen::Options; + } + Action::None + } + } + } + + fn check(&mut self) -> Action { + let path = clean_path(&self.disc_field); + if path.is_empty() { + self.notice = Some(("Enter the path to your disc image.".into(), true)); + return Action::None; + } + self.checking = true; + self.notice = None; + Action::Check(PathBuf::from(path)) + } + + fn disc_key(&mut self, key: KeyEvent) -> Action { + if self.checking { + return Action::None; + } + match key.code { + KeyCode::Enter => self.check(), + KeyCode::Esc => Action::Quit, + _ => { + edit(&mut self.disc_field, key); + Action::None + } + } + } + + fn options_key(&mut self, key: KeyEvent) -> Action { + let items = self.items().len(); + let current = self.current(); + self.notice = None; + match key.code { + KeyCode::Up => self.cursor = self.cursor.checked_sub(1).unwrap_or(items - 1), + KeyCode::Down | KeyCode::Tab => self.cursor = (self.cursor + 1) % items, + KeyCode::Char(' ') => self.toggle(current), + KeyCode::Esc => { + self.screen = Screen::Disc; + } + KeyCode::Enter => self.continue_to_output(), + KeyCode::Char(c) if current == Opt::EnemySeed && c.is_ascii_digit() => { + if self.seed_text.len() < SEED_DIGITS { + self.seed_text.push(c); + } + } + KeyCode::Backspace if current == Opt::EnemySeed => { + self.seed_text.pop(); + } + KeyCode::Char('r' | 'R') if current == Opt::EnemySeed => self.seed_text = new_seed(), + KeyCode::Char('l' | 'L') => self.prompt = Some(Prompt::Load(self.settings_path())), + KeyCode::Char('s' | 'S') => self.prompt = Some(Prompt::Save(self.settings_path())), + _ => {} + } + Action::None + } + + fn continue_to_output(&mut self) { + let selection = self.patch_selection(); + if selection.random_enemies && selection.enemy_seed.is_none() { + self.notice = Some(("Enter an enemy seed from 0 to 4294967295.".into(), true)); + return; + } + if let Err(error) = selection.into_plan() { + self.notice = Some((error.into(), true)); + return; + } + let Some((input, _)) = &self.disc else { + return; + }; + let suggestion = dw4vhp_core::naming::default_output(input, selection.enemy_seed) + .display() + .to_string(); + if self.output_field.is_empty() || self.output_field == self.suggested { + self.output_field = suggestion.clone(); + } + self.suggested = suggestion; + self.screen = Screen::Output; + } + + fn output_key(&mut self, key: KeyEvent) -> Action { + self.notice = None; + match key.code { + KeyCode::Esc => { + self.screen = Screen::Options; + Action::None + } + KeyCode::Enter => { + let output = PathBuf::from(clean_path(&self.output_field)); + if output.as_os_str().is_empty() { + self.notice = Some(("Enter where to save the patched game.".into(), true)); + return Action::None; + } + match output.try_exists() { + Ok(true) => { + self.prompt = Some(Prompt::Overwrite); + Action::None + } + Ok(false) => self.start(false), + Err(error) => { + self.notice = Some((error.to_string(), true)); + Action::None + } + } + } + _ => { + edit(&mut self.output_field, key); + Action::None + } + } + } + + fn start(&mut self, overwrite: bool) -> Action { + let Some((input, _)) = &self.disc else { + return Action::None; + }; + let output = PathBuf::from(clean_path(&self.output_field)); + self.pending_output = output.clone(); + self.progress = None; + self.started = Instant::now(); + self.screen = Screen::Patching; + Action::Patch { + input: input.clone(), + output, + selection: self.patch_selection(), + overwrite, + } + } + + fn prompt_key(&mut self, prompt: Prompt, key: KeyEvent) -> Action { + match (prompt, key.code) { + (Prompt::Overwrite, KeyCode::Char('y' | 'Y')) => return self.start(true), + (Prompt::Overwrite, KeyCode::Char('n' | 'N') | KeyCode::Esc) => {} + (Prompt::Overwrite, _) => self.prompt = Some(Prompt::Overwrite), + (Prompt::Load(_) | Prompt::Save(_), KeyCode::Esc) => {} + (Prompt::Load(field), KeyCode::Enter) => self.load(&field), + (Prompt::Save(field), KeyCode::Enter) => self.save(&field), + (Prompt::Load(mut field), _) => { + edit(&mut field, key); + self.prompt = Some(Prompt::Load(field)); + } + (Prompt::Save(mut field), _) => { + edit(&mut field, key); + self.prompt = Some(Prompt::Save(field)); + } + } + Action::None + } + + fn load(&mut self, field: &str) { + match dw4vhp_core::settings::read(Path::new(&clean_path(field))) { + Ok(selection) => { + self.selection = PatchSelection { + enemy_seed: None, + ..selection + }; + self.seed_text = selection.enemy_seed.map(|s| s.to_string()).unwrap_or_default(); + self.cursor = self.cursor.min(self.items().len() - 1); + self.notice = Some(("Settings loaded.".into(), false)); + } + Err(error) => self.notice = Some((error, true)), + } + } + + fn save(&mut self, field: &str) { + let path = PathBuf::from(clean_path(field)); + if !path + .extension() + .is_some_and(|ext| ext.eq_ignore_ascii_case("json")) + { + self.notice = Some(("Save settings with a .json extension.".into(), true)); + return; + } + let result = dw4vhp_core::settings::encode(self.patch_selection()).and_then(|json| { + std::fs::write(&path, json).map_err(|_| "Unable to save the settings file.".to_string()) + }); + self.notice = Some(match result { + Ok(()) => (format!("Settings saved to {}", path.display()), false), + Err(error) => (error, true), + }); + } +} + +/// Typing, Backspace and Ctrl+U (clear) for a text field. +fn edit(field: &mut String, key: KeyEvent) { + let ctrl = key.modifiers.contains(KeyModifiers::CONTROL); + // AltGr arrives as Ctrl+Alt on Windows and still types a character. + let alt = key.modifiers.contains(KeyModifiers::ALT); + match key.code { + KeyCode::Char('u') if ctrl && !alt => field.clear(), + KeyCode::Char(c) if !ctrl || alt => field.push(c), + KeyCode::Backspace => { + field.pop(); + } + _ => {} + } +} + +/// Paths dropped onto a console window arrive quoted when they contain spaces. +pub fn clean_path(text: &str) -> String { + let text = text.trim(); + text.strip_prefix('"') + .and_then(|t| t.strip_suffix('"')) + .unwrap_or(text) + .to_string() +} + +fn parse_seed(text: &str) -> Option { + let text = text.trim(); + if text.is_empty() || text.len() > SEED_DIGITS || !text.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + text.parse().ok() +} + +fn new_seed() -> String { + getrandom::u32().unwrap_or_default().to_string() +} + +/// The step under way, matching the desktop app's wording. +pub fn phase_label(phase: Phase) -> String { + match phase { + Phase::Inspecting => "Checking your disc...".into(), + Phase::Unpacking => "Unpacking the disc image...".into(), + Phase::Restoring => "Restoring the original game files...".into(), + Phase::Building => "Preparing game files...".into(), + Phase::RandomisingEnemies { area, areas } => { + format!("Randomising enemies: area {area} of {areas}...") + } + Phase::RandomisingBosses { difficulty } => format!( + "Randomising bosses: {}...", + match difficulty { + 0 => "Normal", + 1 => "Hard", + _ => "Very Hard", + } + ), + Phase::Recording => "Saving update data...".into(), + Phase::Copying => "Copying game files...".into(), + Phase::Writing | Phase::Extending => "Writing your new game...".into(), + Phase::Packing => "Compressing the disc image...".into(), + Phase::Verifying | Phase::Hashing => "Verifying your new game...".into(), + } +} diff --git a/crates/dw4vhp-tui/src/main.rs b/crates/dw4vhp-tui/src/main.rs new file mode 100644 index 0000000..d32cf34 --- /dev/null +++ b/crates/dw4vhp-tui/src/main.rs @@ -0,0 +1,102 @@ +//! Terminal front end for consoles without the desktop app's WebView, such as +//! Windows 7. Pass a disc image path (or drop one onto the executable) to start +//! with it checked. +mod app; +mod ui; + +use app::{Action, App, Msg}; +use dw4vhp_core::disc::inspect_retail_for_plan; +use dw4vhp_core::options::PatchSelection; +use dw4vhp_core::patch::{patch_file, PatchOptions}; +use ratatui::crossterm::event::{self, Event, KeyEventKind}; +use ratatui::DefaultTerminal; +use std::path::PathBuf; +use std::sync::mpsc::{channel, Receiver, Sender}; +use std::time::Duration; + +fn main() -> std::io::Result<()> { + let initial = std::env::args_os().nth(1).map(PathBuf::from); + // crossterm writes ANSI escapes whenever TERM is set, even when the console + // refused virtual-terminal mode. The Windows 7 console always refuses it and + // would print the escapes as text, so let only the console decide. + #[cfg(windows)] + std::env::remove_var("TERM"); + let mut terminal = ratatui::try_init()?; + let result = run(&mut terminal, initial); + ratatui::restore(); + result +} + +fn run(terminal: &mut DefaultTerminal, initial: Option) -> std::io::Result<()> { + let (tx, rx): (Sender, Receiver) = channel(); + let mut app = App::new(); + if let Some(path) = initial { + let action = app.open(&path); + perform(action, &tx); + } + loop { + terminal.draw(|frame| ui::draw(frame, &app))?; + // Redraw at most ten times a second: the Windows 7 console API is slow. + if event::poll(Duration::from_millis(100))? { + // Windows reports key releases too; act on presses only. + if let Event::Key(key) = event::read()? { + if key.kind != KeyEventKind::Release { + match app.key(key) { + Action::Quit => return Ok(()), + action => perform(action, &tx), + } + } + } + } + while let Ok(msg) = rx.try_recv() { + app.receive(msg); + } + } +} + +fn perform(action: Action, tx: &Sender) { + let tx = tx.clone(); + match action { + Action::None | Action::Quit => {} + Action::Check(path) => { + std::thread::spawn(move || { + let plan = PatchSelection::default().analysis_plan(); + let result = inspect_retail_for_plan(&path, &plan) + .map_err(|error| error.disc_notice()) + .and_then(|report| { + let release = report.release.ok_or_else(|| { + dw4vhp_core::error::Error::NotThisDisc.disc_notice() + })?; + Ok(format!("{} - {}", release.label(), release.serial())) + }); + let _ = tx.send(Msg::Checked(result)); + }); + } + Action::Patch { + input, + output, + selection, + overwrite, + } => { + std::thread::spawn(move || { + let result = selection + .into_plan() + .map_err(str::to_owned) + .and_then(|plan| { + let progress_tx = tx.clone(); + patch_file( + &input, + &output, + &plan, + &PatchOptions { overwrite }, + &mut |p| { + let _ = progress_tx.send(Msg::Progress(p)); + }, + ) + .map_err(|error| error.to_string()) + }); + let _ = tx.send(Msg::Finished(result)); + }); + } + } +} diff --git a/crates/dw4vhp-tui/src/ui.rs b/crates/dw4vhp-tui/src/ui.rs new file mode 100644 index 0000000..23d3dbe --- /dev/null +++ b/crates/dw4vhp-tui/src/ui.rs @@ -0,0 +1,294 @@ +//! Drawing. Windows 7's console only renders 16 colours, ignores text attributes +//! and its raster font may lack box-drawing glyphs, so everything here uses ASCII +//! and named colours only. +use crate::app::{phase_label, App, Prompt, Row, Screen}; +use ratatui::layout::{Constraint, Layout, Rect}; +use ratatui::style::{Color, Style}; +use ratatui::symbols::border; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Block, Borders, Paragraph, Wrap}; +use ratatui::Frame; + +const ASCII: border::Set = border::Set { + top_left: "+", + top_right: "+", + bottom_left: "+", + bottom_right: "+", + vertical_left: "|", + vertical_right: "|", + horizontal_top: "-", + horizontal_bottom: "-", +}; + +const ACCENT: Color = Color::Yellow; +const MUTED: Color = Color::Gray; +const ERROR: Color = Color::LightRed; +const OK: Color = Color::LightGreen; + +pub fn draw(frame: &mut Frame, app: &App) { + let [main, footer] = + Layout::vertical([Constraint::Min(0), Constraint::Length(1)]).areas(frame.area()); + let block = Block::default() + .borders(Borders::ALL) + .border_set(ASCII) + .title(format!(" DW4 Crown Mod {} ", env!("CARGO_PKG_VERSION"))) + .title_style(Style::default().fg(ACCENT)); + let inner = block.inner(main); + frame.render_widget(block, main); + let [header, body] = + Layout::vertical([Constraint::Length(2), Constraint::Min(0)]).areas(inner); + let disc = match &app.disc { + Some((_, label)) => Line::from(vec![ + Span::styled(" Disc: ", Style::default().fg(MUTED)), + Span::raw(label.as_str()), + ]), + None => Line::styled(" No disc chosen yet", Style::default().fg(MUTED)), + }; + frame.render_widget(Paragraph::new(disc), header); + match app.screen { + Screen::Disc => disc_screen(frame, app, body), + Screen::Options => options_screen(frame, app, body), + Screen::Output => output_screen(frame, app, body), + Screen::Patching => patching_screen(frame, app, body), + Screen::Done => done_screen(frame, app, body), + Screen::Failed => failed_screen(frame, app, body), + } + frame.render_widget( + Paragraph::new(keys(app)).style(Style::default().fg(MUTED)), + footer, + ); +} + +fn keys(app: &App) -> &'static str { + match (&app.prompt, app.screen) { + (Some(Prompt::Overwrite), _) => " Y overwrite N cancel", + (Some(_), _) => " Enter confirm Esc cancel Ctrl+U clear", + (None, Screen::Disc) if app.checking => " Please wait...", + (None, Screen::Disc) => " Enter check disc Ctrl+U clear Esc quit", + (None, Screen::Options) => { + " Up/Down move Space toggle Enter continue L load S save Esc back" + } + (None, Screen::Output) => " Enter patch Ctrl+U clear Esc back", + (None, Screen::Patching) => " Please keep this window open", + (None, Screen::Done) => " Enter exit", + (None, Screen::Failed) => " Enter back to options", + } +} + +fn text(s: impl Into) -> Paragraph<'static> { + Paragraph::new(s.into()).wrap(Wrap { trim: true }) +} + +/// A one-line text field showing the end of the text when it is too long. +fn field(frame: &mut Frame, area: Rect, value: &str) { + let width = area.width.saturating_sub(4) as usize; + let chars: Vec = value.chars().collect(); + let shown: String = if chars.len() > width { + let tail: String = chars[chars.len() - width.saturating_sub(3)..].iter().collect(); + format!("...{tail}") + } else { + value.to_string() + }; + let line = Line::from(vec![ + Span::styled("> ", Style::default().fg(ACCENT)), + Span::styled(shown, Style::default().fg(Color::White).bg(Color::Blue)), + Span::styled("_", Style::default().fg(ACCENT)), + ]); + frame.render_widget(Paragraph::new(line), area); +} + +fn notice(frame: &mut Frame, app: &App, area: Rect) { + if let Some((message, error)) = &app.notice { + let colour = if *error { ERROR } else { OK }; + frame.render_widget( + text(message.clone()).style(Style::default().fg(colour)), + area, + ); + } +} + +fn disc_screen(frame: &mut Frame, app: &App, area: Rect) { + let [intro, input, _, status] = Layout::vertical([ + Constraint::Length(4), + Constraint::Length(1), + Constraint::Length(1), + Constraint::Min(0), + ]) + .areas(area.inner(ratatui::layout::Margin::new(1, 0))); + frame.render_widget( + text("Type or paste the path to your clean, original disc image (.iso, .gcm, .ciso or .rvz), then press Enter.\nTip: drag the file onto this window, or right-click and choose Paste."), + intro, + ); + field(frame, input, &app.disc_field); + if app.checking { + frame.render_widget( + text("Checking your disc...").style(Style::default().fg(ACCENT)), + status, + ); + } else { + notice(frame, app, status); + } +} + +fn options_screen(frame: &mut Frame, app: &App, area: Rect) { + let area = area.inner(ratatui::layout::Margin::new(1, 0)); + let rows = app.rows(); + let [list, description, bottom] = Layout::vertical([ + Constraint::Length(rows.len() as u16), + Constraint::Min(2), + Constraint::Length(2), + ]) + .areas(area); + let current = app.current(); + let lines: Vec = rows + .iter() + .map(|row| match row { + Row::Header(title) => Line::styled(*title, Style::default().fg(ACCENT)), + Row::Item(opt) => { + let indent = if opt.nested() { " " } else { " " }; + let label = if *opt == crate::app::Opt::EnemySeed { + format!("{indent} {}: {}", opt.title(), app.seed_text) + } else { + let mark = if app.enabled(*opt) { "[x]" } else { "[ ]" }; + format!("{indent}{mark} {}", opt.title()) + }; + let style = if *opt == current { + Style::default().fg(Color::White).bg(Color::Blue) + } else { + Style::default() + }; + Line::styled(label, style) + } + }) + .collect(); + frame.render_widget(Paragraph::new(lines), list); + frame.render_widget( + text(current.description()).style(Style::default().fg(MUTED)), + description.inner(ratatui::layout::Margin::new(0, 0)), + ); + match &app.prompt { + Some(Prompt::Load(value)) => prompt_field(frame, bottom, "Load settings from:", value), + Some(Prompt::Save(value)) => prompt_field(frame, bottom, "Save settings to:", value), + _ => notice(frame, app, bottom), + } +} + +fn prompt_field(frame: &mut Frame, area: Rect, label: &str, value: &str) { + let [top, line] = + Layout::vertical([Constraint::Length(1), Constraint::Length(1)]).areas(area); + frame.render_widget(Paragraph::new(label.to_string()), top); + field(frame, line, value); +} + +fn chosen(app: &App) -> Vec { + let mut chosen: Vec = app + .items() + .into_iter() + .filter(|opt| *opt != crate::app::Opt::EnemySeed && app.enabled(*opt)) + .map(|opt| format!(" - {}", opt.title())) + .collect(); + if let Some(seed) = app.patch_selection().enemy_seed { + chosen.push(format!(" - Enemy seed {seed}")); + } + chosen +} + +fn output_screen(frame: &mut Frame, app: &App, area: Rect) { + let area = area.inner(ratatui::layout::Margin::new(1, 0)); + let [label, input, _, summary, bottom] = Layout::vertical([ + Constraint::Length(1), + Constraint::Length(1), + Constraint::Length(1), + Constraint::Min(0), + Constraint::Length(2), + ]) + .areas(area); + frame.render_widget( + Paragraph::new("Save the patched game as (edit if needed), then press Enter:"), + label, + ); + field(frame, input, &app.output_field); + let mut lines = vec![Line::styled("Options:", Style::default().fg(ACCENT))]; + lines.extend(chosen(app).into_iter().map(Line::from)); + frame.render_widget(Paragraph::new(lines), summary); + if let Some(Prompt::Overwrite) = app.prompt { + frame.render_widget( + text("That file already exists. Overwrite it? (Y/N)").style(Style::default().fg(ERROR)), + bottom, + ); + } else { + notice(frame, app, bottom); + } +} + +fn patching_screen(frame: &mut Frame, app: &App, area: Rect) { + let area = area.inner(ratatui::layout::Margin::new(1, 0)); + let [status, bar, _, info] = Layout::vertical([ + Constraint::Length(1), + Constraint::Length(1), + Constraint::Length(1), + Constraint::Min(0), + ]) + .areas(area); + let (label, fraction) = match &app.progress { + Some(p) => ( + phase_label(p.phase), + if p.total == 0 { + 0.0 + } else { + (p.done as f64 / p.total as f64).clamp(0.0, 1.0) + }, + ), + None => ("Starting...".into(), 0.0), + }; + frame.render_widget(Paragraph::new(label), status); + let width = bar.width.saturating_sub(8) as usize; + let filled = (fraction * width as f64).round() as usize; + let line = Line::from(vec![ + Span::raw("["), + Span::styled("#".repeat(filled), Style::default().fg(OK)), + Span::styled(".".repeat(width - filled), Style::default().fg(MUTED)), + Span::raw(format!("] {:>3}%", (fraction * 100.0) as u32)), + ]); + frame.render_widget(Paragraph::new(line), bar); + let elapsed = app.started.elapsed().as_secs(); + frame.render_widget( + text(format!( + "Elapsed {:02}:{:02}\n\nRandom enemies can take several minutes. Closing this window stops the patch; your original disc is never changed.", + elapsed / 60, + elapsed % 60 + )), + info, + ); +} + +fn done_screen(frame: &mut Frame, app: &App, area: Rect) { + let Some((path, outcome, seed)) = &app.outcome else { + return; + }; + let mut lines = vec![ + Line::styled("Done! Your patched game is ready.", Style::default().fg(OK)), + Line::raw(""), + Line::raw(format!("File: {}", path.display())), + Line::raw(format!("Size: {:.2} GB", outcome.bytes as f64 / 1e9)), + Line::raw(format!("MD5: {}", outcome.md5)), + ]; + if let Some(seed) = seed { + lines.push(Line::raw(format!("Seed: {seed}"))); + } + frame.render_widget( + Paragraph::new(lines).wrap(Wrap { trim: false }), + area.inner(ratatui::layout::Margin::new(1, 0)), + ); +} + +fn failed_screen(frame: &mut Frame, app: &App, area: Rect) { + let area = area.inner(ratatui::layout::Margin::new(1, 0)); + let [title, message] = + Layout::vertical([Constraint::Length(2), Constraint::Min(0)]).areas(area); + frame.render_widget( + Paragraph::new("Patching failed.").style(Style::default().fg(ERROR)), + title, + ); + frame.render_widget(text(app.failure.clone()), message); +} diff --git a/tools/build-win7-tui.sh b/tools/build-win7-tui.sh new file mode 100755 index 0000000..03340d2 --- /dev/null +++ b/tools/build-win7-tui.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# Cross-builds the terminal front end for Windows 7+ from Linux and zips it. +# +# Rust's tier-1 Windows targets need Windows 10, so this uses the tier-3 +# x86_64-win7-windows-msvc target: nightly, std rebuilt from source, the static +# CRT (no VC++ redistributable) and cargo-xwin for the MSVC CRT/SDK libraries +# (downloading them accepts Microsoft's licence). +# +# Requires rustup with a nightly toolchain and the rust-src component, +# cargo-xwin, clang, lld and bsdtar. TOOLCHAINS overrides where they live. +set -euo pipefail + +root="$(cd "$(dirname "$0")/.." && pwd)" +toolchains="${TOOLCHAINS:-$root/../.toolchains}" +target=x86_64-win7-windows-msvc +version="$(sed -n 's/^version = "\(.*\)"/\1/p' "$root/crates/dw4vhp-tui/Cargo.toml" | head -1)" + +export RUSTUP_HOME="$toolchains/rustup" CARGO_HOME="$toolchains/cargo" +export PATH="$CARGO_HOME/bin:$PATH" XWIN_ACCEPT_LICENSE=1 XWIN_CACHE_DIR="$toolchains/xwin" +export RUSTFLAGS="-C target-feature=+crt-static" + +cd "$root" +cargo +nightly xwin build --release -p dw4vhp-tui --target "$target" -Zbuild-std \ + --target-dir target/win7 + +exe="target/win7/$target/release/dw4-crown-mod-tui.exe" +# Anything Windows 7 lacks would stop the program loading at all. +if llvm-readobj --coff-imports "$exe" | + grep -E "ProcessPrng|bcryptprimitives|api-ms-win|WaitOnAddress|WakeByAddress|GetSystemTimePreciseAsFileTime|CreateFile2|SetThreadDescription"; then + echo "error: $exe imports an API that Windows 7 lacks" >&2 + exit 1 +fi + +out="dist/win7" +mkdir -p "$out" +zip="$out/dw4-crown-mod-tui-$version-windows7-x86_64.zip" +rm -f "$zip" +stage="$(mktemp -d)" +trap 'rm -rf "$stage"' EXIT +cp "$exe" "$stage/" +# Windows 7 Notepad shows LF-only text as a single line. +sed 's/$/\r/' crates/dw4vhp-tui/README.txt >"$stage/README.txt" +bsdtar -a -cf "$zip" -C "$stage" dw4-crown-mod-tui.exe README.txt +echo "$zip" From 99cecff8811f8ae457e2dd008d81d7e0042aa92e Mon Sep 17 00:00:00 2001 From: crashbashash <109347317+crashbashash@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:38:07 +0000 Subject: [PATCH 2/5] Stop the TUI footer scrolling the legacy Windows console - Writing the bottom-right cell wraps and scrolls a console without VT mode, hiding the top row; found by forcing crossterm's WinAPI path under Wine --- crates/dw4vhp-tui/src/ui.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/dw4vhp-tui/src/ui.rs b/crates/dw4vhp-tui/src/ui.rs index 23d3dbe..8da1be4 100644 --- a/crates/dw4vhp-tui/src/ui.rs +++ b/crates/dw4vhp-tui/src/ui.rs @@ -53,6 +53,12 @@ pub fn draw(frame: &mut Frame, app: &App) { Screen::Done => done_screen(frame, app, body), Screen::Failed => failed_screen(frame, app, body), } + // Writing the bottom-right cell makes the legacy Windows console wrap and + // scroll the whole screen up a line, so the footer stops one column short. + let footer = Rect { + width: footer.width.saturating_sub(1), + ..footer + }; frame.render_widget( Paragraph::new(keys(app)).style(Style::default().fg(MUTED)), footer, From 38170a538dfde6399ce51f9441c9f4cca00ebe14 Mon Sep 17 00:00:00 2001 From: crashbashash <109347317+crashbashash@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:52:10 +0000 Subject: [PATCH 3/5] Log boss replacements only when DW4_RANDOM_LOG is set - The unconditional eprintln! wrote over the TUI's screen during random-boss patches; the other random-enemy logs already use this variable --- crates/dw4vhp-core/src/crown/random/boss.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/dw4vhp-core/src/crown/random/boss.rs b/crates/dw4vhp-core/src/crown/random/boss.rs index eb5e2f5..7d67ee0 100644 --- a/crates/dw4vhp-core/src/crown/random/boss.rs +++ b/crates/dw4vhp-core/src/crown/random/boss.rs @@ -818,10 +818,12 @@ impl Randomiser { arena.entry, arena.generators.join(",") )); - eprintln!( - "BOSS IMAGE tier {difficulty} {}: {} -> {to}", - arena.entry, arena.model - ); + if std::env::var_os("DW4_RANDOM_LOG").is_some() { + eprintln!( + "BOSS IMAGE tier {difficulty} {}: {} -> {to}", + arena.entry, arena.model + ); + } bosses.push(json!({"stage": arena.entry, "area": arena.name, "generators": arena.generators, "original": arena.model, "boss": to, "changed": changed, "patrols": slot.patrols, "patrolFloors": arena.floors})); tick(); From f45be65442bd26c9b1e7f3ccb482c7657ccca2d4 Mon Sep 17 00:00:00 2001 From: crashbashash <109347317+crashbashash@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:21:56 +0000 Subject: [PATCH 4/5] Build, test and release the Windows 7 terminal version in CI - tools/win7.mjs (npm run build:win7 / check:win7) replaces the Linux-only script: pinned nightly-2026-11-17, std rebuilt with the static CRT, native MSVC on Windows and cargo-xwin elsewhere, then fails on any import Windows 7 lacks and zips the exe with a CRLF README - CI Windows 7 runs the core and TUI tests built for x86_64-win7-windows-msvc and the release build on every push and PR; the release workflow builds and requires the windows7 zip before publishing - release-notes.mjs checks the TUI crate version; README gains the CI Windows 7 badge, Windows 7 requirements and download instructions; DEVELOPMENT.md documents the build - cargo fmt for the TUI and the Tauri commands change --- .github/workflows/ci-win7.yml | 38 +++++++++++++ .github/workflows/release-win7.yml | 50 ++++++++++++++++ .github/workflows/release.yml | 7 ++- README.md | 25 +++++++- crates/dw4vhp-tauri/src/commands.rs | 10 +++- crates/dw4vhp-tui/src/app.rs | 5 +- crates/dw4vhp-tui/src/main.rs | 6 +- crates/dw4vhp-tui/src/ui.rs | 10 ++-- docs/DEVELOPMENT.md | 25 ++++++-- package.json | 2 + tools/build-win7-tui.sh | 44 --------------- tools/release-notes.mjs | 2 +- tools/release-notes.test.mjs | 2 +- tools/win7.mjs | 88 +++++++++++++++++++++++++++++ 14 files changed, 249 insertions(+), 65 deletions(-) create mode 100644 .github/workflows/ci-win7.yml create mode 100644 .github/workflows/release-win7.yml delete mode 100755 tools/build-win7-tui.sh create mode 100644 tools/win7.mjs diff --git a/.github/workflows/ci-win7.yml b/.github/workflows/ci-win7.yml new file mode 100644 index 0000000..1ce6e37 --- /dev/null +++ b/.github/workflows/ci-win7.yml @@ -0,0 +1,38 @@ +name: CI Windows 7 + +on: + push: + branches: [main] + pull_request: + +concurrency: + group: ci-win7-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + tui: + name: terminal version (win7 target tests, build, import check) + runs-on: windows-latest + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + # dtolnay/rust-toolchain; keep the toolchain in step with tools/win7.mjs. + - uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 + with: + toolchain: nightly-2026-11-17 + components: rust-src, llvm-tools + - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + - uses: actions/setup-node@v4 + - run: npm run check:win7 + - run: npm run build:win7 -- --out . + - name: Upload Windows 7 build + # v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: windows7-tui + path: dw4-crown-mod-*-windows7-x86_64.zip + if-no-files-found: error diff --git a/.github/workflows/release-win7.yml b/.github/workflows/release-win7.yml new file mode 100644 index 0000000..1c23fd2 --- /dev/null +++ b/.github/workflows/release-win7.yml @@ -0,0 +1,50 @@ +name: Release Windows 7 + +on: + workflow_call: + inputs: + release_tag: + required: true + type: string + +permissions: + # Build-only reusable workflow; the caller publishes every platform together. + contents: read + +jobs: + build: + name: Build Windows 7 terminal version (zip) + runs-on: windows-latest + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + # dtolnay/rust-toolchain; keep the toolchain in step with tools/win7.mjs. + - uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 + with: + toolchain: nightly-2026-11-17 + components: rust-src, llvm-tools + - uses: actions/setup-node@v4 + - name: Prepare version-checked release notes + shell: pwsh + env: + RELEASE_TAG: ${{ inputs.release_tag }} + run: node tools/release-notes.mjs --tag "$env:RELEASE_TAG" --output release-notes.md + - name: Verify application source matches the release tag + shell: pwsh + env: + RELEASE_TAG: ${{ inputs.release_tag }} + run: | + git fetch --depth 1 origin "refs/tags/$env:RELEASE_TAG" + if ($LASTEXITCODE -ne 0) { throw "Release tag was not found" } + git diff --exit-code FETCH_HEAD -- crates src public Cargo.toml Cargo.lock package.json package-lock.json + if ($LASTEXITCODE -ne 0) { throw "Application source differs from the release tag" } + - name: Build, check imports and package (zip) + run: npm run build:win7 -- --out . + - name: Upload Windows 7 assets + # v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: win7-assets + path: dw4-crown-mod-*-windows7-x86_64.zip + if-no-files-found: error diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a10cd5b..961bed4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -26,9 +26,13 @@ jobs: uses: ./.github/workflows/release-linux.yml with: release_tag: ${{ inputs.tag || github.ref_name }} + win7: + uses: ./.github/workflows/release-win7.yml + with: + release_tag: ${{ inputs.tag || github.ref_name }} publish: name: Publish complete release - needs: [windows, linux] + needs: [windows, linux, win7] runs-on: ubuntu-latest permissions: contents: write @@ -54,6 +58,7 @@ jobs: for file in \ "dw4-crown-mod-${RELEASE_TAG}-windows-x86_64.zip" \ "dw4-crown-mod-${version}-windows-x86_64.msi" \ + "dw4-crown-mod-${RELEASE_TAG}-windows7-x86_64.zip" \ "dw4-crown-mod-${RELEASE_TAG}-linux-x86_64.AppImage" \ "dw4-crown-mod-${RELEASE_TAG}-linux-x86_64.deb" \ "dw4-crown-mod-${RELEASE_TAG}-linux-x86_64.tar.gz"; do diff --git a/README.md b/README.md index 33a53c5..0d31a15 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,12 @@ # Digimon World 4 Crown Mod & Enemy Randomiser DW4 Crown Mod is a mod patcher and seeded enemy randomiser for **Digimon World 4** -on **PlayStation 2 (PS2)** and **GameCube**, available for **Windows and Linux**. +on **PlayStation 2 (PS2)** and **GameCube**, available for **Windows and Linux**, +with a terminal version for **Windows 7**. [![CI Linux](https://img.shields.io/github/actions/workflow/status/crashbashash/DW4_Crown_Mod/ci-linux.yml?label=CI%20Linux&branch=main)](https://github.com/crashbashash/DW4_Crown_Mod/actions/workflows/ci-linux.yml) [![CI Windows](https://img.shields.io/github/actions/workflow/status/crashbashash/DW4_Crown_Mod/ci-windows.yml?label=CI%20Windows&branch=main)](https://github.com/crashbashash/DW4_Crown_Mod/actions/workflows/ci-windows.yml) +[![CI Windows 7](https://img.shields.io/github/actions/workflow/status/crashbashash/DW4_Crown_Mod/ci-win7.yml?label=CI%20Windows%207&branch=main)](https://github.com/crashbashash/DW4_Crown_Mod/actions/workflows/ci-win7.yml) [![Release](https://img.shields.io/github/actions/workflow/status/crashbashash/DW4_Crown_Mod/release.yml?label=Release)](https://github.com/crashbashash/DW4_Crown_Mod/actions/workflows/release.yml) Buy me a coffee at ko-fi.com @@ -17,7 +19,7 @@ Open the app and choose your own copy of the game to create a new, modded copy. ## Quick start -1. [Download the app](#download) for Windows or Linux. +1. [Download the app](#download) for Windows or Linux. On Windows 7, use the [terminal version](#windows-7). 2. Open it and choose your game disc image (`.iso`, or `.ciso` / `.rvz` for GameCube). 3. Select at least one option in Settings (grouped into Gameplay, Balance, Cosmetics and Bugfixes tabs). Choose **Random enemies** alone for the original balance, or enable **Crown Mod** for stronger enemies and increased rewards. Under Random enemies, optionally enable **Random bosses** on any supported PS2 or GameCube disc; every boss except the four world bosses is shuffled. 4. Click **Patch ISO**. @@ -82,7 +84,8 @@ The same randomiser seed reproduces enemy choices within the same rules version. The app detects your release automatically. Existing Crown Mod images can be updated; unsupported or unrecognised images are refused. -- Windows or Linux. Nothing else to install. +- Windows 10 or later, or Linux, for the app; 64-bit Windows 7 SP1 or later for the + [terminal version](#windows-7). Nothing else to install. - About **2.2 GB** of free disk space for the new file (more for `.ciso` and `.rvz`, which are unpacked while patching). The app shows the exact amount. ## Download @@ -90,10 +93,26 @@ The same randomiser seed reproduces enemy choices within the same rules version. Get the latest version from the **Releases** page of this project: - **Windows:** `.msi` installer or a plain `.zip` +- **Windows 7:** `-windows7-x86_64.zip`, the [terminal version](#windows-7) - **Linux:** `.AppImage`, `.deb`, or a plain download The downloads are unsigned, so Windows may show a warning the first time you run it. +### Windows 7 + +The desktop app needs Windows 10 or later. The Windows 7 download is the same +patcher in a console window, with every option and the same settings files. + +1. Unzip it, then double-click `dw4-crown-mod-tui.exe`, or drag your disc image onto it. +2. Type or paste the path to your disc image and press **Enter**. You can also drag + the file onto the window, or right-click in it and choose **Paste**. +3. Move with the arrow keys, turn options on or off with **Space**, and press + **Enter** to continue. **L** and **S** load and save a settings file. +4. Check the output name and press **Enter** to patch. + +The terminal version patches clean discs only. To update an existing Crown Mod +image, patch your original disc again. + ## Updating the app The app checks for newer versions at startup and shows their release notes before diff --git a/crates/dw4vhp-tauri/src/commands.rs b/crates/dw4vhp-tauri/src/commands.rs index df2278a..ecaf584 100644 --- a/crates/dw4vhp-tauri/src/commands.rs +++ b/crates/dw4vhp-tauri/src/commands.rs @@ -229,7 +229,9 @@ fn verdict(result: &Result) -> DiscStatusPayload { ), reason: None, mod_metadata: None, - disc_info: report.release.map(|release| disc_info(release, false, None)), + disc_info: report + .release + .map(|release| disc_info(release, false, None)), size: report.size, output_size: report.output_size, copies: Some(report.copies), @@ -243,7 +245,11 @@ fn verdict(result: &Result) -> DiscStatusPayload { | Error::CrownData(_) => "refused", _ => "unknown", }, - reason: matches!(error, Error::AlreadyModded { .. } | Error::AlreadyCrownMod { .. }).then_some("already-modded"), + reason: matches!( + error, + Error::AlreadyModded { .. } | Error::AlreadyCrownMod { .. } + ) + .then_some("already-modded"), text: error.disc_notice(), mod_metadata: None, disc_info: None, diff --git a/crates/dw4vhp-tui/src/app.rs b/crates/dw4vhp-tui/src/app.rs index 2976c2f..6d673a4 100644 --- a/crates/dw4vhp-tui/src/app.rs +++ b/crates/dw4vhp-tui/src/app.rs @@ -455,7 +455,10 @@ impl App { enemy_seed: None, ..selection }; - self.seed_text = selection.enemy_seed.map(|s| s.to_string()).unwrap_or_default(); + self.seed_text = selection + .enemy_seed + .map(|s| s.to_string()) + .unwrap_or_default(); self.cursor = self.cursor.min(self.items().len() - 1); self.notice = Some(("Settings loaded.".into(), false)); } diff --git a/crates/dw4vhp-tui/src/main.rs b/crates/dw4vhp-tui/src/main.rs index d32cf34..b6f7d1d 100644 --- a/crates/dw4vhp-tui/src/main.rs +++ b/crates/dw4vhp-tui/src/main.rs @@ -64,9 +64,9 @@ fn perform(action: Action, tx: &Sender) { let result = inspect_retail_for_plan(&path, &plan) .map_err(|error| error.disc_notice()) .and_then(|report| { - let release = report.release.ok_or_else(|| { - dw4vhp_core::error::Error::NotThisDisc.disc_notice() - })?; + let release = report + .release + .ok_or_else(|| dw4vhp_core::error::Error::NotThisDisc.disc_notice())?; Ok(format!("{} - {}", release.label(), release.serial())) }); let _ = tx.send(Msg::Checked(result)); diff --git a/crates/dw4vhp-tui/src/ui.rs b/crates/dw4vhp-tui/src/ui.rs index 8da1be4..990be00 100644 --- a/crates/dw4vhp-tui/src/ui.rs +++ b/crates/dw4vhp-tui/src/ui.rs @@ -35,8 +35,7 @@ pub fn draw(frame: &mut Frame, app: &App) { .title_style(Style::default().fg(ACCENT)); let inner = block.inner(main); frame.render_widget(block, main); - let [header, body] = - Layout::vertical([Constraint::Length(2), Constraint::Min(0)]).areas(inner); + let [header, body] = Layout::vertical([Constraint::Length(2), Constraint::Min(0)]).areas(inner); let disc = match &app.disc { Some((_, label)) => Line::from(vec![ Span::styled(" Disc: ", Style::default().fg(MUTED)), @@ -90,7 +89,9 @@ fn field(frame: &mut Frame, area: Rect, value: &str) { let width = area.width.saturating_sub(4) as usize; let chars: Vec = value.chars().collect(); let shown: String = if chars.len() > width { - let tail: String = chars[chars.len() - width.saturating_sub(3)..].iter().collect(); + let tail: String = chars[chars.len() - width.saturating_sub(3)..] + .iter() + .collect(); format!("...{tail}") } else { value.to_string() @@ -180,8 +181,7 @@ fn options_screen(frame: &mut Frame, app: &App, area: Rect) { } fn prompt_field(frame: &mut Frame, area: Rect, label: &str, value: &str) { - let [top, line] = - Layout::vertical([Constraint::Length(1), Constraint::Length(1)]).areas(area); + let [top, line] = Layout::vertical([Constraint::Length(1), Constraint::Length(1)]).areas(area); frame.render_widget(Paragraph::new(label.to_string()), top); field(frame, line, value); } diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index c68c096..04d269f 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -10,6 +10,8 @@ See [CONTRIBUTING](../CONTRIBUTING.md) for the contributor checklist and the - `crates/dw4vhp-core`: the engine that edits the disc. It can be tested on its own. - `crates/dw4vhp-tauri`: the desktop window. A Tauri shell plus the React app in `src/`. +- `crates/dw4vhp-tui`: the terminal version for Windows 7, where the desktop app's + WebView2 and Rust's Windows 10 baseline rule out the desktop window. ## Building from source @@ -69,12 +71,26 @@ verification fingerprints. The "before" values always come from the player's own ## Releases -Release builds (Windows zip/MSI, Linux AppImage/deb/tarball) are produced by CI for -tagged releases. The release workflow waits for both platform builds, uploads all -assets to a draft, and publishes only after upload completes. Release workflows -compile and package both platforms; they do not launch the packaged GUI. +Release builds (Windows zip/MSI, Windows 7 terminal zip, Linux AppImage/deb/tarball) +are produced by CI for tagged releases. The release workflow waits for every platform +build, uploads all assets to a draft, and publishes only after upload completes. +Release workflows compile and package every platform; they do not launch the packaged GUI. Live desktop and emulator checks are separate. Release assets are unsigned. +### Windows 7 terminal version + +`npm run build:win7` builds `crates/dw4vhp-tui` for the tier-3 +`x86_64-win7-windows-msvc` target with the nightly pinned in `tools/win7.mjs` (and +the CI and release workflows), rebuilding std from source with the static CRT. It +then fails if the executable imports any function Windows 7 lacks, and writes the +release zip to `dist/win7`. Install the pinned nightly with the `rust-src` and +`llvm-tools` components through rustup. Windows hosts build natively; other hosts +cross-build with `cargo-xwin`, which downloads the MSVC CRT and SDK and accepts +Microsoft's licence on your behalf. + +`npm run check:win7` (Windows hosts) runs the core and terminal tests built for the +same target. CI Windows 7 runs both on every push and pull request. + ## Image identification New outputs carry the [versioned image signature](image-signature.md), including patch @@ -87,6 +103,7 @@ options. Detection checks it first and retains the game-data scan for older imag - `npm run check:core`: engine checks without GTK/WebKit or a game image. - `npm run check:frontend`: browser-side checks using the mock backend. - `npm run check:desktop`: builds the frontend and checks the native shell. +- `npm run check:win7`: core and terminal tests built for the Windows 7 target (Windows hosts). - Real-disc audits: configure the inputs below explicitly. Unconfigured native cases skip, so a green ordinary test run does not establish real-disc coverage. - Live validation: cold-boot the rebuilt image or exercise the packaged desktop diff --git a/package.json b/package.json index 4d4cfe3..9e5c598 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,8 @@ "check:core": "node tools/check.mjs core", "check:frontend": "node tools/check.mjs frontend", "check:desktop": "node tools/check.mjs desktop", + "check:win7": "node tools/win7.mjs test", + "build:win7": "node tools/win7.mjs", "bindings": "node tools/bindings.mjs", "bindings:check": "node tools/bindings.mjs --check", "docs:rules": "node tools/rules-docs.mjs", diff --git a/tools/build-win7-tui.sh b/tools/build-win7-tui.sh deleted file mode 100755 index 03340d2..0000000 --- a/tools/build-win7-tui.sh +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env bash -# Cross-builds the terminal front end for Windows 7+ from Linux and zips it. -# -# Rust's tier-1 Windows targets need Windows 10, so this uses the tier-3 -# x86_64-win7-windows-msvc target: nightly, std rebuilt from source, the static -# CRT (no VC++ redistributable) and cargo-xwin for the MSVC CRT/SDK libraries -# (downloading them accepts Microsoft's licence). -# -# Requires rustup with a nightly toolchain and the rust-src component, -# cargo-xwin, clang, lld and bsdtar. TOOLCHAINS overrides where they live. -set -euo pipefail - -root="$(cd "$(dirname "$0")/.." && pwd)" -toolchains="${TOOLCHAINS:-$root/../.toolchains}" -target=x86_64-win7-windows-msvc -version="$(sed -n 's/^version = "\(.*\)"/\1/p' "$root/crates/dw4vhp-tui/Cargo.toml" | head -1)" - -export RUSTUP_HOME="$toolchains/rustup" CARGO_HOME="$toolchains/cargo" -export PATH="$CARGO_HOME/bin:$PATH" XWIN_ACCEPT_LICENSE=1 XWIN_CACHE_DIR="$toolchains/xwin" -export RUSTFLAGS="-C target-feature=+crt-static" - -cd "$root" -cargo +nightly xwin build --release -p dw4vhp-tui --target "$target" -Zbuild-std \ - --target-dir target/win7 - -exe="target/win7/$target/release/dw4-crown-mod-tui.exe" -# Anything Windows 7 lacks would stop the program loading at all. -if llvm-readobj --coff-imports "$exe" | - grep -E "ProcessPrng|bcryptprimitives|api-ms-win|WaitOnAddress|WakeByAddress|GetSystemTimePreciseAsFileTime|CreateFile2|SetThreadDescription"; then - echo "error: $exe imports an API that Windows 7 lacks" >&2 - exit 1 -fi - -out="dist/win7" -mkdir -p "$out" -zip="$out/dw4-crown-mod-tui-$version-windows7-x86_64.zip" -rm -f "$zip" -stage="$(mktemp -d)" -trap 'rm -rf "$stage"' EXIT -cp "$exe" "$stage/" -# Windows 7 Notepad shows LF-only text as a single line. -sed 's/$/\r/' crates/dw4vhp-tui/README.txt >"$stage/README.txt" -bsdtar -a -cf "$zip" -C "$stage" dw4-crown-mod-tui.exe README.txt -echo "$zip" diff --git a/tools/release-notes.mjs b/tools/release-notes.mjs index 4e22394..15fd32b 100644 --- a/tools/release-notes.mjs +++ b/tools/release-notes.mjs @@ -7,7 +7,7 @@ export function releaseNotes(root, tag) { const read = (path) => readFileSync(resolve(root, path), "utf8"); const version = JSON.parse(read("package.json")).version; if (tag !== `v${version}`) throw Error(`Tag ${tag} does not match app version v${version}. Update the package versions before releasing.`); - for (const path of ["crates/dw4vhp-core/Cargo.toml", "crates/dw4vhp-tauri/Cargo.toml"]) { + for (const path of ["crates/dw4vhp-core/Cargo.toml", "crates/dw4vhp-tauri/Cargo.toml", "crates/dw4vhp-tui/Cargo.toml"]) { if (read(path).match(/^version\s*=\s*"([^"]+)"/m)?.[1] !== version) throw Error(`${path} version does not match ${version}`); } if (JSON.parse(read("crates/dw4vhp-tauri/tauri.conf.json")).version !== version) throw Error("Tauri version does not match package.json"); diff --git a/tools/release-notes.test.mjs b/tools/release-notes.test.mjs index 5bd4bd9..80c1f8d 100644 --- a/tools/release-notes.test.mjs +++ b/tools/release-notes.test.mjs @@ -7,7 +7,7 @@ const directories = []; afterEach(() => { for (const dir of directories.splice(0)) rmSync(dir, { recursive: true, force: true }); }); function fixture(changelog) { const root = mkdtempSync(join(tmpdir(), "crown-release-notes-")); directories.push(root); - for (const dir of ["crates/dw4vhp-core", "crates/dw4vhp-tauri"]) { + for (const dir of ["crates/dw4vhp-core", "crates/dw4vhp-tauri", "crates/dw4vhp-tui"]) { mkdirSync(join(root, dir), { recursive: true }); writeFileSync(join(root, dir, "Cargo.toml"), '[package]\nversion = "1.2.3"\n'); } diff --git a/tools/win7.mjs b/tools/win7.mjs new file mode 100644 index 0000000..c2ac69e --- /dev/null +++ b/tools/win7.mjs @@ -0,0 +1,88 @@ +/** + * Builds, tests and packages the Windows 7 terminal version (crates/dw4vhp-tui). + * + * Rust's tier-1 Windows targets need Windows 10, so this uses the tier-3 + * x86_64-win7-windows-msvc target: a pinned nightly (rust-src and llvm-tools + * components) with std rebuilt from source and the static CRT, so players need no + * VC++ redistributable. Windows hosts build natively; other hosts cross-build with + * cargo-xwin, which downloads the MSVC CRT and SDK (accepting Microsoft's licence). + * + * node tools/win7.mjs [--out DIR] build, check imports, write the release zip + * node tools/win7.mjs test run core and TUI tests built for the target (Windows hosts) + */ +import { spawnSync } from "node:child_process"; +import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import process from "node:process"; +import { fileURLToPath } from "node:url"; + +const TOOLCHAIN = "nightly-2026-11-17"; +const TARGET = "x86_64-win7-windows-msvc"; +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const windows = process.platform === "win32"; +// Functions Windows 7 lacks. Importing any of them stops the program loading at all. +const NEWER_THAN_WINDOWS_7 = + /ProcessPrng|bcryptprimitives|api-ms-win|WaitOnAddress|WakeByAddress|GetSystemTimePreciseAsFileTime|CreateFile2|SetThreadDescription/i; + +function run(command, args, { env = process.env, capture = false } = {}) { + process.stdout.write(`\n> ${command} ${args.join(" ")}\n`); + const result = spawnSync(command, args, { + cwd: root, + env, + encoding: "utf8", + stdio: capture ? ["ignore", "pipe", "inherit"] : "inherit", + }); + if (result.error) throw result.error; + if (result.status !== 0) process.exit(result.status ?? 1); + return result.stdout; +} + +function cargo(action, args) { + const env = { ...process.env, RUSTFLAGS: "-C target-feature=+crt-static" }; + if (!windows) env.XWIN_ACCEPT_LICENSE = "1"; + const subcommand = windows ? [action] : ["xwin", action]; + run("cargo", [`+${TOOLCHAIN}`, ...subcommand, "--locked", "--target", TARGET, "-Zbuild-std", + "--target-dir", "target/win7", ...args], { env }); +} + +if (process.argv[2] === "test") { + if (!windows) throw new Error("Windows 7 target tests run on Windows hosts only."); + cargo("test", ["-p", "dw4vhp-core", "-p", "dw4vhp-tui"]); + process.exit(0); +} + +const args = process.argv.slice(2); +const out = resolve(root, args.includes("--out") ? args[args.indexOf("--out") + 1] : "dist/win7"); +const version = JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version; + +cargo("build", ["--release", "-p", "dw4vhp-tui"]); +const exe = join(root, "target/win7", TARGET, "release/dw4-crown-mod-tui.exe"); + +const sysroot = run("rustc", [`+${TOOLCHAIN}`, "--print", "sysroot"], { capture: true }).trim(); +const host = /^host: (\S+)$/m.exec(run("rustc", [`+${TOOLCHAIN}`, "-vV"], { capture: true }))[1]; +const readobj = join(sysroot, "lib/rustlib", host, "bin", windows ? "llvm-readobj.exe" : "llvm-readobj"); +const imports = run(readobj, ["--coff-imports", exe], { capture: true }) + .split("\n") + .filter(line => /^\s*(Name|Symbol):/.test(line)); +if (!imports.some(line => /KERNEL32\.dll/i.test(line))) throw new Error(`No import table read from ${exe}`); +const newer = imports.filter(line => NEWER_THAN_WINDOWS_7.test(line)); +if (newer.length) throw new Error(`${exe} imports functions Windows 7 lacks:\n${newer.join("\n")}`); +process.stdout.write(`${imports.length} import lines checked: all available on Windows 7.\n`); + +const stage = mkdtempSync(join(tmpdir(), "dw4-win7-")); +try { + copyFileSync(exe, join(stage, "dw4-crown-mod-tui.exe")); + // Windows 7 Notepad shows LF-only text as a single line. + const readme = readFileSync(join(root, "crates/dw4vhp-tui/README.txt"), "utf8"); + writeFileSync(join(stage, "README.txt"), readme.replace(/\r?\n/g, "\r\n")); + mkdirSync(out, { recursive: true }); + const zip = join(out, `dw4-crown-mod-v${version}-windows7-x86_64.zip`); + rmSync(zip, { force: true }); + // bsdtar writes zip archives; Windows ships it as System32\tar.exe. + const tar = windows ? join(process.env.SystemRoot ?? "C:\\Windows", "System32", "tar.exe") : "bsdtar"; + run(tar, ["-a", "-cf", zip, "-C", stage, "dw4-crown-mod-tui.exe", "README.txt"]); + process.stdout.write(`${zip}\n`); +} finally { + rmSync(stage, { recursive: true, force: true }); +} From ee7263415ea2609293000f0032fad1c41e09015c Mon Sep 17 00:00:00 2001 From: crashbashash <109347317+crashbashash@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:22:00 +0000 Subject: [PATCH 5/5] Release v0.21.0 Terminal version for Windows 7 and later, built and checked in CI and attached to the release as dw4-crown-mod-v0.21.0-windows7-x86_64.zip. Validation: npm run check:core and check:desktop; release-notes tests; npm run build:win7 (cross-build, import check, zip); TUI patches on a Windows 7 SP1 VM byte-identical to Linux for PS2 USA/Europe/Japan and GameCube USA (.rvz)/Japan (.ciso) with all options except random crown colours, seed 1520. Refs #2 --- CHANGELOG.md | 4 ++++ Cargo.lock | 4 ++-- crates/dw4vhp-core/Cargo.toml | 2 +- crates/dw4vhp-tauri/Cargo.lock | 4 ++-- crates/dw4vhp-tauri/Cargo.toml | 2 +- crates/dw4vhp-tauri/tauri.conf.json | 2 +- crates/dw4vhp-tui/Cargo.toml | 2 +- package-lock.json | 4 ++-- package.json | 2 +- 9 files changed, 15 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 14b04e6..2e05244 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## v0.21.0 + +- Added a terminal version for **Windows 7 and later** (`dw4-crown-mod-v0.21.0-windows7-x86_64.zip`): the same patcher in a console window, for PCs that can't run the desktop app. Unzip it, then double-click `dw4-crown-mod-tui.exe` or drag your disc image onto it. It has every option, and it can load and save the same settings files as the desktop app. + ## v0.20.0 - Random bosses now also shuffles the repeat boss fights (Blossomon in Abyss of Grief, SkullGreymon in Grief Wasteland, ShogunGekomon in Mangrove Forest) and the Quest 1, 4, 7 and 8 bosses. Only the four world bosses stay fixed. diff --git a/Cargo.lock b/Cargo.lock index c57d5af..61f500d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -160,7 +160,7 @@ dependencies = [ [[package]] name = "dw4vhp-core" -version = "0.20.0" +version = "0.21.0" dependencies = [ "fs4", "getrandom", @@ -177,7 +177,7 @@ dependencies = [ [[package]] name = "dw4vhp-tui" -version = "0.20.0" +version = "0.21.0" dependencies = [ "dw4vhp-core", "getrandom", diff --git a/crates/dw4vhp-core/Cargo.toml b/crates/dw4vhp-core/Cargo.toml index 708e4da..1ed6651 100644 --- a/crates/dw4vhp-core/Cargo.toml +++ b/crates/dw4vhp-core/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "dw4vhp-core" -version = "0.20.0" +version = "0.21.0" edition = "2021" license = "GPL-3.0-or-later" description = "Engine for the Digimon World 4 Crown Mod ISO patcher" diff --git a/crates/dw4vhp-tauri/Cargo.lock b/crates/dw4vhp-tauri/Cargo.lock index bda1d5b..24d7bfc 100644 --- a/crates/dw4vhp-tauri/Cargo.lock +++ b/crates/dw4vhp-tauri/Cargo.lock @@ -939,7 +939,7 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" [[package]] name = "dw4vhp-core" -version = "0.20.0" +version = "0.21.0" dependencies = [ "fs4", "getrandom 0.4.3", @@ -956,7 +956,7 @@ dependencies = [ [[package]] name = "dw4vhp-tauri" -version = "0.20.0" +version = "0.21.0" dependencies = [ "dw4vhp-core", "reqwest", diff --git a/crates/dw4vhp-tauri/Cargo.toml b/crates/dw4vhp-tauri/Cargo.toml index 5f002af..0328d18 100644 --- a/crates/dw4vhp-tauri/Cargo.toml +++ b/crates/dw4vhp-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "dw4vhp-tauri" -version = "0.20.0" +version = "0.21.0" edition = "2021" license = "GPL-3.0-or-later" description = "Desktop shell for the Digimon World 4 Crown Mod ISO patcher" diff --git a/crates/dw4vhp-tauri/tauri.conf.json b/crates/dw4vhp-tauri/tauri.conf.json index 4e6f124..f795704 100644 --- a/crates/dw4vhp-tauri/tauri.conf.json +++ b/crates/dw4vhp-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "DW4 Crown Mod", - "version": "0.20.0", + "version": "0.21.0", "identifier": "io.github.crashbashash.dw4-veryhard-plus", "mainBinaryName": "dw4-crown-mod", "build": { diff --git a/crates/dw4vhp-tui/Cargo.toml b/crates/dw4vhp-tui/Cargo.toml index 98c3650..707d22c 100644 --- a/crates/dw4vhp-tui/Cargo.toml +++ b/crates/dw4vhp-tui/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "dw4vhp-tui" -version = "0.20.0" +version = "0.21.0" edition = "2021" license = "GPL-3.0-or-later" description = "Terminal front end for the Digimon World 4 Crown Mod ISO patcher" diff --git a/package-lock.json b/package-lock.json index 3260bf6..dafd9fe 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "dw4-crown-mod", - "version": "0.20.0", + "version": "0.21.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "dw4-crown-mod", - "version": "0.20.0", + "version": "0.21.0", "dependencies": { "@tauri-apps/api": "^2", "@tauri-apps/plugin-dialog": "^2", diff --git a/package.json b/package.json index 9e5c598..3685ab5 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "dw4-crown-mod", "private": true, - "version": "0.20.0", + "version": "0.21.0", "type": "module", "scripts": { "dev": "vite",