diff --git a/Cargo.lock b/Cargo.lock index 17f8f93..bbb6800 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,122 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "accesskit" +version = "0.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e883d1d28c5fd5568c79ed2d2bd48d9f2fd3945c8974ed0f53690ceddb051be" +dependencies = [ + "enumn", + "serde", + "uuid", +] + +[[package]] +name = "accesskit_atspi_common" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24f5baf62e34a4a6c30e3d697e4782f821a7337049c44c3b40576a27dfbb580d" +dependencies = [ + "accesskit", + "accesskit_consumer", + "atspi-common", + "phf", + "serde", + "zvariant", +] + +[[package]] +name = "accesskit_consumer" +version = "0.39.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3da8f27636015191b2264ee1df681503170a632cafd832fdc1edfdd4e3a2fd3" +dependencies = [ + "accesskit", + "hashbrown 0.17.1", +] + +[[package]] +name = "accesskit_ios" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5280724673bbfa8b30a838c013500b719392989be3b97c5a9964062c252c232" +dependencies = [ + "accesskit", + "accesskit_consumer", + "hashbrown 0.17.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-ui-kit 0.2.2", +] + +[[package]] +name = "accesskit_macos" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "123828ceeec755b05255e3976cb0852993202de98a0626c97dd8d34246991f84" +dependencies = [ + "accesskit", + "accesskit_consumer", + "hashbrown 0.17.1", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "accesskit_unix" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d5192871228c54f1b0fb4a85cef000e11a3804f25d2165f14afa0daa67f3f6" +dependencies = [ + "accesskit", + "accesskit_atspi_common", + "async-channel", + "async-executor", + "async-task", + "atspi", + "futures-lite", + "futures-util", + "serde", + "zbus", +] + +[[package]] +name = "accesskit_windows" +version = "0.35.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "498668b90da9995302a0055aaecad4756932333da2ddef6baee1c00844c430fc" +dependencies = [ + "accesskit", + "accesskit_consumer", + "hashbrown 0.17.1", + "static_assertions", + "windows", + "windows-core", +] + +[[package]] +name = "accesskit_winit" +version = "0.34.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd4ab4437b520ff03088fbe48676a11e7d44a929535e64b31432c1073e48dbcc" +dependencies = [ + "accesskit", + "accesskit_ios", + "accesskit_macos", + "accesskit_unix", + "accesskit_windows", + "raw-window-handle", + "winit", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "aes" version = "0.9.4" @@ -13,17 +129,317 @@ dependencies = [ "cpufeatures", ] +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.4", + "once_cell", + "serde", + "version_check", + "zerocopy", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android-activity" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd" +dependencies = [ + "android-properties", + "bitflags 2.13.2", + "cc", + "jni", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "num_enum", + "thiserror 2.0.21", +] + +[[package]] +name = "android-properties" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + [[package]] name = "anyhow" version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "arboard" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917" +dependencies = [ + "clipboard-win", + "image", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "parking_lot", + "percent-encoding", + "windows-sys 0.61.2", + "wl-clipboard-rs", + "x11rb", +] + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "as-raw-xcb-connection" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" + +[[package]] +name = "ash" +version = "0.38.0+1.3.281" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" +dependencies = [ + "libloading", +] + +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix 1.1.6", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix 1.1.6", +] + +[[package]] +name = "async-recursion" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix 1.1.6", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "atspi" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c77886257be21c9cd89a4ae7e64860c6f0eefca799bb79127913052bd0eefb3d" +dependencies = [ + "atspi-common", + "atspi-proxies", +] + +[[package]] +name = "atspi-common" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20c5617155740c98003016429ad13fe43ce7a77b007479350a9f8bf95a29f63d" +dependencies = [ + "enumflags2", + "serde", + "static_assertions", + "zbus", + "zbus-lockstep", + "zbus-lockstep-macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "atspi-proxies" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc" +dependencies = [ + "atspi-common", + "serde", + "zbus", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bit-set" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] [[package]] name = "block-buffer" @@ -34,12 +450,137 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2 0.5.3", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2 0.6.5", +] + +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + [[package]] name = "bumpalo" version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "calloop" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec" +dependencies = [ + "bitflags 2.13.2", + "log", + "polling", + "rustix 0.38.44", + "slab", + "thiserror 1.0.69", +] + +[[package]] +name = "calloop" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e" +dependencies = [ + "bitflags 2.13.2", + "polling", + "rustix 1.1.6", + "tracing", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" +dependencies = [ + "calloop 0.13.0", + "rustix 0.38.44", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" +dependencies = [ + "calloop 0.14.5", + "rustix 1.1.6", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "cc" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -52,6 +593,15 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" +[[package]] +name = "cgl" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ced0551234e87afee12411d535648dd89d2e7f34c78b753395567aff3d447ff" +dependencies = [ + "libc", +] + [[package]] name = "cipher" version = "0.5.2" @@ -62,6 +612,54 @@ dependencies = [ "inout", ] +[[package]] +name = "clipboard-win" +version = "5.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" +dependencies = [ + "error-code", +] + +[[package]] +name = "codespan-reporting" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" +dependencies = [ + "serde", + "termcolor", + "unicode-width", +] + +[[package]] +name = "color" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ec7c5eb7a16992b1904d76c517d170ab353b0e0b3d5a0c81a8a0cd1037893cf" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "console" version = "0.16.6" @@ -71,7 +669,7 @@ dependencies = [ "encode_unicode", "libc", "unicode-width", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -80,6 +678,46 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "libc", +] + [[package]] name = "cpubits" version = "0.1.1" @@ -104,6 +742,18 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + [[package]] name = "crypto-common" version = "0.2.2" @@ -113,6 +763,12 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "cursor-icon" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" + [[package]] name = "digest" version = "0.11.3" @@ -124,12 +780,338 @@ dependencies = [ "crypto-common", ] +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "libc", + "objc2 0.6.5", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "dlib" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" +dependencies = [ + "libloading", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" + +[[package]] +name = "ecolor" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31bcbef0d4263a63eb32c4834e5d711613035ce1333468e107d928923e21e6e2" +dependencies = [ + "bytemuck", + "emath", + "serde", +] + +[[package]] +name = "eframe" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c5642501a65ca657d05f00c643a5c14ff2346cb3818032bfe23d58e1f8e5f84" +dependencies = [ + "ahash", + "bytemuck", + "document-features", + "egui", + "egui-wgpu", + "egui-winit", + "egui_glow", + "glutin", + "glutin-winit", + "image", + "js-sys", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "parking_lot", + "percent-encoding", + "pollster", + "profiling", + "raw-window-handle", + "ron", + "send_wrapper", + "serde", + "static_assertions", + "wasm-bindgen", + "web-sys", + "web-time", + "wgpu", + "windows-sys 0.61.2", + "winit", +] + +[[package]] +name = "egui" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bec9144f49b7a28b5f395d3147e325b4fe3e77ba686eac11d1bdf0a7da3f375f" +dependencies = [ + "accesskit", + "ahash", + "bitflags 2.13.2", + "emath", + "epaint", + "itertools", + "log", + "nohash-hasher", + "profiling", + "ron", + "serde", + "smallvec", + "unicode-segmentation", + "web-sys", +] + +[[package]] +name = "egui-wgpu" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0309cbe1febed48af5b974e4bcc424b35e9664863a4d402697147b57a488c864" +dependencies = [ + "ahash", + "bytemuck", + "document-features", + "egui", + "epaint", + "log", + "profiling", + "thiserror 2.0.21", + "type-map", + "web-time", + "wgpu", + "winit", +] + +[[package]] +name = "egui-winit" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e449f4c4a2a60c7ccb4ba7fa4078417bfe1f9ddc03b5e05ce75748e33a70de" +dependencies = [ + "accesskit_winit", + "arboard", + "block2 0.6.2", + "bytemuck", + "egui", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "objc2-ui-kit 0.3.2", + "profiling", + "raw-window-handle", + "serde", + "smithay-clipboard", + "web-time", + "webbrowser", + "windows-sys 0.61.2", + "winit", +] + +[[package]] +name = "egui_extras" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "def286cf47194f3fe45b8e37c503ada7a20a64b59a903b4bc704baec943b1827" +dependencies = [ + "ahash", + "egui", + "enum-map", + "itertools", + "log", + "profiling", +] + +[[package]] +name = "egui_glow" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9275ca5cc35a6b7c94e0e8cedf22542f66cb0cf45ed8ab2657c78ff49fec7268" +dependencies = [ + "bytemuck", + "egui", + "glow", + "log", + "profiling", + "winit", +] + +[[package]] +name = "egui_system_font_provider" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f2a2fdfe3c05dd9f691d2b1388b2312d6dce1af502f217c22136d22d9bd76f6" +dependencies = [ + "epaint", + "fontique", + "log", + "poll-promise", + "skrifa", + "sys-locale", + "unicode-script", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "emath" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e73ce90f54750be8672c02be0743fe47530e6f251e066f0ee2869b59eb297af5" +dependencies = [ + "bytemuck", + "serde", +] + [[package]] name = "encode_unicode" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enum-map" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4532960034c15ba2f55e9eee631040ecc473c32e6c4b200828c759840f13a06" +dependencies = [ + "enum-map-derive", +] + +[[package]] +name = "enum-map-derive" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "enumn" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f9ed6b3789237c8a0c1c505af1c7eb2c560df6186f01b098c3a1064ea532f38" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "epaint" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97bac86ae3dde93fc3951e790951caea739ff39a6c89d909cdaf1d9278dbb1bd" +dependencies = [ + "ahash", + "bytemuck", + "ecolor", + "emath", + "epaint_default_fonts", + "font-types", + "harfrust", + "log", + "nohash-hasher", + "parking_lot", + "profiling", + "self_cell", + "serde", + "skrifa", + "smallvec", + "unicode-general-category", + "unicode-properties", + "unicode-segmentation", + "vello_cpu", +] + +[[package]] +name = "epaint_default_fonts" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfc1cc505827f4c23eedc297975a0fd038268d41293f389dd8ff3b574aefab19" + [[package]] name = "equivalent" version = "1.0.3" @@ -143,7 +1125,42 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "error-code" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" + +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", ] [[package]] @@ -152,21 +1169,166 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "fearless_simd" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fixedbitset" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" + [[package]] name = "flate2" version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", "zlib-rs", ] +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "font-types" +version = "0.12.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" +dependencies = [ + "bytemuck", + "serde", +] + +[[package]] +name = "fontique" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6688bc1294fe7117d788937b6c53480169b29c566954af490830d4c09da9516a" +dependencies = [ + "hashbrown 0.17.1", + "linebender_resource_handle", + "memmap2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-text", + "objc2-foundation 0.3.2", + "parlance", + "read-fonts", + "roxmltree", + "smallvec", + "windows", + "windows-core", + "yeslogic-fontconfig-sys", +] + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + [[package]] name = "futures-core" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "futures-task" version = "0.3.34" @@ -180,11 +1342,34 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", + "futures-macro", "futures-task", "pin-project-lite", "slab", ] +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix 1.1.6", + "windows-link", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -194,10 +1379,116 @@ dependencies = [ "cfg-if", "js-sys", "libc", - "r-efi", + "r-efi 6.0.0", "wasm-bindgen", ] +[[package]] +name = "gl_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d" +dependencies = [ + "khronos_api", + "log", + "xml-rs", +] + +[[package]] +name = "glifo" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282a26c1e23de04bdab3e34a21b6f877a479b96737792516b9b8b8f69b6661be" +dependencies = [ + "bytemuck", + "foldhash 0.2.0", + "hashbrown 0.17.1", + "log", + "peniko", + "png", + "skrifa", + "smallvec", + "vello_common", +] + +[[package]] +name = "glow" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29038e1c483364cc6bb3cf78feee1816002e127c331a1eec55a4d202b9e1adb5" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "glutin" +version = "0.32.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12124de845cacfebedff80e877bb37b5b75c34c5a4c89e47e1cdd67fb6041325" +dependencies = [ + "bitflags 2.13.2", + "cfg_aliases", + "cgl", + "dispatch2", + "glutin_egl_sys", + "glutin_glx_sys", + "glutin_wgl_sys", + "libloading", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "once_cell", + "raw-window-handle", + "wayland-sys", + "windows-sys 0.52.0", + "x11-dl", +] + +[[package]] +name = "glutin-winit" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85edca7075f8fc728f28cb8fbb111a96c3b89e930574369e3e9c27eb75d3788f" +dependencies = [ + "cfg_aliases", + "glutin", + "raw-window-handle", + "winit", +] + +[[package]] +name = "glutin_egl_sys" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c4680ba6195f424febdc3ba46e7a42a0e58743f2edb115297b86d7f8ecc02d2" +dependencies = [ + "gl_generator", + "windows-sys 0.52.0", +] + +[[package]] +name = "glutin_glx_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7bb2938045a88b612499fbcba375a77198e01306f52272e692f8c1f3751185" +dependencies = [ + "gl_generator", + "x11-dl", +] + +[[package]] +name = "glutin_wgl_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e" +dependencies = [ + "gl_generator", +] + [[package]] name = "goblin" version = "0.10.7" @@ -209,11 +1500,93 @@ dependencies = [ "scroll", ] +[[package]] +name = "gpu-allocator" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795" +dependencies = [ + "ash", + "hashbrown 0.16.1", + "log", + "presser", + "thiserror 2.0.21", + "windows", +] + +[[package]] +name = "guillotiere" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b17e70c989c36bad147b27a58d148c0741c51448aa5653436547323e524d0ab" +dependencies = [ + "euclid", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "num-traits", + "zerocopy", +] + +[[package]] +name = "harfrust" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "read-fonts", + "smallvec", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.2.0", +] + [[package]] name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash 0.2.0", +] + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" [[package]] name = "hybrid-array" @@ -224,6 +1597,124 @@ dependencies = [ "typenum", ] +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "moxcms", + "num-traits", + "png", + "tiff", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -231,7 +1722,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", - "hashbrown", + "hashbrown 0.17.1", ] [[package]] @@ -256,12 +1747,89 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + [[package]] name = "js-sys" version = "0.3.107" @@ -273,18 +1841,108 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "khronos-egl" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76" +dependencies = [ + "libc", + "libloading", + "pkg-config", +] + +[[package]] +name = "khronos_api" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" + +[[package]] +name = "kurbo" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2" +dependencies = [ + "arrayvec", + "euclid", + "polycool", + "smallvec", +] + [[package]] name = "libc" version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "bitflags 2.13.2", + "libc", + "plain", + "redox_syscall 0.9.5", +] + +[[package]] +name = "linebender_resource_handle" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" + +[[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 = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[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" @@ -306,48 +1964,803 @@ dependencies = [ "libc", ] +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "naga" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130" +dependencies = [ + "arrayvec", + "bit-set", + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "codespan-reporting", + "half", + "hashbrown 0.17.1", + "indexmap", + "libm", + "log", + "naga-types", + "num-traits", + "once_cell", + "rustc-hash 1.1.0", + "spirv", + "thiserror 2.0.21", + "unicode-ident", +] + +[[package]] +name = "naga-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49" +dependencies = [ + "hashbrown 0.17.1", + "indexmap", + "rustc-hash 1.1.0", + "thiserror 2.0.21", +] + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + [[package]] name = "nix" version = "0.31.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" dependencies = [ - "bitflags", + "bitflags 2.13.2", "cfg-if", "cfg_aliases", "libc", ] +[[package]] +name = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "objc-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" + +[[package]] +name = "objc2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b" +dependencies = [ + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-app-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "libc", + "objc2 0.5.3", + "objc2-core-data", + "objc2-core-image", + "objc2-foundation 0.2.2", + "objc2-quartz-core 0.2.2", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-uniform-type-identifiers 0.3.2", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-contacts" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-data" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-core-location" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-contacts", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags 2.13.2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "dispatch", + "libc", + "objc2 0.5.3", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-link-presentation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", +] + +[[package]] +name = "objc2-symbols" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc" +dependencies = [ + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-image", + "objc2-core-location", + "objc2-foundation 0.2.2", + "objc2-link-presentation", + "objc2-quartz-core 0.2.2", + "objc2-symbols", + "objc2-uniform-type-identifiers 0.2.2", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7902ac02859fc1f7045f8b598c63f1ae0cc7efeaa06a9bc9f3d9a3c955974fa4" +dependencies = [ + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + [[package]] name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "orbclient" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747" +dependencies = [ + "libc", + "libredox", +] + +[[package]] +name = "ordered-float" +version = "5.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "os_pipe" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "owo-colors" version = "4.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c45bb4a6ae1280ec0803b1ef9d3455eb50f01efbbe1447ab020f1d54fba9d8" +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[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 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "parlance" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73072a9470554c8e794778acece2312661218aaabb635600957d952cf01c716e" + +[[package]] +name = "peniko" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "839c8299360d2e998bdb106dc0a6cd71dcc5f4df51df1b620361bf50e283cca6" +dependencies = [ + "bytemuck", + "color", + "kurbo", + "linebender_resource_handle", + "smallvec", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap", +] + +[[package]] +name = "phf" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" +dependencies = [ + "phf_macros", + "phf_shared", + "serde", +] + +[[package]] +name = "phf_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_macros" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "pin-project-lite" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + [[package]] name = "plain" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "poll-promise" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f6a58fecbf9da8965bcdb20ce4fd29788d1acee68ddbb64f0ba1b81bccdb7df" +dependencies = [ + "document-features", + "static_assertions", +] + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 1.1.6", + "windows-sys 0.61.2", +] + +[[package]] +name = "pollster" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc6355899e1c9462875b6757c79f3caa011a1fdae12bbb1a2e72dd1f234f8336" + +[[package]] +name = "polycool" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6" +dependencies = [ + "arrayvec", +] + [[package]] name = "portable-atomic" version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "presser" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -357,6 +2770,33 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + [[package]] name = "quote" version = "1.0.47" @@ -366,23 +2806,182 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + [[package]] name = "r-efi" version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "range-alloc" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "raw-window-metal" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135" +dependencies = [ + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "read-fonts" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" +dependencies = [ + "bytemuck", + "font-types", + "once_cell", +] + +[[package]] +name = "redox_syscall" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_syscall" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "renderdoc-sys" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" + +[[package]] +name = "rfd" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4b9d4857b10297ffb0f64cae711e983a7aeaee561848d56d429d3858bd8ed93" +dependencies = [ + "block2 0.6.2", + "dispatch2", + "js-sys", + "libc", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-uniform-type-identifiers 0.3.2", + "percent-encoding", + "pollster", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "web-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "ron" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81116b9531d61eabc41aeb228e4b6b2435bcca3233b98cf3b3077d4e6e9debb3" +dependencies = [ + "bitflags 2.13.2", + "once_cell", + "serde", + "serde_derive", + "typeid", + "unicode-ident", +] + +[[package]] +name = "roxmltree" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" +dependencies = [ + "memchr", +] + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + [[package]] name = "rustix" version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ - "bitflags", + "bitflags 2.13.2", "errno", "libc", - "linux-raw-sys", - "windows-sys", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", ] [[package]] @@ -400,6 +2999,18 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + [[package]] name = "scroll" version = "0.13.0" @@ -420,6 +3031,18 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "self_cell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "senbei-cli" version = "1.3.4" @@ -440,7 +3063,7 @@ name = "senbei-crypto" version = "1.3.4" dependencies = [ "aes", - "thiserror", + "thiserror 2.0.21", ] [[package]] @@ -448,7 +3071,7 @@ name = "senbei-elf" version = "1.3.4" dependencies = [ "goblin", - "thiserror", + "thiserror 2.0.21", ] [[package]] @@ -464,7 +3087,28 @@ dependencies = [ "serde_json", "sha2", "tempfile", - "thiserror", + "thiserror 2.0.21", +] + +[[package]] +name = "senbei-gui" +version = "1.3.4" +dependencies = [ + "anyhow", + "eframe", + "egui", + "egui_extras", + "egui_system_font_provider", + "fontique", + "png", + "rfd", + "senbei-engine", + "senbei-i18n", + "senbei-io", + "senbei-metadata", + "serde", + "serde_json", + "tempfile", ] [[package]] @@ -505,16 +3149,22 @@ version = "1.3.4" dependencies = [ "serde", "serde_json", - "thiserror", + "thiserror 2.0.21", ] [[package]] name = "senbei-pe" version = "1.3.4" dependencies = [ - "thiserror", + "thiserror 2.0.21", ] +[[package]] +name = "send_wrapper" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73" + [[package]] name = "serde" version = "1.0.229" @@ -558,6 +3208,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "sha2" version = "0.11.1" @@ -569,18 +3230,177 @@ dependencies = [ "digest", ] +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[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 = "simd-adler32" version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "skrifa" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" +dependencies = [ + "bytemuck", + "read-fonts", +] + [[package]] name = "slab" version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" +dependencies = [ + "serde", +] + +[[package]] +name = "smithay-client-toolkit" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" +dependencies = [ + "bitflags 2.13.2", + "calloop 0.13.0", + "calloop-wayland-source 0.3.0", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 0.38.44", + "thiserror 1.0.69", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smithay-client-toolkit" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0512da38f5e2b31201a93524adb8d3136276fa4fe4aafab4e1f727a82b534cc0" +dependencies = [ + "bitflags 2.13.2", + "calloop 0.14.5", + "calloop-wayland-source 0.4.1", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 1.1.6", + "thiserror 2.0.21", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-experimental", + "wayland-protocols-misc", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smithay-clipboard" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71704c03f739f7745053bde45fa203a46c58d25bc5c4efba1d9a60e9dba81226" +dependencies = [ + "libc", + "smithay-client-toolkit 0.20.0", + "wayland-backend", +] + +[[package]] +name = "smol_str" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead" +dependencies = [ + "serde", +] + +[[package]] +name = "spirv" +version = "0.4.0+sdk-1.4.341.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + [[package]] name = "syn" version = "2.0.119" @@ -603,6 +3423,26 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "sys-locale" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4" +dependencies = [ + "libc", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -610,10 +3450,28 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom", + "getrandom 0.4.3", "once_cell", - "rustix", - "windows-sys", + "rustix 1.1.6", + "windows-sys 0.61.2", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", ] [[package]] @@ -622,7 +3480,18 @@ version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "thiserror-impl", + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -636,24 +3505,180 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.19+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "tree_magic_mini" +version = "3.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" +dependencies = [ + "memchr", + "nom", + "petgraph", +] + +[[package]] +name = "type-map" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb30dbbd9036155e74adad6812e9898d03ec374946234fbcebd5dfc7b9187b90" +dependencies = [ + "rustc-hash 2.1.3", +] + [[package]] name = "typed-path" version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + [[package]] name = "typenum" version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unicode-properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" + +[[package]] +name = "unicode-script" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa04c955db05429d464c74d495c1ee677e1866e783a4c3747f9c0cef7756cabf" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + [[package]] name = "unicode-width" version = "0.2.3" @@ -666,6 +3691,79 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3" +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "uuid" +version = "1.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a06f08a856b009bc7bbaf7d3e79808595d032dd19074c0c2ef26e49e03e6bdc" +dependencies = [ + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "vello_common" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbb2141a2bca6e6d598e471fd4d1d7eed8e020aad6a28187edda07f091a325dd" +dependencies = [ + "bytemuck", + "fearless_simd", + "guillotiere", + "log", + "peniko", + "png", + "smallvec", + "thiserror 2.0.21", +] + +[[package]] +name = "vello_cpu" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ace506ca414548966fcf3c283be94eb1cad8254de488791ee698bf438b0890a9" +dependencies = [ + "bytemuck", + "glifo", + "hashbrown 0.17.1", + "png", + "vello_common", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + [[package]] name = "walkdir" version = "2.5.0" @@ -676,6 +3774,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + [[package]] name = "wasm-bindgen" version = "0.2.130" @@ -688,6 +3795,17 @@ dependencies = [ "wasm-bindgen-shared", ] +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + [[package]] name = "wasm-bindgen-macro" version = "0.2.130" @@ -720,6 +3838,151 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wayland-backend" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" +dependencies = [ + "cc", + "downcast-rs", + "rustix 1.1.6", + "scoped-tls", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags 2.13.2", + "rustix 1.1.6", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-csd-frame" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e" +dependencies = [ + "bitflags 2.13.2", + "cursor-icon", + "wayland-backend", +] + +[[package]] +name = "wayland-cursor" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" +dependencies = [ + "rustix 1.1.6", + "wayland-client", + "xcursor", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-experimental" +version = "20250721.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40a1f863128dcaaec790d7b4b396cc9b9a7a079e878e18c47e6c2d2c5a8dcbb1" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-misc" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9567599ef23e09b8dad6e429e5738d4509dfc46b3b21f32841a304d16b29c8" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-plasma" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "dlib", + "log", + "once_cell", + "pkg-config", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "web-time" version = "1.1.0" @@ -730,13 +3993,218 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webbrowser" +version = "1.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe8d20d0214027baf11b8b0cc307c1da7657d8f4db9aa956f7de27a6fb1acbd5" +dependencies = [ + "jni", + "log", + "ndk-context", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "url", + "web-sys", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "wgpu" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527ccdf43dd5b2e8676eed9984ce00e2bbb0a1b85b70c1969dcb6cd2eb55ab9e" +dependencies = [ + "arrayvec", + "bitflags 2.13.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "js-sys", + "log", + "naga", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "smallvec", + "static_assertions", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "wgpu-core", + "wgpu-hal", + "wgpu-types", +] + +[[package]] +name = "wgpu-core" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14" +dependencies = [ + "arrayvec", + "bit-set", + "bit-vec", + "bitflags 2.13.2", + "bytemuck", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "indexmap", + "log", + "naga", + "naga-types", + "once_cell", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "rustc-hash 1.1.0", + "smallvec", + "thiserror 2.0.21", + "wgpu-core-deps-apple", + "wgpu-core-deps-emscripten", + "wgpu-core-deps-wasm", + "wgpu-core-deps-windows-linux-android", + "wgpu-hal", + "wgpu-naga-bridge", + "wgpu-types", +] + +[[package]] +name = "wgpu-core-deps-apple" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "061f3d319a40d39d00b1ecc2c33b89fe21d4e6fe01859df3500a3a8ecccd6b68" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-emscripten" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98b86cf4abf524a902dd35f18ca6a3f08fc2ae9847c8f10b48e30491b1f0b86" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-wasm" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d260ca2ca8adc654f513a869bf3cac0b47f5b8d3f87803d6942015f8de597aae" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-windows-linux-android" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7586165fd5f6d881cb9ce4bb71f40d6caab2c0f1837e3fc1d9788a197fb6004f" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-hal" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6b7fb58561a792bc237628ba0792e332de418fefe145f13b5ed8201e6d52f58" +dependencies = [ + "android_system_properties", + "arrayvec", + "ash", + "bit-set", + "bitflags 2.13.2", + "block2 0.6.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "glow", + "glutin_wgl_sys", + "gpu-allocator", + "hashbrown 0.17.1", + "js-sys", + "khronos-egl", + "libc", + "libloading", + "log", + "naga", + "naga-types", + "ndk-sys", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "once_cell", + "ordered-float", + "parking_lot", + "portable-atomic", + "portable-atomic-util", + "profiling", + "range-alloc", + "raw-window-handle", + "raw-window-metal", + "renderdoc-sys", + "smallvec", + "static_assertions", + "thiserror 2.0.21", + "wasm-bindgen", + "wayland-sys", + "web-sys", + "wgpu-naga-bridge", + "wgpu-types", + "windows", + "windows-core", + "windows-result", +] + +[[package]] +name = "wgpu-naga-bridge" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f62e73117bb7a62bfd9c5a5841438a823f6566c6442a808ee269d2d055c081" +dependencies = [ + "naga", + "wgpu-types", +] + +[[package]] +name = "wgpu-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99dad6f1fbdbbdb4c278a6508b059d44688f5cebddf78d005a46a31340269286" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "js-sys", + "log", + "naga-types", + "raw-window-handle", + "static_assertions", + "web-sys", +] + [[package]] name = "winapi-util" version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -840,6 +4308,24 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[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" @@ -849,6 +4335,22 @@ 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-threading" version = "0.2.1" @@ -858,6 +4360,421 @@ dependencies = [ "windows-link", ] +[[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 = "winit" +version = "0.30.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d" +dependencies = [ + "ahash", + "android-activity", + "atomic-waker", + "bitflags 2.13.2", + "block2 0.5.1", + "bytemuck", + "calloop 0.13.0", + "cfg_aliases", + "concurrent-queue", + "core-foundation", + "core-graphics", + "cursor-icon", + "dpi", + "js-sys", + "libc", + "memmap2", + "ndk", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", + "objc2-ui-kit 0.2.2", + "orbclient", + "percent-encoding", + "pin-project", + "raw-window-handle", + "redox_syscall 0.4.1", + "rustix 0.38.44", + "smithay-client-toolkit 0.19.2", + "smol_str", + "tracing", + "unicode-segmentation", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-plasma", + "web-sys", + "web-time", + "windows-sys 0.52.0", + "x11-dl", + "x11rb", + "xkbcommon-dl", +] + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wl-clipboard-rs" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "959c7ac3b8afde864f7a7448ac16f29b2b83350b7eccbf77fb781c3999aa6848" +dependencies = [ + "libc", + "log", + "os_pipe", + "rustix 1.1.6", + "thiserror 2.0.21", + "tree_magic_mini", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "as-raw-xcb-connection", + "gethostname", + "libc", + "libloading", + "once_cell", + "rustix 1.1.6", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "xcursor" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" + +[[package]] +name = "xkbcommon-dl" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5" +dependencies = [ + "bitflags 2.13.2", + "dlib", + "log", + "once_cell", + "xkeysym", +] + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" + +[[package]] +name = "xml-rs" +version = "0.8.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" + +[[package]] +name = "yeslogic-fontconfig-sys" +version = "6.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d8b8abf912b9a29ff112e1671c97c33636903d13a69712037190e6805af4f76" +dependencies = [ + "dlib", + "once_cell", + "pkg-config", +] + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix 1.1.6", + "serde", + "serde_repr", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus-lockstep" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863" +dependencies = [ + "zbus_xml", + "zvariant", +] + +[[package]] +name = "zbus-lockstep-macros" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10da05367f3a7b7553c8cdf8fa91aee6b64afebe32b51c95177957efc47ca3a0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "zbus-lockstep", + "zbus_xml", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" +dependencies = [ + "serde", + "winnow", + "zvariant", +] + +[[package]] +name = "zbus_xml" +version = "5.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a" +dependencies = [ + "serde", + "winnow", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "939f186d9ecebe044315a5cb6d6f78568bbc21152adc954d5a0c2f58bdbc9920" +dependencies = [ + "serde", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "zip" version = "9.3.0" @@ -866,13 +4783,13 @@ checksum = "eaeb7f16d2605b49aef586996ded29e65642fab7259a3077e537351df6d80426" dependencies = [ "crc32fast", "flate2", - "getrandom", + "getrandom 0.4.3", "indexmap", "libc", "memchr", "nix", "typed-path", - "windows-sys", + "windows-sys 0.61.2", "zopfli", ] @@ -899,3 +4816,59 @@ dependencies = [ "log", "simd-adler32", ] + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] + +[[package]] +name = "zvariant" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.9", + "winnow", +] diff --git a/Cargo.toml b/Cargo.toml index 6cf9462..f676259 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,6 +4,7 @@ members = [ "senbei-crypto", "senbei-elf", "senbei-engine", + "senbei-gui", "senbei-i18n", "senbei-io", "senbei-metadata", @@ -25,11 +26,28 @@ license = "AGPL-3.0-only" [workspace.dependencies] aes = "0.9" anyhow = "1" +# The GUI renders with wgpu (Direct3D 12 or Vulkan); no OpenGL dependency. +eframe = { version = "0.37", default-features = false, features = [ + "accesskit", + "clipboard", + "default_fonts", + "links", + "persistence", + "wayland", + "wgpu", + "x11", +] } +egui = "0.37" +egui_extras = { version = "0.37", default-features = false } +egui_system_font_provider = "0.37" +fontique = "0.11" goblin = "0.10" indicatif = "0.18" libc = "0.2" memmap2 = "0.9" owo-colors = "4" +png = "0.18" +rfd = "0.18" serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.11" diff --git a/senbei-gui/Cargo.toml b/senbei-gui/Cargo.toml new file mode 100644 index 0000000..eeff583 --- /dev/null +++ b/senbei-gui/Cargo.toml @@ -0,0 +1,35 @@ +[package] +name = "senbei-gui" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +description = "Native desktop front end for Senbei" + +[[bin]] +name = "senbei-gui" +path = "src/main.rs" + +[dependencies] +anyhow.workspace = true +egui.workspace = true +egui_extras.workspace = true +senbei-engine.workspace = true +senbei-i18n.workspace = true +senbei-io.workspace = true +senbei-metadata.workspace = true +serde.workspace = true +serde_json.workspace = true + +# The native shell: window, renderer, file dialogs, system fonts. The UI layer +# above it only uses egui, so it also builds for wasm32. +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +eframe.workspace = true +egui_system_font_provider.workspace = true +fontique.workspace = true +png.workspace = true +rfd.workspace = true +tempfile.workspace = true + +[lints] +workspace = true diff --git a/senbei-gui/assets/fonts/Asul-Bold.ttf b/senbei-gui/assets/fonts/Asul-Bold.ttf new file mode 100644 index 0000000..c5f701a Binary files /dev/null and b/senbei-gui/assets/fonts/Asul-Bold.ttf differ diff --git a/senbei-gui/assets/fonts/OFL.txt b/senbei-gui/assets/fonts/OFL.txt new file mode 100644 index 0000000..d068f5c --- /dev/null +++ b/senbei-gui/assets/fonts/OFL.txt @@ -0,0 +1,94 @@ +Copyright (c) 2011 by Mariela Monsalve (marmonsalve@gmail.com), +with Reserved Font Name "Asul". All Rights Reserved. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/senbei-gui/assets/icon-256.png b/senbei-gui/assets/icon-256.png new file mode 100644 index 0000000..2cb9556 Binary files /dev/null and b/senbei-gui/assets/icon-256.png differ diff --git a/senbei-gui/assets/icon-64.png b/senbei-gui/assets/icon-64.png new file mode 100644 index 0000000..2425816 Binary files /dev/null and b/senbei-gui/assets/icon-64.png differ diff --git a/senbei-gui/src/backend.rs b/senbei-gui/src/backend.rs new file mode 100644 index 0000000..e4ca51d --- /dev/null +++ b/senbei-gui/src/backend.rs @@ -0,0 +1,284 @@ +//! The seam between the window and the machine it runs on. +//! +//! The window sends [`Request`]s and drains [`Event`]s; it never touches the +//! filesystem itself, so the same window can sit on another backend (a browser +//! one has no folders and cannot write outputs, and says so in its +//! [`Capabilities`]). + +use std::num::NonZeroUsize; +use std::path::PathBuf; +use std::sync::Arc; + +use senbei_engine::ProtectionProfile; +use senbei_engine::android::ResourceLimits; +use senbei_i18n::Step; +use senbei_io::report::{CompanionState, ContainerReport, InputReport, Mode, Report, ScanReport}; + +pub type ItemId = u64; +pub type GroupId = u64; +pub type JobId = u64; + +/// What a backend can do. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Capabilities { + /// Add folders and run them with folder semantics. + pub folders: bool, + /// Write unpacked outputs. + pub unpack: bool, + /// Show a file in the system file manager. + pub reveal: bool, +} + +/// What one input is, from a light look before anything runs. +#[derive(Debug, Clone)] +pub enum Identity { + /// The system could not read it; its own words, in its own language. + Unreadable(String), + /// It exists but is neither a file nor a folder (a device or a pipe). + NotAFile, + NotTarget { + size: u64, + }, + Windows { + size: u64, + profile: Box, + companion: CompanionState, + companion_path: Option, + }, + Metadata { + size: u64, + identity: Option, + }, + AndroidLibrary { + size: u64, + }, + Package { + size: u64, + container: Result, String>, + }, +} + +impl Identity { + pub fn size(&self) -> Option { + match self { + Identity::Unreadable(_) | Identity::NotAFile => None, + Identity::NotTarget { size } + | Identity::Windows { size, .. } + | Identity::Metadata { size, .. } + | Identity::AndroidLibrary { size } + | Identity::Package { size, .. } => Some(*size), + } + } + + /// True when a run has nothing to recover. + pub fn not_protected(&self) -> bool { + match self { + Identity::NotTarget { .. } => true, + Identity::Windows { profile, .. } => { + profile.recognition != senbei_engine::RecognitionStatus::Recognized + } + _ => false, + } + } +} + +/// Where an unpack writes. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum Output { + /// `unpack\` beside each added file, or inside each added folder. + Beside, + /// One chosen folder. + Folder(PathBuf), +} + +/// Settings a run takes from the window. +#[derive(Debug, Clone)] +pub struct RunOptions { + pub write_log: bool, + pub threads: Option, + pub scan_all: bool, + pub limits: ResourceLimits, + /// Keep the restored image of an inspection or dry run in memory. + pub keep_bytes: bool, + /// Largest restored image kept, in bytes. + pub keep_cap: u64, +} + +/// One piece of work in a job. +#[derive(Debug, Clone)] +pub enum Unit { + /// One file. An unpack writes its output into `out_dir`. + File { path: PathBuf, out_dir: PathBuf }, + /// Every target below `root`, with folder semantics: companions, loose + /// library and metadata pairing, package groups. An unpack mirrors the + /// tree into `out_dir`. + Folder { root: PathBuf, out_dir: PathBuf }, +} + +impl Unit { + pub fn path(&self) -> &PathBuf { + match self { + Unit::File { path, .. } => path, + Unit::Folder { root, .. } => root, + } + } +} + +/// A run of one mode over some units, one after another. +#[derive(Debug, Clone)] +pub struct Job { + pub id: JobId, + pub mode: Mode, + pub units: Vec, + pub options: RunOptions, +} + +/// Bytes a run produced for one output. +#[derive(Debug, Clone)] +pub enum Produced { + /// Held in memory for this session. + Kept(Arc<[u8]>), + /// Written by an unpack; read from disk when shown. + OnDisk(PathBuf), + /// Larger than the memory cap; summarized without bytes. + TooLarge(u64), + /// Keeping bytes is turned off. + NotKept, +} + +/// Bytes to show in the hex view. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum Source { + /// A file on disk, as it is. + File(PathBuf), + /// The loader's header page followed by its `._` payload. + Spliced { stub: PathBuf, companion: PathBuf }, + /// One entry of an app package, by its report label. + Entry { package: PathBuf, label: String }, +} + +/// A dialog the window asked for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Pick { + Files, + Folder, + Output, +} + +/// What the window asks of the backend. +#[derive(Debug, Clone)] +pub enum Request { + Identify(Vec<(ItemId, PathBuf)>), + Scan { + group: GroupId, + root: PathBuf, + scan_all: bool, + limits: ResourceLimits, + }, + Run(Box), + /// Stop the running job before its next input. + Cancel, + Load { + source: Source, + limits: ResourceLimits, + }, + Pick(Pick), + Reveal(PathBuf), + Save { + name: String, + contents: Vec, + }, +} + +/// What the backend reports back. +#[derive(Debug, Clone)] +pub enum Event { + Identified(ItemId, Box), + ScanProgress { + group: GroupId, + found: usize, + }, + Scanned { + group: GroupId, + targets: Vec<(PathBuf, Box)>, + scan: ScanReport, + }, + UnitStarted { + job: JobId, + unit: usize, + at: String, + }, + /// A folder unit's scan finished with this many inputs to process. + UnitScanned { + job: JobId, + unit: usize, + inputs: usize, + at: String, + }, + InputStarted { + job: JobId, + unit: usize, + path: PathBuf, + at: String, + }, + Step { + job: JobId, + step: Step, + position: Option<(u8, u8)>, + at: String, + }, + Detail { + job: JobId, + text: String, + at: String, + }, + Produced { + job: JobId, + path: PathBuf, + restored: Option, + entries: Vec<(String, Produced)>, + }, + InputFinished { + job: JobId, + unit: usize, + report: Box, + at: String, + }, + /// One unit ended. `report` carries the run-level part (mode, scan, + /// run errors, timing); its inputs arrived one by one already. + UnitFinished { + job: JobId, + unit: usize, + report: Box, + at: String, + }, + JobFinished { + job: JobId, + cancelled: bool, + }, + Loaded { + source: Source, + result: Result, LoadError>, + }, + Picked(Pick, Vec), + Saved(Result), + /// Something the window could not do, in English from the system. + Failed(String), +} + +/// Why a view has no bytes to show. +#[derive(Debug, Clone)] +pub enum LoadError { + /// A system or engine message. + Message(senbei_i18n::Message), + /// The file is larger than a view reads. + TooLarge { size: u64, limit: u64 }, +} + +/// A machine the window can run on. +pub trait Backend { + fn capabilities(&self) -> Capabilities; + fn send(&self, request: Request); + /// The next event, if one is waiting. + fn poll(&self) -> Option; +} diff --git a/senbei-gui/src/format.rs b/senbei-gui/src/format.rs new file mode 100644 index 0000000..a651769 --- /dev/null +++ b/senbei-gui/src/format.rs @@ -0,0 +1,136 @@ +//! Number, size, and time formatting shared by every view. + +/// `0x1A2B`, upper-case, at least `width` digits. +pub fn hex(value: u64) -> String { + format!("0x{value:X}") +} + +/// `0x0000_1A2B`-style fixed width, without separators. +pub fn hex_w(value: u64, width: usize) -> String { + format!("0x{value:0width$X}") +} + +/// `12,345` with thousands separators. +pub fn num(value: u64) -> String { + let digits = value.to_string(); + let mut out = String::with_capacity(digits.len() + digits.len() / 3); + for (index, ch) in digits.chars().enumerate() { + if index > 0 && (digits.len() - index).is_multiple_of(3) { + out.push(','); + } + out.push(ch); + } + out +} + +/// Binary size: `512 B`, `1.5 KiB`, `24.9 MiB`, `1.02 GiB`. +pub fn bytes(value: u64) -> String { + const KIB: f64 = 1024.0; + let v = value as f64; + if value < 1024 { + format!("{value} B") + } else if v < KIB * KIB { + format!("{:.1} KiB", v / KIB) + } else if v < KIB * KIB * KIB { + format!("{:.1} MiB", v / (KIB * KIB)) + } else { + format!("{:.2} GiB", v / (KIB * KIB * KIB)) + } +} + +/// `15 ms` or `1.42 s`. +pub fn ms(value: u64) -> String { + if value >= 1000 { + format!("{:.2} s", value as f64 / 1000.0) + } else { + format!("{value} ms") + } +} + +/// `0:01.4` — minutes, seconds, tenths, for a running clock. +pub fn clock(elapsed_ms: u64) -> String { + let tenths = elapsed_ms / 100; + format!("{}:{:02}.{}", tenths / 600, (tenths / 10) % 60, tenths % 10) +} + +/// The final path component, accepting either separator. +pub fn base_name(path: &str) -> &str { + path.rsplit(['\\', '/']).next().unwrap_or(path) +} + +/// `head…tail` of a hash for display. +pub fn short_hash(sha256: &str) -> String { + if sha256.len() <= 24 { + return sha256.to_owned(); + } + format!("{}…{}", &sha256[..16], &sha256[sha256.len() - 8..]) +} + +/// Parse `0x14E0`, `14E0`, or `14e0` as hexadecimal. +pub fn parse_hex(text: &str) -> Option { + let text = text.trim(); + let digits = text + .strip_prefix("0x") + .or_else(|| text.strip_prefix("0X")) + .unwrap_or(text); + if digits.is_empty() { + return None; + } + u64::from_str_radix(&digits.replace('_', ""), 16).ok() +} + +/// Bytes to search for: `4D 5A` or `0x4D5A` as hex, anything else as text. +pub fn parse_needle(text: &str) -> Vec { + let trimmed = text.trim(); + let hexish: String = trimmed + .strip_prefix("0x") + .or_else(|| trimmed.strip_prefix("0X")) + .unwrap_or(trimmed) + .chars() + .filter(|ch| !ch.is_whitespace()) + .collect(); + if hexish.len() >= 2 + && hexish.len().is_multiple_of(2) + && hexish.chars().all(|ch| ch.is_ascii_hexdigit()) + { + return (0..hexish.len()) + .step_by(2) + .filter_map(|index| u8::from_str_radix(&hexish[index..index + 2], 16).ok()) + .collect(); + } + trimmed.bytes().collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn formats_match_the_mockup() { + assert_eq!(hex(0x14E0), "0x14E0"); + assert_eq!(hex_w(0x8664, 4), "0x8664"); + assert_eq!(hex_w(0x1000, 8), "0x00001000"); + assert_eq!(num(1234567), "1,234,567"); + assert_eq!(num(999), "999"); + assert_eq!(bytes(512), "512 B"); + assert_eq!(bytes(2048), "2.0 KiB"); + assert_eq!(bytes(3 * 1024 * 1024), "3.0 MiB"); + assert_eq!(ms(15), "15 ms"); + assert_eq!(ms(1420), "1.42 s"); + assert_eq!(clock(1400), "0:01.4"); + assert_eq!(clock(61_000), "1:01.0"); + assert_eq!(base_name(r"D:\a\b.dll"), "b.dll"); + assert_eq!(base_name("a/b.so"), "b.so"); + } + + #[test] + fn parses_offsets_and_needles() { + assert_eq!(parse_hex("0x14E0"), Some(0x14E0)); + assert_eq!(parse_hex("14e0"), Some(0x14E0)); + assert_eq!(parse_hex("zz"), None); + assert_eq!(parse_needle("4D 5A"), vec![0x4D, 0x5A]); + assert_eq!(parse_needle("0x4D5A"), vec![0x4D, 0x5A]); + assert_eq!(parse_needle("MZ"), b"MZ".to_vec()); + assert_eq!(parse_needle("abc"), b"abc".to_vec()); + } +} diff --git a/senbei-gui/src/labels.rs b/senbei-gui/src/labels.rs new file mode 100644 index 0000000..2fdf4f2 --- /dev/null +++ b/senbei-gui/src/labels.rs @@ -0,0 +1,330 @@ +//! Report values, engine messages, and research notes as the window shows them. +//! +//! Report enums are looked up by their wire spelling (`layout.exe_style`), as +//! the approved mockup did, so a value without a label still reads as text. +//! Engine messages keep their own translations except the three the window +//! words differently; research notes the engine writes in English are matched +//! to translated notes where one exists. + +use std::borrow::Cow; + +use senbei_i18n::{Message, Msg, Step}; +use serde::Serialize; + +use crate::text::{Text, lang, t}; + +/// The wire spelling of a report enum value, such as `not_attempted`. +pub fn wire(value: &impl Serialize) -> Option { + match serde_json::to_value(value).ok()? { + serde_json::Value::String(text) => Some(text), + _ => None, + } +} + +/// The label of a report value: the catalog entry `prefix.value`, or the +/// value itself with spaces when the catalog has none. +pub fn tv(prefix: &str, value: &impl Serialize) -> Cow<'static, str> { + match wire(value) { + Some(value) => tv_str(prefix, &value), + None => "—".into(), + } +} + +/// [`tv`] for a value that is already a wire string. +pub fn tv_str(prefix: &str, value: &str) -> Cow<'static, str> { + match Text::by_key(&format!("{prefix}.{value}")) { + Some(text) => t(text), + None => value.replace('_', " ").into(), + } +} + +/// An engine message ready to show: the text in the display language, the +/// recorded English when the text leaves part of it out, and whether the +/// window hides it because it says nothing about the input. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Shown { + pub text: String, + pub technical: Option, + pub quiet: bool, +} + +/// How the window shows `message`. +/// Why a view has no bytes, in the display language. +pub fn load_error(error: &crate::backend::LoadError) -> String { + match error { + crate::backend::LoadError::Message(shown) => message(shown).text, + crate::backend::LoadError::TooLarge { size, limit } => t(Text::HexTooLarge { + size: crate::format::bytes(*size), + limit: crate::format::bytes(*limit), + }) + .into_owned(), + } +} + +pub fn message(message: &Message) -> Shown { + let quiet = matches!( + message.msg(), + Some(Msg::OutputNotRetained | Msg::DryRunDiscarded | Msg::CompanionUnmatched) + ); + let shown = |text: String, technical: Option| Shown { + text, + technical, + quiet, + }; + match message.msg() { + // The three messages the window words for itself. + Some(Msg::CompanionMissing) => shown(t(Text::MsgCompanionMissing).into_owned(), None), + Some(Msg::InternalPanic { + file, line, column, .. + }) => shown( + t(Text::MsgInternalPanic { + loc: format!("{file}:{line}:{column}"), + }) + .into_owned(), + Some(message.text().to_owned()), + ), + Some(Msg::LimitEntry { requested, limit }) => match limited_entry(message.text()) { + Some(entry) => shown( + t(Text::MsgLimitEntry { + entry: entry.to_owned(), + size: requested.to_string(), + limit: limit.to_string(), + }) + .into_owned(), + Some(message.text().to_owned()), + ), + None => engine(message, quiet), + }, + Some(_) => engine(message, quiet), + None => note(message.text()), + } +} + +/// An engine message in its own translation, with the English it leaves out. +fn engine(message: &Message, quiet: bool) -> Shown { + let lang = lang(); + Shown { + text: message.localized(lang).into_owned(), + technical: message.detail(lang).map(str::to_owned), + quiet, + } +} + +/// The entry an `extract `…`` context names, as a limit error records it. +fn limited_entry(text: &str) -> Option<&str> { + let rest = text.strip_prefix("extract `")?; + Some(&rest[..rest.find('`')?]) +} + +/// How the window shows a research note the engine wrote in English. +pub fn note(text: &str) -> Shown { + let (translated, quiet) = match_note(text); + Shown { + text: translated + .map(|text| t(text).into_owned()) + .unwrap_or_else(|| text.to_owned()), + technical: None, + quiet, + } +} + +/// True when the window hides this note. +pub fn is_quiet(text: &str) -> bool { + match_note(text).1 +} + +fn match_note(text: &str) -> (Option, bool) { + let exact = match text { + "research inspection: no output file was retained" => Some((None, true)), + "dry run: the produced output was discarded" => Some((None, true)), + "a sibling `._` exists but is not this stub's payload" => Some((None, true)), + "prefix decoded in scratch; later stages still require a full recovery" => { + Some((Some(Text::NotePrefixScratch), true)) + } + "anchor and stage1 descriptor validate; full stage decryption requires recovery" => { + Some((Some(Text::NoteAnchorValidates), true)) + } + "bounded anchor probe only" => Some((Some(Text::NoteBoundedAnchor), true)), + "bounded prefix only; not a recovered image" => Some((Some(Text::NoteBoundedPrefix), true)), + "candidates reported without stage validation" => { + Some((Some(Text::NoteCandidatesUnvalidated), true)) + } + "shell table shape matches the declared image; second-stage decryption requires recovery" => { + Some((Some(Text::NoteShellTableMatches), true)) + } + "certificate directory uses a file offset, not an RVA" => { + Some((Some(Text::NoteCertFileOffset), false)) + } + "no import table" => Some((Some(Text::NoteNoImportTable), false)), + "header magic is not a supported protection header" => { + Some((Some(Text::NoteMagicNotSupported), false)) + } + "no anchor field in the decoded payload window" => { + Some((Some(Text::NoteNoAnchorField), false)) + } + "no shell table shape in the decoded payload window" => { + Some((Some(Text::NoteNoShellTable), false)) + } + "shell discovery needs a decoded payload prefix" => { + Some((Some(Text::NoteShellNeedsPrefix), false)) + } + _ => None, + }; + if let Some(found) = exact { + return found; + } + (shaped_note(text), false) +} + +/// Notes that carry values. +fn shaped_note(text: &str) -> Option { + if let Some(rva) = text + .strip_prefix("entry point ") + .and_then(|rest| rest.strip_suffix(" lies in this section")) + { + return Some(Text::NoteEntryPointInside { + rva: rva.to_owned(), + }); + } + if let Some((end, len)) = text + .strip_prefix("raw range ends at ") + .and_then(|rest| rest.split_once(", input is ")) + && let Some(len) = len.strip_suffix(" bytes") + { + return Some(Text::NoteRawPastEof { + end: end.to_owned(), + len: len.to_owned(), + }); + } + if let Some(value) = text + .strip_prefix("header table decoded but info[1] is ") + .and_then(|rest| rest.strip_suffix(", not the supported magic")) + { + return Some(Text::NoteMagicUnsupportedValue { + value: value.to_owned(), + }); + } + let block = text.strip_prefix("relocation block ")?; + if let Some((block, rest)) = block.split_once(" entry ") + && let Some((entry, ty)) = rest.split_once(" has unsupported type ") + { + return Some(Text::NoteRelocUnsupportedType { + block: block.to_owned(), + entry: entry.to_owned(), + ty: ty.to_owned(), + }); + } + if let Some((block, rest)) = block.split_once(" declares size ") + && let Some(size) = rest.strip_suffix(", which does not fit the directory") + { + return Some(Text::NoteRelocBadSize { + block: block.to_owned(), + size: size.to_owned(), + }); + } + None +} + +/// The window's title for a recovery step. +pub fn step_title(step: &Step) -> Cow<'static, str> { + let text = match step { + Step::DecryptHeader => Text::StepDecryptHeader, + Step::DecryptPayload => Text::StepDecryptPayload, + Step::LocateConfig | Step::Pe32LocateConfig => Text::StepLocateConfig, + Step::DecryptStage2 => Text::StepDecryptStage2, + Step::DecryptStages3To5 => Text::StepDecryptStages35, + Step::DecryptSections | Step::DecryptSectionsNewLayout => Text::StepDecryptSections, + Step::LoadSections => Text::StepLoadSections, + Step::DecryptImports | Step::Pe32Imports => Text::StepDecryptImports, + Step::RebuildHeaders => Text::StepRebuildHeaders, + Step::Pe32Stages => Text::StepPe32Stages, + Step::Pe32EighthStage => Text::StepPe32Eighth, + Step::Pe32Load => Text::StepPe32Load, + Step::Pe32Text { .. } => Text::StepPe32Text, + Step::Pe32TextSkip => Text::StepPe32TextSkip, + Step::Pe32Rebuild => Text::StepPe32Rebuild, + Step::InitKeys => Text::StepInitKeys, + Step::DecryptKeyTable => Text::StepDecryptKeyTable, + Step::DecryptPrimary => Text::StepDecryptPrimary, + Step::RelocsParams => Text::StepRelocsParams, + Step::DecryptBlock1 => Text::StepDecryptBlock1, + Step::DecryptBlocks2To3 => Text::StepDecryptBlock23, + Step::DecryptBlock4 => Text::StepDecryptBlock4, + Step::DllSections => Text::StepDllSections, + Step::FixHeaders => Text::StepFixHeaders, + Step::AndroidPrimary => Text::StepAndroidPrimary, + Step::AndroidAuxiliary => Text::StepAndroidAux, + Step::AndroidTables => Text::StepAndroidTables, + other => { + use senbei_i18n::Localize; + return other.localize(lang()).into_owned().into(); + } + }; + t(text) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn report_values_use_their_wire_spelling() { + assert_eq!( + wire(&senbei_engine::LayoutKind::ExeStyle).as_deref(), + Some("exe_style") + ); + assert_eq!( + tv("layout", &senbei_engine::LayoutKind::ExeStyle), + "EXE-style loader" + ); + assert_eq!(tv_str("layout", "brand_new"), "brand new"); + } + + #[test] + fn research_notes_are_matched_with_their_values() { + let shown = note("entry point 0x1B5C lies in this section"); + assert_eq!(shown.text, "entry point 0x1B5C lies in this section"); + assert!(!shown.quiet); + assert_eq!( + shaped_note("raw range ends at 0x2000, input is 0x1000 bytes"), + Some(Text::NoteRawPastEof { + end: "0x2000".into(), + len: "0x1000".into() + }) + ); + assert_eq!( + shaped_note("relocation block 3 entry 7 has unsupported type 9"), + Some(Text::NoteRelocUnsupportedType { + block: "3".into(), + entry: "7".into(), + ty: "9".into() + }) + ); + assert!(is_quiet("bounded anchor probe only")); + assert!(!is_quiet("something new")); + assert_eq!(note("something new").text, "something new"); + } + + #[test] + fn the_window_words_three_messages_itself() { + let missing = message(&Message::new(Msg::CompanionMissing)); + assert!(!missing.text.contains("browser"), "{}", missing.text); + let limit = Message::with_text( + Msg::LimitEntry { + requested: 9000, + limit: 4096, + }, + "extract `lib/arm64-v8a/libx.so`: resource limit: entry of 9000 bytes exceeds the 4096-byte ceiling", + ); + let shown = message(&limit); + assert!( + shown + .text + .starts_with("lib/arm64-v8a/libx.so is 9000 bytes"), + "{}", + shown.text + ); + assert!(shown.technical.is_some()); + assert!(message(&Message::new(Msg::OutputNotRetained)).quiet); + } +} diff --git a/senbei-gui/src/lib.rs b/senbei-gui/src/lib.rs new file mode 100644 index 0000000..d9aa19a --- /dev/null +++ b/senbei-gui/src/lib.rs @@ -0,0 +1,18 @@ +//! Senbei's desktop front end. +//! +//! The window ([`Workbench`]) talks to the machine only through a +//! [`backend::Backend`]; the native backend runs the same recovery pipeline as +//! the command line, in process. + +pub mod backend; +pub mod format; +pub mod labels; +pub mod model; +#[cfg(not(target_arch = "wasm32"))] +pub mod native; +pub mod settings; +pub mod text; +pub mod theme; +pub mod ui; + +pub use ui::Workbench; diff --git a/senbei-gui/src/main.rs b/senbei-gui/src/main.rs new file mode 100644 index 0000000..5d1b815 --- /dev/null +++ b/senbei-gui/src/main.rs @@ -0,0 +1,111 @@ +//! The Senbei desktop window. + +#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] + +#[cfg(not(target_arch = "wasm32"))] +fn main() -> eframe::Result { + native::run() +} + +#[cfg(target_arch = "wasm32")] +fn main() {} + +#[cfg(not(target_arch = "wasm32"))] +mod native { + use std::sync::Arc; + + use senbei_gui::Workbench; + use senbei_gui::native::{NativeBackend, SystemFonts, debug_variables}; + use senbei_gui::settings::Settings; + + const SETTINGS_KEY: &str = "settings"; + const ICON_256: &[u8] = include_bytes!("../assets/icon-256.png"); + const ICON_64: &[u8] = include_bytes!("../assets/icon-64.png"); + + /// An RGBA image from an embedded PNG. + fn decode(png_bytes: &[u8]) -> Option<(Vec, u32, u32)> { + let mut decoder = png::Decoder::new(std::io::Cursor::new(png_bytes)); + decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::ALPHA); + let mut reader = decoder.read_info().ok()?; + let mut buffer = vec![0; reader.output_buffer_size()?]; + let info = reader.next_frame(&mut buffer).ok()?; + if info.color_type != png::ColorType::Rgba || info.bit_depth != png::BitDepth::Eight { + return None; + } + buffer.truncate(info.buffer_size()); + Some((buffer, info.width, info.height)) + } + + struct App { + workbench: Workbench, + } + + impl eframe::App for App { + fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { + self.workbench.logic(ctx); + } + + fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + self.workbench.ui(ui); + } + + fn save(&mut self, storage: &mut dyn eframe::Storage) { + eframe::set_value(storage, SETTINGS_KEY, &self.workbench.settings); + } + } + + pub fn run() -> eframe::Result { + let detected = senbei_io::locale::detect(); + let window_icon = decode(ICON_256).map(|(rgba, width, height)| egui::IconData { + rgba, + width, + height, + }); + let mut viewport = egui::ViewportBuilder::default() + .with_title("Senbei") + .with_app_id("senbei") + .with_inner_size([1440.0, 900.0]) + .with_min_inner_size([960.0, 600.0]) + .with_drag_and_drop(true); + if let Some(icon) = window_icon { + viewport = viewport.with_icon(Arc::new(icon)); + } + let options = eframe::NativeOptions { + viewport, + // The window loads the display language's system fonts itself. + system_font_fallback: false, + ..Default::default() + }; + eframe::run_native( + "Senbei", + options, + Box::new(move |cc| { + let settings: Settings = cc + .storage + .and_then(|storage| eframe::get_value(storage, SETTINGS_KEY)) + .unwrap_or_default(); + let lang = settings.lang(detected); + cc.egui_ctx.add_font_provider(Arc::new( + egui_system_font_provider::SystemFontProvider::new() + .with_locale(Some(lang.tag())), + )); + let mut fonts = SystemFonts::new(); + let icon = decode(ICON_64).map(|(rgba, width, height)| { + egui::ColorImage::from_rgba_unmultiplied( + [width as usize, height as usize], + &rgba, + ) + }); + let workbench = Workbench::new( + Box::new(NativeBackend::new(cc.egui_ctx.clone())), + settings, + detected, + Some(Box::new(move |lang| fonts.set_for(lang))), + debug_variables(), + icon, + ); + Ok(Box::new(App { workbench })) + }), + ) + } +} diff --git a/senbei-gui/src/model.rs b/senbei-gui/src/model.rs new file mode 100644 index 0000000..d7fdf4d --- /dev/null +++ b/senbei-gui/src/model.rs @@ -0,0 +1,601 @@ +//! The session: what was added, what each input is, and what its last run found. + +use std::borrow::Cow; +use std::path::{Path, PathBuf}; + +use senbei_engine::{RecoveryStatus, ValidationStatus}; +use senbei_i18n::{Message, Step}; +use senbei_io::report::{ + EntryReport, EntryStatus, InputReport, InputStatus, Mode, Report, Role, ScanReport, Stage, + StageStatus, +}; + +use crate::backend::{GroupId, Identity, ItemId, Produced}; +use crate::labels::{tv, wire}; +use crate::text::{Text, t}; +use crate::theme::Tone; + +// ------------------------------------------------------------- verdicts + +/// The visible outcome of one input or entry. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Verdict { + Recovered, + Suspect, + Recognized, + Skipped, + Error, + Incomplete, + RecoveryFailed, + RecoveryBlocked, + Entry(EntryStatus), +} + +/// The input-list filter chips. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Filter { + #[default] + All, + Recovered, + Suspect, + Failed, + Skipped, +} + +impl Filter { + pub const ALL: [Filter; 5] = [ + Filter::All, + Filter::Recovered, + Filter::Suspect, + Filter::Failed, + Filter::Skipped, + ]; + + pub fn label(self) -> Cow<'static, str> { + t(match self { + Filter::All => Text::FilterAll, + Filter::Recovered => Text::FilterOk, + Filter::Suspect => Text::FilterSuspect, + Filter::Failed => Text::FilterFailed, + Filter::Skipped => Text::FilterSkipped, + }) + } +} + +impl Verdict { + pub fn of_input(input: &InputReport) -> Verdict { + let profile = input.profile.as_ref(); + let validation = profile.map(|profile| profile.static_validation); + if input.analysis_incomplete { + return Verdict::Incomplete; + } + match input.status { + InputStatus::Error => Verdict::Error, + InputStatus::Suspect => Verdict::Suspect, + _ if matches!( + validation, + Some(ValidationStatus::Warnings | ValidationStatus::Failed) + ) => + { + Verdict::Suspect + } + InputStatus::Skipped => Verdict::Skipped, + InputStatus::Recognized => match profile.map(|profile| profile.recovery) { + Some(RecoveryStatus::Failed) => Verdict::RecoveryFailed, + Some(RecoveryStatus::Blocked) => Verdict::RecoveryBlocked, + Some(RecoveryStatus::Succeeded) => Verdict::Recovered, + _ => Verdict::Recognized, + }, + InputStatus::Ok => Verdict::Recovered, + } + } + + pub fn of_entry(entry: &EntryReport) -> Verdict { + if entry.analysis_incomplete { + Verdict::Incomplete + } else { + Verdict::Entry(entry.status) + } + } + + pub fn tone(self) -> Tone { + match self { + Verdict::Recovered => Tone::Ok, + Verdict::Recognized => Tone::Info, + Verdict::Suspect => Tone::Warn, + Verdict::Error + | Verdict::Incomplete + | Verdict::RecoveryFailed + | Verdict::RecoveryBlocked => Tone::Err, + Verdict::Skipped => Tone::Skip, + Verdict::Entry(EntryStatus::Restored) => Tone::Ok, + Verdict::Entry(EntryStatus::Error) => Tone::Err, + Verdict::Entry(_) => Tone::Skip, + } + } + + pub fn label(self) -> Cow<'static, str> { + match self { + Verdict::Recovered => t(Text::StatusOk), + Verdict::Suspect => t(Text::StatusSuspect), + Verdict::Recognized => t(Text::StatusRecognized), + Verdict::Skipped => t(Text::StatusSkipped), + Verdict::Error => t(Text::StatusError), + Verdict::Incomplete => t(Text::StatusIncomplete), + Verdict::RecoveryFailed => t(Text::RecoveryFailed), + Verdict::RecoveryBlocked => t(Text::RecoveryBlocked), + Verdict::Entry(status) => tv("entryStatus", &status), + } + } + + pub fn filter(self) -> Filter { + match self.tone() { + Tone::Ok | Tone::Info => Filter::Recovered, + Tone::Warn => Filter::Suspect, + Tone::Err => Filter::Failed, + Tone::Skip => Filter::Skipped, + } + } +} + +/// True for an entry that was probed and acted on, as opposed to a listed or +/// probed-and-skipped one. +pub fn is_target_entry(entry: &EntryReport) -> bool { + !matches!( + entry.status, + EntryStatus::NotTarget | EntryStatus::Inventoried + ) +} + +// ------------------------------------------------------------------ log + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Level { + Info, + Step, + Detail, + Warn, + Error, +} + +/// One log line, kept structured so it reads in whatever language is current. +#[derive(Debug, Clone)] +pub enum LogBody { + RunStarted { + mode: Mode, + inputs: usize, + }, + Scan { + candidates: usize, + skipped: usize, + }, + ScanIncomplete, + InputStarted { + index: usize, + total: usize, + path: String, + }, + Companion { + name: String, + }, + Step { + position: Option<(u8, u8)>, + step: Step, + }, + Detail(String), + Stage { + stage: Stage, + status: StageStatus, + duration: Option, + detail: Option, + }, + Message(Message), + Entry { + label: String, + verdict: Verdict, + }, + Finished { + verdict: Verdict, + duration: u64, + }, + Summary(Counts), +} + +#[derive(Debug, Clone)] +pub struct LogLine { + pub at: String, + pub level: Level, + pub body: LogBody, +} + +impl LogLine { + pub fn new(at: impl Into, level: Level, body: LogBody) -> Self { + Self { + at: at.into(), + level, + body, + } + } +} + +/// Counts over a set of inputs, by filter. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Counts { + pub inputs: usize, + pub recovered: usize, + pub suspect: usize, + pub failed: usize, + pub skipped: usize, +} + +impl Counts { + pub fn add(&mut self, verdict: Verdict) { + match verdict.filter() { + Filter::Recovered => self.recovered += 1, + Filter::Suspect => self.suspect += 1, + Filter::Failed => self.failed += 1, + Filter::Skipped | Filter::All => self.skipped += 1, + } + } + + pub fn get(&self, filter: Filter) -> usize { + match filter { + Filter::All => self.inputs, + Filter::Recovered => self.recovered, + Filter::Suspect => self.suspect, + Filter::Failed => self.failed, + Filter::Skipped => self.skipped, + } + } +} + +// ---------------------------------------------------------- inputs, groups + +/// Where an input stands in the current job. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum RunState { + #[default] + Idle, + Queued, + Running, + /// The job was cancelled before reaching it. + WillNotRun, +} + +/// The last finished run of one input. +#[derive(Debug, Clone)] +pub struct ItemResult { + pub mode: Mode, + pub report: InputReport, + pub log: Vec, + pub restored: Option, + pub entries: Vec<(String, Produced)>, +} + +impl ItemResult { + pub fn verdict(&self) -> Verdict { + Verdict::of_input(&self.report) + } + + /// Bytes produced for the entry labelled `label`. + pub fn entry_bytes(&self, label: &str) -> Option<&Produced> { + self.entries + .iter() + .find(|(name, _)| name == label) + .map(|(_, produced)| produced) + } +} + +#[derive(Debug, Clone)] +pub struct Item { + pub id: ItemId, + pub path: PathBuf, + pub name: String, + /// `None` while the input is being identified. + pub identity: Option, + pub run: RunState, + pub result: Option, + /// A package's entry rows are folded. + pub folded: bool, +} + +impl Item { + pub fn new(id: ItemId, path: PathBuf) -> Self { + let name = path + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_else(|| path.display().to_string()); + Self { + id, + path, + name, + identity: None, + run: RunState::Idle, + result: None, + folded: false, + } + } + + pub fn verdict(&self) -> Option { + self.result.as_ref().map(ItemResult::verdict) + } + + pub fn is_package(&self) -> bool { + match (&self.result, &self.identity) { + (Some(result), _) => result.report.role == Role::Container, + (None, Some(Identity::Package { .. })) => true, + _ => false, + } + } + + /// Entries of the last run. + pub fn entries(&self) -> &[EntryReport] { + self.result + .as_ref() + .map(|result| result.report.entries.as_slice()) + .unwrap_or_default() + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum GroupKind { + /// Files added one by one. + Files, + /// A folder added as a whole. + Folder(PathBuf), +} + +/// The run-level part of a group's last run. +#[derive(Debug, Clone)] +pub struct GroupRun { + pub mode: Mode, + pub duration_ms: u64, + pub errors: Vec, + pub cancelled: bool, + pub log: Vec, + /// The whole report of the last folder run, for export. + pub report: Option, +} + +#[derive(Debug, Clone)] +pub struct Group { + pub id: GroupId, + pub kind: GroupKind, + pub items: Vec, + /// Targets found so far while the add-time scan runs. + pub scanning: Option, + pub scan: Option, + pub last_run: Option, + pub folded: bool, +} + +impl Group { + pub fn new(id: GroupId, kind: GroupKind) -> Self { + Self { + id, + kind, + items: Vec::new(), + scanning: None, + scan: None, + last_run: None, + folded: false, + } + } + + pub fn root(&self) -> Option<&Path> { + match &self.kind { + GroupKind::Folder(root) => Some(root), + GroupKind::Files => None, + } + } + + pub fn title(&self) -> Cow<'static, str> { + match &self.kind { + GroupKind::Files => t(Text::GroupFiles), + GroupKind::Folder(root) => root + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_else(|| root.display().to_string()) + .into(), + } + } + + pub fn counts(&self) -> Counts { + let mut counts = Counts { + inputs: self.items.len(), + ..Counts::default() + }; + for verdict in self.items.iter().filter_map(Item::verdict) { + counts.add(verdict); + } + counts + } +} + +/// What the detail pane shows. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Sel { + Group(GroupId), + Item(ItemId), + /// An entry of a package, by its index in the package's last report. + Entry(ItemId, usize), +} + +// ---------------------------------------------------------------- tags + +fn extension_tag(name: &str) -> String { + Path::new(name) + .extension() + .map(|extension| extension.to_string_lossy().to_uppercase()) + .unwrap_or_else(|| "?".to_owned()) +} + +pub fn format_label(format: Option) -> String { + use senbei_engine::TargetFormat; + match format { + Some(TargetFormat::Pe32Plus) => "PE32+".into(), + Some(TargetFormat::Pe32) => "PE32".into(), + Some(TargetFormat::Elf64Aarch64) => "ELF64 AArch64".into(), + Some(other) => wire(&other).unwrap_or_default(), + None => "—".into(), + } +} + +/// The short type tag of an input, from its last run or else its identity. +/// A run that failed before it read the format keeps the tag the file's +/// header gave when it was added. +pub fn kind_tag(item: &Item) -> String { + item.result + .as_ref() + .and_then(|result| known_report_tag(&result.report)) + .or_else(|| identity_tag(item.identity.as_ref()?)) + .unwrap_or_else(|| extension_tag(&item.name)) +} + +/// The tag an identity gives, when it names a format. +fn identity_tag(identity: &Identity) -> Option { + match identity { + Identity::Windows { profile, .. } if profile.observed.format.is_some() => { + Some(format_kind(profile.observed.format, profile.observed.kind)) + } + Identity::Metadata { identity, .. } => Some(metadata_tag( + identity.as_ref().map(|identity| identity.raw_version), + )), + Identity::AndroidLibrary { .. } => Some(identity_format(identity)?), + Identity::Package { + container: Ok(container), + .. + } => Some(container.kind.to_uppercase()), + _ => None, + } +} + +/// The binary format an identity read from the file's header, if any. +pub fn identity_format(identity: &Identity) -> Option { + match identity { + Identity::Windows { profile, .. } if profile.observed.format.is_some() => { + Some(format_label(profile.observed.format)) + } + Identity::AndroidLibrary { .. } => Some(format_label(Some( + senbei_engine::TargetFormat::Elf64Aarch64, + ))), + _ => None, + } +} + +fn format_kind( + format: Option, + kind: Option, +) -> String { + let format = format_label(format); + match kind { + Some(kind) => format!("{format} {}", tv("kindShort", &kind)), + None => format, + } +} + +fn metadata_tag(version: Option) -> String { + t(Text::TagMetadata { + v: version + .map(|version| version.to_string()) + .unwrap_or_else(|| "?".into()), + }) + .into_owned() +} + +/// The tag a report gives, when it names a format, a metadata version, or a +/// container kind. +fn known_report_tag(input: &InputReport) -> Option { + if let Some(container) = &input.container { + return Some(container.kind.to_uppercase()); + } + if input.role == Role::Container { + return None; + } + let observed = &input.profile.as_ref()?.observed; + if observed.platform == senbei_engine::Platform::Il2cppMetadata { + return Some(metadata_tag( + observed.metadata_version.or(input.metadata_version), + )); + } + observed.format?; + Some(format_kind(observed.format, observed.kind)) +} + +/// The type tag of a package entry. +pub fn entry_tag(entry: &EntryReport) -> String { + use senbei_io::report::EntryKind; + match entry.kind { + Some(EntryKind::Metadata) => metadata_tag(entry.metadata_version), + Some(EntryKind::SharedLibrary) => "ELF64 AArch64".into(), + None => extension_tag(entry_inner(&entry.name)), + } +} + +/// The entry part of a package label, after the last `::`. +pub fn entry_inner(label: &str) -> &str { + label.rsplit_once("::").map_or(label, |(_, inner)| inner) +} + +/// The nested-package part of a package label, before the last `::`. +pub fn entry_source(label: &str) -> &str { + label.rsplit_once("::").map_or("", |(outer, _)| outer) +} + +pub fn mode_label(mode: Mode) -> Cow<'static, str> { + t(match mode { + Mode::Inspect => Text::ModeInspect, + Mode::DryRun => Text::ModeDryRun, + Mode::Unpack => Text::ModeUnpack, + }) +} + +pub fn mode_action(mode: Mode) -> Cow<'static, str> { + t(match mode { + Mode::Inspect => Text::TbInspect, + Mode::DryRun => Text::TbDryRun, + Mode::Unpack => Text::TbUnpack, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn input(status: InputStatus) -> InputReport { + let mut input = InputReport::new(Path::new("x.dll"), Role::Content); + input.status = status; + input + } + + #[test] + fn verdicts_follow_the_mockup() { + assert_eq!( + Verdict::of_input(&input(InputStatus::Ok)), + Verdict::Recovered + ); + assert_eq!( + Verdict::of_input(&input(InputStatus::Skipped)), + Verdict::Skipped + ); + let mut incomplete = input(InputStatus::Error); + incomplete.analysis_incomplete = true; + assert_eq!(Verdict::of_input(&incomplete), Verdict::Incomplete); + let mut recognized = input(InputStatus::Recognized); + let mut profile = senbei_engine::ProtectionProfile::new( + senbei_engine::ObservedTarget::windows(None, None), + ); + profile.recovery = RecoveryStatus::Failed; + recognized.profile = Some(profile); + assert_eq!(Verdict::of_input(&recognized), Verdict::RecoveryFailed); + assert_eq!(Verdict::RecoveryFailed.filter(), Filter::Failed); + assert_eq!(Verdict::Recognized.filter(), Filter::Recovered); + } + + #[test] + fn labels_split_at_the_last_separator() { + let label = r"app.apks\split.apk::lib\arm64-v8a\libx.so"; + assert_eq!(entry_inner(label), r"lib\arm64-v8a\libx.so"); + assert_eq!(entry_source(label), r"app.apks\split.apk"); + } +} diff --git a/senbei-gui/src/native.rs b/senbei-gui/src/native.rs new file mode 100644 index 0000000..8055f93 --- /dev/null +++ b/senbei-gui/src/native.rs @@ -0,0 +1,708 @@ +//! The native backend: files, folders, runs, dialogs, and system fonts. + +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::{Arc, Mutex}; + +use senbei_engine::android::ResourceLimits; +use senbei_i18n::{Lang, Message, Msg}; +use senbei_io::job; +use senbei_io::logfile::local_clock; +use senbei_io::observe::{CancelToken, RunObserver}; +use senbei_io::report::{ + Collector, CompanionState, InputReport, InputStatus, Mode, OutputFile, Role, +}; +use senbei_io::scan::{InputClass, classify_input}; + +use crate::backend::{ + Backend, Capabilities, Event, Identity, Job, LoadError, Pick, Produced, Request, Source, Unit, +}; +use crate::theme::{Face, FontSet}; + +/// Hands events to the window and wakes it. +#[derive(Clone)] +struct Sink { + events: Sender, + ctx: egui::Context, +} + +impl Sink { + fn send(&self, event: Event) { + // The window is gone only when the process is closing. + let _ = self.events.send(event); + self.ctx.request_repaint(); + } +} + +pub struct NativeBackend { + requests: Sender, + events: Mutex>, +} + +impl NativeBackend { + pub fn new(ctx: egui::Context) -> Self { + let (requests, incoming) = channel::(); + let (events, outgoing) = channel::(); + let sink = Sink { events, ctx }; + std::thread::Builder::new() + .name("senbei-dispatch".into()) + .spawn(move || dispatch(incoming, sink)) + .expect("spawn the dispatch thread"); + Self { + requests, + events: Mutex::new(outgoing), + } + } +} + +impl Backend for NativeBackend { + fn capabilities(&self) -> Capabilities { + Capabilities { + folders: true, + unpack: true, + reveal: true, + } + } + + fn send(&self, request: Request) { + let _ = self.requests.send(request); + } + + fn poll(&self) -> Option { + self.events.lock().ok()?.try_recv().ok() + } +} + +/// Route each request: jobs run one at a time on the job thread, everything +/// else on a short-lived thread of its own so the window never waits. +fn dispatch(incoming: Receiver, sink: Sink) { + let (jobs, queue) = channel::(); + let cancel: Arc> = Arc::default(); + // Cancel stops the running job and drops every job queued behind it. + let cancelled_through = Arc::new(AtomicU64::new(0)); + let mut last_submitted = 0; + { + let sink = sink.clone(); + let cancel = cancel.clone(); + let cancelled_through = cancelled_through.clone(); + spawn("senbei-jobs", move || { + for job in queue { + if job.id <= cancelled_through.load(Ordering::SeqCst) { + sink.send(Event::JobFinished { + job: job.id, + cancelled: true, + }); + continue; + } + let token = CancelToken::new(); + if let Ok(mut current) = cancel.lock() { + *current = token.clone(); + } + // A cancel that raced the token swap still stops this job. + if job.id <= cancelled_through.load(Ordering::SeqCst) { + token.cancel(); + } + run_job(&job, &sink, &token); + } + }); + } + for request in incoming { + let sink = sink.clone(); + match request { + Request::Run(job) => { + last_submitted = last_submitted.max(job.id); + let _ = jobs.send(*job); + } + Request::Cancel => { + cancelled_through.fetch_max(last_submitted, Ordering::SeqCst); + if let Ok(current) = cancel.lock() { + current.cancel(); + } + } + Request::Identify(items) => spawn("senbei-identify", move || { + let limits = ResourceLimits::default(); + for (id, path) in items { + sink.send(Event::Identified(id, Box::new(identify(&path, &limits)))); + } + }), + Request::Scan { + group, + root, + scan_all, + limits, + } => spawn("senbei-scan", move || { + scan(group, &root, scan_all, &limits, &sink) + }), + Request::Load { source, limits } => spawn("senbei-load", move || { + let result = load(&source, &limits); + sink.send(Event::Loaded { source, result }); + }), + Request::Pick(pick) => spawn("senbei-dialog", move || { + let paths = match pick { + Pick::Files => rfd::FileDialog::new().pick_files().unwrap_or_default(), + Pick::Folder | Pick::Output => { + rfd::FileDialog::new().pick_folder().into_iter().collect() + } + }; + sink.send(Event::Picked(pick, paths)); + }), + Request::Reveal(path) => spawn("senbei-reveal", move || { + if let Err(error) = reveal(&path) { + sink.send(Event::Failed(error.to_string())); + } + }), + Request::Save { name, contents } => spawn("senbei-save", move || { + let Some(path) = rfd::FileDialog::new().set_file_name(&name).save_file() else { + return; + }; + let result = std::fs::write(&path, contents) + .map(|()| path) + .map_err(|error| error.to_string()); + sink.send(Event::Saved(result)); + }), + } + } +} + +fn spawn(name: &str, work: impl FnOnce() + Send + 'static) { + if let Err(error) = std::thread::Builder::new().name(name.into()).spawn(work) { + eprintln!("senbei-gui: cannot start a worker thread: {error}"); + } +} + +// --------------------------------------------------------------- runs + +/// Sends a run's progress to the window. +struct Observer { + job: u64, + unit: usize, + mode: Mode, + keep_bytes: bool, + keep_cap: u64, + sink: Sink, +} + +impl Observer { + fn produced_file(&self, output: &OutputFile) -> Produced { + let path = PathBuf::from(&output.path); + if self.mode == Mode::Unpack { + return Produced::OnDisk(path); + } + if !self.keep_bytes { + return Produced::NotKept; + } + if output.size > self.keep_cap { + return Produced::TooLarge(output.size); + } + match std::fs::read(&path) { + Ok(bytes) => Produced::Kept(bytes.into()), + Err(_) => Produced::NotKept, + } + } +} + +impl RunObserver for Observer { + fn scanned(&self, inputs: usize) { + self.sink.send(Event::UnitScanned { + job: self.job, + unit: self.unit, + inputs, + at: local_clock(), + }); + } + + fn input_started(&self, path: &Path) { + self.sink.send(Event::InputStarted { + job: self.job, + unit: self.unit, + path: path.to_path_buf(), + at: local_clock(), + }); + } + + fn progress(&self, event: &senbei_engine::progress::Event) { + use senbei_engine::progress::Event as Progress; + let at = local_clock(); + self.sink.send(match event { + Progress::Step { step, position } => Event::Step { + job: self.job, + step: step.clone(), + position: *position, + at, + }, + Progress::Detail(text) => Event::Detail { + job: self.job, + text: text.trim().to_owned(), + at, + }, + }); + } + + fn produced(&self, input: &InputReport) { + let restored = input + .outputs + .first() + .map(|output| self.produced_file(output)); + let entries = input + .entries + .iter() + .filter_map(|entry| { + let output = entry.output.as_ref()?; + Some((entry.name.clone(), self.produced_file(output))) + }) + .collect(); + self.sink.send(Event::Produced { + job: self.job, + path: PathBuf::from(&input.path), + restored, + entries, + }); + } + + fn input_finished(&self, input: &InputReport) { + self.sink.send(Event::InputFinished { + job: self.job, + unit: self.unit, + report: Box::new(input.clone()), + at: local_clock(), + }); + } +} + +fn run_job(job: &Job, sink: &Sink, cancel: &CancelToken) { + for (index, unit) in job.units.iter().enumerate() { + if cancel.is_cancelled() { + break; + } + sink.send(Event::UnitStarted { + job: job.id, + unit: index, + at: local_clock(), + }); + let observer = Arc::new(Observer { + job: job.id, + unit: index, + mode: job.mode, + keep_bytes: job.options.keep_bytes, + keep_cap: job.options.keep_cap, + sink: sink.clone(), + }); + let mut collector = Collector::new(job.mode) + .with_observer(observer) + .with_cancel(cancel.clone()); + let result = run_unit(job, unit, &mut collector); + if let Err(error) = &result { + let message = match error.downcast_ref::() { + Some(Panicked(message)) => message.clone(), + None => senbei_io::message::of_error(error), + }; + // A file unit that never reached its input still gets a row. + if let Unit::File { path, .. } = unit + && collector.summary_mut().inputs == 0 + { + let mut input = InputReport::new(path, Role::Content); + input.status = InputStatus::Error; + input.errors.push(message.clone()); + collector.push(input); + } else { + collector.push_error(message); + } + } + let mut report = collector.finish(); + report.inputs.clear(); + sink.send(Event::UnitFinished { + job: job.id, + unit: index, + report: Box::new(report), + at: local_clock(), + }); + } + sink.send(Event::JobFinished { + job: job.id, + cancelled: cancel.is_cancelled(), + }); +} + +/// A panic caught around a run, with its catalog message. +#[derive(Debug)] +struct Panicked(Message); + +impl std::fmt::Display for Panicked { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(self.0.text()) + } +} + +impl std::error::Error for Panicked {} + +/// Run one unit the way the command line would, with the window's settings. +fn run_unit(job: &Job, unit: &Unit, collector: &mut Collector) -> anyhow::Result<()> { + let options = &job.options; + // Inspections and dry runs write into a workspace that is dropped after + // the run; the observer reads what it keeps before that. + let workspace = match job.mode { + Mode::Unpack => None, + Mode::Inspect | Mode::DryRun => Some(tempfile::tempdir()?), + }; + let no_log = job.mode != Mode::Unpack || !options.write_log; + let mut run = || -> anyhow::Result<()> { + let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match unit { + Unit::File { path, out_dir } => { + let out_dir = workspace + .as_ref() + .map_or(out_dir.as_path(), |dir| dir.path()); + job::run_file_reported( + path, + Some(out_dir), + 2, + true, + no_log, + &options.limits, + collector, + ) + .map(drop) + } + Unit::Folder { root, out_dir } => { + let out_dir = workspace + .as_ref() + .map_or(out_dir.as_path(), |dir| dir.path()); + job::run_folder_reported( + root, + Some(out_dir), + 2, + true, + no_log, + options.scan_all, + &options.limits, + collector, + ) + .map(drop) + } + })); + match caught { + Ok(result) => result, + Err(payload) => { + let text = payload + .downcast_ref::() + .cloned() + .or_else(|| { + payload + .downcast_ref::<&str>() + .map(|text| (*text).to_owned()) + }) + .unwrap_or_default(); + Err(anyhow::Error::new(Panicked(Message::new( + Msg::UnexpectedPanic { message: text }, + )))) + } + } + }; + match options.threads { + Some(count) => senbei_engine::with_thread_cap(count, run), + None => run(), + } +} + +// ------------------------------------------------------- identification + +/// How much of a file identification reads: headers, the key table, and the +/// section table all sit well inside it. +const IDENTIFY_PREFIX: u64 = 1024 * 1024; + +fn read_prefix(path: &Path, max: u64) -> std::io::Result> { + let file = std::fs::File::open(path)?; + let mut buffer = Vec::new(); + file.take(max).read_to_end(&mut buffer)?; + Ok(buffer) +} + +/// What `path` is, without recovering anything. +pub fn identify(path: &Path, limits: &ResourceLimits) -> Identity { + let size = match std::fs::metadata(path) { + Ok(meta) if meta.is_file() => meta.len(), + Ok(_) => return Identity::NotAFile, + Err(error) => return Identity::Unreadable(error.to_string()), + }; + let class = match classify_input(path, limits) { + Ok(class) => class, + Err(error) => return Identity::Unreadable(error.to_string()), + }; + match class { + InputClass::Metadata => { + let identity = read_prefix(path, 64) + .ok() + .and_then(|head| senbei_metadata::identify(&head)); + Identity::Metadata { size, identity } + } + InputClass::AndroidLibrary => Identity::AndroidLibrary { size }, + InputClass::AndroidPackage => Identity::Package { + size, + container: senbei_io::android::inspect_package(path, limits) + .map(Box::new) + .map_err(|error| senbei_io::message::of_error(&error).text().to_owned()), + }, + InputClass::Windows | InputClass::NotTarget => match windows_identity(path, size) { + Some(identity) => identity, + None => Identity::NotTarget { size }, + }, + } +} + +/// The header-level profile of a PE and its companion state. `None` when the +/// file is not a PE at all. +fn windows_identity(path: &Path, size: u64) -> Option { + let stub = read_prefix(path, IDENTIFY_PREFIX).ok()?; + if !stub.starts_with(b"MZ") { + return None; + } + let sibling = companion_path(path); + let (companion, companion_bytes) = match &sibling { + Some(sibling) => match read_prefix(sibling, IDENTIFY_PREFIX) { + Ok(bytes) => (CompanionState::Unmatched, Some(bytes)), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + (CompanionState::Absent, None) + } + Err(_) => (CompanionState::Unreadable, None), + }, + None => (CompanionState::Absent, None), + }; + let spliced = companion_bytes + .as_deref() + .and_then(|payload| senbei_io::windows::splice_companion(&stub, payload)); + let (profile, companion) = match &spliced { + Some(view) => { + let mut profile = senbei_engine::inspect_profile(view); + profile.record_companion_spliced(); + (profile, CompanionState::Spliced) + } + None => (senbei_engine::inspect_profile(&stub), companion), + }; + Some(Identity::Windows { + size, + profile: Box::new(profile), + companion, + companion_path: (companion != CompanionState::Absent) + .then(|| sibling.map(|sibling| sibling.display().to_string())) + .flatten(), + }) +} + +/// `._`, the companion payload a loader may declare. +pub fn companion_path(input: &Path) -> Option { + let mut name = input.file_name()?.to_os_string(); + name.push("._"); + Some(input.with_file_name(name)) +} + +/// Scan a folder the way a folder run does, reporting the count as it grows. +fn scan(group: u64, root: &Path, scan_all: bool, limits: &ResourceLimits, sink: &Sink) { + let found = Arc::new(AtomicUsize::new(0)); + let done = Arc::new(std::sync::atomic::AtomicBool::new(false)); + { + // Report the growing count a few times a second until the scan ends. + let found = found.clone(); + let done = done.clone(); + let sink = sink.clone(); + spawn("senbei-scan-progress", move || { + let mut last = usize::MAX; + while !done.load(Ordering::Relaxed) { + let now = found.load(Ordering::Relaxed); + if now != last { + sink.send(Event::ScanProgress { group, found: now }); + last = now; + } + std::thread::sleep(std::time::Duration::from_millis(150)); + } + }); + } + let result = senbei_io::scan::find_targets_counted(root, scan_all, limits, &found); + done.store(true, Ordering::Relaxed); + let mut paths: Vec = result + .crackproof + .into_iter() + .chain(result.metadata) + .chain(result.android_so) + .chain(result.android_packages) + .collect(); + paths.sort(); + let targets = paths + .into_iter() + .map(|path| { + let identity = identify(&path, limits); + (path, Box::new(identity)) + }) + .collect(); + let stats = result.stats; + sink.send(Event::Scanned { + group, + targets, + scan: senbei_io::report::ScanReport { + non_target_skipped: stats.skipped, + walk_errors: stats.walk_errors, + probe_errors: stats.probe_errors, + }, + }); +} + +// ---------------------------------------------------------------- bytes + +/// Largest file the hex view loads. +const LOAD_LIMIT: u64 = 2 * 1024 * 1024 * 1024; + +fn read_whole(path: &Path) -> Result, LoadError> { + let system = |error: std::io::Error| LoadError::Message(Message::raw(error.to_string())); + let size = std::fs::metadata(path).map_err(system)?.len(); + if size > LOAD_LIMIT { + return Err(LoadError::TooLarge { + size, + limit: LOAD_LIMIT, + }); + } + std::fs::read(path).map_err(system) +} + +fn load(source: &Source, limits: &ResourceLimits) -> Result, LoadError> { + match source { + Source::File(path) => read_whole(path).map(Into::into), + Source::Spliced { stub, companion } => { + let stub = read_whole(stub)?; + let payload = read_whole(companion)?; + senbei_io::windows::splice_companion(&stub, &payload) + .map(Into::into) + .ok_or(LoadError::Message(Message::new(Msg::CompanionMismatch))) + } + Source::Entry { package, label } => { + senbei_io::android::read_package_entry(package, label, limits) + .map(Into::into) + .map_err(|error| LoadError::Message(senbei_io::message::of_error(&error))) + } + } +} + +// ----------------------------------------------------------- the desktop + +fn reveal(path: &Path) -> std::io::Result<()> { + #[cfg(windows)] + { + let mut select = std::ffi::OsString::from("/select,"); + select.push(path); + std::process::Command::new("explorer.exe") + .arg(select) + .spawn()?; + } + #[cfg(not(windows))] + { + let folder = path.parent().unwrap_or(path); + std::process::Command::new("xdg-open").arg(folder).spawn()?; + } + Ok(()) +} + +/// Debug environment variables that change how inputs are decoded. +pub fn debug_variables() -> Vec { + ["DD8_SHIFT", "SEL_DIAG"] + .into_iter() + .filter(|name| std::env::var_os(name).is_some()) + .map(str::to_owned) + .collect() +} + +// ---------------------------------------------------------------- fonts + +/// System fonts, found by family name. +pub struct SystemFonts { + collection: fontique::Collection, + cache: fontique::SourceCache, +} + +impl Default for SystemFonts { + fn default() -> Self { + Self::new() + } +} + +impl SystemFonts { + pub fn new() -> Self { + Self { + collection: fontique::Collection::new(fontique::CollectionOptions { + shared: false, + system_fonts: true, + }), + cache: fontique::SourceCache::default(), + } + } + + fn face(&mut self, family: &str, weight: fontique::FontWeight) -> Option { + let info = self.collection.family_by_name(family)?; + let font = info + .match_font( + fontique::FontWidth::NORMAL, + fontique::FontStyle::Normal, + weight, + false, + )? + .clone(); + let blob = font.load(Some(&mut self.cache))?; + let (data, _) = blob.into_raw_parts(); + Some(Face { + name: format!("{family}:{}:{}", font.weight().value(), font.index()), + data: Arc::new(egui::FontData::from_blob(data, font.index())), + }) + } + + fn faces(&mut self, families: &[&str], weight: fontique::FontWeight) -> Vec { + let mut faces: Vec = Vec::new(); + for family in families { + if let Some(face) = self.face(family, weight) + && !faces.iter().any(|known| known.name == face.name) + { + faces.push(face); + } + } + faces + } + + /// The UI, semibold, and monospace faces for `lang`: the language's own + /// font first (so shared punctuation takes its shape), the other CJK + /// fonts after it for names in other scripts. + pub fn set_for(&mut self, lang: Lang) -> FontSet { + const LATIN: [&str; 3] = ["Segoe UI", "Noto Sans", "DejaVu Sans"]; + let own: &[&str] = match lang { + Lang::En => &[], + Lang::ZhCn => &["Microsoft YaHei UI", "Microsoft YaHei", "Noto Sans CJK SC"], + Lang::ZhTw => &[ + "Microsoft JhengHei UI", + "Microsoft JhengHei", + "Noto Sans CJK TC", + ], + Lang::Ja => &["Yu Gothic UI", "Meiryo UI", "Meiryo", "Noto Sans CJK JP"], + Lang::Ko => &["Malgun Gothic", "Noto Sans CJK KR"], + }; + let others = [ + "Yu Gothic UI", + "Microsoft YaHei UI", + "Microsoft JhengHei UI", + "Malgun Gothic", + "Noto Sans CJK JP", + "Noto Sans CJK SC", + ]; + // Symbols the window draws itself: ⚙ ▶ ✓ ✕ ● ★ → and the like. + const SYMBOLS: [&str; 3] = [ + "Segoe UI Symbol", + "Noto Sans Symbols 2", + "Noto Sans Symbols", + ]; + let mut ui: Vec<&str> = own.to_vec(); + ui.extend(LATIN); + ui.extend(others); + ui.extend(SYMBOLS); + let mono = ["Cascadia Mono", "Consolas", "DejaVu Sans Mono", "Menlo"]; + FontSet { + ui: self.faces(&ui, fontique::FontWeight::NORMAL), + strong: self.faces(&ui, fontique::FontWeight::SEMI_BOLD), + mono: self.faces(&mono, fontique::FontWeight::NORMAL), + } + } +} diff --git a/senbei-gui/src/settings.rs b/senbei-gui/src/settings.rs new file mode 100644 index 0000000..5a43c5f --- /dev/null +++ b/senbei-gui/src/settings.rs @@ -0,0 +1,120 @@ +//! Settings the window keeps between sessions. + +use std::num::NonZeroUsize; +use std::path::PathBuf; + +use senbei_engine::android::ResourceLimits; +use senbei_i18n::Lang; +use serde::{Deserialize, Serialize}; + +use crate::backend::{Output, RunOptions}; + +const MIB: u64 = 1024 * 1024; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Settings { + /// A language tag, or `None` to follow `SENBEI_LANG` and the system. + pub language: Option, + pub output: Output, + /// The last folder chosen for outputs, offered again in the output menu. + pub recent_output: Option, + pub write_log: bool, + /// `0` is automatic. + pub threads: usize, + pub scan_all: bool, + pub max_entry_mib: u64, + pub max_total_mib: u64, + pub max_entries: usize, + pub max_depth: usize, + pub keep_bytes: bool, + pub keep_cap_mib: u64, + pub legal_accepted: bool, +} + +impl Default for Settings { + fn default() -> Self { + let limits = ResourceLimits::default(); + Self { + language: None, + output: Output::Beside, + recent_output: None, + write_log: true, + threads: 0, + scan_all: false, + max_entry_mib: limits.max_entry_bytes / MIB, + max_total_mib: limits.max_total_bytes / MIB, + max_entries: limits.max_entries, + max_depth: limits.max_depth, + keep_bytes: true, + keep_cap_mib: 512, + legal_accepted: false, + } + } +} + +impl Settings { + /// Everything but the legal notice and the language back to defaults. + pub fn reset(&mut self) { + *self = Settings { + language: self.language.clone(), + legal_accepted: self.legal_accepted, + recent_output: self.recent_output.clone(), + ..Settings::default() + }; + } + + pub fn lang(&self, detected: Lang) -> Lang { + self.language + .as_deref() + .and_then(Lang::from_tag) + .unwrap_or(detected) + } + + pub fn limits(&self) -> ResourceLimits { + ResourceLimits { + max_entry_bytes: self.max_entry_mib.max(1).saturating_mul(MIB), + max_total_bytes: self.max_total_mib.max(1).saturating_mul(MIB), + max_entries: self.max_entries.max(1), + max_depth: self.max_depth, + } + } + + pub fn run_options(&self) -> RunOptions { + RunOptions { + write_log: self.write_log, + threads: NonZeroUsize::new(self.threads), + scan_all: self.scan_all, + limits: self.limits(), + keep_bytes: self.keep_bytes, + keep_cap: self.keep_cap_mib.max(1).saturating_mul(MIB), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn defaults_match_the_command_line() { + let settings = Settings::default(); + assert_eq!(settings.limits(), ResourceLimits::default()); + assert_eq!(settings.keep_cap_mib, 512); + assert!(settings.write_log); + } + + #[test] + fn reset_keeps_the_language_and_the_notice() { + let mut settings = Settings { + language: Some("ja".into()), + legal_accepted: true, + threads: 4, + ..Settings::default() + }; + settings.reset(); + assert_eq!(settings.language.as_deref(), Some("ja")); + assert!(settings.legal_accepted); + assert_eq!(settings.threads, 0); + } +} diff --git a/senbei-gui/src/text/catalog.rs b/senbei-gui/src/text/catalog.rs new file mode 100644 index 0000000..10950aa --- /dev/null +++ b/senbei-gui/src/text/catalog.rs @@ -0,0 +1,1295 @@ +// Generated from the approved GUI mockup catalog. Edit the wording here; +// every language must keep the same placeholders. + +use std::borrow::Cow; + +use senbei_i18n::{Lang, Localize}; + +/// Text the desktop front end shows. English is the approved mockup wording. +#[derive(Debug, Clone, PartialEq, Eq)] +#[allow(clippy::enum_variant_names)] +pub enum Text { + // tb + TbAddFiles, + TbAddFolder, + TbUnpack, + TbUnpackN { + n: String, + }, + TbUnpackAll, + TbUnpackTip, + TbDryRun, + TbDryRunN { + n: String, + }, + TbDryRunAll, + TbDryRunTip, + TbInspect, + TbInspectN { + n: String, + }, + TbInspectAll, + TbInspectTip, + TbOutput, + TbOutputBeside, + TbOutputTip, + TbSettings, + // banner + BannerEnv { + vars: String, + }, + BannerEnvHint, + // empty + EmptyTitle, + EmptyFolders, + EmptyLocal, + // drag + DragTitle, + // inputs + InputsTitle, + InputsClear, + InputsSearch, + InputsNone, + // filter + FilterAll, + FilterOk, + FilterSuspect, + FilterFailed, + FilterSkipped, + // group + GroupFiles, + GroupScanning { + n: String, + }, + // mode + ModeInspect, + ModeDryRun, + ModeUnpack, + // menu + MenuCopyPath, + MenuRemove, + // pending + PendingNotRun, + PendingNotProtected, + PendingIdentified, + PendingNext, + PendingUnpackDesc, + PendingDryRunDesc, + PendingInspectDesc, + PendingNotProtectedNote, + PendingNotAFile, + // scan + ScanRunning, + ScanFound, + ScanStatus { + n: String, + p: String, + }, + // run + RunRunning, + RunQueued, + RunWillNotRun, + RunStep { + i: String, + n: String, + s: String, + }, + RunQueue { + n: String, + }, + RunStopping, + RunCancel, + RunProgress, + RunCancelledNote, + // step + StepDecryptHeader, + StepDecryptPayload, + StepLocateConfig, + StepDecryptStage2, + StepDecryptStages35, + StepDecryptSections, + StepLoadSections, + StepDecryptImports, + StepRebuildHeaders, + StepInitKeys, + StepDecryptKeyTable, + StepDecryptPrimary, + StepRelocsParams, + StepDecryptBlock1, + StepDecryptBlock23, + StepDecryptBlock4, + StepDllSections, + StepFixHeaders, + StepPe32Stages, + StepPe32Eighth, + StepPe32Load, + StepPe32Text, + StepPe32TextSkip, + StepPe32Rebuild, + StepAndroidPrimary, + StepAndroidAux, + StepAndroidTables, + // detail + DetailPick, + DetailExportJson, + DetailExportText, + DetailLastRun { + mode: String, + t: String, + }, + DetailCopy, + DetailTechnical, + // companion + CompanionSplicedPill, + // tab + TabOverview, + TabResearch, + TabHex, + TabCompare, + TabLog, + TabEntries, + // batch + BatchSummary, + BatchInputs, + BatchScan, + BatchNonTarget, + BatchWalkErrors, + BatchProbeErrors, + BatchScanNote, + BatchScanIncomplete, + // pkg + PkgTitle, + PkgKind, + PkgPackage, + PkgVersion, + PkgEntries, + PkgCandidates, + PkgNested, + PkgNote, + PkgResult, + PkgManifests, + PkgUnnamed, + PkgTargets, + PkgNoTargets, + PkgInventory { + n: String, + }, + // entries + EntriesTitle, + EntriesOthers { + n: String, + }, + EntriesSummary { + n: String, + }, + EntriesShowNonTargets { + n: String, + }, + EntriesRemapped { + n: String, + }, + EntriesRemappedLabel, + // col + ColName, + ColType, + ColOutcome, + ColRoute, + ColTime, + ColAddress, + ColSize, + ColFileOffset, + ColMapping, + ColKind, + ColLength, + ColSource, + ColRaw, + ColDecoded, + ColMeaning, + ColCheck, + ColStart, + ColEnd, + ColLimit, + ColStatus, + ColNote, + ColSeverity, + ColArea, + ColMessage, + ColValue, + ColVsize, + ColRawOffset, + ColRawSize, + ColCharacteristics, + ColBacking, + ColField, + ColCommand, + ColFlags, + ColImage, + ColMetadata, + ColOffsetSize, + ColEntry, + ColInit, + ColDirect, + ColNested, + ColDepth, + ColStream, + ColClassification, + // common + CommonYes, + CommonNo, + // ov + OvMessages, + OvRecognition, + OvPlatform, + OvFormat, + OvKind, + OvMetadata, + OvMetadataVersion, + OvMetadataLayout, + OvCapSeeded, + OvCapStructural, + OvCapIndices, + OvCapContext, + OvProvenance, + OvEvidence, + OvNoEvidence, + OvRoutes, + OvSelected, + OvNoRoutes, + OvStages, + OvValidation, + OvValidationMetadata, + OvValidationWarnings, + OvValidationFailed, + OvIdentity, + OvSource, + OvCompanion, + OvRecovered, + OvOutput, + OvOpenFolder, + OvRestoredElf, + OvElfSections, + OvElfSymbols, + OvElfRelocs, + // research + ResearchNone, + ResearchNotCollected, + ResearchRunInspect, + ResearchSplicedNote, + ResearchJump { + space: String, + }, + ResearchRegionsNote, + ResearchRegionsNone, + ResearchAStreamsNote, + ResearchAArtifactsNote, + // rs + RsGrpInput, + RsGrpProtection, + RsGrpRecovery, + RsGrpExtraction, + RsGrpRestoration, + RsGrpMetadata, + RsGrpProfile, + RsPeHeader, + RsSections, + RsDirectories, + RsRegions, + RsHeaderTable, + RsPayload, + RsDiscovery, + RsTrace, + RsIssues, + RsRestored, + RsAStage1, + RsAStreams, + RsAModules, + RsAArtifacts, + RsAScalars, + RsARDescriptor, + RsARStaticConfig, + RsARPrimary, + RsARAuxiliary, + RsARElfMaterialization, + RsARCleaning, + RsARValidation, + RsMReport, + RsMImages, + RsMRaw, + RsProfile, + // pe + PeOffset, + PeMachine, + PeFormat, + PeEntry, + PeNotFileBacked, + PeAlignment, + PeFlags, + PeInputLen, + PeParseIssue, + // mapping + MappingInSection { + s: String, + }, + MappingPartial { + n: String, + }, + // prot + ProtMagic, + ProtMagicOk, + ProtMagicBad, + ProtWords, + // payload + PayloadSource, + PayloadDest, + PayloadPrefix, + PayloadTotal, + PayloadChecks, + PayloadInBounds, + PayloadOutOfBounds, + PayloadProbe, + PayloadDecoded, + PayloadLimit { + l: String, + }, + PayloadFirstWords, + PayloadUnrecognized, + // disc + DiscPayloadOffset, + DiscImageRva, + DiscSource, + DiscScanned { + n: String, + }, + DiscNone, + // trace + TraceSummary { + n: String, + s: String, + }, + TraceEvents { + n: String, + }, + TraceTruncated { + l: String, + n: String, + }, + // streams + StreamsTitle { + id: String, + }, + StreamsSummary { + d: String, + k: String, + n: String, + s: String, + }, + StreamsOrigin, + StreamsRoot, + StreamsParent { + c: String, + r: String, + s: String, + }, + StreamsRecords, + // issues + IssuesNone, + IssuesWork, + IssuesScratch, + IssuesCandidates, + IssuesBudget, + // restored + RestoredOpenCompare, + RestoredObservations, + // meta + MetaRoute { + r: String, + }, + MetaDiscoveryError, + MetaImage, + MetaMethods, + MetaModulus, + MetaClean, + MetaSeedResidues, + MetaResidues, + // hex + HexVOriginal, + HexVSpliced, + HexVRestored, + HexGoto, + HexAsFile, + HexAsRva, + HexFind, + HexFindHint, + HexFindNext, + HexFindNone, + HexTooLarge { + limit: String, + size: String, + }, + HexRvaUnmapped { + o: String, + }, + HexCopySel, + HexInspector, + HexInspectorHint, + HexRegions, + HexNoRegions, + HexRHeaders, + HexRStubPage, + HexRHeaderTable, + HexRElfHeader, + HexRProgramHeaders, + HexRLoad { + n: String, + }, + HexRPrivateSection, + HexRStage2, + HexRStreams, + HexSize { + s: String, + }, + HexAt { + o: String, + }, + HexInCompanion { + o: String, + }, + HexInStub, + // cmp + CmpNoChange, + CmpHeaders, + CmpOriginal, + CmpRestored, + CmpFileSize, + CmpSections, + CmpBytes, + CmpBytesNote { + len: String, + n: String, + s: String, + }, + CmpNextDiff, + // log + LogFAll, + LogFNosteps, + LogFProblems, + LogCopy, + LogLvInfo, + LogLvStep, + LogLvWarn, + LogLvError, + LogRunStarted { + mode: String, + n: String, + }, + LogScan { + n: String, + s: String, + }, + LogInputStarted { + i: String, + n: String, + p: String, + }, + LogCompanion { + p: String, + }, + LogStep { + i: String, + n: String, + s: String, + }, + LogEntry { + o: String, + p: String, + }, + LogInputFinished { + o: String, + t: String, + }, + LogSummary { + failed: String, + ok: String, + skipped: String, + suspect: String, + }, + // status + StatusReady, + // close + CloseTitle, + CloseBody, + CloseKeep, + CloseStop, + // legal + LegalTitle, + LegalP1, + LegalP2, + LegalP3, + LegalP4, + LegalAccept, + LegalQuit, + // settings + SettingsTitle, + SettingsTabGeneral, + SettingsTabProcessing, + SettingsTabAndroid, + SettingsTabMemory, + SettingsTabAbout, + SettingsLanguage, + SettingsOutput, + SettingsOutputRecent, + SettingsOutputChoose, + SettingsOutputHelp, + SettingsLog, + SettingsLogHelp, + SettingsThreads, + SettingsThreadsAuto { + n: String, + }, + SettingsScanAll, + SettingsScanAllHelp, + SettingsAndroidNote, + SettingsMaxEntry, + SettingsMaxEntryHelp, + SettingsMaxTotal, + SettingsMaxTotalHelp, + SettingsMaxEntries, + SettingsMaxEntriesHelp, + SettingsMaxDepth, + SettingsMaxDepthHelp, + SettingsKeepBytes, + SettingsKeepBytesHelp, + SettingsKeepCap, + SettingsKeepCapHelp, + SettingsReset, + SettingsDone, + // about + AboutVersion { + v: String, + }, + AboutDesc, + AboutLicense, + AboutSource, + AboutLegal, + // tag + TagMetadata { + v: String, + }, + // status + StatusOk, + StatusSuspect, + StatusRecognized, + StatusSkipped, + StatusError, + StatusIncomplete, + // entryStatus + EntryStatusRestored, + EntryStatusDuplicate, + EntryStatusNotTarget, + EntryStatusUnchanged, + EntryStatusInventoried, + EntryStatusError, + // entryKind + EntryKindSharedLibrary, + EntryKindMetadata, + // recognition + RecognitionNotAttempted, + RecognitionRecognized, + RecognitionNotRecognized, + RecognitionBlocked, + // recovery + RecoveryFailed, + RecoveryBlocked, + // outcome + OutcomeSucceeded, + OutcomeRejected, + OutcomeFailed, + OutcomeNotAttempted, + // validation + ValidationClean, + ValidationWarnings, + ValidationFailed, + ValidationNotRun, + // stage + StageDetection, + StageManifestInventory, + StageEntryProbe, + StageRecovery, + StageStaticValidation, + StageOutputWrite, + // stageStatus + StageStatusOk, + StageStatusSkipped, + StageStatusFailed, + StageStatusBlocked, + // traceStage + TraceStageHeader, + TraceStagePayload, + TraceStagePe32Shell, + TraceStagePe32Stages, + TraceStageExeStage1, + TraceStageExeStage2, + TraceStageExeStage3, + TraceStageExeStage4, + TraceStageExeStage5, + TraceStageDllStages, + TraceStageSections, + TraceStageImports, + TraceStageTls, + TraceStageOutput, + TraceStageFinalize, + // evidence + EvidenceHeaderMagic, + EvidenceCompanionSpliced, + EvidenceExternalCompanionDeclaration, + EvidencePrivateSection, + EvidenceAesSchedule, + EvidenceValidatedMetadataTransform, + // platform + PlatformWindowsPe, + PlatformAndroidElf, + PlatformIl2cppMetadata, + // kind + KindNativeExe, + KindManagedExe, + KindNativeDll, + KindManagedDll, + // kindShort + KindShortNativeExe, + KindShortManagedExe, + KindShortNativeDll, + KindShortManagedDll, + // layout + LayoutExeStyle, + LayoutDll, + LayoutAndroidStaged, + LayoutMetadataSeeded, + LayoutMetadataStructural, + LayoutMetadataMethodIndices, + // metaLayout + MetaLayoutKnown, + MetaLayoutContextRequired, + MetaLayoutUnverified, + // companion + CompanionAbsent, + CompanionSpliced, + CompanionPaired, + CompanionUnmatched, + CompanionUnreadable, + // space + SpaceFileOffset, + SpaceWorkingImageRva, + SpaceProtectedHeaderOffset, + SpaceDecodedPayloadOffset, + // spaceShort + SpaceShortFileOffset, + SpaceShortWorkingImageRva, + SpaceShortProtectedHeaderOffset, + SpaceShortDecodedPayloadOffset, + // mapping + MappingZero, + MappingHeaderBacked, + MappingFileBacked, + MappingUnmapped, + // backing + BackingFileBacked, + BackingVirtualOnly, + BackingRawTruncated { + n: String, + }, + // region + RegionHeadersToFirstSection, + RegionBetweenSections, + RegionOverlay, + // semantic + SemanticKey, + SemanticMagic, + SemanticDestinationRva, + SemanticPayloadSource, + SemanticTotalLength, + SemanticEndMarker, + // severity + SeverityInfo, + SeverityWarning, + SeverityUnavailable, + // probe + ProbeDecoded, + ProbeUnavailable, + ProbeFailed, + ProbeBudgetLimited, + // shellKind + ShellKindPe32ShellTable, + ShellKindPe32PlusAnchor, + // candidate + CandidateObserved, + CandidateStructuralCandidate, + CandidateTrialValidated, + CandidateRejected, + // check + CheckSourcePrefix, + CheckSourceRawTail, + // msg + NoteEntryPointInside { + rva: String, + }, + NoteRawPastEof { + end: String, + len: String, + }, + NoteCertFileOffset, + NoteNoImportTable, + MsgCompanionMissing, + MsgLimitEntry { + entry: String, + limit: String, + size: String, + }, + MsgInternalPanic { + loc: String, + }, + NoteMagicUnsupportedValue { + value: String, + }, + NotePrefixScratch, + NoteAnchorValidates, + NoteBoundedAnchor, + NoteBoundedPrefix, + NoteCandidatesUnvalidated, + NoteMagicNotSupported, + NoteNoAnchorField, + NoteNoShellTable, + NoteShellNeedsPrefix, + NoteShellTableMatches, + NoteRelocUnsupportedType { + block: String, + entry: String, + ty: String, + }, + NoteRelocBadSize { + block: String, + size: String, + }, +} + +impl Localize for Text { + fn localize(&self, lang: Lang) -> Cow<'static, str> { + match lang { + Lang::En => super::en::text(self), + Lang::ZhCn => super::zh_cn::text(self), + Lang::ZhTw => super::zh_tw::text(self), + Lang::Ja => super::ja::text(self), + Lang::Ko => super::ko::text(self), + } + } +} + +impl Text { + /// The text for a catalog key such as `layout.exe_style`, when it takes no + /// arguments. Report values are looked up by their wire spelling this way. + pub fn by_key(key: &str) -> Option { + Some(match key { + "tb.add_files" => Text::TbAddFiles, + "tb.add_folder" => Text::TbAddFolder, + "tb.unpack" => Text::TbUnpack, + "tb.unpack.all" => Text::TbUnpackAll, + "tb.unpack_tip" => Text::TbUnpackTip, + "tb.dry_run" => Text::TbDryRun, + "tb.dry_run.all" => Text::TbDryRunAll, + "tb.dry_run_tip" => Text::TbDryRunTip, + "tb.inspect" => Text::TbInspect, + "tb.inspect.all" => Text::TbInspectAll, + "tb.inspect_tip" => Text::TbInspectTip, + "tb.output" => Text::TbOutput, + "tb.output_beside" => Text::TbOutputBeside, + "tb.output_tip" => Text::TbOutputTip, + "tb.settings" => Text::TbSettings, + "banner.env_hint" => Text::BannerEnvHint, + "empty.title" => Text::EmptyTitle, + "empty.folders" => Text::EmptyFolders, + "empty.local" => Text::EmptyLocal, + "drag.title" => Text::DragTitle, + "inputs.title" => Text::InputsTitle, + "inputs.clear" => Text::InputsClear, + "inputs.search" => Text::InputsSearch, + "inputs.none" => Text::InputsNone, + "filter.all" => Text::FilterAll, + "filter.ok" => Text::FilterOk, + "filter.suspect" => Text::FilterSuspect, + "filter.failed" => Text::FilterFailed, + "filter.skipped" => Text::FilterSkipped, + "group.files" => Text::GroupFiles, + "mode.inspect" => Text::ModeInspect, + "mode.dry_run" => Text::ModeDryRun, + "mode.unpack" => Text::ModeUnpack, + "menu.copy_path" => Text::MenuCopyPath, + "menu.remove" => Text::MenuRemove, + "pending.not_run" => Text::PendingNotRun, + "pending.not_protected" => Text::PendingNotProtected, + "pending.identified" => Text::PendingIdentified, + "pending.next" => Text::PendingNext, + "pending.unpack_desc" => Text::PendingUnpackDesc, + "pending.dry_run_desc" => Text::PendingDryRunDesc, + "pending.inspect_desc" => Text::PendingInspectDesc, + "pending.not_protected_note" => Text::PendingNotProtectedNote, + "pending.not_a_file" => Text::PendingNotAFile, + "scan.running" => Text::ScanRunning, + "scan.found" => Text::ScanFound, + "run.running" => Text::RunRunning, + "run.queued" => Text::RunQueued, + "run.will_not_run" => Text::RunWillNotRun, + "run.stopping" => Text::RunStopping, + "run.cancel" => Text::RunCancel, + "run.progress" => Text::RunProgress, + "run.cancelled_note" => Text::RunCancelledNote, + "step.decrypt_header" => Text::StepDecryptHeader, + "step.decrypt_payload" => Text::StepDecryptPayload, + "step.locate_config" => Text::StepLocateConfig, + "step.decrypt_stage2" => Text::StepDecryptStage2, + "step.decrypt_stages_3_5" => Text::StepDecryptStages35, + "step.decrypt_sections" => Text::StepDecryptSections, + "step.load_sections" => Text::StepLoadSections, + "step.decrypt_imports" => Text::StepDecryptImports, + "step.rebuild_headers" => Text::StepRebuildHeaders, + "step.init_keys" => Text::StepInitKeys, + "step.decrypt_key_table" => Text::StepDecryptKeyTable, + "step.decrypt_primary" => Text::StepDecryptPrimary, + "step.relocs_params" => Text::StepRelocsParams, + "step.decrypt_block1" => Text::StepDecryptBlock1, + "step.decrypt_block23" => Text::StepDecryptBlock23, + "step.decrypt_block4" => Text::StepDecryptBlock4, + "step.dll_sections" => Text::StepDllSections, + "step.fix_headers" => Text::StepFixHeaders, + "step.pe32_stages" => Text::StepPe32Stages, + "step.pe32_eighth" => Text::StepPe32Eighth, + "step.pe32_load" => Text::StepPe32Load, + "step.pe32_text" => Text::StepPe32Text, + "step.pe32_text_skip" => Text::StepPe32TextSkip, + "step.pe32_rebuild" => Text::StepPe32Rebuild, + "step.android_primary" => Text::StepAndroidPrimary, + "step.android_aux" => Text::StepAndroidAux, + "step.android_tables" => Text::StepAndroidTables, + "detail.pick" => Text::DetailPick, + "detail.export_json" => Text::DetailExportJson, + "detail.export_text" => Text::DetailExportText, + "detail.copy" => Text::DetailCopy, + "detail.technical" => Text::DetailTechnical, + "companion.spliced_pill" => Text::CompanionSplicedPill, + "tab.overview" => Text::TabOverview, + "tab.research" => Text::TabResearch, + "tab.hex" => Text::TabHex, + "tab.compare" => Text::TabCompare, + "tab.log" => Text::TabLog, + "tab.entries" => Text::TabEntries, + "batch.summary" => Text::BatchSummary, + "batch.inputs" => Text::BatchInputs, + "batch.scan" => Text::BatchScan, + "batch.non_target" => Text::BatchNonTarget, + "batch.walk_errors" => Text::BatchWalkErrors, + "batch.probe_errors" => Text::BatchProbeErrors, + "batch.scan_note" => Text::BatchScanNote, + "batch.scan_incomplete" => Text::BatchScanIncomplete, + "pkg.title" => Text::PkgTitle, + "pkg.kind" => Text::PkgKind, + "pkg.package" => Text::PkgPackage, + "pkg.version" => Text::PkgVersion, + "pkg.entries" => Text::PkgEntries, + "pkg.candidates" => Text::PkgCandidates, + "pkg.nested" => Text::PkgNested, + "pkg.note" => Text::PkgNote, + "pkg.result" => Text::PkgResult, + "pkg.manifests" => Text::PkgManifests, + "pkg.unnamed" => Text::PkgUnnamed, + "pkg.targets" => Text::PkgTargets, + "pkg.no_targets" => Text::PkgNoTargets, + "entries.title" => Text::EntriesTitle, + "entries.remapped_label" => Text::EntriesRemappedLabel, + "col.name" => Text::ColName, + "col.type" => Text::ColType, + "col.outcome" => Text::ColOutcome, + "col.route" => Text::ColRoute, + "col.time" => Text::ColTime, + "col.address" => Text::ColAddress, + "col.size" => Text::ColSize, + "col.file_offset" => Text::ColFileOffset, + "col.mapping" => Text::ColMapping, + "col.kind" => Text::ColKind, + "col.length" => Text::ColLength, + "col.source" => Text::ColSource, + "col.raw" => Text::ColRaw, + "col.decoded" => Text::ColDecoded, + "col.meaning" => Text::ColMeaning, + "col.check" => Text::ColCheck, + "col.start" => Text::ColStart, + "col.end" => Text::ColEnd, + "col.limit" => Text::ColLimit, + "col.status" => Text::ColStatus, + "col.note" => Text::ColNote, + "col.severity" => Text::ColSeverity, + "col.area" => Text::ColArea, + "col.message" => Text::ColMessage, + "col.value" => Text::ColValue, + "col.vsize" => Text::ColVsize, + "col.raw_offset" => Text::ColRawOffset, + "col.raw_size" => Text::ColRawSize, + "col.characteristics" => Text::ColCharacteristics, + "col.backing" => Text::ColBacking, + "col.field" => Text::ColField, + "col.command" => Text::ColCommand, + "col.flags" => Text::ColFlags, + "col.image" => Text::ColImage, + "col.metadata" => Text::ColMetadata, + "col.offset_size" => Text::ColOffsetSize, + "col.entry" => Text::ColEntry, + "col.init" => Text::ColInit, + "col.direct" => Text::ColDirect, + "col.nested" => Text::ColNested, + "col.depth" => Text::ColDepth, + "col.stream" => Text::ColStream, + "col.classification" => Text::ColClassification, + "common.yes" => Text::CommonYes, + "common.no" => Text::CommonNo, + "ov.messages" => Text::OvMessages, + "ov.recognition" => Text::OvRecognition, + "ov.platform" => Text::OvPlatform, + "ov.format" => Text::OvFormat, + "ov.kind" => Text::OvKind, + "ov.metadata" => Text::OvMetadata, + "ov.metadata_version" => Text::OvMetadataVersion, + "ov.metadata_layout" => Text::OvMetadataLayout, + "ov.cap_seeded" => Text::OvCapSeeded, + "ov.cap_structural" => Text::OvCapStructural, + "ov.cap_indices" => Text::OvCapIndices, + "ov.cap_context" => Text::OvCapContext, + "ov.provenance" => Text::OvProvenance, + "ov.evidence" => Text::OvEvidence, + "ov.no_evidence" => Text::OvNoEvidence, + "ov.routes" => Text::OvRoutes, + "ov.selected" => Text::OvSelected, + "ov.no_routes" => Text::OvNoRoutes, + "ov.stages" => Text::OvStages, + "ov.validation" => Text::OvValidation, + "ov.validation_metadata" => Text::OvValidationMetadata, + "ov.validation_warnings" => Text::OvValidationWarnings, + "ov.validation_failed" => Text::OvValidationFailed, + "ov.identity" => Text::OvIdentity, + "ov.source" => Text::OvSource, + "ov.companion" => Text::OvCompanion, + "ov.recovered" => Text::OvRecovered, + "ov.output" => Text::OvOutput, + "ov.open_folder" => Text::OvOpenFolder, + "ov.restored_elf" => Text::OvRestoredElf, + "ov.elf_sections" => Text::OvElfSections, + "ov.elf_symbols" => Text::OvElfSymbols, + "ov.elf_relocs" => Text::OvElfRelocs, + "research.none" => Text::ResearchNone, + "research.not_collected" => Text::ResearchNotCollected, + "research.run_inspect" => Text::ResearchRunInspect, + "research.spliced_note" => Text::ResearchSplicedNote, + "research.regions_note" => Text::ResearchRegionsNote, + "research.regions_none" => Text::ResearchRegionsNone, + "research.a_streams_note" => Text::ResearchAStreamsNote, + "research.a_artifacts_note" => Text::ResearchAArtifactsNote, + "rs.grp_input" => Text::RsGrpInput, + "rs.grp_protection" => Text::RsGrpProtection, + "rs.grp_recovery" => Text::RsGrpRecovery, + "rs.grp_extraction" => Text::RsGrpExtraction, + "rs.grp_restoration" => Text::RsGrpRestoration, + "rs.grp_metadata" => Text::RsGrpMetadata, + "rs.grp_profile" => Text::RsGrpProfile, + "rs.pe_header" => Text::RsPeHeader, + "rs.sections" => Text::RsSections, + "rs.directories" => Text::RsDirectories, + "rs.regions" => Text::RsRegions, + "rs.header_table" => Text::RsHeaderTable, + "rs.payload" => Text::RsPayload, + "rs.discovery" => Text::RsDiscovery, + "rs.trace" => Text::RsTrace, + "rs.issues" => Text::RsIssues, + "rs.restored" => Text::RsRestored, + "rs.a_stage1" => Text::RsAStage1, + "rs.a_streams" => Text::RsAStreams, + "rs.a_modules" => Text::RsAModules, + "rs.a_artifacts" => Text::RsAArtifacts, + "rs.a_scalars" => Text::RsAScalars, + "rs.a_r.descriptor" => Text::RsARDescriptor, + "rs.a_r.static_config" => Text::RsARStaticConfig, + "rs.a_r.primary" => Text::RsARPrimary, + "rs.a_r.auxiliary" => Text::RsARAuxiliary, + "rs.a_r.elf_materialization" => Text::RsARElfMaterialization, + "rs.a_r.cleaning" => Text::RsARCleaning, + "rs.a_r.validation" => Text::RsARValidation, + "rs.m_report" => Text::RsMReport, + "rs.m_images" => Text::RsMImages, + "rs.m_raw" => Text::RsMRaw, + "rs.profile" => Text::RsProfile, + "pe.offset" => Text::PeOffset, + "pe.machine" => Text::PeMachine, + "pe.format" => Text::PeFormat, + "pe.entry" => Text::PeEntry, + "pe.not_file_backed" => Text::PeNotFileBacked, + "pe.alignment" => Text::PeAlignment, + "pe.flags" => Text::PeFlags, + "pe.input_len" => Text::PeInputLen, + "pe.parse_issue" => Text::PeParseIssue, + "prot.magic" => Text::ProtMagic, + "prot.magic_ok" => Text::ProtMagicOk, + "prot.magic_bad" => Text::ProtMagicBad, + "prot.words" => Text::ProtWords, + "payload.source" => Text::PayloadSource, + "payload.dest" => Text::PayloadDest, + "payload.prefix" => Text::PayloadPrefix, + "payload.total" => Text::PayloadTotal, + "payload.checks" => Text::PayloadChecks, + "payload.in_bounds" => Text::PayloadInBounds, + "payload.out_of_bounds" => Text::PayloadOutOfBounds, + "payload.probe" => Text::PayloadProbe, + "payload.decoded" => Text::PayloadDecoded, + "payload.first_words" => Text::PayloadFirstWords, + "payload.unrecognized" => Text::PayloadUnrecognized, + "disc.payload_offset" => Text::DiscPayloadOffset, + "disc.image_rva" => Text::DiscImageRva, + "disc.source" => Text::DiscSource, + "disc.none" => Text::DiscNone, + "streams.origin" => Text::StreamsOrigin, + "streams.root" => Text::StreamsRoot, + "streams.records" => Text::StreamsRecords, + "issues.none" => Text::IssuesNone, + "issues.work" => Text::IssuesWork, + "issues.scratch" => Text::IssuesScratch, + "issues.candidates" => Text::IssuesCandidates, + "issues.budget" => Text::IssuesBudget, + "restored.open_compare" => Text::RestoredOpenCompare, + "restored.observations" => Text::RestoredObservations, + "meta.discovery_error" => Text::MetaDiscoveryError, + "meta.image" => Text::MetaImage, + "meta.methods" => Text::MetaMethods, + "meta.modulus" => Text::MetaModulus, + "meta.clean" => Text::MetaClean, + "meta.seed_residues" => Text::MetaSeedResidues, + "meta.residues" => Text::MetaResidues, + "hex.v_original" => Text::HexVOriginal, + "hex.v_spliced" => Text::HexVSpliced, + "hex.v_restored" => Text::HexVRestored, + "hex.goto" => Text::HexGoto, + "hex.as_file" => Text::HexAsFile, + "hex.as_rva" => Text::HexAsRva, + "hex.find" => Text::HexFind, + "hex.find_hint" => Text::HexFindHint, + "hex.find_next" => Text::HexFindNext, + "hex.find_none" => Text::HexFindNone, + "hex.copy_sel" => Text::HexCopySel, + "hex.inspector" => Text::HexInspector, + "hex.inspector_hint" => Text::HexInspectorHint, + "hex.regions" => Text::HexRegions, + "hex.no_regions" => Text::HexNoRegions, + "hex.r_headers" => Text::HexRHeaders, + "hex.r_stub_page" => Text::HexRStubPage, + "hex.r_header_table" => Text::HexRHeaderTable, + "hex.r_elf_header" => Text::HexRElfHeader, + "hex.r_program_headers" => Text::HexRProgramHeaders, + "hex.r_private_section" => Text::HexRPrivateSection, + "hex.r_stage2" => Text::HexRStage2, + "hex.r_streams" => Text::HexRStreams, + "hex.in_stub" => Text::HexInStub, + "cmp.no_change" => Text::CmpNoChange, + "cmp.headers" => Text::CmpHeaders, + "cmp.original" => Text::CmpOriginal, + "cmp.restored" => Text::CmpRestored, + "cmp.file_size" => Text::CmpFileSize, + "cmp.sections" => Text::CmpSections, + "cmp.bytes" => Text::CmpBytes, + "cmp.next_diff" => Text::CmpNextDiff, + "log.f_all" => Text::LogFAll, + "log.f_nosteps" => Text::LogFNosteps, + "log.f_problems" => Text::LogFProblems, + "log.copy" => Text::LogCopy, + "log.lv_info" => Text::LogLvInfo, + "log.lv_step" => Text::LogLvStep, + "log.lv_warn" => Text::LogLvWarn, + "log.lv_error" => Text::LogLvError, + "status.ready" => Text::StatusReady, + "close.title" => Text::CloseTitle, + "close.body" => Text::CloseBody, + "close.keep" => Text::CloseKeep, + "close.stop" => Text::CloseStop, + "legal.title" => Text::LegalTitle, + "legal.p1" => Text::LegalP1, + "legal.p2" => Text::LegalP2, + "legal.p3" => Text::LegalP3, + "legal.p4" => Text::LegalP4, + "legal.accept" => Text::LegalAccept, + "legal.quit" => Text::LegalQuit, + "settings.title" => Text::SettingsTitle, + "settings.tab_general" => Text::SettingsTabGeneral, + "settings.tab_processing" => Text::SettingsTabProcessing, + "settings.tab_android" => Text::SettingsTabAndroid, + "settings.tab_memory" => Text::SettingsTabMemory, + "settings.tab_about" => Text::SettingsTabAbout, + "settings.language" => Text::SettingsLanguage, + "settings.output" => Text::SettingsOutput, + "settings.output_recent" => Text::SettingsOutputRecent, + "settings.output_choose" => Text::SettingsOutputChoose, + "settings.output_help" => Text::SettingsOutputHelp, + "settings.log" => Text::SettingsLog, + "settings.log_help" => Text::SettingsLogHelp, + "settings.threads" => Text::SettingsThreads, + "settings.scan_all" => Text::SettingsScanAll, + "settings.scan_all_help" => Text::SettingsScanAllHelp, + "settings.android_note" => Text::SettingsAndroidNote, + "settings.max_entry" => Text::SettingsMaxEntry, + "settings.max_entry_help" => Text::SettingsMaxEntryHelp, + "settings.max_total" => Text::SettingsMaxTotal, + "settings.max_total_help" => Text::SettingsMaxTotalHelp, + "settings.max_entries" => Text::SettingsMaxEntries, + "settings.max_entries_help" => Text::SettingsMaxEntriesHelp, + "settings.max_depth" => Text::SettingsMaxDepth, + "settings.max_depth_help" => Text::SettingsMaxDepthHelp, + "settings.keep_bytes" => Text::SettingsKeepBytes, + "settings.keep_bytes_help" => Text::SettingsKeepBytesHelp, + "settings.keep_cap" => Text::SettingsKeepCap, + "settings.keep_cap_help" => Text::SettingsKeepCapHelp, + "settings.reset" => Text::SettingsReset, + "settings.done" => Text::SettingsDone, + "about.desc" => Text::AboutDesc, + "about.license" => Text::AboutLicense, + "about.source" => Text::AboutSource, + "about.legal" => Text::AboutLegal, + "status.ok" => Text::StatusOk, + "status.suspect" => Text::StatusSuspect, + "status.recognized" => Text::StatusRecognized, + "status.skipped" => Text::StatusSkipped, + "status.error" => Text::StatusError, + "status.incomplete" => Text::StatusIncomplete, + "entryStatus.restored" => Text::EntryStatusRestored, + "entryStatus.duplicate" => Text::EntryStatusDuplicate, + "entryStatus.not_target" => Text::EntryStatusNotTarget, + "entryStatus.unchanged" => Text::EntryStatusUnchanged, + "entryStatus.inventoried" => Text::EntryStatusInventoried, + "entryStatus.error" => Text::EntryStatusError, + "entryKind.shared_library" => Text::EntryKindSharedLibrary, + "entryKind.metadata" => Text::EntryKindMetadata, + "recognition.not_attempted" => Text::RecognitionNotAttempted, + "recognition.recognized" => Text::RecognitionRecognized, + "recognition.not_recognized" => Text::RecognitionNotRecognized, + "recognition.blocked" => Text::RecognitionBlocked, + "recovery.failed" => Text::RecoveryFailed, + "recovery.blocked" => Text::RecoveryBlocked, + "outcome.succeeded" => Text::OutcomeSucceeded, + "outcome.rejected" => Text::OutcomeRejected, + "outcome.failed" => Text::OutcomeFailed, + "outcome.not_attempted" => Text::OutcomeNotAttempted, + "validation.clean" => Text::ValidationClean, + "validation.warnings" => Text::ValidationWarnings, + "validation.failed" => Text::ValidationFailed, + "validation.not_run" => Text::ValidationNotRun, + "stage.detection" => Text::StageDetection, + "stage.manifest_inventory" => Text::StageManifestInventory, + "stage.entry_probe" => Text::StageEntryProbe, + "stage.recovery" => Text::StageRecovery, + "stage.static_validation" => Text::StageStaticValidation, + "stage.output_write" => Text::StageOutputWrite, + "stageStatus.ok" => Text::StageStatusOk, + "stageStatus.skipped" => Text::StageStatusSkipped, + "stageStatus.failed" => Text::StageStatusFailed, + "stageStatus.blocked" => Text::StageStatusBlocked, + "traceStage.header" => Text::TraceStageHeader, + "traceStage.payload" => Text::TraceStagePayload, + "traceStage.pe32_shell" => Text::TraceStagePe32Shell, + "traceStage.pe32_stages" => Text::TraceStagePe32Stages, + "traceStage.exe_stage1" => Text::TraceStageExeStage1, + "traceStage.exe_stage2" => Text::TraceStageExeStage2, + "traceStage.exe_stage3" => Text::TraceStageExeStage3, + "traceStage.exe_stage4" => Text::TraceStageExeStage4, + "traceStage.exe_stage5" => Text::TraceStageExeStage5, + "traceStage.dll_stages" => Text::TraceStageDllStages, + "traceStage.sections" => Text::TraceStageSections, + "traceStage.imports" => Text::TraceStageImports, + "traceStage.tls" => Text::TraceStageTls, + "traceStage.output" => Text::TraceStageOutput, + "traceStage.finalize" => Text::TraceStageFinalize, + "evidence.header_magic" => Text::EvidenceHeaderMagic, + "evidence.companion_spliced" => Text::EvidenceCompanionSpliced, + "evidence.external_companion_declaration" => Text::EvidenceExternalCompanionDeclaration, + "evidence.private_section" => Text::EvidencePrivateSection, + "evidence.aes_schedule" => Text::EvidenceAesSchedule, + "evidence.validated_metadata_transform" => Text::EvidenceValidatedMetadataTransform, + "platform.windows_pe" => Text::PlatformWindowsPe, + "platform.android_elf" => Text::PlatformAndroidElf, + "platform.il2cpp_metadata" => Text::PlatformIl2cppMetadata, + "kind.native_exe" => Text::KindNativeExe, + "kind.managed_exe" => Text::KindManagedExe, + "kind.native_dll" => Text::KindNativeDll, + "kind.managed_dll" => Text::KindManagedDll, + "kindShort.native_exe" => Text::KindShortNativeExe, + "kindShort.managed_exe" => Text::KindShortManagedExe, + "kindShort.native_dll" => Text::KindShortNativeDll, + "kindShort.managed_dll" => Text::KindShortManagedDll, + "layout.exe_style" => Text::LayoutExeStyle, + "layout.dll" => Text::LayoutDll, + "layout.android_staged" => Text::LayoutAndroidStaged, + "layout.metadata_seeded" => Text::LayoutMetadataSeeded, + "layout.metadata_structural" => Text::LayoutMetadataStructural, + "layout.metadata_method_indices" => Text::LayoutMetadataMethodIndices, + "metaLayout.known" => Text::MetaLayoutKnown, + "metaLayout.context_required" => Text::MetaLayoutContextRequired, + "metaLayout.unverified" => Text::MetaLayoutUnverified, + "companion.absent" => Text::CompanionAbsent, + "companion.spliced" => Text::CompanionSpliced, + "companion.paired" => Text::CompanionPaired, + "companion.unmatched" => Text::CompanionUnmatched, + "companion.unreadable" => Text::CompanionUnreadable, + "space.file_offset" => Text::SpaceFileOffset, + "space.working_image_rva" => Text::SpaceWorkingImageRva, + "space.protected_header_offset" => Text::SpaceProtectedHeaderOffset, + "space.decoded_payload_offset" => Text::SpaceDecodedPayloadOffset, + "spaceShort.file_offset" => Text::SpaceShortFileOffset, + "spaceShort.working_image_rva" => Text::SpaceShortWorkingImageRva, + "spaceShort.protected_header_offset" => Text::SpaceShortProtectedHeaderOffset, + "spaceShort.decoded_payload_offset" => Text::SpaceShortDecodedPayloadOffset, + "mapping.zero" => Text::MappingZero, + "mapping.header_backed" => Text::MappingHeaderBacked, + "mapping.file_backed" => Text::MappingFileBacked, + "mapping.unmapped" => Text::MappingUnmapped, + "backing.file_backed" => Text::BackingFileBacked, + "backing.virtual_only" => Text::BackingVirtualOnly, + "region.headers_to_first_section" => Text::RegionHeadersToFirstSection, + "region.between_sections" => Text::RegionBetweenSections, + "region.overlay" => Text::RegionOverlay, + "semantic.key" => Text::SemanticKey, + "semantic.magic" => Text::SemanticMagic, + "semantic.destination_rva" => Text::SemanticDestinationRva, + "semantic.payload_source" => Text::SemanticPayloadSource, + "semantic.total_length" => Text::SemanticTotalLength, + "semantic.end_marker" => Text::SemanticEndMarker, + "severity.info" => Text::SeverityInfo, + "severity.warning" => Text::SeverityWarning, + "severity.unavailable" => Text::SeverityUnavailable, + "probe.decoded" => Text::ProbeDecoded, + "probe.unavailable" => Text::ProbeUnavailable, + "probe.failed" => Text::ProbeFailed, + "probe.budget_limited" => Text::ProbeBudgetLimited, + "shellKind.pe32_shell_table" => Text::ShellKindPe32ShellTable, + "shellKind.pe32_plus_anchor" => Text::ShellKindPe32PlusAnchor, + "candidate.observed" => Text::CandidateObserved, + "candidate.structural_candidate" => Text::CandidateStructuralCandidate, + "candidate.trial_validated" => Text::CandidateTrialValidated, + "candidate.rejected" => Text::CandidateRejected, + "check.source_prefix" => Text::CheckSourcePrefix, + "check.source_raw_tail" => Text::CheckSourceRawTail, + "msg.cert_file_offset" => Text::NoteCertFileOffset, + "msg.no_import_table" => Text::NoteNoImportTable, + "msg.companion_missing" => Text::MsgCompanionMissing, + "msg.prefix_scratch" => Text::NotePrefixScratch, + "msg.anchor_validates" => Text::NoteAnchorValidates, + "msg.bounded_anchor" => Text::NoteBoundedAnchor, + "msg.bounded_prefix" => Text::NoteBoundedPrefix, + "msg.candidates_unvalidated" => Text::NoteCandidatesUnvalidated, + "msg.magic_not_supported" => Text::NoteMagicNotSupported, + "msg.no_anchor_field" => Text::NoteNoAnchorField, + "msg.no_shell_table" => Text::NoteNoShellTable, + "msg.shell_needs_prefix" => Text::NoteShellNeedsPrefix, + "msg.shell_table_matches" => Text::NoteShellTableMatches, + _ => return None, + }) + } +} diff --git a/senbei-gui/src/text/en.rs b/senbei-gui/src/text/en.rs new file mode 100644 index 0000000..48c7e06 --- /dev/null +++ b/senbei-gui/src/text/en.rs @@ -0,0 +1,564 @@ +// Generated from the approved GUI mockup catalog. Edit the wording here; +// every language must keep the same placeholders. + +use std::borrow::Cow; + +use super::catalog::Text; + +pub(crate) fn text(text: &Text) -> Cow<'static, str> { + match text { + Text::TbAddFiles => "Add files…".into(), + Text::TbAddFolder => "Add folder…".into(), + Text::TbUnpack => "Unpack".into(), + Text::TbUnpackN { n } => format!("Unpack ({n})").into(), + Text::TbUnpackAll => "Unpack all".into(), + Text::TbUnpackTip => "Recover the selected inputs and write the results to the output folder.".into(), + Text::TbDryRun => "Dry run".into(), + Text::TbDryRunN { n } => format!("Dry run ({n})").into(), + Text::TbDryRunAll => "Dry run all".into(), + Text::TbDryRunTip => "Run the real recovery and keep nothing.".into(), + Text::TbInspect => "Inspect".into(), + Text::TbInspectN { n } => format!("Inspect ({n})").into(), + Text::TbInspectAll => "Inspect all".into(), + Text::TbInspectTip => "Run the real recovery, show everything it found, and keep nothing.".into(), + Text::TbOutput => "Output:".into(), + Text::TbOutputBeside => "Beside each input (unpack\\)".into(), + Text::TbOutputTip => "Where unpacked files are written. Inspect and dry run never write outputs.".into(), + Text::TbSettings => "Settings".into(), + Text::BannerEnv { vars } => format!("Debug environment variable {vars} is set. Decoding may differ from a clean run.").into(), + Text::BannerEnvHint => "Unset it and restart to return to normal behavior.".into(), + Text::EmptyTitle => "Drop protected files here".into(), + Text::EmptyFolders => "folders".into(), + Text::EmptyLocal => "Everything runs on this computer. Inputs are never executed or uploaded.".into(), + Text::DragTitle => "Release to add".into(), + Text::InputsTitle => "Inputs".into(), + Text::InputsClear => "Clear".into(), + Text::InputsSearch => "Filter by name".into(), + Text::InputsNone => "No inputs match the filter.".into(), + Text::FilterAll => "All".into(), + Text::FilterOk => "Recovered".into(), + Text::FilterSuspect => "Suspect".into(), + Text::FilterFailed => "Failed".into(), + Text::FilterSkipped => "Skipped".into(), + Text::GroupFiles => "Added files".into(), + Text::GroupScanning { n } => format!("Scanning… candidates so far: {n}").into(), + Text::ModeInspect => "Inspected".into(), + Text::ModeDryRun => "Dry run".into(), + Text::ModeUnpack => "Unpacked".into(), + Text::MenuCopyPath => "Copy path".into(), + Text::MenuRemove => "Remove from list".into(), + Text::PendingNotRun => "Not run yet".into(), + Text::PendingNotProtected => "Not protected".into(), + Text::PendingIdentified => "Identified".into(), + Text::PendingNext => "What to do with it".into(), + Text::PendingUnpackDesc => "Recover it and write the result to the output folder.".into(), + Text::PendingDryRunDesc => "Run the real recovery and keep nothing, to see whether it works.".into(), + Text::PendingInspectDesc => "Run the real recovery and show everything found. Keeps nothing.".into(), + Text::PendingNotProtectedNote => "Senbei found no supported protection in this file, so there is nothing to recover.".into(), + Text::PendingNotAFile => "Not a regular file, so there is nothing to read.".into(), + Text::ScanRunning => "Scanning".into(), + Text::ScanFound => "Candidates so far".into(), + Text::ScanStatus { n, p } => format!("Scanning {p}… candidates so far: {n}").into(), + Text::RunRunning => "Running…".into(), + Text::RunQueued => "Queued".into(), + Text::RunWillNotRun => "Will not run".into(), + Text::RunStep { i, n, s } => format!("Step {i}/{n} · {s}").into(), + Text::RunQueue { n } => format!("Jobs queued: {n}").into(), + Text::RunStopping => "Stopping after the current input…".into(), + Text::RunCancel => "Cancel".into(), + Text::RunProgress => "Progress".into(), + Text::RunCancelledNote => "The job was cancelled before reaching this input.".into(), + Text::StepDecryptHeader => "Decrypting file header".into(), + Text::StepDecryptPayload => "Decrypting payload".into(), + Text::StepLocateConfig => "Locating config layout".into(), + Text::StepDecryptStage2 => "Decrypting stage 2".into(), + Text::StepDecryptStages35 => "Decrypting stages 3–5".into(), + Text::StepDecryptSections => "Decrypting section data".into(), + Text::StepLoadSections => "Loading and decompressing sections".into(), + Text::StepDecryptImports => "Decrypting import strings".into(), + Text::StepRebuildHeaders => "Reconstructing PE headers".into(), + Text::StepInitKeys => "Initializing keys".into(), + Text::StepDecryptKeyTable => "Decrypting key table".into(), + Text::StepDecryptPrimary => "Decrypting primary descriptor".into(), + Text::StepRelocsParams => "Processing relocations and decompression parameters".into(), + Text::StepDecryptBlock1 => "Decrypting code block 1".into(), + Text::StepDecryptBlock23 => "Decrypting code blocks 2–3".into(), + Text::StepDecryptBlock4 => "Decrypting code block 4".into(), + Text::StepDllSections => "Decrypting and decompressing sections".into(), + Text::StepFixHeaders => "Fixing up PE header and section table".into(), + Text::StepPe32Stages => "Decrypting stages".into(), + Text::StepPe32Eighth => "Decrypting the eighth stage".into(), + Text::StepPe32Load => "Loading and decompressing file data".into(), + Text::StepPe32Text => "Decrypting .text".into(), + Text::StepPe32TextSkip => "Skipping .text (already plaintext)".into(), + Text::StepPe32Rebuild => "Rebuilding PE file layout".into(), + Text::StepAndroidPrimary => "Decoding the primary container".into(), + Text::StepAndroidAux => "Decoding the ELF materialization container".into(), + Text::StepAndroidTables => "Rebuilding dynamic-linker tables".into(), + Text::DetailPick => "Select an input or a group on the left.".into(), + Text::DetailExportJson => "Export JSON".into(), + Text::DetailExportText => "Export text".into(), + Text::DetailLastRun { mode, t } => format!("{mode} · {t}").into(), + Text::DetailCopy => "Copy".into(), + Text::DetailTechnical => "Technical detail".into(), + Text::CompanionSplicedPill => "Companion paired".into(), + Text::TabOverview => "Overview".into(), + Text::TabResearch => "Research".into(), + Text::TabHex => "Hex".into(), + Text::TabCompare => "Compare".into(), + Text::TabLog => "Log".into(), + Text::TabEntries => "Entries".into(), + Text::BatchSummary => "Summary".into(), + Text::BatchInputs => "Inputs".into(), + Text::BatchScan => "Folder scan".into(), + Text::BatchNonTarget => "Non-targets skipped".into(), + Text::BatchWalkErrors => "Unreadable entries".into(), + Text::BatchProbeErrors => "Probe errors".into(), + Text::BatchScanNote => "Only .exe, .dll, .so and global-metadata.dat names are probed.".into(), + Text::BatchScanIncomplete => "Analysis is incomplete: some folder entries or selected files could not be examined.".into(), + Text::PkgTitle => "Package".into(), + Text::PkgKind => "Package type".into(), + Text::PkgPackage => "Package name".into(), + Text::PkgVersion => "Version".into(), + Text::PkgEntries => "Top-level entries".into(), + Text::PkgCandidates => "Entries to probe".into(), + Text::PkgNested => "Nested packages".into(), + Text::PkgNote => "Only .so and global-metadata.dat entries are extracted and probed.".into(), + Text::PkgResult => "Result".into(), + Text::PkgManifests => "Manifests".into(), + Text::PkgUnnamed => "not named".into(), + Text::PkgTargets => "Protected entries and metadata".into(), + Text::PkgNoTargets => "No entry in this package is protected, so there is nothing to recover.".into(), + Text::PkgInventory { n } => format!("Entries listed in the package: {n}").into(), + Text::EntriesTitle => "Entry".into(), + Text::EntriesOthers { n } => format!("Other entries (not targets): {n}").into(), + Text::EntriesSummary { n } => format!("Targets: {n}").into(), + Text::EntriesShowNonTargets { n } => format!("Show non-targets ({n})").into(), + Text::EntriesRemapped { n } => format!("Method fields remapped: {n}").into(), + Text::EntriesRemappedLabel => "Method fields remapped".into(), + Text::ColName => "Name".into(), + Text::ColType => "Type".into(), + Text::ColOutcome => "Outcome".into(), + Text::ColRoute => "Route".into(), + Text::ColTime => "Time".into(), + Text::ColAddress => "Address".into(), + Text::ColSize => "Size".into(), + Text::ColFileOffset => "File offset".into(), + Text::ColMapping => "Mapping".into(), + Text::ColKind => "Kind".into(), + Text::ColLength => "Length".into(), + Text::ColSource => "Source".into(), + Text::ColRaw => "Raw".into(), + Text::ColDecoded => "Decoded".into(), + Text::ColMeaning => "Meaning".into(), + Text::ColCheck => "Check".into(), + Text::ColStart => "Start".into(), + Text::ColEnd => "End".into(), + Text::ColLimit => "Limit".into(), + Text::ColStatus => "Status".into(), + Text::ColNote => "Note".into(), + Text::ColSeverity => "Severity".into(), + Text::ColArea => "Area".into(), + Text::ColMessage => "Message".into(), + Text::ColValue => "Value".into(), + Text::ColVsize => "Virtual size".into(), + Text::ColRawOffset => "Raw offset".into(), + Text::ColRawSize => "Raw size".into(), + Text::ColCharacteristics => "Characteristics".into(), + Text::ColBacking => "Backing".into(), + Text::ColField => "Field".into(), + Text::ColCommand => "Command".into(), + Text::ColFlags => "Flags".into(), + Text::ColImage => "Image".into(), + Text::ColMetadata => "Metadata".into(), + Text::ColOffsetSize => "offset +size".into(), + Text::ColEntry => "Entry point".into(), + Text::ColInit => "Init".into(), + Text::ColDirect => "Direct".into(), + Text::ColNested => "Nested stream".into(), + Text::ColDepth => "Depth".into(), + Text::ColStream => "Stream".into(), + Text::ColClassification => "Classification".into(), + Text::CommonYes => "yes".into(), + Text::CommonNo => "no".into(), + Text::OvMessages => "Messages".into(), + Text::OvRecognition => "Recognition".into(), + Text::OvPlatform => "Platform".into(), + Text::OvFormat => "Format".into(), + Text::OvKind => "Kind".into(), + Text::OvMetadata => "il2cpp metadata".into(), + Text::OvMetadataVersion => "Metadata version".into(), + Text::OvMetadataLayout => "Layout definition".into(), + Text::OvCapSeeded => "Seeded method tokens".into(), + Text::OvCapStructural => "Structural method tokens".into(), + Text::OvCapIndices => "Method-index restoration".into(), + Text::OvCapContext => "Needs application context".into(), + Text::OvProvenance => "Module context from".into(), + Text::OvEvidence => "Evidence".into(), + Text::OvNoEvidence => "No protection evidence".into(), + Text::OvRoutes => "Recovery routes".into(), + Text::OvSelected => "selected".into(), + Text::OvNoRoutes => "No route was attempted.".into(), + Text::OvStages => "Stages".into(), + Text::OvValidation => "Static validation".into(), + Text::OvValidationMetadata => "The PE and ELF structure checks do not apply to metadata; the transform validates its own tables.".into(), + Text::OvValidationWarnings => "The restored image has structural findings and may not run. It is counted as suspect; an unpack still writes it.".into(), + Text::OvValidationFailed => "The restored image failed a fatal structure check and is unlikely to run. It is counted as suspect; an unpack still writes it.".into(), + Text::OvIdentity => "Identity".into(), + Text::OvSource => "Input".into(), + Text::OvCompanion => "Companion".into(), + Text::OvRecovered => "Restored image".into(), + Text::OvOutput => "Output".into(), + Text::OvOpenFolder => "Show in folder".into(), + Text::OvRestoredElf => "Restored ELF".into(), + Text::OvElfSections => "Sections · segments".into(), + Text::OvElfSymbols => "Dynamic symbols".into(), + Text::OvElfRelocs => "Relocations · PLT".into(), + Text::ResearchNone => "No research data: recovery stopped before the engine published structural evidence.".into(), + Text::ResearchNotCollected => "This run did not collect research evidence.".into(), + Text::ResearchRunInspect => "Inspect this input".into(), + Text::ResearchSplicedNote => "Spliced view: offsets below 0x1000 address the loader stub; offsets from 0x1000 address the companion at (offset − 0x1000).".into(), + Text::ResearchJump { space } => format!("Show in Hex ({space})").into(), + Text::ResearchRegionsNote => "File ranges outside every section.".into(), + Text::ResearchRegionsNone => "Every file byte belongs to the headers or a section.".into(), + Text::ResearchAStreamsNote => "Each stream is one decoded container level.".into(), + Text::ResearchAArtifactsNote => "Files produced during extraction. They live in a temporary workspace that is discarded afterwards.".into(), + Text::RsGrpInput => "Protected input".into(), + Text::RsGrpProtection => "Protection".into(), + Text::RsGrpRecovery => "Recovery".into(), + Text::RsGrpExtraction => "Extraction".into(), + Text::RsGrpRestoration => "Restoration".into(), + Text::RsGrpMetadata => "Metadata".into(), + Text::RsGrpProfile => "Profile".into(), + Text::RsPeHeader => "PE header".into(), + Text::RsSections => "Sections".into(), + Text::RsDirectories => "Data directories".into(), + Text::RsRegions => "File regions".into(), + Text::RsHeaderTable => "Header table".into(), + Text::RsPayload => "Declared payload".into(), + Text::RsDiscovery => "Stage discovery".into(), + Text::RsTrace => "Recovery trace".into(), + Text::RsIssues => "Issues and work budget".into(), + Text::RsRestored => "Restored image".into(), + Text::RsAStage1 => "Stage 1".into(), + Text::RsAStreams => "Streams".into(), + Text::RsAModules => "Module registry".into(), + Text::RsAArtifacts => "Artifacts".into(), + Text::RsAScalars => "Totals".into(), + Text::RsARDescriptor => "Descriptor".into(), + Text::RsARStaticConfig => "Static configuration".into(), + Text::RsARPrimary => "Primary container".into(), + Text::RsARAuxiliary => "Auxiliary container".into(), + Text::RsARElfMaterialization => "ELF materialization".into(), + Text::RsARCleaning => "Protector removal".into(), + Text::RsARValidation => "Validation".into(), + Text::RsMReport => "Transform report".into(), + Text::RsMImages => "Images".into(), + Text::RsMRaw => "Other fields".into(), + Text::RsProfile => "Recovery profile".into(), + Text::PeOffset => "PE header offset".into(), + Text::PeMachine => "Machine".into(), + Text::PeFormat => "Format".into(), + Text::PeEntry => "Entry point".into(), + Text::PeNotFileBacked => "not file-backed".into(), + Text::PeAlignment => "Section / file alignment".into(), + Text::PeFlags => "Declared flags".into(), + Text::PeInputLen => "Analyzed bytes".into(), + Text::PeParseIssue => "Parse issue".into(), + Text::MappingInSection { s } => format!("in {s}").into(), + Text::MappingPartial { n } => format!("Partially file-backed ({n} bytes)").into(), + Text::ProtMagic => "Magic".into(), + Text::ProtMagicOk => "supported".into(), + Text::ProtMagicBad => "not supported".into(), + Text::ProtWords => "Header words".into(), + Text::PayloadSource => "Source".into(), + Text::PayloadDest => "Destination".into(), + Text::PayloadPrefix => "Prefix length".into(), + Text::PayloadTotal => "Total length".into(), + Text::PayloadChecks => "Bounds checks".into(), + Text::PayloadInBounds => "in bounds".into(), + Text::PayloadOutOfBounds => "out of bounds".into(), + Text::PayloadProbe => "Prefix probe".into(), + Text::PayloadDecoded => "Decoded".into(), + Text::PayloadLimit { l } => format!("limit {l}").into(), + Text::PayloadFirstWords => "First words".into(), + Text::PayloadUnrecognized => "The magic was not recognized, so this is only one possible reading of the header words.".into(), + Text::DiscPayloadOffset => "Payload offset".into(), + Text::DiscImageRva => "Image RVA".into(), + Text::DiscSource => "Source".into(), + Text::DiscScanned { n } => format!("Positions scanned: {n}").into(), + Text::DiscNone => "No candidates.".into(), + Text::TraceSummary { n, s } => format!("Events: {n} · stages: {s}").into(), + Text::TraceEvents { n } => format!("Events: {n}").into(), + Text::TraceTruncated { l, n } => format!("Trace truncated. Events dropped: {n} (limit {l}).").into(), + Text::StreamsTitle { id } => format!("Stream {id}").into(), + Text::StreamsSummary { d, k, n, s } => format!("depth {d} · {k} · records: {n} · {s}").into(), + Text::StreamsOrigin => "Origin".into(), + Text::StreamsRoot => "Top level of the protected file".into(), + Text::StreamsParent { c, r, s } => format!("Stream {s}, record {r}, command {c}").into(), + Text::StreamsRecords => "Records".into(), + Text::IssuesNone => "No issues recorded.".into(), + Text::IssuesWork => "Work budget".into(), + Text::IssuesScratch => "Prefix scratch used".into(), + Text::IssuesCandidates => "Candidates considered".into(), + Text::IssuesBudget => "Budget limited".into(), + Text::RestoredOpenCompare => "Compare with the original…".into(), + Text::RestoredObservations => "Observations on the restored image".into(), + Text::MetaRoute { r } => format!("route: {r}").into(), + Text::MetaDiscoveryError => "Seed discovery did not apply, so the structural route was used:".into(), + Text::MetaImage => "Image".into(), + Text::MetaMethods => "Methods".into(), + Text::MetaModulus => "Modulus".into(), + Text::MetaClean => "Clean".into(), + Text::MetaSeedResidues => "Seed residues".into(), + Text::MetaResidues => "residues".into(), + Text::HexVOriginal => "Original file".into(), + Text::HexVSpliced => "Spliced view".into(), + Text::HexVRestored => "Restored (in memory)".into(), + Text::HexGoto => "Go to".into(), + Text::HexAsFile => "file offset".into(), + Text::HexAsRva => "RVA".into(), + Text::HexFind => "Find".into(), + Text::HexFindHint => "4D 5A or text".into(), + Text::HexFindNext => "Next".into(), + Text::HexFindNone => "No more matches.".into(), + Text::HexTooLarge { limit, size } => format!("This file is {size}; the Hex view reads files up to {limit}.").into(), + Text::HexRvaUnmapped { o } => format!("RVA {o} has no file bytes in this view.").into(), + Text::HexCopySel => "Copy selection".into(), + Text::HexInspector => "At cursor".into(), + Text::HexInspectorHint => "Click a byte to read its value here.".into(), + Text::HexRegions => "Regions".into(), + Text::HexNoRegions => "No regions known for this file.".into(), + Text::HexRHeaders => "Headers".into(), + Text::HexRStubPage => "Loader stub page".into(), + Text::HexRHeaderTable => "Protection header table".into(), + Text::HexRElfHeader => "ELF header".into(), + Text::HexRProgramHeaders => "Program headers".into(), + Text::HexRLoad { n } => format!("LOAD segment {n}").into(), + Text::HexRPrivateSection => "Private loader section".into(), + Text::HexRStage2 => "Stage 2 payload".into(), + Text::HexRStreams => "Encrypted streams".into(), + Text::HexSize { s } => format!("Size {s}").into(), + Text::HexAt { o } => format!("Offset {o}").into(), + Text::HexInCompanion { o } => format!("companion offset {o}").into(), + Text::HexInStub => "loader stub".into(), + Text::CmpNoChange => "No structural differences".into(), + Text::CmpHeaders => "Headers".into(), + Text::CmpOriginal => "Original".into(), + Text::CmpRestored => "Restored".into(), + Text::CmpFileSize => "File size".into(), + Text::CmpSections => "Section count".into(), + Text::CmpBytes => "Section bytes".into(), + Text::CmpBytesNote { len, n, s } => format!("Differing bytes in the first {len} bytes of {s}: {n}.").into(), + Text::CmpNextDiff => "Next difference".into(), + Text::LogFAll => "All".into(), + Text::LogFNosteps => "Hide steps".into(), + Text::LogFProblems => "Problems only".into(), + Text::LogCopy => "Copy log".into(), + Text::LogLvInfo => "INFO".into(), + Text::LogLvStep => "STEP".into(), + Text::LogLvWarn => "WARN".into(), + Text::LogLvError => "ERROR".into(), + Text::LogRunStarted { mode, n } => format!("{mode} started · inputs: {n}").into(), + Text::LogScan { n, s } => format!("Scan finished: candidates {n}, non-targets skipped {s}").into(), + Text::LogInputStarted { i, n, p } => format!("Input {i}/{n}: {p}").into(), + Text::LogCompanion { p } => format!("Companion paired: {p}").into(), + Text::LogStep { i, n, s } => format!("Step {i}/{n}: {s}").into(), + Text::LogEntry { o, p } => format!("Entry {p}: {o}").into(), + Text::LogInputFinished { o, t } => format!("Finished: {o} ({t})").into(), + Text::LogSummary { failed, ok, skipped, suspect } => format!("{ok} recovered · {suspect} suspect · {failed} failed · {skipped} skipped").into(), + Text::StatusReady => "Ready".into(), + Text::CloseTitle => "A job is still running".into(), + Text::CloseBody => "Senbei will stop after the current input finishes, then close. Outputs already written are kept.".into(), + Text::CloseKeep => "Keep running".into(), + Text::CloseStop => "Stop and close".into(), + Text::LegalTitle => "Legal notice: read before use".into(), + Text::LegalP1 => "Senbei is a research and interoperability tool for lawful reverse engineering, security research, and preservation of software you already legitimately possess. Only process binaries you own or are explicitly authorized to analyze.".into(), + Text::LegalP2 => "Circumventing technological protection measures may be restricted in your jurisdiction (for example under DMCA §1201 in the United States, which contains exemptions for security research and interoperability). Ensuring your use is lawful is your responsibility.".into(), + Text::LegalP3 => "Senbei performs a purely static transformation of files on your computer: it bypasses no access control by itself, derives what it needs from the input file, ships no vendor code, and never executes or uploads its inputs. One Android packaging variant’s embedded metadata layer is unwrapped with an XOR keystream recovered during analysis of a single build; that keystream is research output shipped with the tool, not a vendor-distributed key.".into(), + Text::LegalP4 => "Senbei does not enable online play, license fraud, or cheating. Do not redistribute decrypted outputs or upload them anywhere. This software is provided “as is”, without warranty of any kind; the authors accept no liability for misuse. “CrackProof” is a trademark of its owner; this project is not affiliated with or endorsed by the vendor or any publisher.".into(), + Text::LegalAccept => "I understand and accept".into(), + Text::LegalQuit => "Quit".into(), + Text::SettingsTitle => "Settings".into(), + Text::SettingsTabGeneral => "General".into(), + Text::SettingsTabProcessing => "Processing".into(), + Text::SettingsTabAndroid => "Android limits".into(), + Text::SettingsTabMemory => "Memory".into(), + Text::SettingsTabAbout => "About".into(), + Text::SettingsLanguage => "Language".into(), + Text::SettingsOutput => "Default output folder".into(), + Text::SettingsOutputRecent => "Last used folder".into(), + Text::SettingsOutputChoose => "Choose a folder…".into(), + Text::SettingsOutputHelp => "Beside each input means an unpack\\ folder next to the file or folder you added.".into(), + Text::SettingsLog => "Write a log file".into(), + Text::SettingsLogHelp => "Unpack writes senbei-YYYYMMDD-HHMMSS.log into the output folder.".into(), + Text::SettingsThreads => "Worker threads".into(), + Text::SettingsThreadsAuto { n } => format!("Automatic ({n})").into(), + Text::SettingsScanAll => "Probe small files".into(), + Text::SettingsScanAllHelp => "Also probe .exe, .dll, .so and metadata names below the size floor when scanning folders.".into(), + Text::SettingsAndroidNote => "Limits are checked before extraction or allocation. They are not a cap on peak memory use.".into(), + Text::SettingsMaxEntry => "Largest single entry".into(), + Text::SettingsMaxEntryHelp => "Archive entry, decoded buffer, or output.".into(), + Text::SettingsMaxTotal => "Total budget".into(), + Text::SettingsMaxTotalHelp => "Cumulative archive bytes and per-engine task budget.".into(), + Text::SettingsMaxEntries => "Maximum entries".into(), + Text::SettingsMaxEntriesHelp => "Archive entries and stage-2 records.".into(), + Text::SettingsMaxDepth => "Maximum nesting depth".into(), + Text::SettingsMaxDepthHelp => "The package itself is depth 0.".into(), + Text::SettingsKeepBytes => "Keep restored bytes for Hex and Compare".into(), + Text::SettingsKeepBytesHelp => "Inspect and dry run keep the restored image in memory for this session only.".into(), + Text::SettingsKeepCap => "Per-input memory cap".into(), + Text::SettingsKeepCapHelp => "Larger restored images are summarized structurally without bytes.".into(), + Text::SettingsReset => "Reset to defaults".into(), + Text::SettingsDone => "Done".into(), + Text::AboutVersion { v } => format!("Version {v}").into(), + Text::AboutDesc => "Static unpacker for CrackProof-protected Windows PE files and Android AArch64 shared libraries.".into(), + Text::AboutLicense => "License".into(), + Text::AboutSource => "Source code".into(), + Text::AboutLegal => "Show legal notice".into(), + Text::TagMetadata { v } => format!("il2cpp metadata v{v}").into(), + Text::StatusOk => "Recovered".into(), + Text::StatusSuspect => "Suspect".into(), + Text::StatusRecognized => "Recognized".into(), + Text::StatusSkipped => "Skipped".into(), + Text::StatusError => "Error".into(), + Text::StatusIncomplete => "Analysis incomplete".into(), + Text::EntryStatusRestored => "Restored".into(), + Text::EntryStatusDuplicate => "Duplicate".into(), + Text::EntryStatusNotTarget => "Not a target".into(), + Text::EntryStatusUnchanged => "Unchanged".into(), + Text::EntryStatusInventoried => "Listed".into(), + Text::EntryStatusError => "Error".into(), + Text::EntryKindSharedLibrary => "Shared library".into(), + Text::EntryKindMetadata => "il2cpp metadata".into(), + Text::RecognitionNotAttempted => "Not attempted".into(), + Text::RecognitionRecognized => "Recognized".into(), + Text::RecognitionNotRecognized => "Not recognized".into(), + Text::RecognitionBlocked => "Blocked".into(), + Text::RecoveryFailed => "Recovery failed".into(), + Text::RecoveryBlocked => "Recovery blocked".into(), + Text::OutcomeSucceeded => "Succeeded".into(), + Text::OutcomeRejected => "Rejected".into(), + Text::OutcomeFailed => "Failed".into(), + Text::OutcomeNotAttempted => "Not attempted".into(), + Text::ValidationClean => "Clean".into(), + Text::ValidationWarnings => "Warnings".into(), + Text::ValidationFailed => "Failed".into(), + Text::ValidationNotRun => "Not run".into(), + Text::StageDetection => "Detection".into(), + Text::StageManifestInventory => "Manifest inventory".into(), + Text::StageEntryProbe => "Entry probe".into(), + Text::StageRecovery => "Recovery".into(), + Text::StageStaticValidation => "Static validation".into(), + Text::StageOutputWrite => "Output write".into(), + Text::StageStatusOk => "OK".into(), + Text::StageStatusSkipped => "Skipped".into(), + Text::StageStatusFailed => "Failed".into(), + Text::StageStatusBlocked => "Blocked".into(), + Text::TraceStageHeader => "Header".into(), + Text::TraceStagePayload => "Payload".into(), + Text::TraceStagePe32Shell => "PE32 shell".into(), + Text::TraceStagePe32Stages => "PE32 stages".into(), + Text::TraceStageExeStage1 => "Stage 1".into(), + Text::TraceStageExeStage2 => "Stage 2".into(), + Text::TraceStageExeStage3 => "Stage 3".into(), + Text::TraceStageExeStage4 => "Stage 4".into(), + Text::TraceStageExeStage5 => "Stage 5".into(), + Text::TraceStageDllStages => "DLL stages".into(), + Text::TraceStageSections => "Sections".into(), + Text::TraceStageImports => "Imports".into(), + Text::TraceStageTls => "TLS".into(), + Text::TraceStageOutput => "Output".into(), + Text::TraceStageFinalize => "Finalize".into(), + Text::EvidenceHeaderMagic => "Header magic".into(), + Text::EvidenceCompanionSpliced => "Companion spliced".into(), + Text::EvidenceExternalCompanionDeclaration => "Declares an external companion".into(), + Text::EvidencePrivateSection => "Private section".into(), + Text::EvidenceAesSchedule => "AES key schedule".into(), + Text::EvidenceValidatedMetadataTransform => "Validated metadata transform".into(), + Text::PlatformWindowsPe => "Windows PE".into(), + Text::PlatformAndroidElf => "Android ELF".into(), + Text::PlatformIl2cppMetadata => "il2cpp metadata".into(), + Text::KindNativeExe => "Native executable".into(), + Text::KindManagedExe => ".NET executable".into(), + Text::KindNativeDll => "Native DLL".into(), + Text::KindManagedDll => ".NET assembly (DLL)".into(), + Text::KindShortNativeExe => "EXE".into(), + Text::KindShortManagedExe => ".NET EXE".into(), + Text::KindShortNativeDll => "DLL".into(), + Text::KindShortManagedDll => ".NET DLL".into(), + Text::LayoutExeStyle => "EXE-style loader".into(), + Text::LayoutDll => "DLL loader".into(), + Text::LayoutAndroidStaged => "Android staged loader".into(), + Text::LayoutMetadataSeeded => "Seeded metadata transform".into(), + Text::LayoutMetadataStructural => "Structural metadata transform".into(), + Text::LayoutMetadataMethodIndices => "Metadata method-index recovery".into(), + Text::MetaLayoutKnown => "Known".into(), + Text::MetaLayoutContextRequired => "Needs application context".into(), + Text::MetaLayoutUnverified => "Not verified".into(), + Text::CompanionAbsent => "None".into(), + Text::CompanionSpliced => "Spliced".into(), + Text::CompanionPaired => "Paired".into(), + Text::CompanionUnmatched => "Does not match".into(), + Text::CompanionUnreadable => "Unreadable".into(), + Text::SpaceFileOffset => "file offset".into(), + Text::SpaceWorkingImageRva => "image RVA".into(), + Text::SpaceProtectedHeaderOffset => "protected header offset".into(), + Text::SpaceDecodedPayloadOffset => "decoded payload offset".into(), + Text::SpaceShortFileOffset => "FILE".into(), + Text::SpaceShortWorkingImageRva => "RVA".into(), + Text::SpaceShortProtectedHeaderOffset => "HDR".into(), + Text::SpaceShortDecodedPayloadOffset => "PAYLOAD".into(), + Text::MappingZero => "Empty".into(), + Text::MappingHeaderBacked => "In the headers".into(), + Text::MappingFileBacked => "File-backed".into(), + Text::MappingUnmapped => "Not mapped".into(), + Text::BackingFileBacked => "File-backed".into(), + Text::BackingVirtualOnly => "Virtual only".into(), + Text::BackingRawTruncated { n } => format!("Truncated ({n} bytes present)").into(), + Text::RegionHeadersToFirstSection => "Gap between headers and first section".into(), + Text::RegionBetweenSections => "Gap between sections".into(), + Text::RegionOverlay => "Overlay".into(), + Text::SemanticKey => "key".into(), + Text::SemanticMagic => "magic".into(), + Text::SemanticDestinationRva => "destination RVA".into(), + Text::SemanticPayloadSource => "payload source".into(), + Text::SemanticTotalLength => "total length".into(), + Text::SemanticEndMarker => "end marker".into(), + Text::SeverityInfo => "Info".into(), + Text::SeverityWarning => "Warning".into(), + Text::SeverityUnavailable => "Unavailable".into(), + Text::ProbeDecoded => "Decoded".into(), + Text::ProbeUnavailable => "Unavailable".into(), + Text::ProbeFailed => "Failed".into(), + Text::ProbeBudgetLimited => "Budget limited".into(), + Text::ShellKindPe32ShellTable => "PE32 shell table".into(), + Text::ShellKindPe32PlusAnchor => "PE32+ anchor".into(), + Text::CandidateObserved => "Observed".into(), + Text::CandidateStructuralCandidate => "Structural candidate".into(), + Text::CandidateTrialValidated => "Trial validated".into(), + Text::CandidateRejected => "Rejected".into(), + Text::CheckSourcePrefix => "Payload prefix (source)".into(), + Text::CheckSourceRawTail => "Payload tail (source)".into(), + Text::NoteEntryPointInside { rva } => format!("entry point {rva} lies in this section").into(), + Text::NoteRawPastEof { end, len } => format!("raw range ends at {end}, input is {len} bytes").into(), + Text::NoteCertFileOffset => "certificate directory uses a file offset, not an RVA".into(), + Text::NoteNoImportTable => "no import table".into(), + Text::MsgCompanionMissing => "Companion missing? This loader expects a matching ._ payload. Keep it beside the input file and try again.".into(), + Text::MsgLimitEntry { entry, limit, size } => format!("{entry} is {size} bytes, over the {limit}-byte limit. Raise the limit in Settings → Android limits, then run it again.").into(), + Text::MsgInternalPanic { loc } => format!("internal error in the recovery engine at {loc}").into(), + Text::NoteMagicUnsupportedValue { value } => format!("header table decoded but info[1] is {value}, not the supported magic").into(), + Text::NotePrefixScratch => "prefix decoded in scratch; later stages still require a full recovery".into(), + Text::NoteAnchorValidates => "anchor and stage1 descriptor validate; full stage decryption requires recovery".into(), + Text::NoteBoundedAnchor => "bounded anchor probe only".into(), + Text::NoteBoundedPrefix => "bounded prefix only; not a recovered image".into(), + Text::NoteCandidatesUnvalidated => "candidates reported without stage validation".into(), + Text::NoteMagicNotSupported => "header magic is not a supported protection header".into(), + Text::NoteNoAnchorField => "no anchor field in the decoded payload window".into(), + Text::NoteNoShellTable => "no shell table shape in the decoded payload window".into(), + Text::NoteShellNeedsPrefix => "shell discovery needs a decoded payload prefix".into(), + Text::NoteShellTableMatches => "shell table shape matches the declared image; second-stage decryption requires recovery".into(), + Text::NoteRelocUnsupportedType { block, entry, ty } => format!("relocation block {block} entry {entry} has unsupported type {ty}").into(), + Text::NoteRelocBadSize { block, size } => format!("relocation block {block} declares size {size}, which does not fit the directory").into(), + } +} diff --git a/senbei-gui/src/text/ja.rs b/senbei-gui/src/text/ja.rs new file mode 100644 index 0000000..09601dd --- /dev/null +++ b/senbei-gui/src/text/ja.rs @@ -0,0 +1,564 @@ +// Generated from the approved GUI mockup catalog. Edit the wording here; +// every language must keep the same placeholders. + +use std::borrow::Cow; + +use super::catalog::Text; + +pub(crate) fn text(text: &Text) -> Cow<'static, str> { + match text { + Text::TbAddFiles => "ファイルを追加…".into(), + Text::TbAddFolder => "フォルダーを追加…".into(), + Text::TbUnpack => "アンパック".into(), + Text::TbUnpackN { n } => format!("アンパック ({n})").into(), + Text::TbUnpackAll => "すべてアンパック".into(), + Text::TbUnpackTip => "選択した入力を復元し、出力フォルダーに書き込みます。".into(), + Text::TbDryRun => "ドライラン".into(), + Text::TbDryRunN { n } => format!("ドライラン ({n})").into(), + Text::TbDryRunAll => "すべてドライラン".into(), + Text::TbDryRunTip => "実際の復元を実行し、結果は保存しません。".into(), + Text::TbInspect => "検査".into(), + Text::TbInspectN { n } => format!("検査 ({n})").into(), + Text::TbInspectAll => "すべて検査".into(), + Text::TbInspectTip => "実際の復元を実行して検出内容をすべて表示し、結果は保存しません。".into(), + Text::TbOutput => "出力:".into(), + Text::TbOutputBeside => "各入力の隣 (unpack\\)".into(), + Text::TbOutputTip => "アンパック済みファイルの出力先です。検査とドライランでは出力を書き込みません。".into(), + Text::TbSettings => "設定".into(), + Text::BannerEnv { vars } => format!("デバッグ環境変数{vars}が設定されています。通常の実行とデコード結果が異なる場合があります。").into(), + Text::BannerEnvHint => "通常の動作に戻すには、環境変数を解除して再起動してください。".into(), + Text::EmptyTitle => "保護されたファイルをここにドロップ".into(), + Text::EmptyFolders => "フォルダー".into(), + Text::EmptyLocal => "処理はすべてこのコンピューター上で完結します。入力が実行されたりアップロードされたりすることはありません。".into(), + Text::DragTitle => "ドロップして追加".into(), + Text::InputsTitle => "入力".into(), + Text::InputsClear => "クリア".into(), + Text::InputsSearch => "名前で絞り込み".into(), + Text::InputsNone => "条件に一致する入力はありません。".into(), + Text::FilterAll => "すべて".into(), + Text::FilterOk => "復元済み".into(), + Text::FilterSuspect => "要注意".into(), + Text::FilterFailed => "失敗".into(), + Text::FilterSkipped => "スキップ".into(), + Text::GroupFiles => "追加したファイル".into(), + Text::GroupScanning { n } => format!("スキャン中… これまでの候補: {n}").into(), + Text::ModeInspect => "検査済み".into(), + Text::ModeDryRun => "ドライラン".into(), + Text::ModeUnpack => "アンパック済み".into(), + Text::MenuCopyPath => "パスをコピー".into(), + Text::MenuRemove => "リストから削除".into(), + Text::PendingNotRun => "未実行".into(), + Text::PendingNotProtected => "保護なし".into(), + Text::PendingIdentified => "識別結果".into(), + Text::PendingNext => "実行する操作".into(), + Text::PendingUnpackDesc => "復元し、結果を出力フォルダーに書き込みます。".into(), + Text::PendingDryRunDesc => "実際の復元を実行し、結果は保存せずに成否を確認します。".into(), + Text::PendingInspectDesc => "実際の復元を実行し、検出内容をすべて表示します。結果は保存しません。".into(), + Text::PendingNotProtectedNote => "このファイルには対応する保護が見つからなかったため、復元する対象がありません。".into(), + Text::PendingNotAFile => "通常ファイルではないため、読み取る内容がありません。".into(), + Text::ScanRunning => "スキャン中".into(), + Text::ScanFound => "これまでの候補".into(), + Text::ScanStatus { n, p } => format!("{p}をスキャン中… これまでの候補: {n}").into(), + Text::RunRunning => "実行中…".into(), + Text::RunQueued => "待機中".into(), + Text::RunWillNotRun => "実行されません".into(), + Text::RunStep { i, n, s } => format!("ステップ {i}/{n} · {s}").into(), + Text::RunQueue { n } => format!("待機中のジョブ: {n}").into(), + Text::RunStopping => "現在の入力の完了後に停止します…".into(), + Text::RunCancel => "キャンセル".into(), + Text::RunProgress => "進行状況".into(), + Text::RunCancelledNote => "この入力に到達する前にジョブがキャンセルされました。".into(), + Text::StepDecryptHeader => "ファイルヘッダーを復号中".into(), + Text::StepDecryptPayload => "ペイロードを復号中".into(), + Text::StepLocateConfig => "構成レイアウトを特定中".into(), + Text::StepDecryptStage2 => "ステージ2を復号中".into(), + Text::StepDecryptStages35 => "ステージ3–5を復号中".into(), + Text::StepDecryptSections => "セクションデータを復号中".into(), + Text::StepLoadSections => "セクションを読み込み・展開中".into(), + Text::StepDecryptImports => "インポート文字列を復号中".into(), + Text::StepRebuildHeaders => "PEヘッダーを再構築中".into(), + Text::StepInitKeys => "鍵を初期化中".into(), + Text::StepDecryptKeyTable => "鍵テーブルを復号中".into(), + Text::StepDecryptPrimary => "プライマリ記述子を復号中".into(), + Text::StepRelocsParams => "再配置と展開パラメーターを処理中".into(), + Text::StepDecryptBlock1 => "コードブロック1を復号中".into(), + Text::StepDecryptBlock23 => "コードブロック2–3を復号中".into(), + Text::StepDecryptBlock4 => "コードブロック4を復号中".into(), + Text::StepDllSections => "セクションを復号・展開中".into(), + Text::StepFixHeaders => "PEヘッダーとセクションテーブルを修正中".into(), + Text::StepPe32Stages => "ステージを復号中".into(), + Text::StepPe32Eighth => "第8ステージを復号中".into(), + Text::StepPe32Load => "ファイルデータを読み込み・展開中".into(), + Text::StepPe32Text => ".textを復号中".into(), + Text::StepPe32TextSkip => ".textをスキップ中 (すでに平文)".into(), + Text::StepPe32Rebuild => "PEファイルレイアウトを再構築中".into(), + Text::StepAndroidPrimary => "プライマリコンテナーをデコード中".into(), + Text::StepAndroidAux => "ELF実体化コンテナーをデコード中".into(), + Text::StepAndroidTables => "動的リンカーテーブルを再構築中".into(), + Text::DetailPick => "左側から入力またはグループを選択してください。".into(), + Text::DetailExportJson => "JSONをエクスポート".into(), + Text::DetailExportText => "テキストをエクスポート".into(), + Text::DetailLastRun { mode, t } => format!("{mode} · {t}").into(), + Text::DetailCopy => "コピー".into(), + Text::DetailTechnical => "技術詳細".into(), + Text::CompanionSplicedPill => "コンパニオン対応付け済み".into(), + Text::TabOverview => "概要".into(), + Text::TabResearch => "解析詳細".into(), + Text::TabHex => "16進".into(), + Text::TabCompare => "比較".into(), + Text::TabLog => "ログ".into(), + Text::TabEntries => "エントリ".into(), + Text::BatchSummary => "集計".into(), + Text::BatchInputs => "入力".into(), + Text::BatchScan => "フォルダースキャン".into(), + Text::BatchNonTarget => "スキップした対象外".into(), + Text::BatchWalkErrors => "読み取れないフォルダー項目".into(), + Text::BatchProbeErrors => "プローブエラー".into(), + Text::BatchScanNote => ".exe、.dll、.so、およびglobal-metadata.datの名前のみをプローブします。".into(), + Text::BatchScanIncomplete => "解析が不完全です。一部のフォルダー項目または選択したファイルを調査できませんでした。".into(), + Text::PkgTitle => "パッケージ".into(), + Text::PkgKind => "パッケージ種別".into(), + Text::PkgPackage => "パッケージ名".into(), + Text::PkgVersion => "バージョン".into(), + Text::PkgEntries => "トップレベルエントリ".into(), + Text::PkgCandidates => "プローブ対象エントリ".into(), + Text::PkgNested => "ネストされたパッケージ".into(), + Text::PkgNote => ".soとglobal-metadata.datのエントリのみを展開してプローブします。".into(), + Text::PkgResult => "結果".into(), + Text::PkgManifests => "マニフェスト".into(), + Text::PkgUnnamed => "名前なし".into(), + Text::PkgTargets => "保護されたエントリとメタデータ".into(), + Text::PkgNoTargets => "このパッケージに保護されたエントリはないため、復元する対象がありません。".into(), + Text::PkgInventory { n } => format!("パッケージ内の記載エントリ: {n}").into(), + Text::EntriesTitle => "エントリ".into(), + Text::EntriesOthers { n } => format!("その他のエントリ (対象外): {n}").into(), + Text::EntriesSummary { n } => format!("対象: {n}").into(), + Text::EntriesShowNonTargets { n } => format!("対象外を表示 ({n})").into(), + Text::EntriesRemapped { n } => format!("再マップされたメソッドフィールド: {n}").into(), + Text::EntriesRemappedLabel => "再マップされたメソッドフィールド".into(), + Text::ColName => "名前".into(), + Text::ColType => "種別".into(), + Text::ColOutcome => "結果".into(), + Text::ColRoute => "ルート".into(), + Text::ColTime => "時間".into(), + Text::ColAddress => "アドレス".into(), + Text::ColSize => "サイズ".into(), + Text::ColFileOffset => "ファイルオフセット".into(), + Text::ColMapping => "マッピング".into(), + Text::ColKind => "種類".into(), + Text::ColLength => "長さ".into(), + Text::ColSource => "ソース".into(), + Text::ColRaw => "生データ".into(), + Text::ColDecoded => "デコード後".into(), + Text::ColMeaning => "意味".into(), + Text::ColCheck => "検査項目".into(), + Text::ColStart => "開始".into(), + Text::ColEnd => "終了".into(), + Text::ColLimit => "上限".into(), + Text::ColStatus => "状態".into(), + Text::ColNote => "備考".into(), + Text::ColSeverity => "重要度".into(), + Text::ColArea => "分類".into(), + Text::ColMessage => "メッセージ".into(), + Text::ColValue => "値".into(), + Text::ColVsize => "仮想サイズ".into(), + Text::ColRawOffset => "ファイル内オフセット".into(), + Text::ColRawSize => "ファイル内サイズ".into(), + Text::ColCharacteristics => "属性".into(), + Text::ColBacking => "ファイル内データ".into(), + Text::ColField => "フィールド".into(), + Text::ColCommand => "コマンド".into(), + Text::ColFlags => "フラグ".into(), + Text::ColImage => "イメージ".into(), + Text::ColMetadata => "メタデータ".into(), + Text::ColOffsetSize => "オフセット +サイズ".into(), + Text::ColEntry => "エントリポイント".into(), + Text::ColInit => "初期化".into(), + Text::ColDirect => "直接".into(), + Text::ColNested => "ネストされたストリーム".into(), + Text::ColDepth => "深さ".into(), + Text::ColStream => "ストリーム".into(), + Text::ColClassification => "分類".into(), + Text::CommonYes => "あり".into(), + Text::CommonNo => "なし".into(), + Text::OvMessages => "メッセージ".into(), + Text::OvRecognition => "認識".into(), + Text::OvPlatform => "プラットフォーム".into(), + Text::OvFormat => "フォーマット".into(), + Text::OvKind => "種類".into(), + Text::OvMetadata => "il2cppメタデータ".into(), + Text::OvMetadataVersion => "メタデータバージョン".into(), + Text::OvMetadataLayout => "レイアウト定義".into(), + Text::OvCapSeeded => "シード方式のメソッドトークン".into(), + Text::OvCapStructural => "構造方式のメソッドトークン".into(), + Text::OvCapIndices => "メソッドインデックス復元".into(), + Text::OvCapContext => "アプリケーションコンテキストが必要".into(), + Text::OvProvenance => "モジュールコンテキストの取得元".into(), + Text::OvEvidence => "根拠".into(), + Text::OvNoEvidence => "保護の根拠なし".into(), + Text::OvRoutes => "復元ルート".into(), + Text::OvSelected => "選択済み".into(), + Text::OvNoRoutes => "試行されたルートはありません。".into(), + Text::OvStages => "ステージ".into(), + Text::OvValidation => "静的検証".into(), + Text::OvValidationMetadata => "PEおよびELFの構造検査はメタデータには適用されません。変換処理自体がテーブルを検証します。".into(), + Text::OvValidationWarnings => "復元イメージに構造上の問題が検出されたため、正常に動作しない可能性があります。「要注意」として集計されますが、アンパック時にはそのまま書き込まれます。".into(), + Text::OvValidationFailed => "復元イメージが致命的な構造検査に失敗したため、動作しない可能性が高いです。「要注意」として集計されますが、アンパック時にはそのまま書き込まれます。".into(), + Text::OvIdentity => "識別情報".into(), + Text::OvSource => "入力".into(), + Text::OvCompanion => "コンパニオン".into(), + Text::OvRecovered => "復元イメージ".into(), + Text::OvOutput => "出力".into(), + Text::OvOpenFolder => "フォルダーで表示".into(), + Text::OvRestoredElf => "復元ELF".into(), + Text::OvElfSections => "セクション · セグメント".into(), + Text::OvElfSymbols => "動的シンボル".into(), + Text::OvElfRelocs => "再配置 · PLT".into(), + Text::ResearchNone => "解析データなし: エンジンが構造の根拠を出力する前に復元が停止しました。".into(), + Text::ResearchNotCollected => "この実行では解析の根拠を収集していません。".into(), + Text::ResearchRunInspect => "この入力を検査".into(), + Text::ResearchSplicedNote => "連結ビュー: 0x1000未満のオフセットはローダースタブを、0x1000以上のオフセットはコンパニオンの(オフセット − 0x1000)を指します。".into(), + Text::ResearchJump { space } => format!("16進で表示 ({space})").into(), + Text::ResearchRegionsNote => "どのセクションにも属さないファイル範囲です。".into(), + Text::ResearchRegionsNone => "ファイルのすべてのバイトがヘッダーまたはセクションに属しています。".into(), + Text::ResearchAStreamsNote => "各ストリームはデコードされた1つのコンテナー階層に対応します。".into(), + Text::ResearchAArtifactsNote => "抽出中に生成されたファイルです。一時ワークスペースに置かれ、処理後に破棄されます。".into(), + Text::RsGrpInput => "保護された入力".into(), + Text::RsGrpProtection => "保護".into(), + Text::RsGrpRecovery => "復元".into(), + Text::RsGrpExtraction => "抽出".into(), + Text::RsGrpRestoration => "復元".into(), + Text::RsGrpMetadata => "メタデータ".into(), + Text::RsGrpProfile => "プロファイル".into(), + Text::RsPeHeader => "PEヘッダー".into(), + Text::RsSections => "セクション".into(), + Text::RsDirectories => "データディレクトリ".into(), + Text::RsRegions => "ファイル領域".into(), + Text::RsHeaderTable => "ヘッダーテーブル".into(), + Text::RsPayload => "宣言ペイロード".into(), + Text::RsDiscovery => "ステージ探索".into(), + Text::RsTrace => "復元トレース".into(), + Text::RsIssues => "問題と処理バジェット".into(), + Text::RsRestored => "復元イメージ".into(), + Text::RsAStage1 => "ステージ1".into(), + Text::RsAStreams => "ストリーム".into(), + Text::RsAModules => "モジュールレジストリ".into(), + Text::RsAArtifacts => "成果物".into(), + Text::RsAScalars => "合計".into(), + Text::RsARDescriptor => "記述子".into(), + Text::RsARStaticConfig => "静的構成".into(), + Text::RsARPrimary => "プライマリコンテナー".into(), + Text::RsARAuxiliary => "補助コンテナー".into(), + Text::RsARElfMaterialization => "ELF実体化".into(), + Text::RsARCleaning => "プロテクター除去".into(), + Text::RsARValidation => "検証".into(), + Text::RsMReport => "変換レポート".into(), + Text::RsMImages => "イメージ".into(), + Text::RsMRaw => "その他のフィールド".into(), + Text::RsProfile => "復元プロファイル".into(), + Text::PeOffset => "PEヘッダーオフセット".into(), + Text::PeMachine => "マシン".into(), + Text::PeFormat => "フォーマット".into(), + Text::PeEntry => "エントリポイント".into(), + Text::PeNotFileBacked => "ファイル内になし".into(), + Text::PeAlignment => "セクション / ファイルアライメント".into(), + Text::PeFlags => "宣言フラグ".into(), + Text::PeInputLen => "解析バイト数".into(), + Text::PeParseIssue => "パースの問題".into(), + Text::MappingInSection { s } => format!("{s}内").into(), + Text::MappingPartial { n } => format!("一部のみファイル内 ({n}バイト)").into(), + Text::ProtMagic => "マジック".into(), + Text::ProtMagicOk => "対応".into(), + Text::ProtMagicBad => "非対応".into(), + Text::ProtWords => "ヘッダーワード".into(), + Text::PayloadSource => "ソース".into(), + Text::PayloadDest => "展開先".into(), + Text::PayloadPrefix => "プレフィックス長".into(), + Text::PayloadTotal => "総長".into(), + Text::PayloadChecks => "境界検査".into(), + Text::PayloadInBounds => "範囲内".into(), + Text::PayloadOutOfBounds => "範囲外".into(), + Text::PayloadProbe => "プレフィックスプローブ".into(), + Text::PayloadDecoded => "デコード済み".into(), + Text::PayloadLimit { l } => format!("上限 {l}").into(), + Text::PayloadFirstWords => "先頭ワード".into(), + Text::PayloadUnrecognized => "マジックが認識されなかったため、これはヘッダーワードの解釈の一例にすぎません。".into(), + Text::DiscPayloadOffset => "ペイロードオフセット".into(), + Text::DiscImageRva => "イメージRVA".into(), + Text::DiscSource => "ソース".into(), + Text::DiscScanned { n } => format!("スキャンした位置: {n}").into(), + Text::DiscNone => "候補はありません。".into(), + Text::TraceSummary { n, s } => format!("イベント: {n} · ステージ: {s}").into(), + Text::TraceEvents { n } => format!("イベント: {n}").into(), + Text::TraceTruncated { l, n } => format!("トレースが切り詰められました。破棄されたイベント: {n} (上限 {l})。").into(), + Text::StreamsTitle { id } => format!("ストリーム {id}").into(), + Text::StreamsSummary { d, k, n, s } => format!("深さ {d} · {k} · レコード: {n} · {s}").into(), + Text::StreamsOrigin => "生成元".into(), + Text::StreamsRoot => "保護されたファイルのトップレベル".into(), + Text::StreamsParent { c, r, s } => format!("ストリーム {s}、レコード {r}、コマンド {c}").into(), + Text::StreamsRecords => "レコード".into(), + Text::IssuesNone => "問題は記録されていません。".into(), + Text::IssuesWork => "処理バジェット".into(), + Text::IssuesScratch => "使用したプレフィックス作業領域".into(), + Text::IssuesCandidates => "検討した候補".into(), + Text::IssuesBudget => "バジェット制限到達".into(), + Text::RestoredOpenCompare => "元ファイルと比較…".into(), + Text::RestoredObservations => "復元イメージの観測結果".into(), + Text::MetaRoute { r } => format!("ルート: {r}").into(), + Text::MetaDiscoveryError => "シード探索が適用できなかったため、構造ルートを使用しました:".into(), + Text::MetaImage => "イメージ".into(), + Text::MetaMethods => "メソッド数".into(), + Text::MetaModulus => "モジュラス".into(), + Text::MetaClean => "問題なし".into(), + Text::MetaSeedResidues => "シード剰余".into(), + Text::MetaResidues => "剰余あり".into(), + Text::HexVOriginal => "元ファイル".into(), + Text::HexVSpliced => "連結ビュー".into(), + Text::HexVRestored => "復元済み (メモリ内)".into(), + Text::HexGoto => "移動".into(), + Text::HexAsFile => "ファイルオフセット".into(), + Text::HexAsRva => "RVA".into(), + Text::HexFind => "検索".into(), + Text::HexFindHint => "4D 5A またはテキスト".into(), + Text::HexFindNext => "次へ".into(), + Text::HexFindNone => "これ以上一致する箇所はありません。".into(), + Text::HexTooLarge { limit, size } => format!("このファイルは{size}です。16進ビューは{limit}までのファイルを読み取ります。").into(), + Text::HexRvaUnmapped { o } => format!("このビューにはRVA {o}に対応するファイルバイトがありません。").into(), + Text::HexCopySel => "選択範囲をコピー".into(), + Text::HexInspector => "カーソル位置".into(), + Text::HexInspectorHint => "バイトをクリックするとここに値が表示されます。".into(), + Text::HexRegions => "領域".into(), + Text::HexNoRegions => "このファイルで既知の領域はありません。".into(), + Text::HexRHeaders => "ヘッダー".into(), + Text::HexRStubPage => "ローダースタブページ".into(), + Text::HexRHeaderTable => "保護ヘッダーテーブル".into(), + Text::HexRElfHeader => "ELFヘッダー".into(), + Text::HexRProgramHeaders => "プログラムヘッダー".into(), + Text::HexRLoad { n } => format!("LOADセグメント {n}").into(), + Text::HexRPrivateSection => "専用ローダーセクション".into(), + Text::HexRStage2 => "ステージ2ペイロード".into(), + Text::HexRStreams => "暗号化ストリーム".into(), + Text::HexSize { s } => format!("サイズ {s}").into(), + Text::HexAt { o } => format!("オフセット {o}").into(), + Text::HexInCompanion { o } => format!("コンパニオンオフセット {o}").into(), + Text::HexInStub => "ローダースタブ".into(), + Text::CmpNoChange => "構造上の差異なし".into(), + Text::CmpHeaders => "ヘッダー".into(), + Text::CmpOriginal => "元ファイル".into(), + Text::CmpRestored => "復元済み".into(), + Text::CmpFileSize => "ファイルサイズ".into(), + Text::CmpSections => "セクション数".into(), + Text::CmpBytes => "セクションバイト".into(), + Text::CmpBytesNote { len, n, s } => format!("{s}の先頭{len}バイト中の相違バイト数: {n}。").into(), + Text::CmpNextDiff => "次の相違点".into(), + Text::LogFAll => "すべて".into(), + Text::LogFNosteps => "ステップを隠す".into(), + Text::LogFProblems => "問題のみ".into(), + Text::LogCopy => "ログをコピー".into(), + Text::LogLvInfo => "INFO".into(), + Text::LogLvStep => "STEP".into(), + Text::LogLvWarn => "WARN".into(), + Text::LogLvError => "ERROR".into(), + Text::LogRunStarted { mode, n } => format!("{mode}を開始 · 入力: {n}").into(), + Text::LogScan { n, s } => format!("スキャン完了: 候補 {n}、スキップした対象外 {s}").into(), + Text::LogInputStarted { i, n, p } => format!("入力 {i}/{n}: {p}").into(), + Text::LogCompanion { p } => format!("コンパニオンを対応付け: {p}").into(), + Text::LogStep { i, n, s } => format!("ステップ {i}/{n}: {s}").into(), + Text::LogEntry { o, p } => format!("エントリ {p}: {o}").into(), + Text::LogInputFinished { o, t } => format!("完了: {o} ({t})").into(), + Text::LogSummary { failed, ok, skipped, suspect } => format!("復元済み {ok} · 要注意 {suspect} · 失敗 {failed} · スキップ {skipped}").into(), + Text::StatusReady => "準備完了".into(), + Text::CloseTitle => "ジョブを実行中です".into(), + Text::CloseBody => "現在の入力が完了した後に停止し、ウィンドウを閉じます。すでに書き込まれた出力はそのまま保持されます。".into(), + Text::CloseKeep => "実行を続ける".into(), + Text::CloseStop => "停止して閉じる".into(), + Text::LegalTitle => "法的通知: ご利用前にお読みください".into(), + Text::LegalP1 => "Senbeiは、すでに正当に所有しているソフトウェアの合法的なリバースエンジニアリング、セキュリティ研究、および保全のための研究・相互運用性ツールです。ご自身が所有するバイナリ、または解析の明示的な許可を得ているバイナリのみを処理してください。".into(), + Text::LegalP2 => "技術的保護手段の回避は、お住まいの法域で制限されている場合があります (たとえば米国のDMCA §1201。同条にはセキュリティ研究および相互運用性のための例外規定があります)。ご利用が合法であることを確認するのはご自身の責任です。".into(), + Text::LegalP3 => "Senbeiはお使いのコンピューター上のファイルに対して純粋に静的な変換を行います。それ自体でアクセス制御を回避することはなく、必要な情報は入力ファイルから導出し、ベンダーのコードを同梱せず、入力を実行したりアップロードしたりすることも一切ありません。あるAndroidパッケージング形式における埋め込みメタデータ層は、単一ビルドの解析中に復元されたXORキーストリームで解除されます。このキーストリームは本ツールに同梱された研究成果物であり、ベンダーが配布した鍵ではありません。".into(), + Text::LegalP4 => "Senbeiはオンラインプレイ、ライセンス詐欺、またはチート行為を可能にするものではありません。復号された出力を再配布したり、どこかにアップロードしたりしないでください。本ソフトウェアは「現状有姿」で提供され、いかなる種類の保証もありません。誤用について作成者は一切の責任を負いません。「CrackProof」はその所有者の商標です。本プロジェクトはベンダーやいかなるパブリッシャーとも提携しておらず、承認も受けていません。".into(), + Text::LegalAccept => "理解して同意する".into(), + Text::LegalQuit => "終了".into(), + Text::SettingsTitle => "設定".into(), + Text::SettingsTabGeneral => "一般".into(), + Text::SettingsTabProcessing => "処理".into(), + Text::SettingsTabAndroid => "Androidの上限".into(), + Text::SettingsTabMemory => "メモリ".into(), + Text::SettingsTabAbout => "バージョン情報".into(), + Text::SettingsLanguage => "言語".into(), + Text::SettingsOutput => "既定の出力フォルダー".into(), + Text::SettingsOutputRecent => "前回使用したフォルダー".into(), + Text::SettingsOutputChoose => "フォルダーを選択…".into(), + Text::SettingsOutputHelp => "「各入力の隣」を選択すると、追加したファイルまたはフォルダーの隣にunpack\\フォルダーを作成します。".into(), + Text::SettingsLog => "ログファイルを書き込む".into(), + Text::SettingsLogHelp => "アンパック時に、出力フォルダーへsenbei-YYYYMMDD-HHMMSS.logを書き込みます。".into(), + Text::SettingsThreads => "ワーカースレッド数".into(), + Text::SettingsThreadsAuto { n } => format!("自動 ({n})").into(), + Text::SettingsScanAll => "小さいファイルもプローブする".into(), + Text::SettingsScanAllHelp => "フォルダーのスキャン時、サイズ下限未満の.exe、.dll、.so、およびメタデータの名前もプローブします。".into(), + Text::SettingsAndroidNote => "上限は展開またはメモリ割り当ての前に検査されます。ピーク時のメモリ使用量を制限するものではありません。".into(), + Text::SettingsMaxEntry => "単一エントリの最大サイズ".into(), + Text::SettingsMaxEntryHelp => "アーカイブエントリ、デコード済みバッファー、または出力のサイズです。".into(), + Text::SettingsMaxTotal => "総バジェット".into(), + Text::SettingsMaxTotalHelp => "アーカイブの累積バイト数およびエンジンごとのタスクバジェットです。".into(), + Text::SettingsMaxEntries => "最大エントリ数".into(), + Text::SettingsMaxEntriesHelp => "アーカイブエントリおよびステージ2レコードの数です。".into(), + Text::SettingsMaxDepth => "最大ネスト深さ".into(), + Text::SettingsMaxDepthHelp => "パッケージ自体を深さ0とします。".into(), + Text::SettingsKeepBytes => "16進と「比較」用に復元バイトを保持".into(), + Text::SettingsKeepBytesHelp => "検査とドライランでは、このセッション中に限り復元イメージをメモリ内に保持します。".into(), + Text::SettingsKeepCap => "入力ごとのメモリ上限".into(), + Text::SettingsKeepCapHelp => "これを超える復元イメージはバイトデータを保持せず、構造のみを要約します。".into(), + Text::SettingsReset => "既定値に戻す".into(), + Text::SettingsDone => "完了".into(), + Text::AboutVersion { v } => format!("バージョン {v}").into(), + Text::AboutDesc => "CrackProofで保護されたWindows PEファイルおよびAndroid AArch64共有ライブラリ用の静的アンパッカー。".into(), + Text::AboutLicense => "ライセンス".into(), + Text::AboutSource => "ソースコード".into(), + Text::AboutLegal => "法的通知を表示".into(), + Text::TagMetadata { v } => format!("il2cppメタデータ v{v}").into(), + Text::StatusOk => "復元済み".into(), + Text::StatusSuspect => "要注意".into(), + Text::StatusRecognized => "認識済み".into(), + Text::StatusSkipped => "スキップ".into(), + Text::StatusError => "エラー".into(), + Text::StatusIncomplete => "解析不完全".into(), + Text::EntryStatusRestored => "復元済み".into(), + Text::EntryStatusDuplicate => "重複".into(), + Text::EntryStatusNotTarget => "対象外".into(), + Text::EntryStatusUnchanged => "変更なし".into(), + Text::EntryStatusInventoried => "記載のみ".into(), + Text::EntryStatusError => "エラー".into(), + Text::EntryKindSharedLibrary => "共有ライブラリ".into(), + Text::EntryKindMetadata => "il2cppメタデータ".into(), + Text::RecognitionNotAttempted => "未試行".into(), + Text::RecognitionRecognized => "認識済み".into(), + Text::RecognitionNotRecognized => "未認識".into(), + Text::RecognitionBlocked => "ブロック".into(), + Text::RecoveryFailed => "復元失敗".into(), + Text::RecoveryBlocked => "復元ブロック".into(), + Text::OutcomeSucceeded => "成功".into(), + Text::OutcomeRejected => "却下".into(), + Text::OutcomeFailed => "失敗".into(), + Text::OutcomeNotAttempted => "未試行".into(), + Text::ValidationClean => "問題なし".into(), + Text::ValidationWarnings => "警告あり".into(), + Text::ValidationFailed => "失敗".into(), + Text::ValidationNotRun => "未実行".into(), + Text::StageDetection => "検出".into(), + Text::StageManifestInventory => "マニフェスト一覧化".into(), + Text::StageEntryProbe => "エントリプローブ".into(), + Text::StageRecovery => "復元".into(), + Text::StageStaticValidation => "静的検証".into(), + Text::StageOutputWrite => "出力書き込み".into(), + Text::StageStatusOk => "OK".into(), + Text::StageStatusSkipped => "スキップ".into(), + Text::StageStatusFailed => "失敗".into(), + Text::StageStatusBlocked => "ブロック".into(), + Text::TraceStageHeader => "ヘッダー".into(), + Text::TraceStagePayload => "ペイロード".into(), + Text::TraceStagePe32Shell => "PE32シェル".into(), + Text::TraceStagePe32Stages => "PE32ステージ".into(), + Text::TraceStageExeStage1 => "ステージ1".into(), + Text::TraceStageExeStage2 => "ステージ2".into(), + Text::TraceStageExeStage3 => "ステージ3".into(), + Text::TraceStageExeStage4 => "ステージ4".into(), + Text::TraceStageExeStage5 => "ステージ5".into(), + Text::TraceStageDllStages => "DLLステージ".into(), + Text::TraceStageSections => "セクション".into(), + Text::TraceStageImports => "インポート".into(), + Text::TraceStageTls => "TLS".into(), + Text::TraceStageOutput => "出力".into(), + Text::TraceStageFinalize => "最終処理".into(), + Text::EvidenceHeaderMagic => "ヘッダーマジック".into(), + Text::EvidenceCompanionSpliced => "コンパニオン連結".into(), + Text::EvidenceExternalCompanionDeclaration => "外部コンパニオン宣言".into(), + Text::EvidencePrivateSection => "専用セクション".into(), + Text::EvidenceAesSchedule => "AES鍵スケジュール".into(), + Text::EvidenceValidatedMetadataTransform => "検証済みメタデータ変換".into(), + Text::PlatformWindowsPe => "Windows PE".into(), + Text::PlatformAndroidElf => "Android ELF".into(), + Text::PlatformIl2cppMetadata => "il2cppメタデータ".into(), + Text::KindNativeExe => "ネイティブ実行ファイル".into(), + Text::KindManagedExe => ".NET実行ファイル".into(), + Text::KindNativeDll => "ネイティブDLL".into(), + Text::KindManagedDll => ".NETアセンブリ (DLL)".into(), + Text::KindShortNativeExe => "EXE".into(), + Text::KindShortManagedExe => ".NET EXE".into(), + Text::KindShortNativeDll => "DLL".into(), + Text::KindShortManagedDll => ".NET DLL".into(), + Text::LayoutExeStyle => "EXE形式ローダー".into(), + Text::LayoutDll => "DLLローダー".into(), + Text::LayoutAndroidStaged => "Android段階型ローダー".into(), + Text::LayoutMetadataSeeded => "シード方式メタデータ変換".into(), + Text::LayoutMetadataStructural => "構造方式メタデータ変換".into(), + Text::LayoutMetadataMethodIndices => "メタデータメソッドインデックス復元".into(), + Text::MetaLayoutKnown => "既知".into(), + Text::MetaLayoutContextRequired => "アプリケーションコンテキストが必要".into(), + Text::MetaLayoutUnverified => "未検証".into(), + Text::CompanionAbsent => "なし".into(), + Text::CompanionSpliced => "連結済み".into(), + Text::CompanionPaired => "対応付け済み".into(), + Text::CompanionUnmatched => "不一致".into(), + Text::CompanionUnreadable => "読み取り不能".into(), + Text::SpaceFileOffset => "ファイルオフセット".into(), + Text::SpaceWorkingImageRva => "イメージRVA".into(), + Text::SpaceProtectedHeaderOffset => "保護ヘッダーオフセット".into(), + Text::SpaceDecodedPayloadOffset => "デコード済みペイロードオフセット".into(), + Text::SpaceShortFileOffset => "FILE".into(), + Text::SpaceShortWorkingImageRva => "RVA".into(), + Text::SpaceShortProtectedHeaderOffset => "HDR".into(), + Text::SpaceShortDecodedPayloadOffset => "PAYLOAD".into(), + Text::MappingZero => "空".into(), + Text::MappingHeaderBacked => "ヘッダー内".into(), + Text::MappingFileBacked => "ファイル内".into(), + Text::MappingUnmapped => "未マップ".into(), + Text::BackingFileBacked => "ファイル内".into(), + Text::BackingVirtualOnly => "メモリ上のみ".into(), + Text::BackingRawTruncated { n } => format!("切り詰め (ファイル内は{n}バイトのみ)").into(), + Text::RegionHeadersToFirstSection => "ヘッダーと最初のセクションの間隙".into(), + Text::RegionBetweenSections => "セクション間の間隙".into(), + Text::RegionOverlay => "オーバーレイ".into(), + Text::SemanticKey => "鍵".into(), + Text::SemanticMagic => "マジック".into(), + Text::SemanticDestinationRva => "展開先RVA".into(), + Text::SemanticPayloadSource => "ペイロードソース".into(), + Text::SemanticTotalLength => "総長".into(), + Text::SemanticEndMarker => "終端マーカー".into(), + Text::SeverityInfo => "情報".into(), + Text::SeverityWarning => "警告".into(), + Text::SeverityUnavailable => "利用不可".into(), + Text::ProbeDecoded => "デコード済み".into(), + Text::ProbeUnavailable => "利用不可".into(), + Text::ProbeFailed => "失敗".into(), + Text::ProbeBudgetLimited => "バジェット制限到達".into(), + Text::ShellKindPe32ShellTable => "PE32シェルテーブル".into(), + Text::ShellKindPe32PlusAnchor => "PE32+アンカー".into(), + Text::CandidateObserved => "観測".into(), + Text::CandidateStructuralCandidate => "構造候補".into(), + Text::CandidateTrialValidated => "試行検証済み".into(), + Text::CandidateRejected => "却下".into(), + Text::CheckSourcePrefix => "ペイロードプレフィックス (ソース)".into(), + Text::CheckSourceRawTail => "ペイロード末尾 (ソース)".into(), + Text::NoteEntryPointInside { rva } => format!("エントリポイント{rva}はこのセクション内にあります").into(), + Text::NoteRawPastEof { end, len } => format!("ファイル内範囲の終端は{end}ですが、入力は{len}バイトです").into(), + Text::NoteCertFileOffset => "証明書ディレクトリはRVAではなくファイルオフセットを使用します".into(), + Text::NoteNoImportTable => "インポートテーブルがありません".into(), + Text::MsgCompanionMissing => "コンパニオンが見つからない可能性があります。このローダーには対応する._ペイロードが必要です。入力ファイルの隣に配置して再試行してください。".into(), + Text::MsgLimitEntry { entry, limit, size } => format!("{entry}は{size}バイトあり、上限の{limit}バイトを超えています。「設定」→「Androidの上限」で上限を引き上げてから再実行してください。").into(), + Text::MsgInternalPanic { loc } => format!("{loc}で復元エンジンの内部エラーが発生しました").into(), + Text::NoteMagicUnsupportedValue { value } => format!("ヘッダーテーブルをデコードしましたが、info[1]が{value}であり、対応しているマジックではありません").into(), + Text::NotePrefixScratch => "作業領域でプレフィックスをデコードしました。後続ステージには完全な復元が必要です".into(), + Text::NoteAnchorValidates => "アンカーとstage1記述子を検証しました。ステージ全体の復号には復元が必要です".into(), + Text::NoteBoundedAnchor => "境界付きアンカープローブのみ".into(), + Text::NoteBoundedPrefix => "境界付きプレフィックスのみ (復元イメージではありません)".into(), + Text::NoteCandidatesUnvalidated => "ステージ検証なしで報告された候補".into(), + Text::NoteMagicNotSupported => "ヘッダーマジックが対応している保護ヘッダーではありません".into(), + Text::NoteNoAnchorField => "デコード済みペイロードウィンドウ内にアンカーフィールドがありません".into(), + Text::NoteNoShellTable => "デコード済みペイロードウィンドウ内にシェルテーブル構造がありません".into(), + Text::NoteShellNeedsPrefix => "シェルの探索にはデコード済みのペイロードプレフィックスが必要です".into(), + Text::NoteShellTableMatches => "シェルテーブル構造が宣言イメージと一致します。第2ステージの復号には復元が必要です".into(), + Text::NoteRelocUnsupportedType { block, entry, ty } => format!("再配置ブロック{block}のエントリ{entry}に非対応の種別{ty}があります").into(), + Text::NoteRelocBadSize { block, size } => format!("再配置ブロック{block}の宣言サイズ{size}がディレクトリと整合しません").into(), + } +} diff --git a/senbei-gui/src/text/ko.rs b/senbei-gui/src/text/ko.rs new file mode 100644 index 0000000..6f3a67b --- /dev/null +++ b/senbei-gui/src/text/ko.rs @@ -0,0 +1,564 @@ +// Generated from the approved GUI mockup catalog. Edit the wording here; +// every language must keep the same placeholders. + +use std::borrow::Cow; + +use super::catalog::Text; + +pub(crate) fn text(text: &Text) -> Cow<'static, str> { + match text { + Text::TbAddFiles => "파일 추가…".into(), + Text::TbAddFolder => "폴더 추가…".into(), + Text::TbUnpack => "언패킹".into(), + Text::TbUnpackN { n } => format!("언패킹 ({n})").into(), + Text::TbUnpackAll => "모두 언패킹".into(), + Text::TbUnpackTip => "선택한 입력을 복원하여 결과를 출력 폴더에 기록합니다.".into(), + Text::TbDryRun => "시험 실행".into(), + Text::TbDryRunN { n } => format!("시험 실행 ({n})").into(), + Text::TbDryRunAll => "모두 시험 실행".into(), + Text::TbDryRunTip => "실제 복원을 실행하되 아무것도 저장하지 않습니다.".into(), + Text::TbInspect => "검사".into(), + Text::TbInspectN { n } => format!("검사 ({n})").into(), + Text::TbInspectAll => "모두 검사".into(), + Text::TbInspectTip => "실제 복원을 실행하고 발견된 모든 내용을 표시하며, 아무것도 저장하지 않습니다.".into(), + Text::TbOutput => "출력:".into(), + Text::TbOutputBeside => "각 입력 옆 (unpack\\)".into(), + Text::TbOutputTip => "언패킹된 파일이 기록되는 위치입니다. 검사와 시험 실행은 출력을 기록하지 않습니다.".into(), + Text::TbSettings => "설정".into(), + Text::BannerEnv { vars } => format!("디버그 환경 변수 {vars}이(가) 설정되어 있습니다. 디코딩 결과가 정상 실행과 다를 수 있습니다.").into(), + Text::BannerEnvHint => "변수를 해제하고 다시 시작하면 정상 동작으로 돌아갑니다.".into(), + Text::EmptyTitle => "보호된 파일을 여기에 놓기".into(), + Text::EmptyFolders => "폴더".into(), + Text::EmptyLocal => "모든 작업은 이 컴퓨터에서 실행됩니다. 입력은 절대 실행되거나 업로드되지 않습니다.".into(), + Text::DragTitle => "놓아서 추가".into(), + Text::InputsTitle => "입력".into(), + Text::InputsClear => "비우기".into(), + Text::InputsSearch => "이름으로 필터링".into(), + Text::InputsNone => "필터와 일치하는 입력이 없습니다.".into(), + Text::FilterAll => "전체".into(), + Text::FilterOk => "복원됨".into(), + Text::FilterSuspect => "의심됨".into(), + Text::FilterFailed => "실패함".into(), + Text::FilterSkipped => "건너뜀".into(), + Text::GroupFiles => "추가된 파일".into(), + Text::GroupScanning { n } => format!("스캔 중… 현재까지 후보: {n}").into(), + Text::ModeInspect => "검사됨".into(), + Text::ModeDryRun => "시험 실행".into(), + Text::ModeUnpack => "언패킹됨".into(), + Text::MenuCopyPath => "경로 복사".into(), + Text::MenuRemove => "목록에서 제거".into(), + Text::PendingNotRun => "미실행".into(), + Text::PendingNotProtected => "보호되지 않음".into(), + Text::PendingIdentified => "식별됨".into(), + Text::PendingNext => "수행할 작업".into(), + Text::PendingUnpackDesc => "복원하여 결과를 출력 폴더에 기록합니다.".into(), + Text::PendingDryRunDesc => "실제 복원을 실행하여 작동 여부를 확인하며, 아무것도 저장하지 않습니다.".into(), + Text::PendingInspectDesc => "실제 복원을 실행하고 발견된 모든 내용을 표시합니다. 아무것도 저장하지 않습니다.".into(), + Text::PendingNotProtectedNote => "Senbei가 이 파일에서 지원되는 보호를 찾지 못하여 복원할 내용이 없습니다.".into(), + Text::PendingNotAFile => "일반 파일이 아니므로 읽을 내용이 없습니다.".into(), + Text::ScanRunning => "스캔 중".into(), + Text::ScanFound => "현재까지 후보".into(), + Text::ScanStatus { n, p } => format!("{p} 스캔 중… 현재까지 후보: {n}").into(), + Text::RunRunning => "실행 중…".into(), + Text::RunQueued => "대기 중".into(), + Text::RunWillNotRun => "실행 안 함".into(), + Text::RunStep { i, n, s } => format!("단계 {i}/{n} · {s}").into(), + Text::RunQueue { n } => format!("대기 중인 작업: {n}").into(), + Text::RunStopping => "현재 입력 완료 후 중지 중…".into(), + Text::RunCancel => "취소".into(), + Text::RunProgress => "진행 상태".into(), + Text::RunCancelledNote => "이 입력에 도달하기 전에 작업이 취소되었습니다.".into(), + Text::StepDecryptHeader => "파일 헤더 복호화 중".into(), + Text::StepDecryptPayload => "페이로드 복호화 중".into(), + Text::StepLocateConfig => "구성 레이아웃 탐색 중".into(), + Text::StepDecryptStage2 => "단계 2 복호화 중".into(), + Text::StepDecryptStages35 => "단계 3–5 복호화 중".into(), + Text::StepDecryptSections => "섹션 데이터 복호화 중".into(), + Text::StepLoadSections => "섹션 로드 및 압축 해제 중".into(), + Text::StepDecryptImports => "임포트 문자열 복호화 중".into(), + Text::StepRebuildHeaders => "PE 헤더 재구성 중".into(), + Text::StepInitKeys => "키 초기화 중".into(), + Text::StepDecryptKeyTable => "키 테이블 복호화 중".into(), + Text::StepDecryptPrimary => "기본 디스크립터 복호화 중".into(), + Text::StepRelocsParams => "재배치 및 압축 해제 매개변수 처리 중".into(), + Text::StepDecryptBlock1 => "코드 블록 1 복호화 중".into(), + Text::StepDecryptBlock23 => "코드 블록 2–3 복호화 중".into(), + Text::StepDecryptBlock4 => "코드 블록 4 복호화 중".into(), + Text::StepDllSections => "섹션 복호화 및 압축 해제 중".into(), + Text::StepFixHeaders => "PE 헤더 및 섹션 테이블 보정 중".into(), + Text::StepPe32Stages => "단계 복호화 중".into(), + Text::StepPe32Eighth => "여덟 번째 단계 복호화 중".into(), + Text::StepPe32Load => "파일 데이터 로드 및 압축 해제 중".into(), + Text::StepPe32Text => ".text 복호화 중".into(), + Text::StepPe32TextSkip => ".text 건너뛰는 중 (이미 평문)".into(), + Text::StepPe32Rebuild => "PE 파일 레이아웃 재구성 중".into(), + Text::StepAndroidPrimary => "기본 컨테이너 디코딩 중".into(), + Text::StepAndroidAux => "ELF 구체화 컨테이너 디코딩 중".into(), + Text::StepAndroidTables => "동적 링커 테이블 재구성 중".into(), + Text::DetailPick => "왼쪽에서 입력 또는 그룹을 선택합니다.".into(), + Text::DetailExportJson => "JSON 내보내기".into(), + Text::DetailExportText => "텍스트 내보내기".into(), + Text::DetailLastRun { mode, t } => format!("{mode} · {t}").into(), + Text::DetailCopy => "복사".into(), + Text::DetailTechnical => "기술 세부 정보".into(), + Text::CompanionSplicedPill => "컴패니언 파일 연결됨".into(), + Text::TabOverview => "개요".into(), + Text::TabResearch => "연구 분석".into(), + Text::TabHex => "16진수".into(), + Text::TabCompare => "비교".into(), + Text::TabLog => "로그".into(), + Text::TabEntries => "항목".into(), + Text::BatchSummary => "요약".into(), + Text::BatchInputs => "입력".into(), + Text::BatchScan => "폴더 스캔".into(), + Text::BatchNonTarget => "건너뛴 비대상".into(), + Text::BatchWalkErrors => "읽을 수 없는 폴더 항목".into(), + Text::BatchProbeErrors => "프로브 오류".into(), + Text::BatchScanNote => ".exe, .dll, .so 및 global-metadata.dat 이름만 프로브합니다.".into(), + Text::BatchScanIncomplete => "분석이 불완전합니다: 일부 폴더 항목 또는 선택한 파일을 조사할 수 없었습니다.".into(), + Text::PkgTitle => "패키지".into(), + Text::PkgKind => "패키지 유형".into(), + Text::PkgPackage => "패키지 이름".into(), + Text::PkgVersion => "버전".into(), + Text::PkgEntries => "최상위 항목".into(), + Text::PkgCandidates => "프로브할 항목".into(), + Text::PkgNested => "중첩 패키지".into(), + Text::PkgNote => ".so 및 global-metadata.dat 항목만 추출하여 프로브합니다.".into(), + Text::PkgResult => "결과".into(), + Text::PkgManifests => "매니페스트".into(), + Text::PkgUnnamed => "이름 없음".into(), + Text::PkgTargets => "보호된 항목 및 메타데이터".into(), + Text::PkgNoTargets => "이 패키지에 보호된 항목이 없으므로 복원할 내용이 없습니다.".into(), + Text::PkgInventory { n } => format!("패키지에 나열된 항목: {n}").into(), + Text::EntriesTitle => "항목".into(), + Text::EntriesOthers { n } => format!("기타 항목 (비대상): {n}").into(), + Text::EntriesSummary { n } => format!("대상: {n}").into(), + Text::EntriesShowNonTargets { n } => format!("비대상 표시 ({n})").into(), + Text::EntriesRemapped { n } => format!("재매핑된 메서드 필드: {n}").into(), + Text::EntriesRemappedLabel => "재매핑된 메서드 필드".into(), + Text::ColName => "이름".into(), + Text::ColType => "유형".into(), + Text::ColOutcome => "결과".into(), + Text::ColRoute => "경로".into(), + Text::ColTime => "시간".into(), + Text::ColAddress => "주소".into(), + Text::ColSize => "크기".into(), + Text::ColFileOffset => "파일 오프셋".into(), + Text::ColMapping => "매핑".into(), + Text::ColKind => "종류".into(), + Text::ColLength => "길이".into(), + Text::ColSource => "소스".into(), + Text::ColRaw => "원시 값".into(), + Text::ColDecoded => "디코딩됨".into(), + Text::ColMeaning => "의미".into(), + Text::ColCheck => "검사 항목".into(), + Text::ColStart => "시작".into(), + Text::ColEnd => "끝".into(), + Text::ColLimit => "제한".into(), + Text::ColStatus => "상태".into(), + Text::ColNote => "비고".into(), + Text::ColSeverity => "심각도".into(), + Text::ColArea => "분류".into(), + Text::ColMessage => "메시지".into(), + Text::ColValue => "값".into(), + Text::ColVsize => "가상 크기".into(), + Text::ColRawOffset => "원시 오프셋".into(), + Text::ColRawSize => "원시 크기".into(), + Text::ColCharacteristics => "특성".into(), + Text::ColBacking => "파일 데이터".into(), + Text::ColField => "필드".into(), + Text::ColCommand => "명령".into(), + Text::ColFlags => "플래그".into(), + Text::ColImage => "이미지".into(), + Text::ColMetadata => "메타데이터".into(), + Text::ColOffsetSize => "오프셋 +크기".into(), + Text::ColEntry => "엔트리 포인트".into(), + Text::ColInit => "초기화".into(), + Text::ColDirect => "직접".into(), + Text::ColNested => "중첩 스트림".into(), + Text::ColDepth => "깊이".into(), + Text::ColStream => "스트림".into(), + Text::ColClassification => "분류".into(), + Text::CommonYes => "예".into(), + Text::CommonNo => "아니요".into(), + Text::OvMessages => "메시지".into(), + Text::OvRecognition => "인식".into(), + Text::OvPlatform => "플랫폼".into(), + Text::OvFormat => "형식".into(), + Text::OvKind => "종류".into(), + Text::OvMetadata => "il2cpp 메타데이터".into(), + Text::OvMetadataVersion => "메타데이터 버전".into(), + Text::OvMetadataLayout => "레이아웃 정의".into(), + Text::OvCapSeeded => "시드 기반 메서드 토큰".into(), + Text::OvCapStructural => "구조적 메서드 토큰".into(), + Text::OvCapIndices => "메서드 인덱스 복원".into(), + Text::OvCapContext => "애플리케이션 컨텍스트 필요".into(), + Text::OvProvenance => "모듈 컨텍스트 출처".into(), + Text::OvEvidence => "근거".into(), + Text::OvNoEvidence => "보호 근거 없음".into(), + Text::OvRoutes => "복원 경로".into(), + Text::OvSelected => "선택됨".into(), + Text::OvNoRoutes => "시도된 경로가 없습니다.".into(), + Text::OvStages => "단계".into(), + Text::OvValidation => "정적 검증".into(), + Text::OvValidationMetadata => "PE 및 ELF 구조 검사는 메타데이터에 적용되지 않으며, 변환 과정에서 자체 테이블을 검증합니다.".into(), + Text::OvValidationWarnings => "복원된 이미지에 구조적 문제가 발견되어 실행되지 않을 수 있습니다. 의심됨으로 집계되지만 언패킹 시 파일은 기록됩니다.".into(), + Text::OvValidationFailed => "복원된 이미지가 치명적인 구조 검사에 실패하여 실행되지 않을 가능성이 높습니다. 의심됨으로 집계되지만 언패킹 시 파일은 기록됩니다.".into(), + Text::OvIdentity => "식별 정보".into(), + Text::OvSource => "입력".into(), + Text::OvCompanion => "컴패니언 파일".into(), + Text::OvRecovered => "복원된 이미지".into(), + Text::OvOutput => "출력".into(), + Text::OvOpenFolder => "폴더에서 표시".into(), + Text::OvRestoredElf => "복원된 ELF".into(), + Text::OvElfSections => "섹션 · 세그먼트".into(), + Text::OvElfSymbols => "동적 심볼".into(), + Text::OvElfRelocs => "재배치 · PLT".into(), + Text::ResearchNone => "연구 데이터 없음: 엔진이 구조적 근거를 기록하기 전에 복원이 중지되었습니다.".into(), + Text::ResearchNotCollected => "이 실행에서는 연구 근거를 수집하지 않았습니다.".into(), + Text::ResearchRunInspect => "이 입력 검사".into(), + Text::ResearchSplicedNote => "결합 보기: 0x1000 미만의 오프셋은 로더 스텁을 가리키며, 0x1000 이상의 오프셋은 (오프셋 − 0x1000) 위치의 컴패니언 파일을 가리킵니다.".into(), + Text::ResearchJump { space } => format!("16진수에서 표시 ({space})").into(), + Text::ResearchRegionsNote => "모든 섹션 외부의 파일 범위입니다.".into(), + Text::ResearchRegionsNone => "모든 파일 바이트가 헤더 또는 섹션에 속합니다.".into(), + Text::ResearchAStreamsNote => "각 스트림은 디코딩된 컨테이너 단계 하나를 나타냅니다.".into(), + Text::ResearchAArtifactsNote => "추출 중에 생성된 파일입니다. 임시 작업 공간에 존재하며 작업 후 폐기됩니다.".into(), + Text::RsGrpInput => "보호된 입력".into(), + Text::RsGrpProtection => "보호".into(), + Text::RsGrpRecovery => "복원".into(), + Text::RsGrpExtraction => "추출".into(), + Text::RsGrpRestoration => "복원".into(), + Text::RsGrpMetadata => "메타데이터".into(), + Text::RsGrpProfile => "프로필".into(), + Text::RsPeHeader => "PE 헤더".into(), + Text::RsSections => "섹션".into(), + Text::RsDirectories => "데이터 디렉터리".into(), + Text::RsRegions => "파일 영역".into(), + Text::RsHeaderTable => "헤더 테이블".into(), + Text::RsPayload => "선언된 페이로드".into(), + Text::RsDiscovery => "단계 탐색".into(), + Text::RsTrace => "복원 추적".into(), + Text::RsIssues => "문제 및 작업 한도".into(), + Text::RsRestored => "복원된 이미지".into(), + Text::RsAStage1 => "단계 1".into(), + Text::RsAStreams => "스트림".into(), + Text::RsAModules => "모듈 레지스트리".into(), + Text::RsAArtifacts => "산출물".into(), + Text::RsAScalars => "합계".into(), + Text::RsARDescriptor => "디스크립터".into(), + Text::RsARStaticConfig => "정적 구성".into(), + Text::RsARPrimary => "기본 컨테이너".into(), + Text::RsARAuxiliary => "보조 컨테이너".into(), + Text::RsARElfMaterialization => "ELF 구체화".into(), + Text::RsARCleaning => "프로텍터 제거".into(), + Text::RsARValidation => "검증".into(), + Text::RsMReport => "변환 보고서".into(), + Text::RsMImages => "이미지".into(), + Text::RsMRaw => "기타 필드".into(), + Text::RsProfile => "복원 프로필".into(), + Text::PeOffset => "PE 헤더 오프셋".into(), + Text::PeMachine => "머신".into(), + Text::PeFormat => "형식".into(), + Text::PeEntry => "엔트리 포인트".into(), + Text::PeNotFileBacked => "파일에 없음".into(), + Text::PeAlignment => "섹션 / 파일 정렬".into(), + Text::PeFlags => "선언된 플래그".into(), + Text::PeInputLen => "분석된 바이트".into(), + Text::PeParseIssue => "구문 분석 문제".into(), + Text::MappingInSection { s } => format!("{s} 내부").into(), + Text::MappingPartial { n } => format!("일부만 파일 내 ({n}바이트)").into(), + Text::ProtMagic => "매직".into(), + Text::ProtMagicOk => "지원됨".into(), + Text::ProtMagicBad => "지원되지 않음".into(), + Text::ProtWords => "헤더 워드".into(), + Text::PayloadSource => "소스".into(), + Text::PayloadDest => "대상 위치".into(), + Text::PayloadPrefix => "프리픽스 길이".into(), + Text::PayloadTotal => "전체 길이".into(), + Text::PayloadChecks => "경계 검사".into(), + Text::PayloadInBounds => "범위 내".into(), + Text::PayloadOutOfBounds => "범위 초과".into(), + Text::PayloadProbe => "프리픽스 프로브".into(), + Text::PayloadDecoded => "디코딩됨".into(), + Text::PayloadLimit { l } => format!("제한 {l}").into(), + Text::PayloadFirstWords => "첫 워드".into(), + Text::PayloadUnrecognized => "매직이 인식되지 않았으므로, 이는 헤더 워드에 대한 가능한 해석 중 하나일 뿐입니다.".into(), + Text::DiscPayloadOffset => "페이로드 오프셋".into(), + Text::DiscImageRva => "이미지 RVA".into(), + Text::DiscSource => "소스".into(), + Text::DiscScanned { n } => format!("스캔한 위치: {n}").into(), + Text::DiscNone => "후보가 없습니다.".into(), + Text::TraceSummary { n, s } => format!("이벤트: {n} · 단계: {s}").into(), + Text::TraceEvents { n } => format!("이벤트: {n}").into(), + Text::TraceTruncated { l, n } => format!("추적이 잘렸습니다. 생략된 이벤트: {n} (제한 {l}).").into(), + Text::StreamsTitle { id } => format!("스트림 {id}").into(), + Text::StreamsSummary { d, k, n, s } => format!("깊이 {d} · {k} · 레코드: {n} · {s}").into(), + Text::StreamsOrigin => "출처".into(), + Text::StreamsRoot => "보호된 파일의 최상위 수준".into(), + Text::StreamsParent { c, r, s } => format!("스트림 {s}, 레코드 {r}, 명령 {c}").into(), + Text::StreamsRecords => "레코드".into(), + Text::IssuesNone => "기록된 문제가 없습니다.".into(), + Text::IssuesWork => "작업 한도".into(), + Text::IssuesScratch => "사용된 프리픽스 스크래치".into(), + Text::IssuesCandidates => "검토된 후보".into(), + Text::IssuesBudget => "한도 도달".into(), + Text::RestoredOpenCompare => "원본과 비교…".into(), + Text::RestoredObservations => "복원된 이미지 관측 사항".into(), + Text::MetaRoute { r } => format!("경로: {r}").into(), + Text::MetaDiscoveryError => "시드 탐색이 적용되지 않아 구조적 경로가 사용되었습니다:".into(), + Text::MetaImage => "이미지".into(), + Text::MetaMethods => "메서드".into(), + Text::MetaModulus => "모듈러스".into(), + Text::MetaClean => "정상".into(), + Text::MetaSeedResidues => "시드 나머지".into(), + Text::MetaResidues => "나머지".into(), + Text::HexVOriginal => "원본 파일".into(), + Text::HexVSpliced => "결합 보기".into(), + Text::HexVRestored => "복원됨 (메모리 내)".into(), + Text::HexGoto => "이동".into(), + Text::HexAsFile => "파일 오프셋".into(), + Text::HexAsRva => "RVA".into(), + Text::HexFind => "찾기".into(), + Text::HexFindHint => "4D 5A 또는 텍스트".into(), + Text::HexFindNext => "다음".into(), + Text::HexFindNone => "더 이상 일치하는 항목이 없습니다.".into(), + Text::HexTooLarge { limit, size } => format!("이 파일은 {size}이며, 16진수 보기는 최대 {limit}까지의 파일을 읽습니다.").into(), + Text::HexRvaUnmapped { o } => format!("이 보기에는 RVA {o}에 해당하는 파일 바이트가 없습니다.").into(), + Text::HexCopySel => "선택 영역 복사".into(), + Text::HexInspector => "커서 위치".into(), + Text::HexInspectorHint => "바이트를 클릭하면 여기에 값을 표시합니다.".into(), + Text::HexRegions => "영역".into(), + Text::HexNoRegions => "이 파일에 대해 알려진 영역이 없습니다.".into(), + Text::HexRHeaders => "헤더".into(), + Text::HexRStubPage => "로더 스텁 페이지".into(), + Text::HexRHeaderTable => "보호 헤더 테이블".into(), + Text::HexRElfHeader => "ELF 헤더".into(), + Text::HexRProgramHeaders => "프로그램 헤더".into(), + Text::HexRLoad { n } => format!("LOAD 세그먼트 {n}").into(), + Text::HexRPrivateSection => "전용 로더 섹션".into(), + Text::HexRStage2 => "단계 2 페이로드".into(), + Text::HexRStreams => "암호화된 스트림".into(), + Text::HexSize { s } => format!("크기 {s}").into(), + Text::HexAt { o } => format!("오프셋 {o}").into(), + Text::HexInCompanion { o } => format!("컴패니언 파일 오프셋 {o}").into(), + Text::HexInStub => "로더 스텁".into(), + Text::CmpNoChange => "구조적 차이 없음".into(), + Text::CmpHeaders => "헤더".into(), + Text::CmpOriginal => "원본".into(), + Text::CmpRestored => "복원됨".into(), + Text::CmpFileSize => "파일 크기".into(), + Text::CmpSections => "섹션 수".into(), + Text::CmpBytes => "섹션 바이트".into(), + Text::CmpBytesNote { len, n, s } => format!("{s}의 처음 {len}바이트 중 다른 바이트: {n}.").into(), + Text::CmpNextDiff => "다음 차이".into(), + Text::LogFAll => "전체".into(), + Text::LogFNosteps => "단계 숨기기".into(), + Text::LogFProblems => "문제만".into(), + Text::LogCopy => "로그 복사".into(), + Text::LogLvInfo => "INFO".into(), + Text::LogLvStep => "STEP".into(), + Text::LogLvWarn => "WARN".into(), + Text::LogLvError => "ERROR".into(), + Text::LogRunStarted { mode, n } => format!("{mode} 시작됨 · 입력: {n}").into(), + Text::LogScan { n, s } => format!("스캔 완료: 후보 {n}, 건너뛴 비대상 {s}").into(), + Text::LogInputStarted { i, n, p } => format!("입력 {i}/{n}: {p}").into(), + Text::LogCompanion { p } => format!("컴패니언 파일 연결됨: {p}").into(), + Text::LogStep { i, n, s } => format!("단계 {i}/{n}: {s}").into(), + Text::LogEntry { o, p } => format!("항목 {p}: {o}").into(), + Text::LogInputFinished { o, t } => format!("완료: {o} ({t})").into(), + Text::LogSummary { failed, ok, skipped, suspect } => format!("복원됨 {ok} · 의심됨 {suspect} · 실패함 {failed} · 건너뜀 {skipped}").into(), + Text::StatusReady => "준비".into(), + Text::CloseTitle => "작업이 아직 실행 중입니다".into(), + Text::CloseBody => "Senbei는 현재 입력이 완료된 후 중지하고 닫힙니다. 이미 기록된 출력은 유지됩니다.".into(), + Text::CloseKeep => "계속 실행".into(), + Text::CloseStop => "중지 후 닫기".into(), + Text::LegalTitle => "법적 고지: 사용 전 필독".into(), + Text::LegalP1 => "Senbei는 이미 적법하게 보유한 소프트웨어의 합법적인 리버스 엔지니어링, 보안 연구 및 보존을 위한 연구 및 상호운용성 도구입니다. 본인이 소유하거나 분석할 명시적 권한이 있는 바이너리만 처리하십시오.".into(), + Text::LegalP2 => "기술적 보호 조치를 우회하는 행위는 관할권에 따라 제한될 수 있습니다(예: 보안 연구 및 상호운용성에 대한 예외 조항을 포함하는 미국 DMCA §1201). 사용의 적법성을 보장하는 것은 사용자 본인의 책임입니다.".into(), + Text::LegalP3 => "Senbei는 컴퓨터의 파일에 대해 순수하게 정적인 변환만 수행합니다. 자체적으로 접근 통제를 우회하지 않고, 필요한 정보를 입력 파일에서 도출하며, 벤더 코드를 포함하지 않고, 입력을 절대 실행하거나 업로드하지 않습니다. 한 Android 패키징 변형의 내장 메타데이터 계층은 단일 빌드 분석 중 복원된 XOR 키스트림으로 해제되며, 해당 키스트림은 도구와 함께 제공되는 연구 산출물이지 벤더가 배포한 키가 아닙니다.".into(), + Text::LegalP4 => "Senbei는 온라인 플레이, 라이선스 사기 또는 부정행위를 가능하게 하지 않습니다. 복호화된 출력을 재배포하거나 어디에도 업로드하지 마십시오. 이 소프트웨어는 어떠한 종류의 보증도 없이 “있는 그대로” 제공되며, 작성자는 오용에 대해 어떠한 책임도 지지 않습니다. “CrackProof”는 해당 소유자의 상표이며, 이 프로젝트는 벤더나 어떠한 퍼블리셔와도 제휴하거나 보증받지 않았습니다.".into(), + Text::LegalAccept => "이해했으며 동의합니다".into(), + Text::LegalQuit => "종료".into(), + Text::SettingsTitle => "설정".into(), + Text::SettingsTabGeneral => "일반".into(), + Text::SettingsTabProcessing => "처리".into(), + Text::SettingsTabAndroid => "Android 제한".into(), + Text::SettingsTabMemory => "메모리".into(), + Text::SettingsTabAbout => "정보".into(), + Text::SettingsLanguage => "언어".into(), + Text::SettingsOutput => "기본 출력 폴더".into(), + Text::SettingsOutputRecent => "최근 사용한 폴더".into(), + Text::SettingsOutputChoose => "폴더 선택…".into(), + Text::SettingsOutputHelp => "각 입력 옆은 추가한 파일이나 폴더 옆의 unpack\\ 폴더를 의미합니다.".into(), + Text::SettingsLog => "로그 파일 기록".into(), + Text::SettingsLogHelp => "언패킹 시 출력 폴더에 senbei-YYYYMMDD-HHMMSS.log를 기록합니다.".into(), + Text::SettingsThreads => "작업자 스레드".into(), + Text::SettingsThreadsAuto { n } => format!("자동 ({n})").into(), + Text::SettingsScanAll => "작은 파일 프로브".into(), + Text::SettingsScanAllHelp => "폴더를 스캔할 때 최소 크기 기준 미만인 .exe, .dll, .so 및 메타데이터 이름도 프로브합니다.".into(), + Text::SettingsAndroidNote => "제한은 추출 또는 할당 전에 확인됩니다. 최대 메모리 사용량에 대한 상한선은 아닙니다.".into(), + Text::SettingsMaxEntry => "단일 항목 최대 크기".into(), + Text::SettingsMaxEntryHelp => "아카이브 항목, 디코딩된 버퍼 또는 출력입니다.".into(), + Text::SettingsMaxTotal => "전체 한도".into(), + Text::SettingsMaxTotalHelp => "누적 아카이브 바이트 및 엔진당 작업 한도입니다.".into(), + Text::SettingsMaxEntries => "최대 항목 수".into(), + Text::SettingsMaxEntriesHelp => "아카이브 항목 및 단계 2 레코드입니다.".into(), + Text::SettingsMaxDepth => "최대 중첩 깊이".into(), + Text::SettingsMaxDepthHelp => "패키지 자체는 깊이 0입니다.".into(), + Text::SettingsKeepBytes => "16진수 및 비교를 위해 복원된 바이트 유지".into(), + Text::SettingsKeepBytesHelp => "검사와 시험 실행은 이 세션 동안만 복원된 이미지를 메모리에 유지합니다.".into(), + Text::SettingsKeepCap => "입력당 메모리 한도".into(), + Text::SettingsKeepCapHelp => "더 큰 복원된 이미지는 바이트 없이 구조적으로 요약됩니다.".into(), + Text::SettingsReset => "기본값으로 재설정".into(), + Text::SettingsDone => "완료".into(), + Text::AboutVersion { v } => format!("버전 {v}").into(), + Text::AboutDesc => "CrackProof로 보호된 Windows PE 파일 및 Android AArch64 공유 라이브러리용 정적 언패커입니다.".into(), + Text::AboutLicense => "라이선스".into(), + Text::AboutSource => "소스 코드".into(), + Text::AboutLegal => "법적 고지 표시".into(), + Text::TagMetadata { v } => format!("il2cpp 메타데이터 v{v}").into(), + Text::StatusOk => "복원됨".into(), + Text::StatusSuspect => "의심됨".into(), + Text::StatusRecognized => "인식됨".into(), + Text::StatusSkipped => "건너뜀".into(), + Text::StatusError => "오류".into(), + Text::StatusIncomplete => "분석 미완료".into(), + Text::EntryStatusRestored => "복원됨".into(), + Text::EntryStatusDuplicate => "중복".into(), + Text::EntryStatusNotTarget => "비대상".into(), + Text::EntryStatusUnchanged => "변경 없음".into(), + Text::EntryStatusInventoried => "목록화됨".into(), + Text::EntryStatusError => "오류".into(), + Text::EntryKindSharedLibrary => "공유 라이브러리".into(), + Text::EntryKindMetadata => "il2cpp 메타데이터".into(), + Text::RecognitionNotAttempted => "시도 안 함".into(), + Text::RecognitionRecognized => "인식됨".into(), + Text::RecognitionNotRecognized => "인식되지 않음".into(), + Text::RecognitionBlocked => "차단됨".into(), + Text::RecoveryFailed => "복원 실패".into(), + Text::RecoveryBlocked => "복원 차단됨".into(), + Text::OutcomeSucceeded => "성공함".into(), + Text::OutcomeRejected => "거부됨".into(), + Text::OutcomeFailed => "실패함".into(), + Text::OutcomeNotAttempted => "시도 안 함".into(), + Text::ValidationClean => "정상".into(), + Text::ValidationWarnings => "경고".into(), + Text::ValidationFailed => "실패함".into(), + Text::ValidationNotRun => "미실행".into(), + Text::StageDetection => "탐지".into(), + Text::StageManifestInventory => "매니페스트 목록화".into(), + Text::StageEntryProbe => "항목 프로브".into(), + Text::StageRecovery => "복원".into(), + Text::StageStaticValidation => "정적 검증".into(), + Text::StageOutputWrite => "출력 기록".into(), + Text::StageStatusOk => "정상".into(), + Text::StageStatusSkipped => "건너뜀".into(), + Text::StageStatusFailed => "실패함".into(), + Text::StageStatusBlocked => "차단됨".into(), + Text::TraceStageHeader => "헤더".into(), + Text::TraceStagePayload => "페이로드".into(), + Text::TraceStagePe32Shell => "PE32 셸".into(), + Text::TraceStagePe32Stages => "PE32 단계".into(), + Text::TraceStageExeStage1 => "단계 1".into(), + Text::TraceStageExeStage2 => "단계 2".into(), + Text::TraceStageExeStage3 => "단계 3".into(), + Text::TraceStageExeStage4 => "단계 4".into(), + Text::TraceStageExeStage5 => "단계 5".into(), + Text::TraceStageDllStages => "DLL 단계".into(), + Text::TraceStageSections => "섹션".into(), + Text::TraceStageImports => "임포트".into(), + Text::TraceStageTls => "TLS".into(), + Text::TraceStageOutput => "출력".into(), + Text::TraceStageFinalize => "마무리".into(), + Text::EvidenceHeaderMagic => "헤더 매직".into(), + Text::EvidenceCompanionSpliced => "컴패니언 파일 결합됨".into(), + Text::EvidenceExternalCompanionDeclaration => "외부 컴패니언 파일 선언".into(), + Text::EvidencePrivateSection => "전용 섹션".into(), + Text::EvidenceAesSchedule => "AES 키 스케줄".into(), + Text::EvidenceValidatedMetadataTransform => "검증된 메타데이터 변환".into(), + Text::PlatformWindowsPe => "Windows PE".into(), + Text::PlatformAndroidElf => "Android ELF".into(), + Text::PlatformIl2cppMetadata => "il2cpp 메타데이터".into(), + Text::KindNativeExe => "네이티브 실행 파일".into(), + Text::KindManagedExe => ".NET 실행 파일".into(), + Text::KindNativeDll => "네이티브 DLL".into(), + Text::KindManagedDll => ".NET 어셈블리 (DLL)".into(), + Text::KindShortNativeExe => "EXE".into(), + Text::KindShortManagedExe => ".NET EXE".into(), + Text::KindShortNativeDll => "DLL".into(), + Text::KindShortManagedDll => ".NET DLL".into(), + Text::LayoutExeStyle => "EXE 스타일 로더".into(), + Text::LayoutDll => "DLL 로더".into(), + Text::LayoutAndroidStaged => "Android 단계별 로더".into(), + Text::LayoutMetadataSeeded => "시드 기반 메타데이터 변환".into(), + Text::LayoutMetadataStructural => "구조적 메타데이터 변환".into(), + Text::LayoutMetadataMethodIndices => "메타데이터 메서드 인덱스 복원".into(), + Text::MetaLayoutKnown => "알려짐".into(), + Text::MetaLayoutContextRequired => "애플리케이션 컨텍스트 필요".into(), + Text::MetaLayoutUnverified => "미검증".into(), + Text::CompanionAbsent => "없음".into(), + Text::CompanionSpliced => "결합됨".into(), + Text::CompanionPaired => "연결됨".into(), + Text::CompanionUnmatched => "일치하지 않음".into(), + Text::CompanionUnreadable => "읽을 수 없음".into(), + Text::SpaceFileOffset => "파일 오프셋".into(), + Text::SpaceWorkingImageRva => "이미지 RVA".into(), + Text::SpaceProtectedHeaderOffset => "보호 헤더 오프셋".into(), + Text::SpaceDecodedPayloadOffset => "디코딩된 페이로드 오프셋".into(), + Text::SpaceShortFileOffset => "FILE".into(), + Text::SpaceShortWorkingImageRva => "RVA".into(), + Text::SpaceShortProtectedHeaderOffset => "HDR".into(), + Text::SpaceShortDecodedPayloadOffset => "PAYLOAD".into(), + Text::MappingZero => "비어 있음".into(), + Text::MappingHeaderBacked => "헤더 내".into(), + Text::MappingFileBacked => "파일 내".into(), + Text::MappingUnmapped => "매핑 안 됨".into(), + Text::BackingFileBacked => "파일 내".into(), + Text::BackingVirtualOnly => "메모리 전용".into(), + Text::BackingRawTruncated { n } => format!("잘림 (파일에 {n}바이트만 있음)").into(), + Text::RegionHeadersToFirstSection => "헤더와 첫 섹션 사이의 간격".into(), + Text::RegionBetweenSections => "섹션 간 간격".into(), + Text::RegionOverlay => "오버레이".into(), + Text::SemanticKey => "키".into(), + Text::SemanticMagic => "매직".into(), + Text::SemanticDestinationRva => "대상 RVA".into(), + Text::SemanticPayloadSource => "페이로드 소스".into(), + Text::SemanticTotalLength => "전체 길이".into(), + Text::SemanticEndMarker => "종료 마커".into(), + Text::SeverityInfo => "정보".into(), + Text::SeverityWarning => "경고".into(), + Text::SeverityUnavailable => "사용 불가".into(), + Text::ProbeDecoded => "디코딩됨".into(), + Text::ProbeUnavailable => "사용 불가".into(), + Text::ProbeFailed => "실패함".into(), + Text::ProbeBudgetLimited => "한도 도달".into(), + Text::ShellKindPe32ShellTable => "PE32 셸 테이블".into(), + Text::ShellKindPe32PlusAnchor => "PE32+ 앵커".into(), + Text::CandidateObserved => "관측됨".into(), + Text::CandidateStructuralCandidate => "구조적 후보".into(), + Text::CandidateTrialValidated => "시험 검증됨".into(), + Text::CandidateRejected => "거부됨".into(), + Text::CheckSourcePrefix => "페이로드 프리픽스 (소스)".into(), + Text::CheckSourceRawTail => "페이로드 테일 (소스)".into(), + Text::NoteEntryPointInside { rva } => format!("엔트리 포인트 {rva}이(가) 이 섹션 내부에 있습니다").into(), + Text::NoteRawPastEof { end, len } => format!("원시 범위가 {end}에서 끝나지만 입력은 {len}바이트입니다").into(), + Text::NoteCertFileOffset => "인증서 디렉터리는 RVA가 아닌 파일 오프셋을 사용합니다".into(), + Text::NoteNoImportTable => "임포트 테이블 없음".into(), + Text::MsgCompanionMissing => "컴패니언 파일이 누락되었습니까? 이 로더는 일치하는 ._ 페이로드를 필요로 합니다. 입력 파일 옆에 두고 다시 시도하십시오.".into(), + Text::MsgLimitEntry { entry, limit, size } => format!("{entry}이(가) {size}바이트로 {limit}바이트 제한을 초과합니다. 설정 → Android 제한에서 제한을 높인 후 다시 실행하십시오.").into(), + Text::MsgInternalPanic { loc } => format!("{loc}의 복원 엔진 내부 오류").into(), + Text::NoteMagicUnsupportedValue { value } => format!("헤더 테이블이 디코딩되었으나 info[1]이(가) 지원되는 매직이 아닌 {value}입니다").into(), + Text::NotePrefixScratch => "스크래치에서 프리픽스가 디코딩되었으며, 이후 단계는 전체 복원이 필요합니다".into(), + Text::NoteAnchorValidates => "앵커 및 stage1 디스크립터가 검증되었으며, 전체 단계 복호화는 복원이 필요합니다".into(), + Text::NoteBoundedAnchor => "제한된 앵커 프로브 전용".into(), + Text::NoteBoundedPrefix => "제한된 프리픽스 전용 (복원된 이미지 아님)".into(), + Text::NoteCandidatesUnvalidated => "단계 검증 없이 보고된 후보".into(), + Text::NoteMagicNotSupported => "헤더 매직이 지원되는 보호 헤더가 아닙니다".into(), + Text::NoteNoAnchorField => "디코딩된 페이로드 창에 앵커 필드가 없습니다".into(), + Text::NoteNoShellTable => "디코딩된 페이로드 창에 셸 테이블 형태가 없습니다".into(), + Text::NoteShellNeedsPrefix => "셸 탐색에는 디코딩된 페이로드 프리픽스가 필요합니다".into(), + Text::NoteShellTableMatches => "셸 테이블 형태가 선언된 이미지와 일치하며, 2단계 복호화는 복원이 필요합니다".into(), + Text::NoteRelocUnsupportedType { block, entry, ty } => format!("재배치 블록 {block} 항목 {entry}에 지원되지 않는 유형 {ty}이(가) 있습니다").into(), + Text::NoteRelocBadSize { block, size } => format!("재배치 블록 {block}이(가) 디렉터리에 맞지 않는 크기 {size}을(를) 선언합니다").into(), + } +} diff --git a/senbei-gui/src/text/mod.rs b/senbei-gui/src/text/mod.rs new file mode 100644 index 0000000..00794cb --- /dev/null +++ b/senbei-gui/src/text/mod.rs @@ -0,0 +1,77 @@ +//! Every piece of text the desktop front end shows, in each display language. +//! +//! Engine messages come from `senbei-i18n`; this catalog covers the window +//! itself. English is the approved wording; a translation that names a +//! placeholder its English lacks does not compile. +#![deny(unused_variables)] + +use std::borrow::Cow; + +use senbei_i18n::{Lang, Localize}; + +mod catalog; +mod en; +mod ja; +mod ko; +mod zh_cn; +mod zh_tw; + +pub use catalog::Text; + +/// The display language of this window. +pub fn lang() -> Lang { + senbei_i18n::current() +} + +/// `text` in the display language. +pub fn t(text: Text) -> Cow<'static, str> { + text.localize(lang()) +} + +/// Split text marked with `…` into plain and strong runs. +pub fn strong_runs(text: &str) -> Vec<(bool, &str)> { + let mut runs = Vec::new(); + let mut rest = text; + while let Some(start) = rest.find("") { + if start > 0 { + runs.push((false, &rest[..start])); + } + let after = &rest[start + "".len()..]; + let end = after.find("").unwrap_or(after.len()); + runs.push((true, &after[..end])); + rest = after.get(end + "".len()..).unwrap_or(""); + } + if !rest.is_empty() { + runs.push((false, rest)); + } + runs +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn strong_markup_splits_into_runs() { + assert_eq!( + strong_runs("a b c"), + vec![(false, "a "), (true, "b"), (false, " c")] + ); + assert_eq!(strong_runs("plain"), vec![(false, "plain")]); + assert_eq!(strong_runs("x"), vec![(true, "x")]); + } + + #[test] + fn every_language_renders_every_text() { + for lang in Lang::ALL { + assert!(!Text::TbAddFiles.localize(lang).is_empty()); + let step = Text::RunStep { + i: "5".into(), + n: "9".into(), + s: "x".into(), + } + .localize(lang); + assert!(step.contains('5') && step.contains('9'), "{lang:?}: {step}"); + } + } +} diff --git a/senbei-gui/src/text/zh_cn.rs b/senbei-gui/src/text/zh_cn.rs new file mode 100644 index 0000000..d9ea806 --- /dev/null +++ b/senbei-gui/src/text/zh_cn.rs @@ -0,0 +1,564 @@ +// Generated from the approved GUI mockup catalog. Edit the wording here; +// every language must keep the same placeholders. + +use std::borrow::Cow; + +use super::catalog::Text; + +pub(crate) fn text(text: &Text) -> Cow<'static, str> { + match text { + Text::TbAddFiles => "添加文件…".into(), + Text::TbAddFolder => "添加文件夹…".into(), + Text::TbUnpack => "解包".into(), + Text::TbUnpackN { n } => format!("解包 ({n})").into(), + Text::TbUnpackAll => "全部解包".into(), + Text::TbUnpackTip => "恢复选中的输入项,并将结果写入输出文件夹。".into(), + Text::TbDryRun => "试运行".into(), + Text::TbDryRunN { n } => format!("试运行 ({n})").into(), + Text::TbDryRunAll => "全部试运行".into(), + Text::TbDryRunTip => "执行实际的恢复流程,但不保留任何内容。".into(), + Text::TbInspect => "检查".into(), + Text::TbInspectN { n } => format!("检查 ({n})").into(), + Text::TbInspectAll => "全部检查".into(), + Text::TbInspectTip => "执行实际的恢复流程,显示发现的全部内容,但不保留任何内容。".into(), + Text::TbOutput => "输出:".into(), + Text::TbOutputBeside => "位于各输入项旁 (unpack\\)".into(), + Text::TbOutputTip => "解包后文件的写出位置。检查与试运行绝不写出输出。".into(), + Text::TbSettings => "设置".into(), + Text::BannerEnv { vars } => format!("已设置调试环境变量 {vars}。解码结果可能与正常运行不同。").into(), + Text::BannerEnvHint => "取消设置并重启以恢复正常行为。".into(), + Text::EmptyTitle => "将受保护文件拖放到此处".into(), + Text::EmptyFolders => "文件夹".into(), + Text::EmptyLocal => "所有操作均在本机运行。输入项绝不会被执行或上传。".into(), + Text::DragTitle => "松开以添加".into(), + Text::InputsTitle => "输入项".into(), + Text::InputsClear => "清空".into(), + Text::InputsSearch => "按名称筛选".into(), + Text::InputsNone => "没有匹配筛选条件的输入项。".into(), + Text::FilterAll => "全部".into(), + Text::FilterOk => "已恢复".into(), + Text::FilterSuspect => "可疑".into(), + Text::FilterFailed => "失败".into(), + Text::FilterSkipped => "已跳过".into(), + Text::GroupFiles => "已添加的文件".into(), + Text::GroupScanning { n } => format!("正在扫描… 当前候选:{n}").into(), + Text::ModeInspect => "已检查".into(), + Text::ModeDryRun => "已试运行".into(), + Text::ModeUnpack => "已解包".into(), + Text::MenuCopyPath => "复制路径".into(), + Text::MenuRemove => "从列表中移除".into(), + Text::PendingNotRun => "尚未运行".into(), + Text::PendingNotProtected => "未受保护".into(), + Text::PendingIdentified => "已识别".into(), + Text::PendingNext => "可执行的操作".into(), + Text::PendingUnpackDesc => "恢复该项,并将结果写入输出文件夹。".into(), + Text::PendingDryRunDesc => "执行实际的恢复流程但不保留任何内容,以检验恢复是否可行。".into(), + Text::PendingInspectDesc => "执行实际的恢复流程并显示发现的全部内容。不保留任何内容。".into(), + Text::PendingNotProtectedNote => "Senbei 在此文件中未发现受支持的保护,因此没有需要恢复的内容。".into(), + Text::PendingNotAFile => "不是普通文件,因此没有可读取的内容。".into(), + Text::ScanRunning => "正在扫描".into(), + Text::ScanFound => "当前候选".into(), + Text::ScanStatus { n, p } => format!("正在扫描 {p}… 当前候选:{n}").into(), + Text::RunRunning => "正在运行…".into(), + Text::RunQueued => "排队中".into(), + Text::RunWillNotRun => "不会运行".into(), + Text::RunStep { i, n, s } => format!("步骤 {i}/{n} · {s}").into(), + Text::RunQueue { n } => format!("排队任务:{n}").into(), + Text::RunStopping => "将在当前输入项完成后停止…".into(), + Text::RunCancel => "取消".into(), + Text::RunProgress => "进度".into(), + Text::RunCancelledNote => "任务在到达此输入项前已取消。".into(), + Text::StepDecryptHeader => "正在解密文件头部".into(), + Text::StepDecryptPayload => "正在解密载荷".into(), + Text::StepLocateConfig => "正在定位配置布局".into(), + Text::StepDecryptStage2 => "正在解密阶段 2".into(), + Text::StepDecryptStages35 => "正在解密阶段 3–5".into(), + Text::StepDecryptSections => "正在解密节数据".into(), + Text::StepLoadSections => "正在加载并解压各节".into(), + Text::StepDecryptImports => "正在解密导入字符串".into(), + Text::StepRebuildHeaders => "正在重建 PE 头部".into(), + Text::StepInitKeys => "正在初始化密钥".into(), + Text::StepDecryptKeyTable => "正在解密密钥表".into(), + Text::StepDecryptPrimary => "正在解密主描述符".into(), + Text::StepRelocsParams => "正在处理重定位与解压参数".into(), + Text::StepDecryptBlock1 => "正在解密代码块 1".into(), + Text::StepDecryptBlock23 => "正在解密代码块 2–3".into(), + Text::StepDecryptBlock4 => "正在解密代码块 4".into(), + Text::StepDllSections => "正在解密并解压各节".into(), + Text::StepFixHeaders => "正在修正 PE 头部与节表".into(), + Text::StepPe32Stages => "正在解密各阶段".into(), + Text::StepPe32Eighth => "正在解密第八阶段".into(), + Text::StepPe32Load => "正在加载并解压文件数据".into(), + Text::StepPe32Text => "正在解密 .text".into(), + Text::StepPe32TextSkip => "正在跳过 .text(已是明文)".into(), + Text::StepPe32Rebuild => "正在重建 PE 文件布局".into(), + Text::StepAndroidPrimary => "正在解码主容器".into(), + Text::StepAndroidAux => "正在解码 ELF 物化容器".into(), + Text::StepAndroidTables => "正在重建动态链接器表".into(), + Text::DetailPick => "请在左侧选择一个输入项或分组。".into(), + Text::DetailExportJson => "导出 JSON".into(), + Text::DetailExportText => "导出文本".into(), + Text::DetailLastRun { mode, t } => format!("{mode} · {t}").into(), + Text::DetailCopy => "复制".into(), + Text::DetailTechnical => "技术细节".into(), + Text::CompanionSplicedPill => "已配对伴生文件".into(), + Text::TabOverview => "概览".into(), + Text::TabResearch => "研究".into(), + Text::TabHex => "十六进制".into(), + Text::TabCompare => "对比".into(), + Text::TabLog => "日志".into(), + Text::TabEntries => "条目".into(), + Text::BatchSummary => "汇总".into(), + Text::BatchInputs => "输入项".into(), + Text::BatchScan => "文件夹扫描".into(), + Text::BatchNonTarget => "已跳过非目标".into(), + Text::BatchWalkErrors => "无法读取的目录项".into(), + Text::BatchProbeErrors => "探测错误".into(), + Text::BatchScanNote => "仅探测名称匹配 .exe、.dll、.so 与 global-metadata.dat 的文件。".into(), + Text::BatchScanIncomplete => "分析不完整:部分文件夹条目或所选文件无法检查。".into(), + Text::PkgTitle => "应用包".into(), + Text::PkgKind => "应用包类型".into(), + Text::PkgPackage => "包名".into(), + Text::PkgVersion => "版本".into(), + Text::PkgEntries => "顶层条目".into(), + Text::PkgCandidates => "待探测条目".into(), + Text::PkgNested => "嵌套应用包".into(), + Text::PkgNote => "仅提取并探测 .so 与 global-metadata.dat 条目。".into(), + Text::PkgResult => "结果".into(), + Text::PkgManifests => "清单".into(), + Text::PkgUnnamed => "未命名".into(), + Text::PkgTargets => "受保护条目与元数据".into(), + Text::PkgNoTargets => "此应用包中没有受保护的条目,因此没有需要恢复的内容。".into(), + Text::PkgInventory { n } => format!("应用包中列出的条目:{n}").into(), + Text::EntriesTitle => "条目".into(), + Text::EntriesOthers { n } => format!("其他条目(非目标):{n}").into(), + Text::EntriesSummary { n } => format!("目标:{n}").into(), + Text::EntriesShowNonTargets { n } => format!("显示非目标 ({n})").into(), + Text::EntriesRemapped { n } => format!("已重映射方法字段:{n}").into(), + Text::EntriesRemappedLabel => "已重映射方法字段".into(), + Text::ColName => "名称".into(), + Text::ColType => "类型".into(), + Text::ColOutcome => "结果".into(), + Text::ColRoute => "路线".into(), + Text::ColTime => "用时".into(), + Text::ColAddress => "地址".into(), + Text::ColSize => "大小".into(), + Text::ColFileOffset => "文件偏移".into(), + Text::ColMapping => "映射".into(), + Text::ColKind => "种类".into(), + Text::ColLength => "长度".into(), + Text::ColSource => "来源".into(), + Text::ColRaw => "原始值".into(), + Text::ColDecoded => "解码值".into(), + Text::ColMeaning => "含义".into(), + Text::ColCheck => "检查项".into(), + Text::ColStart => "起始".into(), + Text::ColEnd => "结束".into(), + Text::ColLimit => "限制".into(), + Text::ColStatus => "状态".into(), + Text::ColNote => "说明".into(), + Text::ColSeverity => "严重性".into(), + Text::ColArea => "类别".into(), + Text::ColMessage => "消息".into(), + Text::ColValue => "值".into(), + Text::ColVsize => "虚拟大小".into(), + Text::ColRawOffset => "原始偏移".into(), + Text::ColRawSize => "原始大小".into(), + Text::ColCharacteristics => "属性标志".into(), + Text::ColBacking => "文件数据".into(), + Text::ColField => "字段".into(), + Text::ColCommand => "命令".into(), + Text::ColFlags => "标志".into(), + Text::ColImage => "映像".into(), + Text::ColMetadata => "元数据".into(), + Text::ColOffsetSize => "偏移 +大小".into(), + Text::ColEntry => "入口点".into(), + Text::ColInit => "初始化".into(), + Text::ColDirect => "直接".into(), + Text::ColNested => "嵌套流".into(), + Text::ColDepth => "深度".into(), + Text::ColStream => "流".into(), + Text::ColClassification => "分类".into(), + Text::CommonYes => "是".into(), + Text::CommonNo => "否".into(), + Text::OvMessages => "消息".into(), + Text::OvRecognition => "识别".into(), + Text::OvPlatform => "平台".into(), + Text::OvFormat => "格式".into(), + Text::OvKind => "种类".into(), + Text::OvMetadata => "il2cpp 元数据".into(), + Text::OvMetadataVersion => "元数据版本".into(), + Text::OvMetadataLayout => "布局定义".into(), + Text::OvCapSeeded => "基于种子的方法令牌".into(), + Text::OvCapStructural => "结构化方法令牌".into(), + Text::OvCapIndices => "方法索引恢复".into(), + Text::OvCapContext => "需要应用上下文".into(), + Text::OvProvenance => "模块上下文来源".into(), + Text::OvEvidence => "依据".into(), + Text::OvNoEvidence => "无保护依据".into(), + Text::OvRoutes => "恢复路线".into(), + Text::OvSelected => "已选用".into(), + Text::OvNoRoutes => "未尝试任何路线。".into(), + Text::OvStages => "阶段".into(), + Text::OvValidation => "静态验证".into(), + Text::OvValidationMetadata => "PE 与 ELF 结构检查不适用于元数据;该变换会自行验证其表结构。".into(), + Text::OvValidationWarnings => "恢复映像存在结构问题,可能无法运行。该项计为可疑;解包时仍会写出。".into(), + Text::OvValidationFailed => "恢复映像未通过致命结构检查,极可能无法运行。该项计为可疑;解包时仍会写出。".into(), + Text::OvIdentity => "标识信息".into(), + Text::OvSource => "输入项".into(), + Text::OvCompanion => "伴生文件".into(), + Text::OvRecovered => "恢复映像".into(), + Text::OvOutput => "输出".into(), + Text::OvOpenFolder => "在文件夹中显示".into(), + Text::OvRestoredElf => "已恢复的 ELF".into(), + Text::OvElfSections => "节 · 段".into(), + Text::OvElfSymbols => "动态符号".into(), + Text::OvElfRelocs => "重定位 · PLT".into(), + Text::ResearchNone => "无研究数据:恢复在引擎发布结构化依据前已停止。".into(), + Text::ResearchNotCollected => "本次运行未收集研究依据。".into(), + Text::ResearchRunInspect => "检查此输入项".into(), + Text::ResearchSplicedNote => "拼接视图:低于 0x1000 的偏移针对加载器存根寻址;自 0x1000 起的偏移按 (偏移 − 0x1000) 针对伴生文件寻址。".into(), + Text::ResearchJump { space } => format!("在十六进制中显示 ({space})").into(), + Text::ResearchRegionsNote => "位于所有节之外的文件范围。".into(), + Text::ResearchRegionsNone => "每个文件字节均属于头部或某个节。".into(), + Text::ResearchAStreamsNote => "每个流对应一层已解码容器。".into(), + Text::ResearchAArtifactsNote => "提取期间产生的文件。它们存放在临时工作区中,随后即被丢弃。".into(), + Text::RsGrpInput => "受保护输入项".into(), + Text::RsGrpProtection => "保护".into(), + Text::RsGrpRecovery => "恢复".into(), + Text::RsGrpExtraction => "提取".into(), + Text::RsGrpRestoration => "恢复".into(), + Text::RsGrpMetadata => "元数据".into(), + Text::RsGrpProfile => "概况".into(), + Text::RsPeHeader => "PE 头部".into(), + Text::RsSections => "节".into(), + Text::RsDirectories => "数据目录".into(), + Text::RsRegions => "文件区域".into(), + Text::RsHeaderTable => "头部表".into(), + Text::RsPayload => "声明的载荷".into(), + Text::RsDiscovery => "阶段发现".into(), + Text::RsTrace => "恢复跟踪".into(), + Text::RsIssues => "问题与工作预算".into(), + Text::RsRestored => "恢复映像".into(), + Text::RsAStage1 => "阶段 1".into(), + Text::RsAStreams => "流".into(), + Text::RsAModules => "模块注册表".into(), + Text::RsAArtifacts => "产物".into(), + Text::RsAScalars => "总计".into(), + Text::RsARDescriptor => "描述符".into(), + Text::RsARStaticConfig => "静态配置".into(), + Text::RsARPrimary => "主容器".into(), + Text::RsARAuxiliary => "辅助容器".into(), + Text::RsARElfMaterialization => "ELF 物化".into(), + Text::RsARCleaning => "保护器移除".into(), + Text::RsARValidation => "验证".into(), + Text::RsMReport => "变换报告".into(), + Text::RsMImages => "映像".into(), + Text::RsMRaw => "其他字段".into(), + Text::RsProfile => "恢复概况".into(), + Text::PeOffset => "PE 头部偏移".into(), + Text::PeMachine => "目标架构".into(), + Text::PeFormat => "格式".into(), + Text::PeEntry => "入口点".into(), + Text::PeNotFileBacked => "不在文件中".into(), + Text::PeAlignment => "节对齐 / 文件对齐".into(), + Text::PeFlags => "声明的标志".into(), + Text::PeInputLen => "已分析字节数".into(), + Text::PeParseIssue => "解析问题".into(), + Text::MappingInSection { s } => format!("位于 {s}").into(), + Text::MappingPartial { n } => format!("部分在文件中({n} 字节)").into(), + Text::ProtMagic => "魔数".into(), + Text::ProtMagicOk => "受支持".into(), + Text::ProtMagicBad => "不受支持".into(), + Text::ProtWords => "头部字".into(), + Text::PayloadSource => "源地址".into(), + Text::PayloadDest => "目标地址".into(), + Text::PayloadPrefix => "前缀长度".into(), + Text::PayloadTotal => "总长度".into(), + Text::PayloadChecks => "边界检查".into(), + Text::PayloadInBounds => "在边界内".into(), + Text::PayloadOutOfBounds => "超出边界".into(), + Text::PayloadProbe => "前缀探测".into(), + Text::PayloadDecoded => "已解码".into(), + Text::PayloadLimit { l } => format!("限制 {l}").into(), + Text::PayloadFirstWords => "起始字".into(), + Text::PayloadUnrecognized => "未识别出魔数,因此这只是头部字的一种可能解读。".into(), + Text::DiscPayloadOffset => "载荷偏移".into(), + Text::DiscImageRva => "映像 RVA".into(), + Text::DiscSource => "来源".into(), + Text::DiscScanned { n } => format!("已扫描位置:{n}").into(), + Text::DiscNone => "无候选。".into(), + Text::TraceSummary { n, s } => format!("事件:{n} · 阶段:{s}").into(), + Text::TraceEvents { n } => format!("事件:{n}").into(), + Text::TraceTruncated { l, n } => format!("跟踪已截断。已丢弃事件:{n}(限制 {l})。").into(), + Text::StreamsTitle { id } => format!("流 {id}").into(), + Text::StreamsSummary { d, k, n, s } => format!("深度 {d} · {k} · 记录:{n} · {s}").into(), + Text::StreamsOrigin => "来源".into(), + Text::StreamsRoot => "受保护文件的顶层".into(), + Text::StreamsParent { c, r, s } => format!("流 {s},记录 {r},命令 {c}").into(), + Text::StreamsRecords => "记录".into(), + Text::IssuesNone => "未记录任何问题。".into(), + Text::IssuesWork => "工作预算".into(), + Text::IssuesScratch => "已用前缀暂存空间".into(), + Text::IssuesCandidates => "已评估候选".into(), + Text::IssuesBudget => "受预算限制".into(), + Text::RestoredOpenCompare => "与原始文件对比…".into(), + Text::RestoredObservations => "恢复映像观察结果".into(), + Text::MetaRoute { r } => format!("路线:{r}").into(), + Text::MetaDiscoveryError => "种子发现不适用,已改用结构化路线:".into(), + Text::MetaImage => "映像".into(), + Text::MetaMethods => "方法数".into(), + Text::MetaModulus => "模数".into(), + Text::MetaClean => "干净".into(), + Text::MetaSeedResidues => "种子余数".into(), + Text::MetaResidues => "余数".into(), + Text::HexVOriginal => "原始文件".into(), + Text::HexVSpliced => "拼接视图".into(), + Text::HexVRestored => "已恢复(内存中)".into(), + Text::HexGoto => "跳转至".into(), + Text::HexAsFile => "文件偏移".into(), + Text::HexAsRva => "RVA".into(), + Text::HexFind => "查找".into(), + Text::HexFindHint => "4D 5A 或文本".into(), + Text::HexFindNext => "下一个".into(), + Text::HexFindNone => "无更多匹配项。".into(), + Text::HexTooLarge { limit, size } => format!("此文件为 {size};十六进制视图最多读取 {limit} 的文件。").into(), + Text::HexRvaUnmapped { o } => format!("在此视图中 RVA {o} 没有对应的文件字节。").into(), + Text::HexCopySel => "复制选区".into(), + Text::HexInspector => "光标位置".into(), + Text::HexInspectorHint => "点击任一字节以在此处查看其数值。".into(), + Text::HexRegions => "区域".into(), + Text::HexNoRegions => "此文件没有已知区域。".into(), + Text::HexRHeaders => "头部".into(), + Text::HexRStubPage => "加载器存根页".into(), + Text::HexRHeaderTable => "保护头部表".into(), + Text::HexRElfHeader => "ELF 头部".into(), + Text::HexRProgramHeaders => "程序头部".into(), + Text::HexRLoad { n } => format!("LOAD 段 {n}").into(), + Text::HexRPrivateSection => "私有加载器节".into(), + Text::HexRStage2 => "阶段 2 载荷".into(), + Text::HexRStreams => "加密流".into(), + Text::HexSize { s } => format!("大小 {s}").into(), + Text::HexAt { o } => format!("偏移 {o}").into(), + Text::HexInCompanion { o } => format!("伴生文件偏移 {o}").into(), + Text::HexInStub => "加载器存根".into(), + Text::CmpNoChange => "无结构差异".into(), + Text::CmpHeaders => "头部".into(), + Text::CmpOriginal => "原始".into(), + Text::CmpRestored => "已恢复".into(), + Text::CmpFileSize => "文件大小".into(), + Text::CmpSections => "节数量".into(), + Text::CmpBytes => "节字节".into(), + Text::CmpBytesNote { len, n, s } => format!("{s} 前 {len} 字节中不同的字节数:{n}。").into(), + Text::CmpNextDiff => "下一处差异".into(), + Text::LogFAll => "全部".into(), + Text::LogFNosteps => "隐藏步骤".into(), + Text::LogFProblems => "仅问题".into(), + Text::LogCopy => "复制日志".into(), + Text::LogLvInfo => "INFO".into(), + Text::LogLvStep => "STEP".into(), + Text::LogLvWarn => "WARN".into(), + Text::LogLvError => "ERROR".into(), + Text::LogRunStarted { mode, n } => format!("{mode}已开始 · 输入项:{n}").into(), + Text::LogScan { n, s } => format!("扫描完成:候选 {n},已跳过非目标 {s}").into(), + Text::LogInputStarted { i, n, p } => format!("输入项 {i}/{n}:{p}").into(), + Text::LogCompanion { p } => format!("已配对伴生文件:{p}").into(), + Text::LogStep { i, n, s } => format!("步骤 {i}/{n}:{s}").into(), + Text::LogEntry { o, p } => format!("条目 {p}:{o}").into(), + Text::LogInputFinished { o, t } => format!("已完成:{o} ({t})").into(), + Text::LogSummary { failed, ok, skipped, suspect } => format!("已恢复 {ok} · 可疑 {suspect} · 失败 {failed} · 已跳过 {skipped}").into(), + Text::StatusReady => "就绪".into(), + Text::CloseTitle => "仍有任务正在运行".into(), + Text::CloseBody => "Senbei 将在当前输入项完成后停止并关闭。已写出的输出会保留。".into(), + Text::CloseKeep => "继续运行".into(), + Text::CloseStop => "停止并关闭".into(), + Text::LegalTitle => "法律声明:使用前请阅读".into(), + Text::LegalP1 => "Senbei 是一款用于研究与互操作性的工具,用于对你已合法拥有的软件进行合法的逆向工程、安全研究与保存。请仅处理你拥有或已获明确授权分析的二进制文件。".into(), + Text::LegalP2 => "规避技术保护措施在你所在的司法管辖区可能受到限制(例如美国 DMCA §1201 的规定,其中包含针对安全研究与互操作性的豁免条款)。确保使用行为合法是你本人的责任。".into(), + Text::LegalP3 => "Senbei 在你的计算机上对文件执行纯静态转换:它本身不绕过任何访问控制,所需内容均从输入文件中推导,不包含任何厂商代码,且绝不执行或上传其输入项。某一种 Android 打包变体的内嵌元数据层使用在分析单个构建版本时恢复出的 XOR 密钥流解封;该密钥流是随工具附带的研究成果,而非厂商分发的密钥。".into(), + Text::LegalP4 => "Senbei 不提供联机游戏、授权欺诈或作弊功能。请勿二次分发解密后的输出或将其上传至任何地方。本软件按“原样”提供,不附带任何形式的担保;作者对滥用行为不承担任何责任。“CrackProof”是其所有者的商标;本项目与该厂商或任何发行商均无关联,亦未获得其背书。".into(), + Text::LegalAccept => "我已理解并接受".into(), + Text::LegalQuit => "退出".into(), + Text::SettingsTitle => "设置".into(), + Text::SettingsTabGeneral => "常规".into(), + Text::SettingsTabProcessing => "处理".into(), + Text::SettingsTabAndroid => "Android 限制".into(), + Text::SettingsTabMemory => "内存".into(), + Text::SettingsTabAbout => "关于".into(), + Text::SettingsLanguage => "语言".into(), + Text::SettingsOutput => "默认输出文件夹".into(), + Text::SettingsOutputRecent => "上次使用的文件夹".into(), + Text::SettingsOutputChoose => "选择文件夹…".into(), + Text::SettingsOutputHelp => "“位于各输入项旁”表示在你添加的文件或文件夹旁创建 unpack\\ 文件夹。".into(), + Text::SettingsLog => "写入日志文件".into(), + Text::SettingsLogHelp => "解包会将 senbei-YYYYMMDD-HHMMSS.log 写入输出文件夹。".into(), + Text::SettingsThreads => "工作线程".into(), + Text::SettingsThreadsAuto { n } => format!("自动 ({n})").into(), + Text::SettingsScanAll => "探测小文件".into(), + Text::SettingsScanAllHelp => "扫描文件夹时,同时探测低于大小下限的 .exe、.dll、.so 与元数据文件名。".into(), + Text::SettingsAndroidNote => "提取或分配前会检查限制。这些限制不是内存使用峰值的上限。".into(), + Text::SettingsMaxEntry => "单个条目上限".into(), + Text::SettingsMaxEntryHelp => "归档条目、解码缓冲区或输出。".into(), + Text::SettingsMaxTotal => "总预算".into(), + Text::SettingsMaxTotalHelp => "累计归档字节数及单次引擎任务预算。".into(), + Text::SettingsMaxEntries => "最大条目数".into(), + Text::SettingsMaxEntriesHelp => "归档条目与阶段 2 记录。".into(), + Text::SettingsMaxDepth => "最大嵌套深度".into(), + Text::SettingsMaxDepthHelp => "应用包本身的深度为 0。".into(), + Text::SettingsKeepBytes => "为十六进制与对比视图保留恢复字节".into(), + Text::SettingsKeepBytesHelp => "检查与试运行仅在本次会话期间将恢复映像保留在内存中。".into(), + Text::SettingsKeepCap => "单输入项内存上限".into(), + Text::SettingsKeepCapHelp => "超出此大小的恢复映像仅保留结构汇总,不保留字节数据。".into(), + Text::SettingsReset => "恢复默认设置".into(), + Text::SettingsDone => "完成".into(), + Text::AboutVersion { v } => format!("版本 {v}").into(), + Text::AboutDesc => "适用于受 CrackProof 保护的 Windows PE 文件与 Android AArch64 共享库的静态解包工具。".into(), + Text::AboutLicense => "许可证".into(), + Text::AboutSource => "源代码".into(), + Text::AboutLegal => "显示法律声明".into(), + Text::TagMetadata { v } => format!("il2cpp 元数据 v{v}").into(), + Text::StatusOk => "已恢复".into(), + Text::StatusSuspect => "可疑".into(), + Text::StatusRecognized => "已识别".into(), + Text::StatusSkipped => "已跳过".into(), + Text::StatusError => "错误".into(), + Text::StatusIncomplete => "分析不完整".into(), + Text::EntryStatusRestored => "已恢复".into(), + Text::EntryStatusDuplicate => "重复".into(), + Text::EntryStatusNotTarget => "非目标".into(), + Text::EntryStatusUnchanged => "未更改".into(), + Text::EntryStatusInventoried => "已列出".into(), + Text::EntryStatusError => "错误".into(), + Text::EntryKindSharedLibrary => "共享库".into(), + Text::EntryKindMetadata => "il2cpp 元数据".into(), + Text::RecognitionNotAttempted => "未尝试".into(), + Text::RecognitionRecognized => "已识别".into(), + Text::RecognitionNotRecognized => "未识别".into(), + Text::RecognitionBlocked => "受阻".into(), + Text::RecoveryFailed => "恢复失败".into(), + Text::RecoveryBlocked => "恢复受阻".into(), + Text::OutcomeSucceeded => "成功".into(), + Text::OutcomeRejected => "已拒绝".into(), + Text::OutcomeFailed => "失败".into(), + Text::OutcomeNotAttempted => "未尝试".into(), + Text::ValidationClean => "干净".into(), + Text::ValidationWarnings => "警告".into(), + Text::ValidationFailed => "失败".into(), + Text::ValidationNotRun => "未运行".into(), + Text::StageDetection => "检测".into(), + Text::StageManifestInventory => "清单清点".into(), + Text::StageEntryProbe => "条目探测".into(), + Text::StageRecovery => "恢复".into(), + Text::StageStaticValidation => "静态验证".into(), + Text::StageOutputWrite => "输出写入".into(), + Text::StageStatusOk => "正常".into(), + Text::StageStatusSkipped => "已跳过".into(), + Text::StageStatusFailed => "失败".into(), + Text::StageStatusBlocked => "受阻".into(), + Text::TraceStageHeader => "头部".into(), + Text::TraceStagePayload => "载荷".into(), + Text::TraceStagePe32Shell => "PE32 外壳".into(), + Text::TraceStagePe32Stages => "PE32 阶段".into(), + Text::TraceStageExeStage1 => "阶段 1".into(), + Text::TraceStageExeStage2 => "阶段 2".into(), + Text::TraceStageExeStage3 => "阶段 3".into(), + Text::TraceStageExeStage4 => "阶段 4".into(), + Text::TraceStageExeStage5 => "阶段 5".into(), + Text::TraceStageDllStages => "DLL 阶段".into(), + Text::TraceStageSections => "节".into(), + Text::TraceStageImports => "导入".into(), + Text::TraceStageTls => "TLS".into(), + Text::TraceStageOutput => "输出".into(), + Text::TraceStageFinalize => "收尾".into(), + Text::EvidenceHeaderMagic => "头部魔数".into(), + Text::EvidenceCompanionSpliced => "已拼接伴生文件".into(), + Text::EvidenceExternalCompanionDeclaration => "声明了外部伴生文件".into(), + Text::EvidencePrivateSection => "私有节".into(), + Text::EvidenceAesSchedule => "AES 密钥编排表".into(), + Text::EvidenceValidatedMetadataTransform => "已验证的元数据变换".into(), + Text::PlatformWindowsPe => "Windows PE".into(), + Text::PlatformAndroidElf => "Android ELF".into(), + Text::PlatformIl2cppMetadata => "il2cpp 元数据".into(), + Text::KindNativeExe => "原生可执行文件".into(), + Text::KindManagedExe => ".NET 可执行文件".into(), + Text::KindNativeDll => "原生 DLL".into(), + Text::KindManagedDll => ".NET 程序集 (DLL)".into(), + Text::KindShortNativeExe => "EXE".into(), + Text::KindShortManagedExe => ".NET EXE".into(), + Text::KindShortNativeDll => "DLL".into(), + Text::KindShortManagedDll => ".NET DLL".into(), + Text::LayoutExeStyle => "EXE 风格加载器".into(), + Text::LayoutDll => "DLL 加载器".into(), + Text::LayoutAndroidStaged => "Android 分阶段加载器".into(), + Text::LayoutMetadataSeeded => "基于种子的元数据变换".into(), + Text::LayoutMetadataStructural => "结构化元数据变换".into(), + Text::LayoutMetadataMethodIndices => "元数据方法索引恢复".into(), + Text::MetaLayoutKnown => "已知".into(), + Text::MetaLayoutContextRequired => "需要应用上下文".into(), + Text::MetaLayoutUnverified => "未验证".into(), + Text::CompanionAbsent => "无".into(), + Text::CompanionSpliced => "已拼接".into(), + Text::CompanionPaired => "已配对".into(), + Text::CompanionUnmatched => "不匹配".into(), + Text::CompanionUnreadable => "不可读".into(), + Text::SpaceFileOffset => "文件偏移".into(), + Text::SpaceWorkingImageRva => "映像 RVA".into(), + Text::SpaceProtectedHeaderOffset => "保护头部偏移".into(), + Text::SpaceDecodedPayloadOffset => "解码载荷偏移".into(), + Text::SpaceShortFileOffset => "FILE".into(), + Text::SpaceShortWorkingImageRva => "RVA".into(), + Text::SpaceShortProtectedHeaderOffset => "HDR".into(), + Text::SpaceShortDecodedPayloadOffset => "PAYLOAD".into(), + Text::MappingZero => "空".into(), + Text::MappingHeaderBacked => "位于头部中".into(), + Text::MappingFileBacked => "在文件中".into(), + Text::MappingUnmapped => "未映射".into(), + Text::BackingFileBacked => "在文件中".into(), + Text::BackingVirtualOnly => "仅在内存中".into(), + Text::BackingRawTruncated { n } => format!("已截断(文件中仅有 {n} 字节)").into(), + Text::RegionHeadersToFirstSection => "头部与首个节之间的间隙".into(), + Text::RegionBetweenSections => "节间间隙".into(), + Text::RegionOverlay => "附加数据".into(), + Text::SemanticKey => "密钥".into(), + Text::SemanticMagic => "魔数".into(), + Text::SemanticDestinationRva => "目标 RVA".into(), + Text::SemanticPayloadSource => "载荷源地址".into(), + Text::SemanticTotalLength => "总长度".into(), + Text::SemanticEndMarker => "结束标记".into(), + Text::SeverityInfo => "信息".into(), + Text::SeverityWarning => "警告".into(), + Text::SeverityUnavailable => "不可用".into(), + Text::ProbeDecoded => "已解码".into(), + Text::ProbeUnavailable => "不可用".into(), + Text::ProbeFailed => "失败".into(), + Text::ProbeBudgetLimited => "受预算限制".into(), + Text::ShellKindPe32ShellTable => "PE32 外壳表".into(), + Text::ShellKindPe32PlusAnchor => "PE32+ 锚点".into(), + Text::CandidateObserved => "已观察到".into(), + Text::CandidateStructuralCandidate => "结构候选".into(), + Text::CandidateTrialValidated => "已试解验证".into(), + Text::CandidateRejected => "已拒绝".into(), + Text::CheckSourcePrefix => "载荷前缀(源)".into(), + Text::CheckSourceRawTail => "载荷尾部(源)".into(), + Text::NoteEntryPointInside { rva } => format!("入口点 {rva} 位于此节内").into(), + Text::NoteRawPastEof { end, len } => format!("原始范围在 {end} 处结束,输入长度为 {len} 字节").into(), + Text::NoteCertFileOffset => "证书目录使用文件偏移,而非 RVA".into(), + Text::NoteNoImportTable => "无导入表".into(), + Text::MsgCompanionMissing => "缺少伴生文件?此加载器需要匹配的 ._ 载荷。请将其放在输入文件旁并重试。".into(), + Text::MsgLimitEntry { entry, limit, size } => format!("{entry} 为 {size} 字节,超出 {limit} 字节的限制。请在“设置 → Android 限制”中调高限制后重新运行。").into(), + Text::MsgInternalPanic { loc } => format!("恢复引擎在 {loc} 处发生内部错误").into(), + Text::NoteMagicUnsupportedValue { value } => format!("头部表已解码,但 info[1] 为 {value},不是受支持的魔数").into(), + Text::NotePrefixScratch => "已在暂存区解码前缀;后续阶段仍需完整恢复".into(), + Text::NoteAnchorValidates => "锚点与 stage1 描述符已通过验证;完整阶段解密仍需执行恢复".into(), + Text::NoteBoundedAnchor => "仅有界锚点探测".into(), + Text::NoteBoundedPrefix => "仅有界前缀;非已恢复映像".into(), + Text::NoteCandidatesUnvalidated => "报告的候选未经阶段验证".into(), + Text::NoteMagicNotSupported => "头部魔数不是受支持的保护头部".into(), + Text::NoteNoAnchorField => "已解码载荷窗口中无锚点字段".into(), + Text::NoteNoShellTable => "已解码载荷窗口中无外壳表结构".into(), + Text::NoteShellNeedsPrefix => "外壳发现需要已解码的载荷前缀".into(), + Text::NoteShellTableMatches => "外壳表结构与声明的映像匹配;第二阶段解密仍需执行恢复".into(), + Text::NoteRelocUnsupportedType { block, entry, ty } => format!("重定位块 {block} 条目 {entry} 具有不受支持的类型 {ty}").into(), + Text::NoteRelocBadSize { block, size } => format!("重定位块 {block} 声明的大小 {size} 与目录不符").into(), + } +} diff --git a/senbei-gui/src/text/zh_tw.rs b/senbei-gui/src/text/zh_tw.rs new file mode 100644 index 0000000..7164812 --- /dev/null +++ b/senbei-gui/src/text/zh_tw.rs @@ -0,0 +1,564 @@ +// Generated from the approved GUI mockup catalog. Edit the wording here; +// every language must keep the same placeholders. + +use std::borrow::Cow; + +use super::catalog::Text; + +pub(crate) fn text(text: &Text) -> Cow<'static, str> { + match text { + Text::TbAddFiles => "加入檔案…".into(), + Text::TbAddFolder => "加入資料夾…".into(), + Text::TbUnpack => "解包".into(), + Text::TbUnpackN { n } => format!("解包 ({n})").into(), + Text::TbUnpackAll => "全部解包".into(), + Text::TbUnpackTip => "恢復所選輸入項並將結果寫入輸出資料夾。".into(), + Text::TbDryRun => "試執行".into(), + Text::TbDryRunN { n } => format!("試執行 ({n})").into(), + Text::TbDryRunAll => "全部試執行".into(), + Text::TbDryRunTip => "執行真實恢復流程,但不保留任何結果。".into(), + Text::TbInspect => "檢查".into(), + Text::TbInspectN { n } => format!("檢查 ({n})").into(), + Text::TbInspectAll => "全部檢查".into(), + Text::TbInspectTip => "執行真實恢復流程,顯示所發現的一切,但不保留任何結果。".into(), + Text::TbOutput => "輸出:".into(), + Text::TbOutputBeside => "各輸入項旁 (unpack\\)".into(), + Text::TbOutputTip => "解包後檔案的寫入位置。檢查與試執行絕不會寫入輸出。".into(), + Text::TbSettings => "設定".into(), + Text::BannerEnv { vars } => format!("已設定除錯環境變數 {vars}。解碼結果可能與正常執行不同。").into(), + Text::BannerEnvHint => "取消設定並重新啟動以恢復正常行為。".into(), + Text::EmptyTitle => "將受保護檔案拖放至此".into(), + Text::EmptyFolders => "資料夾".into(), + Text::EmptyLocal => "所有處理皆在此電腦上本機執行。輸入項絕不會被執行或上傳。".into(), + Text::DragTitle => "放開以加入".into(), + Text::InputsTitle => "輸入項".into(), + Text::InputsClear => "清除".into(), + Text::InputsSearch => "依名稱篩選".into(), + Text::InputsNone => "沒有符合篩選條件的輸入項。".into(), + Text::FilterAll => "全部".into(), + Text::FilterOk => "已恢復".into(), + Text::FilterSuspect => "可疑".into(), + Text::FilterFailed => "失敗".into(), + Text::FilterSkipped => "已略過".into(), + Text::GroupFiles => "已加入的檔案".into(), + Text::GroupScanning { n } => format!("掃描中… 目前候選:{n}").into(), + Text::ModeInspect => "已檢查".into(), + Text::ModeDryRun => "已試執行".into(), + Text::ModeUnpack => "已解包".into(), + Text::MenuCopyPath => "複製路徑".into(), + Text::MenuRemove => "從清單移除".into(), + Text::PendingNotRun => "尚未執行".into(), + Text::PendingNotProtected => "未受保護".into(), + Text::PendingIdentified => "已識別".into(), + Text::PendingNext => "後續操作".into(), + Text::PendingUnpackDesc => "進行恢復並將結果寫入輸出資料夾。".into(), + Text::PendingDryRunDesc => "執行真實恢復流程但不保留任何結果,以確認是否可行。".into(), + Text::PendingInspectDesc => "執行真實恢復流程並顯示發現的所有內容。不保留任何結果。".into(), + Text::PendingNotProtectedNote => "Senbei 在此檔案中未發現受支援的保護,因此沒有可恢復的內容。".into(), + Text::PendingNotAFile => "不是一般檔案,因此沒有可讀取的內容。".into(), + Text::ScanRunning => "掃描中".into(), + Text::ScanFound => "目前候選".into(), + Text::ScanStatus { n, p } => format!("正在掃描 {p}… 目前候選:{n}").into(), + Text::RunRunning => "執行中…".into(), + Text::RunQueued => "佇列中".into(), + Text::RunWillNotRun => "不會執行".into(), + Text::RunStep { i, n, s } => format!("步驟 {i}/{n} · {s}").into(), + Text::RunQueue { n } => format!("佇列中的工作:{n}").into(), + Text::RunStopping => "將在目前輸入項完成後停止…".into(), + Text::RunCancel => "取消".into(), + Text::RunProgress => "進度".into(), + Text::RunCancelledNote => "工作在處理到此輸入項之前已取消。".into(), + Text::StepDecryptHeader => "解密檔案標頭".into(), + Text::StepDecryptPayload => "解密載荷".into(), + Text::StepLocateConfig => "定位組態配置".into(), + Text::StepDecryptStage2 => "解密階段 2".into(), + Text::StepDecryptStages35 => "解密階段 3–5".into(), + Text::StepDecryptSections => "解密節區資料".into(), + Text::StepLoadSections => "載入並解壓縮節區".into(), + Text::StepDecryptImports => "解密匯入字串".into(), + Text::StepRebuildHeaders => "重建 PE 標頭".into(), + Text::StepInitKeys => "初始化金鑰".into(), + Text::StepDecryptKeyTable => "解密金鑰表".into(), + Text::StepDecryptPrimary => "解密主要描述元".into(), + Text::StepRelocsParams => "處理重定位與解壓縮參數".into(), + Text::StepDecryptBlock1 => "解密程式碼區塊 1".into(), + Text::StepDecryptBlock23 => "解密程式碼區塊 2–3".into(), + Text::StepDecryptBlock4 => "解密程式碼區塊 4".into(), + Text::StepDllSections => "解密並解壓縮節區".into(), + Text::StepFixHeaders => "修補 PE 標頭與節區表".into(), + Text::StepPe32Stages => "解密各階段".into(), + Text::StepPe32Eighth => "解密第 8 階段".into(), + Text::StepPe32Load => "載入並解壓縮檔案資料".into(), + Text::StepPe32Text => "解密 .text".into(), + Text::StepPe32TextSkip => "略過 .text(已為明文)".into(), + Text::StepPe32Rebuild => "重建 PE 檔案配置".into(), + Text::StepAndroidPrimary => "解碼主要容器".into(), + Text::StepAndroidAux => "解碼 ELF 實體化容器".into(), + Text::StepAndroidTables => "重建動態連結器表".into(), + Text::DetailPick => "請在左側選取輸入項或群組。".into(), + Text::DetailExportJson => "匯出 JSON".into(), + Text::DetailExportText => "匯出文字".into(), + Text::DetailLastRun { mode, t } => format!("{mode} · {t}").into(), + Text::DetailCopy => "複製".into(), + Text::DetailTechnical => "技術細節".into(), + Text::CompanionSplicedPill => "已配對伴生檔案".into(), + Text::TabOverview => "概覽".into(), + Text::TabResearch => "研究".into(), + Text::TabHex => "十六進位".into(), + Text::TabCompare => "比較".into(), + Text::TabLog => "記錄".into(), + Text::TabEntries => "條目".into(), + Text::BatchSummary => "摘要".into(), + Text::BatchInputs => "輸入項".into(), + Text::BatchScan => "資料夾掃描".into(), + Text::BatchNonTarget => "已略過的非目標".into(), + Text::BatchWalkErrors => "無法讀取的資料夾項目".into(), + Text::BatchProbeErrors => "探測錯誤".into(), + Text::BatchScanNote => "僅會探測名稱為 .exe、.dll、.so 與 global-metadata.dat 的檔案。".into(), + Text::BatchScanIncomplete => "分析不完整:部分資料夾項目或所選檔案無法檢驗。".into(), + Text::PkgTitle => "應用程式套件".into(), + Text::PkgKind => "應用程式套件類型".into(), + Text::PkgPackage => "應用程式套件名稱".into(), + Text::PkgVersion => "版本".into(), + Text::PkgEntries => "頂層條目".into(), + Text::PkgCandidates => "待探測條目".into(), + Text::PkgNested => "巢狀應用程式套件".into(), + Text::PkgNote => "僅會解壓縮並探測 .so 與 global-metadata.dat 條目。".into(), + Text::PkgResult => "結果".into(), + Text::PkgManifests => "資訊清單".into(), + Text::PkgUnnamed => "未命名".into(), + Text::PkgTargets => "受保護條目與中繼資料".into(), + Text::PkgNoTargets => "此應用程式套件中沒有任何受保護的條目,因此沒有可恢復的內容。".into(), + Text::PkgInventory { n } => format!("應用程式套件中列出的條目:{n}").into(), + Text::EntriesTitle => "條目".into(), + Text::EntriesOthers { n } => format!("其他條目(非目標):{n}").into(), + Text::EntriesSummary { n } => format!("目標:{n}").into(), + Text::EntriesShowNonTargets { n } => format!("顯示非目標 ({n})").into(), + Text::EntriesRemapped { n } => format!("已重新映射的方法欄位:{n}").into(), + Text::EntriesRemappedLabel => "已重新映射的方法欄位".into(), + Text::ColName => "名稱".into(), + Text::ColType => "類型".into(), + Text::ColOutcome => "結果".into(), + Text::ColRoute => "路線".into(), + Text::ColTime => "時間".into(), + Text::ColAddress => "位址".into(), + Text::ColSize => "大小".into(), + Text::ColFileOffset => "檔案偏移".into(), + Text::ColMapping => "映射".into(), + Text::ColKind => "種類".into(), + Text::ColLength => "長度".into(), + Text::ColSource => "來源".into(), + Text::ColRaw => "原始值".into(), + Text::ColDecoded => "解碼值".into(), + Text::ColMeaning => "含義".into(), + Text::ColCheck => "檢查項".into(), + Text::ColStart => "起始".into(), + Text::ColEnd => "結束".into(), + Text::ColLimit => "限制".into(), + Text::ColStatus => "狀態".into(), + Text::ColNote => "備註".into(), + Text::ColSeverity => "嚴重性".into(), + Text::ColArea => "類別".into(), + Text::ColMessage => "訊息".into(), + Text::ColValue => "值".into(), + Text::ColVsize => "虛擬大小".into(), + Text::ColRawOffset => "原始偏移".into(), + Text::ColRawSize => "原始大小".into(), + Text::ColCharacteristics => "特徵旗標".into(), + Text::ColBacking => "檔案資料".into(), + Text::ColField => "欄位".into(), + Text::ColCommand => "命令".into(), + Text::ColFlags => "旗標".into(), + Text::ColImage => "映像".into(), + Text::ColMetadata => "中繼資料".into(), + Text::ColOffsetSize => "偏移 +大小".into(), + Text::ColEntry => "進入點".into(), + Text::ColInit => "初始化".into(), + Text::ColDirect => "直接".into(), + Text::ColNested => "巢狀串流".into(), + Text::ColDepth => "深度".into(), + Text::ColStream => "串流".into(), + Text::ColClassification => "分類".into(), + Text::CommonYes => "是".into(), + Text::CommonNo => "否".into(), + Text::OvMessages => "訊息".into(), + Text::OvRecognition => "識別".into(), + Text::OvPlatform => "平台".into(), + Text::OvFormat => "格式".into(), + Text::OvKind => "種類".into(), + Text::OvMetadata => "il2cpp 中繼資料".into(), + Text::OvMetadataVersion => "中繼資料版本".into(), + Text::OvMetadataLayout => "結構配置定義".into(), + Text::OvCapSeeded => "基於種子的方法權杖".into(), + Text::OvCapStructural => "結構化方法權杖".into(), + Text::OvCapIndices => "方法索引恢復".into(), + Text::OvCapContext => "需要應用程式上下文".into(), + Text::OvProvenance => "模組上下文來源".into(), + Text::OvEvidence => "依據".into(), + Text::OvNoEvidence => "無保護依據".into(), + Text::OvRoutes => "恢復路線".into(), + Text::OvSelected => "已選用".into(), + Text::OvNoRoutes => "未嘗試任何路線。".into(), + Text::OvStages => "階段".into(), + Text::OvValidation => "靜態驗證".into(), + Text::OvValidationMetadata => "PE 與 ELF 結構檢查不適用於中繼資料;轉換流程會自行驗證其資料表。".into(), + Text::OvValidationWarnings => "恢復映像存在結構問題,可能無法正常執行。此項目計為可疑;解包時仍會寫出檔案。".into(), + Text::OvValidationFailed => "恢復映像未通過致命結構檢查,極可能無法執行。此項目計為可疑;解包時仍會寫出檔案。".into(), + Text::OvIdentity => "檔案識別資訊".into(), + Text::OvSource => "輸入項".into(), + Text::OvCompanion => "伴生檔案".into(), + Text::OvRecovered => "恢復映像".into(), + Text::OvOutput => "輸出".into(), + Text::OvOpenFolder => "在資料夾中顯示".into(), + Text::OvRestoredElf => "已恢復的 ELF".into(), + Text::OvElfSections => "節區 · 區段".into(), + Text::OvElfSymbols => "動態符號".into(), + Text::OvElfRelocs => "重定位 · PLT".into(), + Text::ResearchNone => "無研究資料:在引擎發佈結構依據前,恢復便已停止。".into(), + Text::ResearchNotCollected => "此次執行未收集研究依據。".into(), + Text::ResearchRunInspect => "檢查此輸入項".into(), + Text::ResearchSplicedNote => "拼接檢視:低於 0x1000 的偏移定址載入器存根;自 0x1000 起的偏移定址伴生檔案的 (偏移 − 0x1000) 處。".into(), + Text::ResearchJump { space } => format!("在十六進位中顯示 ({space})").into(), + Text::ResearchRegionsNote => "不屬於任何節區的檔案範圍。".into(), + Text::ResearchRegionsNone => "每個檔案位元組皆屬於標頭或某個節區。".into(), + Text::ResearchAStreamsNote => "每個串流對應一個已解碼的容器層級。".into(), + Text::ResearchAArtifactsNote => "提取期間產生的檔案。這些檔案存放於暫存工作區,完成後即會捨棄。".into(), + Text::RsGrpInput => "受保護輸入項".into(), + Text::RsGrpProtection => "保護".into(), + Text::RsGrpRecovery => "恢復".into(), + Text::RsGrpExtraction => "提取".into(), + Text::RsGrpRestoration => "恢復".into(), + Text::RsGrpMetadata => "中繼資料".into(), + Text::RsGrpProfile => "概況".into(), + Text::RsPeHeader => "PE 標頭".into(), + Text::RsSections => "節區".into(), + Text::RsDirectories => "資料目錄".into(), + Text::RsRegions => "檔案區域".into(), + Text::RsHeaderTable => "標頭表".into(), + Text::RsPayload => "宣告的載荷".into(), + Text::RsDiscovery => "階段探索".into(), + Text::RsTrace => "恢復追蹤".into(), + Text::RsIssues => "問題與工作配額".into(), + Text::RsRestored => "恢復映像".into(), + Text::RsAStage1 => "階段 1".into(), + Text::RsAStreams => "串流".into(), + Text::RsAModules => "模組登錄表".into(), + Text::RsAArtifacts => "產物".into(), + Text::RsAScalars => "統計總計".into(), + Text::RsARDescriptor => "描述元".into(), + Text::RsARStaticConfig => "靜態組態".into(), + Text::RsARPrimary => "主要容器".into(), + Text::RsARAuxiliary => "輔助容器".into(), + Text::RsARElfMaterialization => "ELF 實體化".into(), + Text::RsARCleaning => "保護器移除".into(), + Text::RsARValidation => "驗證".into(), + Text::RsMReport => "轉換報告".into(), + Text::RsMImages => "映像".into(), + Text::RsMRaw => "其他欄位".into(), + Text::RsProfile => "恢復概況".into(), + Text::PeOffset => "PE 標頭偏移".into(), + Text::PeMachine => "目標架構".into(), + Text::PeFormat => "格式".into(), + Text::PeEntry => "進入點".into(), + Text::PeNotFileBacked => "不在檔案中".into(), + Text::PeAlignment => "節區 / 檔案對齊".into(), + Text::PeFlags => "宣告的旗標".into(), + Text::PeInputLen => "已分析位元組數".into(), + Text::PeParseIssue => "剖析問題".into(), + Text::MappingInSection { s } => format!("位於 {s}").into(), + Text::MappingPartial { n } => format!("部分在檔案中({n} 位元組)").into(), + Text::ProtMagic => "魔術數字".into(), + Text::ProtMagicOk => "受支援".into(), + Text::ProtMagicBad => "不支援".into(), + Text::ProtWords => "標頭雙字組".into(), + Text::PayloadSource => "來源".into(), + Text::PayloadDest => "目的地".into(), + Text::PayloadPrefix => "前綴長度".into(), + Text::PayloadTotal => "總長度".into(), + Text::PayloadChecks => "邊界檢查".into(), + Text::PayloadInBounds => "在邊界內".into(), + Text::PayloadOutOfBounds => "超出邊界".into(), + Text::PayloadProbe => "前綴探測".into(), + Text::PayloadDecoded => "已解碼".into(), + Text::PayloadLimit { l } => format!("限制 {l}").into(), + Text::PayloadFirstWords => "起始雙字組".into(), + Text::PayloadUnrecognized => "無法識別該魔術數字,因此這只是對標頭雙字組的一種可能解讀。".into(), + Text::DiscPayloadOffset => "載荷偏移".into(), + Text::DiscImageRva => "映像 RVA".into(), + Text::DiscSource => "來源".into(), + Text::DiscScanned { n } => format!("已掃描位置:{n}").into(), + Text::DiscNone => "無候選項目。".into(), + Text::TraceSummary { n, s } => format!("事件:{n} · 階段:{s}").into(), + Text::TraceEvents { n } => format!("事件:{n}").into(), + Text::TraceTruncated { l, n } => format!("追蹤已截斷。已捨棄事件:{n}(限制 {l})。").into(), + Text::StreamsTitle { id } => format!("串流 {id}").into(), + Text::StreamsSummary { d, k, n, s } => format!("深度 {d} · {k} · 記錄:{n} · {s}").into(), + Text::StreamsOrigin => "來源".into(), + Text::StreamsRoot => "受保護檔案的頂層".into(), + Text::StreamsParent { c, r, s } => format!("串流 {s},記錄 {r},命令 {c}").into(), + Text::StreamsRecords => "記錄".into(), + Text::IssuesNone => "未記錄任何問題。".into(), + Text::IssuesWork => "工作配額".into(), + Text::IssuesScratch => "已使用前綴暫存空間".into(), + Text::IssuesCandidates => "已評估候選數".into(), + Text::IssuesBudget => "受配額限制".into(), + Text::RestoredOpenCompare => "與原始檔案比較…".into(), + Text::RestoredObservations => "恢復映像的觀察結果".into(), + Text::MetaRoute { r } => format!("路線:{r}").into(), + Text::MetaDiscoveryError => "種子探索不適用,因此改用結構化路線:".into(), + Text::MetaImage => "映像".into(), + Text::MetaMethods => "方法數".into(), + Text::MetaModulus => "模數".into(), + Text::MetaClean => "乾淨".into(), + Text::MetaSeedResidues => "種子餘數".into(), + Text::MetaResidues => "有餘數".into(), + Text::HexVOriginal => "原始檔案".into(), + Text::HexVSpliced => "拼接檢視".into(), + Text::HexVRestored => "已恢復(記憶體中)".into(), + Text::HexGoto => "跳至".into(), + Text::HexAsFile => "檔案偏移".into(), + Text::HexAsRva => "RVA".into(), + Text::HexFind => "尋找".into(), + Text::HexFindHint => "4D 5A 或文字".into(), + Text::HexFindNext => "下一個".into(), + Text::HexFindNone => "找不到更多相符項目。".into(), + Text::HexTooLarge { limit, size } => format!("此檔案為 {size};十六進位檢視最多讀取 {limit} 的檔案。").into(), + Text::HexRvaUnmapped { o } => format!("RVA {o} 在此檢視中沒有對應的檔案位元組。").into(), + Text::HexCopySel => "複製選取範圍".into(), + Text::HexInspector => "游標位置".into(), + Text::HexInspectorHint => "點選任一位元組以在此處檢視其數值。".into(), + Text::HexRegions => "區域".into(), + Text::HexNoRegions => "此檔案無已知區域。".into(), + Text::HexRHeaders => "標頭".into(), + Text::HexRStubPage => "載入器存根分頁".into(), + Text::HexRHeaderTable => "保護標頭表".into(), + Text::HexRElfHeader => "ELF 標頭".into(), + Text::HexRProgramHeaders => "程式標頭".into(), + Text::HexRLoad { n } => format!("LOAD 區段 {n}").into(), + Text::HexRPrivateSection => "私有載入器節區".into(), + Text::HexRStage2 => "階段 2 載荷".into(), + Text::HexRStreams => "加密串流".into(), + Text::HexSize { s } => format!("大小 {s}").into(), + Text::HexAt { o } => format!("偏移 {o}").into(), + Text::HexInCompanion { o } => format!("伴生檔案偏移 {o}").into(), + Text::HexInStub => "載入器存根".into(), + Text::CmpNoChange => "無結構差異".into(), + Text::CmpHeaders => "標頭".into(), + Text::CmpOriginal => "原始".into(), + Text::CmpRestored => "已恢復".into(), + Text::CmpFileSize => "檔案大小".into(), + Text::CmpSections => "節區數量".into(), + Text::CmpBytes => "節區位元組".into(), + Text::CmpBytesNote { len, n, s } => format!("{s} 前 {len} 位元組中相異的位元組數:{n}。").into(), + Text::CmpNextDiff => "下一個差異".into(), + Text::LogFAll => "全部".into(), + Text::LogFNosteps => "隱藏步驟".into(), + Text::LogFProblems => "僅顯示問題".into(), + Text::LogCopy => "複製記錄".into(), + Text::LogLvInfo => "INFO".into(), + Text::LogLvStep => "STEP".into(), + Text::LogLvWarn => "WARN".into(), + Text::LogLvError => "ERROR".into(), + Text::LogRunStarted { mode, n } => format!("{mode}已開始 · 輸入項:{n}").into(), + Text::LogScan { n, s } => format!("掃描完成:候選 {n},已略過非目標 {s}").into(), + Text::LogInputStarted { i, n, p } => format!("輸入項 {i}/{n}:{p}").into(), + Text::LogCompanion { p } => format!("已配對伴生檔案:{p}").into(), + Text::LogStep { i, n, s } => format!("步驟 {i}/{n}:{s}").into(), + Text::LogEntry { o, p } => format!("條目 {p}:{o}").into(), + Text::LogInputFinished { o, t } => format!("完成:{o} ({t})").into(), + Text::LogSummary { failed, ok, skipped, suspect } => format!("已恢復 {ok} · 可疑 {suspect} · 失敗 {failed} · 已略過 {skipped}").into(), + Text::StatusReady => "就緒".into(), + Text::CloseTitle => "仍有工作正在執行".into(), + Text::CloseBody => "Senbei 將在目前輸入項完成後停止並關閉。已寫入的輸出將會保留。".into(), + Text::CloseKeep => "繼續執行".into(), + Text::CloseStop => "停止並關閉".into(), + Text::LegalTitle => "法律聲明:使用前請詳閱".into(), + Text::LegalP1 => "Senbei 是研究與互通性工具,用於對您已合法持有的軟體進行合法逆向工程、安全研究與保存。請僅處理您擁有或已獲明確授權分析的二進位檔。".into(), + Text::LegalP2 => "規避科技保護措施在您所在的司法管轄區可能受到限制(例如美國 DMCA §1201,其中包含針對安全研究與互通性的豁免條款)。確保您的使用行為合法是您本人的責任。".into(), + Text::LegalP3 => "Senbei 在您的電腦上對檔案執行純靜態轉換:它本身不繞過任何存取控制、從輸入檔案推導所需資訊、不包含任何廠商程式碼,且絕不執行或上傳其輸入項。某一種 Android 封裝變體的內嵌中繼資料層,是使用在分析單一組建時所恢復的 XOR 金鑰流進行解封;該金鑰流為隨附於工具中的研究產出,而非由廠商散佈的金鑰。".into(), + Text::LegalP4 => "Senbei 不提供連線遊玩、授權詐欺或作弊功能。請勿重新散佈已解密的輸出或將其上傳至任何地方。本軟體係依「現狀」提供,不附帶任何形式的擔保;作者對任何濫用行為概不負責。「CrackProof」為其所有權人的商標;本專案與該廠商或任何發行商均無關聯,亦未獲其背書。".into(), + Text::LegalAccept => "我已瞭解並同意".into(), + Text::LegalQuit => "結束".into(), + Text::SettingsTitle => "設定".into(), + Text::SettingsTabGeneral => "一般".into(), + Text::SettingsTabProcessing => "處理".into(), + Text::SettingsTabAndroid => "Android 限制".into(), + Text::SettingsTabMemory => "記憶體".into(), + Text::SettingsTabAbout => "關於".into(), + Text::SettingsLanguage => "語言".into(), + Text::SettingsOutput => "預設輸出資料夾".into(), + Text::SettingsOutputRecent => "上次使用的資料夾".into(), + Text::SettingsOutputChoose => "選擇資料夾…".into(), + Text::SettingsOutputHelp => "「各輸入項旁」代表在您加入的檔案或資料夾旁建立 unpack\\ 資料夾。".into(), + Text::SettingsLog => "寫入記錄檔".into(), + Text::SettingsLogHelp => "解包時會將 senbei-YYYYMMDD-HHMMSS.log 寫入輸出資料夾。".into(), + Text::SettingsThreads => "工作執行緒".into(), + Text::SettingsThreadsAuto { n } => format!("自動 ({n})").into(), + Text::SettingsScanAll => "探測小型檔案".into(), + Text::SettingsScanAllHelp => "掃描資料夾時,一併探測低於檔案大小下限的 .exe、.dll、.so 與中繼資料名稱。".into(), + Text::SettingsAndroidNote => "系統會在解壓縮或配置記憶體前檢查限制。這些限制並非尖峰記憶體使用量的硬性上限。".into(), + Text::SettingsMaxEntry => "單一條目上限".into(), + Text::SettingsMaxEntryHelp => "封存條目、已解碼緩衝區或單一輸出。".into(), + Text::SettingsMaxTotal => "總配額上限".into(), + Text::SettingsMaxTotalHelp => "累計封存位元組數與單一引擎工作配額。".into(), + Text::SettingsMaxEntries => "條目數量上限".into(), + Text::SettingsMaxEntriesHelp => "封存條目與階段 2 記錄數。".into(), + Text::SettingsMaxDepth => "最大巢狀深度".into(), + Text::SettingsMaxDepthHelp => "應用程式套件本身的深度為 0。".into(), + Text::SettingsKeepBytes => "為十六進位與比較保留已恢復位元組".into(), + Text::SettingsKeepBytesHelp => "檢查與試執行僅會在此次工作階段將恢復映像保留於記憶體中。".into(), + Text::SettingsKeepCap => "單一輸入項記憶體上限".into(), + Text::SettingsKeepCapHelp => "超過此大小的恢復映像僅保留結構摘要,不保留位元組內容。".into(), + Text::SettingsReset => "重設為預設值".into(), + Text::SettingsDone => "完成".into(), + Text::AboutVersion { v } => format!("版本 {v}").into(), + Text::AboutDesc => "適用於受 CrackProof 保護之 Windows PE 檔案與 Android AArch64 共用程式庫的靜態解包工具。".into(), + Text::AboutLicense => "授權條款".into(), + Text::AboutSource => "原始碼".into(), + Text::AboutLegal => "顯示法律聲明".into(), + Text::TagMetadata { v } => format!("il2cpp 中繼資料 v{v}").into(), + Text::StatusOk => "已恢復".into(), + Text::StatusSuspect => "可疑".into(), + Text::StatusRecognized => "已識別".into(), + Text::StatusSkipped => "已略過".into(), + Text::StatusError => "錯誤".into(), + Text::StatusIncomplete => "分析不完整".into(), + Text::EntryStatusRestored => "已恢復".into(), + Text::EntryStatusDuplicate => "重複".into(), + Text::EntryStatusNotTarget => "非目標".into(), + Text::EntryStatusUnchanged => "未變更".into(), + Text::EntryStatusInventoried => "已列出".into(), + Text::EntryStatusError => "錯誤".into(), + Text::EntryKindSharedLibrary => "共用程式庫".into(), + Text::EntryKindMetadata => "il2cpp 中繼資料".into(), + Text::RecognitionNotAttempted => "未嘗試".into(), + Text::RecognitionRecognized => "已識別".into(), + Text::RecognitionNotRecognized => "未識別".into(), + Text::RecognitionBlocked => "受阻".into(), + Text::RecoveryFailed => "恢復失敗".into(), + Text::RecoveryBlocked => "恢復受阻".into(), + Text::OutcomeSucceeded => "成功".into(), + Text::OutcomeRejected => "已拒絕".into(), + Text::OutcomeFailed => "失敗".into(), + Text::OutcomeNotAttempted => "未嘗試".into(), + Text::ValidationClean => "乾淨".into(), + Text::ValidationWarnings => "警告".into(), + Text::ValidationFailed => "失敗".into(), + Text::ValidationNotRun => "未執行".into(), + Text::StageDetection => "偵測".into(), + Text::StageManifestInventory => "資訊清單清查".into(), + Text::StageEntryProbe => "條目探測".into(), + Text::StageRecovery => "恢復".into(), + Text::StageStaticValidation => "靜態驗證".into(), + Text::StageOutputWrite => "輸出寫入".into(), + Text::StageStatusOk => "正常".into(), + Text::StageStatusSkipped => "已略過".into(), + Text::StageStatusFailed => "失敗".into(), + Text::StageStatusBlocked => "受阻".into(), + Text::TraceStageHeader => "標頭".into(), + Text::TraceStagePayload => "載荷".into(), + Text::TraceStagePe32Shell => "PE32 外殼".into(), + Text::TraceStagePe32Stages => "PE32 階段".into(), + Text::TraceStageExeStage1 => "階段 1".into(), + Text::TraceStageExeStage2 => "階段 2".into(), + Text::TraceStageExeStage3 => "階段 3".into(), + Text::TraceStageExeStage4 => "階段 4".into(), + Text::TraceStageExeStage5 => "階段 5".into(), + Text::TraceStageDllStages => "DLL 階段".into(), + Text::TraceStageSections => "節區".into(), + Text::TraceStageImports => "匯入表".into(), + Text::TraceStageTls => "TLS".into(), + Text::TraceStageOutput => "輸出".into(), + Text::TraceStageFinalize => "完成處理".into(), + Text::EvidenceHeaderMagic => "標頭魔術數字".into(), + Text::EvidenceCompanionSpliced => "伴生檔案已拼接".into(), + Text::EvidenceExternalCompanionDeclaration => "宣告外部伴生檔案".into(), + Text::EvidencePrivateSection => "私有節區".into(), + Text::EvidenceAesSchedule => "AES 金鑰排程".into(), + Text::EvidenceValidatedMetadataTransform => "已驗證的中繼資料轉換".into(), + Text::PlatformWindowsPe => "Windows PE".into(), + Text::PlatformAndroidElf => "Android ELF".into(), + Text::PlatformIl2cppMetadata => "il2cpp 中繼資料".into(), + Text::KindNativeExe => "原生可執行檔".into(), + Text::KindManagedExe => ".NET 可執行檔".into(), + Text::KindNativeDll => "原生 DLL".into(), + Text::KindManagedDll => ".NET 組件 (DLL)".into(), + Text::KindShortNativeExe => "EXE".into(), + Text::KindShortManagedExe => ".NET EXE".into(), + Text::KindShortNativeDll => "DLL".into(), + Text::KindShortManagedDll => ".NET DLL".into(), + Text::LayoutExeStyle => "EXE 風格載入器".into(), + Text::LayoutDll => "DLL 載入器".into(), + Text::LayoutAndroidStaged => "Android 分階段載入器".into(), + Text::LayoutMetadataSeeded => "基於種子的中繼資料轉換".into(), + Text::LayoutMetadataStructural => "結構化中繼資料轉換".into(), + Text::LayoutMetadataMethodIndices => "中繼資料方法索引恢復".into(), + Text::MetaLayoutKnown => "已知".into(), + Text::MetaLayoutContextRequired => "需要應用程式上下文".into(), + Text::MetaLayoutUnverified => "未驗證".into(), + Text::CompanionAbsent => "無".into(), + Text::CompanionSpliced => "已拼接".into(), + Text::CompanionPaired => "已配對".into(), + Text::CompanionUnmatched => "不相符".into(), + Text::CompanionUnreadable => "無法讀取".into(), + Text::SpaceFileOffset => "檔案偏移".into(), + Text::SpaceWorkingImageRva => "映像 RVA".into(), + Text::SpaceProtectedHeaderOffset => "保護標頭偏移".into(), + Text::SpaceDecodedPayloadOffset => "已解碼載荷偏移".into(), + Text::SpaceShortFileOffset => "FILE".into(), + Text::SpaceShortWorkingImageRva => "RVA".into(), + Text::SpaceShortProtectedHeaderOffset => "HDR".into(), + Text::SpaceShortDecodedPayloadOffset => "PAYLOAD".into(), + Text::MappingZero => "空".into(), + Text::MappingHeaderBacked => "位於標頭內".into(), + Text::MappingFileBacked => "在檔案中".into(), + Text::MappingUnmapped => "未映射".into(), + Text::BackingFileBacked => "在檔案中".into(), + Text::BackingVirtualOnly => "僅在記憶體中".into(), + Text::BackingRawTruncated { n } => format!("已截斷(檔案中僅有 {n} 位元組)").into(), + Text::RegionHeadersToFirstSection => "標頭與第一個節區之間的空隙".into(), + Text::RegionBetweenSections => "節區之間的空隙".into(), + Text::RegionOverlay => "附加資料".into(), + Text::SemanticKey => "金鑰".into(), + Text::SemanticMagic => "魔術數字".into(), + Text::SemanticDestinationRva => "目的地 RVA".into(), + Text::SemanticPayloadSource => "載荷來源".into(), + Text::SemanticTotalLength => "總長度".into(), + Text::SemanticEndMarker => "結束標記".into(), + Text::SeverityInfo => "資訊".into(), + Text::SeverityWarning => "警告".into(), + Text::SeverityUnavailable => "無法使用".into(), + Text::ProbeDecoded => "已解碼".into(), + Text::ProbeUnavailable => "無法使用".into(), + Text::ProbeFailed => "失敗".into(), + Text::ProbeBudgetLimited => "受配額限制".into(), + Text::ShellKindPe32ShellTable => "PE32 外殼表".into(), + Text::ShellKindPe32PlusAnchor => "PE32+ 錨點".into(), + Text::CandidateObserved => "已觀測".into(), + Text::CandidateStructuralCandidate => "結構候選".into(), + Text::CandidateTrialValidated => "試探驗證通過".into(), + Text::CandidateRejected => "已拒絕".into(), + Text::CheckSourcePrefix => "載荷前綴(來源)".into(), + Text::CheckSourceRawTail => "載荷尾端(來源)".into(), + Text::NoteEntryPointInside { rva } => format!("進入點 {rva} 位於此節區內").into(), + Text::NoteRawPastEof { end, len } => format!("原始資料範圍結束於 {end},但輸入僅有 {len} 位元組").into(), + Text::NoteCertFileOffset => "憑證目錄使用的是檔案偏移,而非 RVA".into(), + Text::NoteNoImportTable => "無匯入表".into(), + Text::MsgCompanionMissing => "缺少伴生檔案?此載入器需要相符的 ._ 載荷。請將它放在輸入檔案旁並再試一次。".into(), + Text::MsgLimitEntry { entry, limit, size } => format!("{entry} 為 {size} 位元組,超過 {limit} 位元組的限制。請在「設定 → Android 限制」中調高限制,然後重新執行。").into(), + Text::MsgInternalPanic { loc } => format!("恢復引擎於 {loc} 發生內部錯誤").into(), + Text::NoteMagicUnsupportedValue { value } => format!("標頭表已解碼,但 info[1] 為 {value},而非受支援的魔術數字").into(), + Text::NotePrefixScratch => "前綴已於暫存區解碼;後續階段仍需執行完整恢復".into(), + Text::NoteAnchorValidates => "錨點與 stage1 描述元驗證通過;完整階段解密需執行恢復".into(), + Text::NoteBoundedAnchor => "僅進行有界錨點探測".into(), + Text::NoteBoundedPrefix => "僅有界前綴;並非恢復映像".into(), + Text::NoteCandidatesUnvalidated => "已回報候選項目(未執行階段驗證)".into(), + Text::NoteMagicNotSupported => "標頭魔術數字不是受支援的保護標頭".into(), + Text::NoteNoAnchorField => "已解碼的載荷視窗中無錨點欄位".into(), + Text::NoteNoShellTable => "已解碼的載荷視窗中無外殼表結構".into(), + Text::NoteShellNeedsPrefix => "外殼探索需要已解碼的載荷前綴".into(), + Text::NoteShellTableMatches => "外殼表結構與宣告的映像相符;第二階段解密需執行恢復".into(), + Text::NoteRelocUnsupportedType { block, entry, ty } => format!("重定位區塊 {block} 條目 {entry} 具有不支援的類型 {ty}").into(), + Text::NoteRelocBadSize { block, size } => format!("重定位區塊 {block} 宣告的大小 {size} 與資料目錄不符").into(), + } +} diff --git a/senbei-gui/src/theme.rs b/senbei-gui/src/theme.rs new file mode 100644 index 0000000..427954d --- /dev/null +++ b/senbei-gui/src/theme.rs @@ -0,0 +1,320 @@ +//! The dark workbench theme: the mockup's palette, type scale, and fonts. + +use std::collections::BTreeMap; +use std::sync::Arc; + +use egui::{ + Color32, CornerRadius, FontData, FontDefinitions, FontFamily, FontId, Margin, Stroke, Style, + TextStyle, Visuals, +}; + +// ---------------------------------------------------------------- palette + +const fn rgb(r: u8, g: u8, b: u8) -> Color32 { + Color32::from_rgb(r, g, b) +} + +/// `rgba(r, g, b, alpha)` as a premultiplied colour. +fn rgba(r: u8, g: u8, b: u8, alpha: f32) -> Color32 { + Color32::from_rgba_unmultiplied(r, g, b, (alpha * 255.0).round() as u8) +} + +pub const BG: Color32 = rgb(0x14, 0x16, 0x1a); +pub const PANEL: Color32 = rgb(0x1d, 0x20, 0x26); +pub const PANEL_2: Color32 = rgb(0x23, 0x27, 0x2e); +pub const WELL: Color32 = rgb(0x0c, 0x0e, 0x11); +pub const BORDER: Color32 = rgb(0x2e, 0x32, 0x3b); +pub const BORDER_STRONG: Color32 = rgb(0x3c, 0x41, 0x4c); +pub const TEXT: Color32 = rgb(0xe4, 0xe7, 0xec); +pub const DIM: Color32 = rgb(0x9a, 0xa3, 0xb0); +pub const FAINT: Color32 = rgb(0x80, 0x88, 0x96); +pub const ACCENT: Color32 = rgb(0xe8, 0xb6, 0x4c); +pub const ACCENT_HOVER: Color32 = rgb(0xf0, 0xc4, 0x63); +pub const ACCENT_INK: Color32 = rgb(0x1a, 0x14, 0x08); +pub const BLUE: Color32 = rgb(0x3b, 0x82, 0xf6); +pub const OK: Color32 = rgb(0x6f, 0xcf, 0x7c); +pub const ERR: Color32 = rgb(0xe0, 0x6c, 0x6c); +pub const WARN: Color32 = ACCENT; +pub const SKIP: Color32 = rgb(0x8b, 0x93, 0xa1); +pub const INFO: Color32 = rgb(0x7a, 0xa7, 0xf7); +pub const STRING: Color32 = rgb(0xc9, 0xd4, 0x8b); +pub const ZERO_BYTE: Color32 = rgb(0x4a, 0x50, 0x5b); +pub const HOVER_FILL: Color32 = rgb(0x2a, 0x2f, 0x37); +pub const HOVER_STROKE: Color32 = rgb(0x56, 0x60, 0x70); +pub const HIGHLIGHT_TEXT: Color32 = rgb(0xff, 0xf3, 0xd6); + +pub fn selection() -> Color32 { + rgba(59, 130, 246, 0.20) +} +pub fn row_hover() -> Color32 { + rgba(255, 255, 255, 0.035) +} +pub fn accent_soft() -> Color32 { + rgba(232, 182, 76, 0.14) +} +pub fn highlight() -> Color32 { + rgba(232, 182, 76, 0.28) +} +pub fn diff() -> Color32 { + rgba(224, 108, 108, 0.30) +} +pub fn backdrop() -> Color32 { + rgba(8, 9, 11, 0.72) +} + +/// Section colours, in section order, for hex strips and the region list. +pub const SECTION_COLORS: [Color32; 8] = [ + rgb(0x6f, 0xcf, 0x7c), + rgb(0xe8, 0xb6, 0x4c), + rgb(0xc7, 0x92, 0xea), + rgb(0x4f, 0xc1, 0xc9), + rgb(0xf7, 0x8c, 0x6c), + rgb(0xa3, 0xbe, 0x8c), + rgb(0xd7, 0xda, 0xe0), + rgb(0x82, 0xaa, 0xff), +]; +pub const REGION_HEADERS: Color32 = INFO; +pub const REGION_PROTECTION: Color32 = ERR; +pub const REGION_PREFIX: Color32 = rgb(0xf0, 0xa0, 0x4b); +pub const REGION_TAIL: Color32 = rgb(0xb4, 0x8a, 0x55); +pub const REGION_OTHER: Color32 = SKIP; + +/// What an outcome looks like: the dot, pill, and label colour. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Tone { + Ok, + Warn, + Err, + Info, + Skip, +} + +impl Tone { + pub fn color(self) -> Color32 { + match self { + Tone::Ok => OK, + Tone::Warn => WARN, + Tone::Err => ERR, + Tone::Info => INFO, + Tone::Skip => SKIP, + } + } + + /// The translucent fill behind a pill. + pub fn soft(self) -> Color32 { + match self { + Tone::Ok => rgba(111, 207, 124, 0.13), + Tone::Warn => rgba(232, 182, 76, 0.13), + Tone::Err => rgba(224, 108, 108, 0.13), + Tone::Info => rgba(59, 130, 246, 0.14), + Tone::Skip => Color32::TRANSPARENT, + } + } + + /// The pill border. + pub fn border(self) -> Color32 { + match self { + Tone::Ok => rgba(111, 207, 124, 0.45), + Tone::Warn => rgba(232, 182, 76, 0.45), + Tone::Err => rgba(224, 108, 108, 0.45), + Tone::Info => rgba(59, 130, 246, 0.45), + Tone::Skip => BORDER_STRONG, + } + } +} + +// ------------------------------------------------------------------- type + +/// Font family of the Asul titles, falling back to the UI font for scripts +/// Asul does not cover. +pub fn title_family() -> FontFamily { + FontFamily::Name("title".into()) +} + +/// Semibold UI text. +pub fn strong_family() -> FontFamily { + FontFamily::Name("strong".into()) +} + +pub fn body() -> FontId { + FontId::proportional(13.5) +} +pub fn small() -> FontId { + FontId::proportional(12.0) +} +pub fn tiny() -> FontId { + FontId::proportional(11.5) +} +pub fn mono() -> FontId { + FontId::monospace(12.5) +} +pub fn mono_small() -> FontId { + FontId::monospace(12.0) +} +pub fn strong(size: f32) -> FontId { + FontId::new(size, strong_family()) +} +pub fn title(size: f32) -> FontId { + FontId::new(size, title_family()) +} + +/// One installed font face. +#[derive(Clone)] +pub struct Face { + pub name: String, + pub data: Arc, +} + +/// The faces of one display language, best first. Each list may be empty; +/// egui's bundled fonts back every family. +#[derive(Clone, Default)] +pub struct FontSet { + pub ui: Vec, + pub strong: Vec, + pub mono: Vec, +} + +/// The Asul title face, embedded. Licensed under the SIL Open Font License; +/// see `assets/fonts/OFL.txt`. +const ASUL_BOLD: &[u8] = include_bytes!("../assets/fonts/Asul-Bold.ttf"); + +/// Font definitions: the language's system fonts first, egui's bundled fonts +/// after them for symbols they lack. +pub fn font_definitions(set: &FontSet) -> FontDefinitions { + let mut defs = FontDefinitions::default(); + let bundled_proportional = defs + .families + .get(&FontFamily::Proportional) + .cloned() + .unwrap_or_default(); + let bundled_mono = defs + .families + .get(&FontFamily::Monospace) + .cloned() + .unwrap_or_default(); + let mut install = |faces: &[Face]| -> Vec { + faces + .iter() + .map(|face| { + defs.font_data.insert(face.name.clone(), face.data.clone()); + face.name.clone() + }) + .collect() + }; + let ui = install(&set.ui); + let strong = install(&set.strong); + let mono = install(&set.mono); + defs.font_data.insert( + "Asul-Bold".into(), + Arc::new(FontData::from_static(ASUL_BOLD)), + ); + + let chain = |first: &[String], rest: &[String]| -> Vec { + let mut out: Vec = first.to_vec(); + for name in rest { + if !out.contains(name) { + out.push(name.clone()); + } + } + out + }; + let proportional = chain(&ui, &bundled_proportional); + let strong_chain = chain(&strong, &proportional); + let mut title_chain = vec!["Asul-Bold".to_owned()]; + title_chain.extend(strong_chain.iter().cloned()); + // Monospace falls back to the UI chain so CJK in paths still renders. + let mono_chain = chain(&chain(&mono, &bundled_mono), &proportional); + + let mut families = BTreeMap::new(); + families.insert(FontFamily::Proportional, proportional); + families.insert(FontFamily::Monospace, mono_chain); + families.insert(strong_family(), strong_chain); + families.insert(title_family(), title_chain); + defs.families = families; + defs +} + +// ------------------------------------------------------------------ style + +/// The workbench style: flat fills, 1 px strokes, 4 px corners. +pub fn style(base: &Style) -> Style { + let mut style = base.clone(); + style.text_styles = [ + (TextStyle::Body, body()), + (TextStyle::Button, body()), + (TextStyle::Small, small()), + (TextStyle::Monospace, mono()), + (TextStyle::Heading, strong(17.0)), + ] + .into(); + let spacing = &mut style.spacing; + spacing.item_spacing = egui::vec2(8.0, 4.0); + spacing.button_padding = egui::vec2(10.0, 4.0); + spacing.interact_size.y = 24.0; + spacing.window_margin = Margin::same(12); + spacing.menu_margin = Margin::same(4); + spacing.scroll.bar_width = 10.0; + spacing.scroll.floating = false; + spacing.combo_width = 120.0; + spacing.text_edit_width = 160.0; + style.visuals = visuals(); + style.interaction.selectable_labels = false; + style.url_in_tooltip = false; + style +} + +fn visuals() -> Visuals { + let mut visuals = Visuals::dark(); + let radius = CornerRadius::same(4); + visuals.override_text_color = Some(TEXT); + visuals.panel_fill = PANEL; + visuals.window_fill = PANEL; + visuals.window_stroke = Stroke::new(1.0, BORDER_STRONG); + visuals.window_corner_radius = CornerRadius::same(8); + visuals.menu_corner_radius = CornerRadius::same(6); + visuals.extreme_bg_color = WELL; + visuals.faint_bg_color = row_hover(); + visuals.code_bg_color = PANEL_2; + visuals.hyperlink_color = INFO; + visuals.warn_fg_color = WARN; + visuals.error_fg_color = ERR; + visuals.selection.bg_fill = selection(); + visuals.selection.stroke = Stroke::new(1.0, BLUE); + visuals.text_edit_bg_color = Some(WELL); + visuals.striped = false; + + let w = &mut visuals.widgets; + w.noninteractive.bg_fill = PANEL; + w.noninteractive.weak_bg_fill = PANEL; + w.noninteractive.bg_stroke = Stroke::new(1.0, BORDER); + w.noninteractive.fg_stroke = Stroke::new(1.0, TEXT); + w.noninteractive.corner_radius = radius; + + w.inactive.bg_fill = PANEL_2; + w.inactive.weak_bg_fill = PANEL_2; + w.inactive.bg_stroke = Stroke::new(1.0, BORDER_STRONG); + w.inactive.fg_stroke = Stroke::new(1.0, TEXT); + w.inactive.corner_radius = radius; + w.inactive.expansion = 0.0; + + w.hovered.bg_fill = HOVER_FILL; + w.hovered.weak_bg_fill = HOVER_FILL; + w.hovered.bg_stroke = Stroke::new(1.0, HOVER_STROKE); + w.hovered.fg_stroke = Stroke::new(1.0, TEXT); + w.hovered.corner_radius = radius; + w.hovered.expansion = 0.0; + + w.active.bg_fill = PANEL_2; + w.active.weak_bg_fill = PANEL_2; + w.active.bg_stroke = Stroke::new(1.0, HOVER_STROKE); + w.active.fg_stroke = Stroke::new(1.0, TEXT); + w.active.corner_radius = radius; + w.active.expansion = 0.0; + + w.open.bg_fill = PANEL_2; + w.open.weak_bg_fill = PANEL_2; + w.open.bg_stroke = Stroke::new(1.0, HOVER_STROKE); + w.open.fg_stroke = Stroke::new(1.0, TEXT); + w.open.corner_radius = radius; + visuals +} diff --git a/senbei-gui/src/ui/compare.rs b/senbei-gui/src/ui/compare.rs new file mode 100644 index 0000000..af85b0d --- /dev/null +++ b/senbei-gui/src/ui/compare.rs @@ -0,0 +1,583 @@ +//! The compare tab: the protected input's headers and sections beside the +//! restored image's. + +use egui::{ComboBox, CornerRadius, Rect, RichText, ScrollArea, Sense, Ui, pos2, vec2}; +use senbei_engine::windows::{PeInspection, SectionInspection}; + +use super::detail::padded; +use super::hex::{self, Subject}; +use super::table::{self, col}; +use super::widgets::{self, CardSpec}; +use super::{Draw, HexView, ViewState}; +use crate::format; +use crate::labels::tv; +use crate::model::{Item, ItemResult}; +use crate::text::{Text, t}; +use crate::theme::{self, Tone}; + +/// Longest stretch of a section the byte comparison covers. +const COMPARE_LIMIT: u64 = 1024 * 1024; +const ROW: f32 = 19.0; + +/// One compared value: label, original, restored, changed. +struct Field { + label: String, + original: String, + restored: String, + changed: bool, +} + +fn field(label: impl Into, original: String, restored: String) -> Field { + let changed = original != restored; + Field { + label: label.into(), + original, + restored, + changed, + } +} + +fn opt(value: Option>, width: usize) -> String { + value.map_or_else(|| "—".into(), |value| format::hex_w(value.into(), width)) +} + +fn header_fields(a_len: u64, b_len: u64, a: &PeInspection, b: &PeInspection) -> Vec { + let entry = t(Text::PeEntry); + let overlay = |pe: &PeInspection| { + pe.overlay + .as_ref() + .map_or_else(|| "—".into(), |overlay| format::bytes(overlay.length)) + }; + vec![ + field( + t(Text::CmpFileSize), + format::bytes(a_len), + format::bytes(b_len), + ), + field( + format!("{entry} (RVA)"), + opt(a.entry_point_rva, 0), + opt(b.entry_point_rva, 0), + ), + field( + format!("{entry} ({})", t(Text::ColFileOffset)), + opt(a.entry_point_file_offset, 0), + opt(b.entry_point_file_offset, 0), + ), + field("ImageBase", opt(a.image_base, 0), opt(b.image_base, 0)), + field( + "SizeOfImage", + opt(a.size_of_image, 0), + opt(b.size_of_image, 0), + ), + field( + "SizeOfHeaders", + opt(a.size_of_headers, 0), + opt(b.size_of_headers, 0), + ), + field( + t(Text::PeAlignment), + format!( + "{} / {}", + opt(a.section_alignment, 0), + opt(a.file_alignment, 0) + ), + format!( + "{} / {}", + opt(b.section_alignment, 0), + opt(b.file_alignment, 0) + ), + ), + field( + "Characteristics", + opt(a.characteristics, 4), + opt(b.characteristics, 4), + ), + field( + "DllCharacteristics", + opt(a.dll_characteristics, 4), + opt(b.dll_characteristics, 4), + ), + field( + t(Text::CmpSections), + a.sections.len().to_string(), + b.sections.len().to_string(), + ), + field( + tv("region", &senbei_engine::windows::FileRegionKind::Overlay), + overlay(a), + overlay(b), + ), + ] +} + +/// A three-column table whose changed rows get the soft warn fill and a +/// warn-coloured restored value, as in the mockup. +fn changed_table(ui: &mut Ui, id: &str, head: [String; 3], rows: &[Field], mono_label: bool) { + let [name, original, restored] = head; + let cols = [col(name), col(original), col(restored)]; + ui.scope(|ui| { + // Changed rows reuse the table's selection highlight; keep their text + // colour so the labels do not read as links. + let visuals = ui.visuals_mut(); + visuals.selection.bg_fill = Tone::Warn.soft(); + visuals.selection.stroke.color = theme::TEXT; + changed_rows(ui, id, &cols, rows, mono_label); + }); +} + +fn changed_rows(ui: &mut Ui, id: &str, cols: &[table::Col], rows: &[Field], mono_label: bool) { + table::table( + ui, + id, + cols, + rows.len(), + |_| table::lines(1), + |index, row| { + let field = &rows[index]; + row.set_selected(field.changed); + let label = RichText::new(&field.label); + table::text( + row, + if mono_label { + label.font(theme::mono_small()) + } else { + label + }, + ); + table::mono(row, field.original.clone()); + let restored = RichText::new(&field.restored).font(theme::mono_small()); + table::text( + row, + if field.changed { + restored.color(theme::WARN) + } else { + restored + }, + ); + }, + ); +} + +fn section_cell(section: Option<&SectionInspection>) -> String { + section.map_or_else( + || "—".into(), + |section| { + format!( + "{} · {} · {}+{}", + format::hex(u64::from(section.virtual_address)), + format::hex(u64::from(section.virtual_size)), + format::hex(u64::from(section.raw_offset)), + format::hex(u64::from(section.raw_size)) + ) + }, + ) +} + +pub fn tab<'a>( + ui: &mut Ui, + draw: &mut Draw<'a>, + view: &mut ViewState, + item: &'a Item, + result: &'a ItemResult, +) { + let Some(research) = &result.report.research else { + return; + }; + let (Some(a), Some(restored)) = (&research.input.pe, &research.restored) else { + return; + }; + let Some(b) = &restored.pe else { + return; + }; + let fields = header_fields(research.input.input_len, restored.input_len, a, b); + let mut names: Vec<&str> = Vec::new(); + for section in a.sections.iter().chain(&b.sections) { + if !names.contains(§ion.name.as_str()) { + names.push(§ion.name); + } + } + let section_rows: Vec = names + .iter() + .map(|name| { + let x = a.sections.iter().find(|section| section.name == *name); + let y = b.sections.iter().find(|section| section.name == *name); + let changed = match (x, y) { + (Some(x), Some(y)) => { + x.raw_offset != y.raw_offset + || x.raw_size != y.raw_size + || x.virtual_size != y.virtual_size + || x.characteristics != y.characteristics + } + _ => true, + }; + Field { + label: (*name).to_owned(), + original: section_cell(x), + restored: section_cell(y), + changed, + } + }) + .collect(); + let directory_rows: Vec = a + .directories + .iter() + .zip(&b.directories) + .filter(|(x, y)| x.size > 0 || y.size > 0) + .map(|(x, y)| Field { + label: x.name.to_owned(), + original: format!( + "{} +{}", + format::hex(u64::from(x.address)), + format::hex(u64::from(x.size)) + ), + restored: format!( + "{} +{}", + format::hex(u64::from(y.address)), + format::hex(u64::from(y.size)) + ), + changed: x.address != y.address || x.size != y.size, + }) + .collect(); + let shared: Vec = a + .sections + .iter() + .filter(|section| b.sections.iter().any(|other| other.name == section.name)) + .map(|section| section.name.clone()) + .collect(); + if !view + .compare_section + .as_ref() + .is_some_and(|name| shared.contains(name)) + { + view.compare_section = shared + .iter() + .find(|name| *name == ".text") + .or(shared.first()) + .cloned(); + view.compare_diff = None; + } + let subject = Subject::Item(item); + let spliced = research.input_view == senbei_io::report::ResearchInputView::SplicedCompanion; + let original_view = if spliced { + HexView::Spliced + } else { + HexView::Original + }; + let original = hex::view_bytes(draw, &subject, original_view); + let restored_bytes = hex::view_bytes(draw, &subject, HexView::Restored); + + padded(ui, ("compare", item.id), |ui| { + if !fields.iter().any(|field| field.changed) { + widgets::pill(ui, t(Text::CmpNoChange), Tone::Ok); + ui.add_space(12.0); + } + let head = [ + t(Text::ColField).into_owned(), + t(Text::CmpOriginal).into_owned(), + t(Text::CmpRestored).into_owned(), + ]; + let name_head = [ + t(Text::ColName).into_owned(), + t(Text::CmpOriginal).into_owned(), + t(Text::CmpRestored).into_owned(), + ]; + let directories_aside = format!("RVA +{}", t(Text::ColSize)); + widgets::card_grid( + ui, + ("compare-cards", item.id), + vec![ + CardSpec::new(t(Text::CmpHeaders), |ui| { + changed_table(ui, "compare-fields", head, &fields, false); + }), + CardSpec::new(t(Text::RsDirectories), |ui| { + changed_table(ui, "compare-dirs", name_head.clone(), &directory_rows, true); + }) + .aside(move |ui| { + ui.label(widgets::faint(directories_aside).font(theme::small())); + }), + ], + ); + let sections_aside = format!( + "RVA · {} · {}+{}", + t(Text::ColVsize), + t(Text::ColRawOffset), + t(Text::ColRawSize) + ); + widgets::wide_card( + ui, + CardSpec::new(t(Text::RsSections), |ui| { + changed_table( + ui, + "compare-sections", + name_head.clone(), + §ion_rows, + true, + ); + }) + .aside(move |ui| { + ui.label(widgets::faint(sections_aside).font(theme::small())); + }), + ); + ui.add_space(12.0); + let mut next = false; + let section_name = view.compare_section.clone().unwrap_or_default(); + let mut chosen = None; + widgets::wide_card( + ui, + CardSpec::new(t(Text::CmpBytes), |ui| { + let x = a + .sections + .iter() + .find(|section| section.name == section_name); + let y = b + .sections + .iter() + .find(|section| section.name == section_name); + match (x, y, &original, &restored_bytes) { + (Some(x), Some(y), Ok(left), Ok(right)) => { + let view_name = t(if spliced { + Text::HexVSpliced + } else { + Text::HexVOriginal + }); + compare_bytes(ui, view, x, y, left, right, &view_name); + } + (_, _, Err(Some(message)), _) | (_, _, _, Err(Some(message))) => { + widgets::note(ui, message.clone()); + } + _ => { + ui.spinner(); + } + } + }) + .aside(|ui| { + ComboBox::from_id_salt(("compare-section", item.id)) + .selected_text(§ion_name) + .show_ui(ui, |ui| { + for name in &shared { + if ui.selectable_label(*name == section_name, name).clicked() { + chosen = Some(name.clone()); + } + } + }) + .response + .accessible_name(t(Text::RsSections)); + if widgets::ghost_button(ui, t(Text::CmpNextDiff)).clicked() { + next = true; + } + }), + ); + if let Some(name) = chosen { + view.compare_section = Some(name); + view.compare_diff = None; + } + if next { + // Advanced on the next frame, once the rows are known. + ui.ctx() + .data_mut(|data| data.insert_temp(egui::Id::unique("compare-next"), true)); + ui.ctx().request_repaint(); + } + }); +} + +#[allow(clippy::too_many_arguments)] +fn compare_bytes( + ui: &mut Ui, + view: &mut ViewState, + x: &SectionInspection, + y: &SectionInspection, + left: &[u8], + right: &[u8], + view_name: &str, +) { + let a_start = u64::from(x.raw_offset); + let b_start = u64::from(y.raw_offset); + let available = |bytes: &[u8], start: u64, size: u32| { + (bytes.len() as u64) + .saturating_sub(start) + .min(u64::from(size)) + }; + let len = available(left, a_start, x.raw_size) + .min(available(right, b_start, y.raw_size)) + .min(COMPARE_LIMIT); + let a = &left[a_start as usize..(a_start + len) as usize]; + let b = &right[b_start as usize..(b_start + len) as usize]; + let rows = len.div_ceil(16) as usize; + let mut differing = 0usize; + let mut diff_rows = Vec::new(); + for row in 0..rows { + let start = row * 16; + let end = (start + 16).min(a.len()); + let count = a[start..end] + .iter() + .zip(&b[start..end]) + .filter(|(p, q)| p != q) + .count(); + if count > 0 { + differing += count; + diff_rows.push(row); + } + } + let advance = ui + .ctx() + .data_mut(|data| data.remove_temp::(egui::Id::unique("compare-next"))) + .unwrap_or(false); + let mut scroll_to = None; + if advance && !diff_rows.is_empty() { + let next = view + .compare_diff + .map_or(0, |index| (index + 1) % diff_rows.len()); + view.compare_diff = Some(next); + scroll_to = Some(diff_rows[next]); + } + let current_row = view + .compare_diff + .and_then(|index| diff_rows.get(index)) + .copied(); + widgets::note( + ui, + t(Text::CmpBytesNote { + len: format::hex(len), + n: format::num(differing as u64), + s: x.name.clone(), + }), + ); + ui.add_space(8.0); + let font = theme::mono(); + let char_width = ui + .painter() + .layout_no_wrap("0".into(), font.clone(), theme::TEXT) + .size() + .x; + let column = |index: usize| (index * 3 + usize::from(index >= 8)) as f32 * char_width; + let block = column(15) + 2.0 * char_width; + let offset_width = 6.0 * char_width; + let left_x = 4.0 + 14.0 + offset_width + 14.0; + let right_x = left_x + block + 14.0; + egui::Frame::new() + .fill(theme::WELL) + .stroke(egui::Stroke::new(1.0, theme::BORDER)) + .corner_radius(CornerRadius::same(4)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + // Column heads. + let (head, _) = + ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::hover()); + let painter = ui.painter(); + let left_head = format!( + "{} · {view_name} @ {}", + t(Text::CmpOriginal), + format::hex(a_start) + ); + let right_head = format!("{} @ {}", t(Text::CmpRestored), format::hex(b_start)); + painter.text( + pos2(head.left() + left_x, head.center().y), + egui::Align2::LEFT_CENTER, + left_head, + theme::small(), + theme::DIM, + ); + painter.text( + pos2(head.left() + right_x, head.center().y), + egui::Align2::LEFT_CENTER, + right_head, + theme::small(), + theme::DIM, + ); + painter.hline( + head.x_range(), + head.bottom(), + egui::Stroke::new(1.0, theme::BORDER), + ); + let mut area = ScrollArea::vertical() + .id_salt(("compare-rows", x.name.as_str())) + .max_height(360.0) + .auto_shrink([false, true]); + if let Some(row) = scroll_to { + area = area.vertical_scroll_offset((row as f32 * ROW - 2.0 * ROW).max(0.0)); + } + ui.spacing_mut().item_spacing.y = 0.0; + area.show_rows(ui, ROW, rows, |ui, range| { + for row in range { + let (rect, _) = + ui.allocate_exact_size(vec2(ui.available_width(), ROW), Sense::hover()); + paint_row( + ui, + rect, + row, + a, + b, + current_row == Some(row), + (left_x, right_x, offset_width), + &column, + ); + } + }); + }); +} + +#[allow(clippy::too_many_arguments)] +fn paint_row( + ui: &Ui, + rect: Rect, + row: usize, + a: &[u8], + b: &[u8], + current: bool, + (left_x, right_x, offset_width): (f32, f32, f32), + column: &dyn Fn(usize) -> f32, +) { + let painter = ui.painter(); + let font = theme::mono(); + let start = row * 16; + let end = (start + 16).min(a.len()); + let any = a[start..end] != b[start..end]; + if current { + painter.rect_filled(rect, 0, theme::accent_soft()); + } + let strip = Rect::from_min_size(rect.min, vec2(4.0, rect.height())); + if current { + painter.rect_filled(strip, 0, theme::ACCENT); + } else if any { + painter.rect_filled(strip, 0, theme::ERR.gamma_multiply(0.55)); + } + painter.text( + pos2(rect.left() + 18.0 + offset_width, rect.top() + 1.0), + egui::Align2::RIGHT_TOP, + format!("+{start:04X}"), + font.clone(), + theme::FAINT, + ); + for (index, (p, q)) in a[start..end].iter().zip(&b[start..end]).enumerate() { + let differs = p != q; + for (x, value) in [(left_x, *p), (right_x, *q)] { + let at = pos2(rect.left() + x + column(index), rect.top()); + if differs { + let width = painter + .layout_no_wrap("00".into(), font.clone(), theme::TEXT) + .size() + .x; + painter.rect_filled( + Rect::from_min_size(at - vec2(1.0, 0.0), vec2(width + 2.0, ROW)), + 0, + theme::diff(), + ); + } + let color = if differs { + egui::Color32::from_rgb(0xff, 0xd9, 0xd9) + } else if value == 0 { + theme::ZERO_BYTE + } else { + theme::TEXT + }; + painter.text( + at + vec2(0.0, 1.0), + egui::Align2::LEFT_TOP, + format!("{value:02X}"), + font.clone(), + color, + ); + } + } +} diff --git a/senbei-gui/src/ui/detail.rs b/senbei-gui/src/ui/detail.rs new file mode 100644 index 0000000..3012e89 --- /dev/null +++ b/senbei-gui/src/ui/detail.rs @@ -0,0 +1,2087 @@ +//! The detail pane: what the selected group, input, or entry is and what its +//! last run found. + +use std::collections::HashSet; + +use egui::{ + Align, CornerRadius, Frame, Layout, Margin, Rect, RichText, ScrollArea, Sense, Stroke, + StrokeKind, Ui, pos2, vec2, +}; +use senbei_engine::{Platform, ProtectionProfile, RecognitionStatus, ValidationStatus}; +use senbei_i18n::Message; +use senbei_io::report::{ + CompanionState, EntryReport, EntryStatus, InputReport, InputStatus, Mode, Role, Stage, + StageStatus, +}; +use serde_json::Value; + +use super::table::{self, col, num_col}; +use super::widgets::{self, CardSpec, MsgKind}; +use super::{Action, Draw, Tab, ViewState, hex, logview, research}; +use crate::backend::{Identity, Output}; +use crate::format; +use crate::labels::{self, Shown, step_title, tv}; +use crate::model::{ + Group, Item, ItemResult, RunState, Sel, Verdict, entry_inner, entry_source, entry_tag, + format_label, identity_format, is_target_entry, kind_tag, mode_label, +}; +use crate::text::{Text, t}; +use crate::theme::{self, Tone}; + +// ------------------------------------------------------------------ shell + +pub struct TabSpec { + pub tab: Tab, + pub label: String, + pub badge: Option, +} + +fn tab(tab: Tab, text: Text) -> TabSpec { + TabSpec { + tab, + label: t(text).into_owned(), + badge: None, + } +} + +/// The head of a detail view. +pub struct Head { + pub title: String, + pub tag: Option, + pub pills: Vec<(String, Tone)>, + pub path: String, + pub tabs: Vec, + pub export: Option, +} + +fn pill_width(ui: &Ui, text: &str) -> f32 { + ui.painter() + .layout_no_wrap(text.to_owned(), theme::small(), theme::TEXT) + .size() + .x + + 18.0 +} + +/// A detail view: title row, path line, tabs, and a body on the panel colour. +pub fn shell<'a>( + ui: &mut Ui, + draw: &mut Draw<'a>, + view: &mut ViewState, + head: Head, + body: impl FnOnce(&mut Ui, &mut Draw<'a>, &mut ViewState), +) { + if !head.tabs.is_empty() && !head.tabs.iter().any(|spec| spec.tab == view.tab) { + view.tab = head.tabs[0].tab; + } + let has_tabs = !head.tabs.is_empty(); + let mut selected_tab: Option = None; + let header = Frame::new() + .fill(theme::BG) + .inner_margin(Margin { + left: 16, + right: 16, + top: 10, + bottom: if has_tabs { 0 } else { 4 }, + }) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.spacing_mut().item_spacing.y = 2.0; + ui.horizontal(|ui| { + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = 4.0; + if let Some(sel) = head.export { + if widgets::ghost_button(ui, t(Text::DetailExportText)).clicked() { + draw.act(Action::Export { sel, json: false }); + } + if widgets::ghost_button(ui, t(Text::DetailExportJson)).clicked() { + draw.act(Action::Export { sel, json: true }); + } + } + ui.with_layout(Layout::left_to_right(Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = 10.0; + let reserved: f32 = head + .pills + .iter() + .map(|(text, _)| pill_width(ui, text) + 10.0) + .sum::() + + head + .tag + .as_deref() + .map_or(0.0, |tag| pill_width(ui, tag) + 10.0); + let title_width = (ui.available_width() - reserved).max(80.0); + ui.scope(|ui| { + ui.set_max_width(title_width); + ui.add( + egui::Label::new( + RichText::new(&head.title).font(theme::strong(17.0)), + ) + .truncate(), + ); + }); + if let Some(tag) = &head.tag { + widgets::tag(ui, tag); + } + for (text, tone) in &head.pills { + widgets::pill(ui, text, *tone); + } + }); + }); + }); + if !head.path.is_empty() { + ui.add_space(2.0); + ui.add( + egui::Label::new( + RichText::new(&head.path) + .font(theme::mono_small()) + .color(theme::FAINT), + ) + .truncate() + .selectable(true), + ); + } + ui.add_space(if has_tabs { 6.0 } else { 0.0 }); + if has_tabs { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + for spec in &head.tabs { + let on = spec.tab == view.tab; + let (rect, clicked) = tab_button(ui, spec, on); + if on { + selected_tab = Some(rect); + } + if clicked { + view.tab = spec.tab; + } + } + }); + } + }); + // The header's bottom border, open under the selected tab. + let rect = header.response.rect; + let stroke = Stroke::new(1.0, theme::BORDER); + let y = rect.bottom() - 0.5; + match selected_tab { + Some(tab) => { + ui.painter().hline(rect.left()..=tab.left(), y, stroke); + ui.painter().hline(tab.right()..=rect.right(), y, stroke); + } + None => { + ui.painter().hline(rect.x_range(), y, stroke); + } + } + let body_rect = ui.available_rect_before_wrap(); + ui.painter().rect_filled(body_rect, 0, theme::PANEL); + body(ui, draw, view); +} + +fn tab_button(ui: &mut Ui, spec: &TabSpec, on: bool) -> (Rect, bool) { + let label = ui + .painter() + .layout_no_wrap(spec.label.clone(), theme::body(), theme::TEXT); + let badge = spec.badge.map(|count| { + ui.painter() + .layout_no_wrap(count.to_string(), theme::tiny(), theme::FAINT) + }); + let width = label.size().x + badge.as_ref().map_or(0.0, |badge| badge.size().x + 4.0) + 24.0; + let (rect, response) = ui.allocate_exact_size(vec2(width, 30.0), Sense::click()); + widgets::describe(&response, egui::Role::Tab, &spec.label, Some(on)); + let color = if on || response.hovered() { + theme::TEXT + } else { + theme::DIM + }; + if on { + let painted = rect.translate(vec2(0.0, 1.0)); + ui.painter().rect( + painted, + CornerRadius { + nw: 4, + ne: 4, + sw: 0, + se: 0, + }, + theme::PANEL, + Stroke::NONE, + StrokeKind::Inside, + ); + let stroke = Stroke::new(1.0, theme::BORDER); + let (l, r, top, bottom) = ( + painted.left() + 0.5, + painted.right() - 0.5, + painted.top() + 0.5, + painted.bottom(), + ); + ui.painter().vline(l, top..=bottom, stroke); + ui.painter().vline(r, top..=bottom, stroke); + ui.painter().hline(l..=r, top, stroke); + } + let text_pos = pos2( + rect.left() + 12.0, + rect.center().y - label.size().y / 2.0 + 1.0, + ); + let label_width = label.size().x; + ui.painter().galley(text_pos, label, color); + if let Some(badge) = badge { + let pos = pos2( + text_pos.x + label_width + 4.0, + rect.center().y - badge.size().y / 2.0 + 1.0, + ); + ui.painter().galley(pos, badge, theme::FAINT); + } + (rect, response.clicked()) +} + +/// A padded, scrolling body. +pub fn padded(ui: &mut Ui, id: impl egui::AsIdSalt, add: impl FnOnce(&mut Ui)) { + ScrollArea::vertical() + .id_salt(id) + .auto_shrink([false, false]) + .show(ui, |ui| { + Frame::new() + .inner_margin(Margin { + left: 16, + right: 16, + top: 14, + bottom: 24, + }) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + add(ui); + }); + }); +} + +fn pick(ui: &mut Ui) { + let rect = ui.available_rect_before_wrap(); + ui.painter().rect_filled(rect, 0, theme::PANEL); + ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| { + ui.centered_and_justified(|ui| { + ui.label(widgets::faint(t(Text::DetailPick))); + }); + }); +} + +// --------------------------------------------------------------- dispatch + +pub fn pane(ui: &mut Ui, draw: &mut Draw<'_>, view: &mut ViewState) { + let session = draw.session; + match view.selected { + None => pick(ui), + Some(Sel::Group(id)) => match session.group(id) { + Some(group) if group.scanning.is_some() => scanning(ui, draw, view, group), + Some(group) => group_detail(ui, draw, view, group), + None => pick(ui), + }, + Some(Sel::Item(id)) => match session.item(id) { + Some((_, item)) => item_pane(ui, draw, view, item), + None => pick(ui), + }, + Some(Sel::Entry(id, index)) => { + match session + .item(id) + .and_then(|(_, item)| item.entries().get(index).map(|entry| (item, entry))) + { + Some((item, entry)) => entry_detail(ui, draw, view, item, index, entry), + None => pick(ui), + } + } + } +} + +fn item_pane<'a>(ui: &mut Ui, draw: &mut Draw<'a>, view: &mut ViewState, item: &'a Item) { + match (item.run, &item.result) { + (RunState::Running | RunState::Queued, _) | (RunState::WillNotRun, None) => { + run_detail(ui, draw, view, item) + } + (_, None) => pending(ui, draw, view, item), + (_, Some(result)) if result.report.role == Role::Container => { + package_detail(ui, draw, view, item, result) + } + (_, Some(result)) => item_detail(ui, draw, view, item, result), + } +} + +fn last_run_line(item: &Item, result: &ItemResult) -> String { + format!( + "{} · {}", + item.path.display(), + t(Text::DetailLastRun { + mode: mode_label(result.mode).into_owned(), + t: format::ms(result.report.duration_ms), + }) + ) +} + +// ----------------------------------------------------------------- groups + +fn group_detail<'a>(ui: &mut Ui, draw: &mut Draw<'a>, view: &mut ViewState, group: &'a Group) { + let live = draw + .jobs + .running + .as_ref() + .and_then(|running| running.group_runs.get(&group.id)); + let run = live.or(group.last_run.as_ref()); + let has_results = group.items.iter().any(|item| item.result.is_some()); + let pill = if live.is_some() { + Some((t(Text::RunRunning).into_owned(), Tone::Info)) + } else { + run.map(|run| (mode_label(run.mode).into_owned(), Tone::Info)) + }; + let head = Head { + title: group.title().into_owned(), + tag: None, + pills: pill.into_iter().collect(), + path: group + .root() + .map(|root| root.display().to_string()) + .unwrap_or_default(), + tabs: vec![ + tab(Tab::Overview, Text::TabOverview), + tab(Tab::Log, Text::TabLog), + ], + export: has_results.then_some(Sel::Group(group.id)), + }; + shell(ui, draw, view, head, |ui, draw, view| { + if view.tab == Tab::Log { + let lines = run.map(|run| run.log.as_slice()).unwrap_or_default(); + logview::log_view(ui, view, ("group-log", group.id), lines); + return; + } + let counts = group.counts(); + let duration = match run { + Some(run) if run.duration_ms > 0 => run.duration_ms, + _ => group + .items + .iter() + .filter_map(|item| item.result.as_ref()) + .map(|result| result.report.duration_ms) + .sum(), + }; + padded(ui, ("group", group.id), |ui| { + let scan = group.scan; + let incomplete = scan.is_some_and(|scan| scan.walk_errors > 0 || scan.probe_errors > 0); + let mut blocks: Vec<(MsgKind, Shown)> = Vec::new(); + if incomplete { + blocks.push(( + MsgKind::Warning, + Shown { + text: t(Text::BatchScanIncomplete).into_owned(), + technical: None, + quiet: false, + }, + )); + } + for error in run.map(|run| run.errors.as_slice()).unwrap_or_default() { + blocks.push((MsgKind::Error, labels::message(error))); + } + if !blocks.is_empty() { + widgets::wide_card( + ui, + CardSpec::new(t(Text::OvMessages), move |ui| { + widgets::messages(ui, &blocks) + }), + ); + ui.add_space(12.0); + } + let mut cards = vec![ + CardSpec::new(t(Text::BatchSummary), move |ui| { + let keys = [ + t(Text::BatchInputs), + t(Text::FilterOk), + t(Text::FilterSuspect), + t(Text::FilterFailed), + t(Text::FilterSkipped), + ]; + let refs: Vec<&str> = keys.iter().map(|key| key.as_ref()).collect(); + widgets::kv(ui, &refs, |rows| { + rows.text(&keys[0], counts.inputs.to_string()); + rows.text( + &keys[1], + widgets::toned(counts.recovered.to_string(), Tone::Ok), + ); + rows.text(&keys[2], count_text(counts.suspect, Tone::Warn)); + rows.text(&keys[3], count_text(counts.failed, Tone::Err)); + rows.text(&keys[4], counts.skipped.to_string()); + }); + }) + .aside(move |ui| { + // Nothing has run yet: no time to show. + if has_results || duration > 0 { + ui.label(widgets::faint(format::ms(duration)).font(theme::small())); + } + }), + ]; + if let Some(scan) = scan { + cards.push(CardSpec::new(t(Text::BatchScan), move |ui| { + let keys = [ + t(Text::BatchNonTarget), + t(Text::BatchWalkErrors), + t(Text::BatchProbeErrors), + ]; + let refs: Vec<&str> = keys.iter().map(|key| key.as_ref()).collect(); + widgets::kv(ui, &refs, |rows| { + rows.text(&keys[0], scan.non_target_skipped.to_string()); + rows.text(&keys[1], count_text(scan.walk_errors, Tone::Warn)); + rows.text(&keys[2], count_text(scan.probe_errors, Tone::Warn)); + }); + ui.add_space(8.0); + widgets::note(ui, t(Text::BatchScanNote)); + })); + } + widgets::card_grid(ui, ("group-cards", group.id), cards); + let actions = &mut *draw.actions; + widgets::wide_card( + ui, + CardSpec::new(t(Text::BatchInputs), |ui| { + group_table(ui, actions, group); + }), + ); + }); + }); +} + +fn count_text(count: usize, tone: Tone) -> RichText { + if count > 0 { + widgets::toned(count.to_string(), tone) + } else { + RichText::new(count.to_string()) + } +} + +fn group_table(ui: &mut Ui, actions: &mut Vec, group: &Group) { + let cols = [ + col("").width(18.0), + col(t(Text::ColName)).width(260.0).grow(), + col(t(Text::ColType)).width(130.0), + col(t(Text::ColOutcome)).width(130.0), + col(t(Text::ColRoute)).width(210.0), + num_col(t(Text::ColTime)).width(80.0), + ]; + let items = &group.items; + let mut clicked = None; + table::table_clickable( + ui, + ("group-table", group.id), + &cols, + items.len(), + |_| table::lines(1), + |index, row| { + let item = &items[index]; + // The same state the inputs panel shows for this row. + let state = super::inputs::row_state(item); + table::cell(row, |ui| { + widgets::dot(ui, state.dot); + }); + table::text(row, item.name.clone()); + table::cell(row, |ui| { + widgets::tag(ui, kind_tag(item)); + }); + table::text(row, RichText::new(state.label).color(state.color)); + let route = match &item.result { + Some(result) if result.report.container.is_some() => t(Text::EntriesSummary { + n: result + .report + .entries + .iter() + .filter(|entry| is_target_entry(entry)) + .count() + .to_string(), + }) + .into_owned(), + Some(result) => result + .report + .profile + .as_ref() + .and_then(|profile| profile.selected) + .map(|layout| tv("layout", &layout).into_owned()) + .unwrap_or_else(|| "—".into()), + None => String::new(), + }; + table::text(row, route); + table::num(row, state.time.unwrap_or_default()); + }, + |index| clicked = Some(index), + ); + if let Some(index) = clicked { + actions.push(Action::Select { + sel: Sel::Item(items[index].id), + toggle: false, + }); + } +} + +fn scanning<'a>(ui: &mut Ui, draw: &mut Draw<'a>, view: &mut ViewState, group: &'a Group) { + let head = Head { + title: group.title().into_owned(), + tag: None, + pills: vec![(t(Text::ScanRunning).into_owned(), Tone::Info)], + path: group + .root() + .map(|root| root.display().to_string()) + .unwrap_or_default(), + tabs: Vec::new(), + export: None, + }; + let found = group.scanning.unwrap_or_default(); + shell(ui, draw, view, head, |ui, _, _| { + padded(ui, ("scanning", group.id), |ui| { + widgets::wide_card( + ui, + CardSpec::new(t(Text::BatchScan), move |ui| { + let key = t(Text::ScanFound); + widgets::kv(ui, &[&key], |rows| { + rows.text(&key, found.to_string()); + }); + ui.add_space(8.0); + widgets::note(ui, t(Text::BatchScanNote)); + }), + ); + }); + }); +} + +// ----------------------------------------------------- inputs not yet run + +fn pending<'a>(ui: &mut Ui, draw: &mut Draw<'a>, view: &mut ViewState, item: &'a Item) { + let not_protected = item.identity.as_ref().is_some_and(Identity::not_protected); + let head = Head { + title: item.name.clone(), + tag: Some(kind_tag(item)), + pills: vec![( + t(if not_protected { + Text::PendingNotProtected + } else { + Text::PendingNotRun + }) + .into_owned(), + Tone::Skip, + )], + path: item.path.display().to_string(), + tabs: vec![ + tab(Tab::Overview, Text::TabOverview), + tab(Tab::Hex, Text::TabHex), + ], + export: None, + }; + let caps = draw.caps; + shell(ui, draw, view, head, |ui, draw, view| { + if view.tab == Tab::Hex { + hex::tab(ui, draw, view, hex::Subject::Item(item)); + return; + } + let actions = &mut *draw.actions; + padded(ui, ("pending", item.id), |ui| { + let unreadable = match &item.identity { + Some(Identity::Unreadable(error)) => Some(labels::note(error)), + Some(Identity::NotAFile) => Some(labels::note(&t(Text::PendingNotAFile))), + _ => None, + }; + if let Some(error) = unreadable { + widgets::wide_card( + ui, + CardSpec::new(t(Text::OvMessages), |ui| { + widgets::messages(ui, &[(MsgKind::Error, error)]); + }), + ); + ui.add_space(12.0); + } + if let Some(Identity::Package { + container: Err(error), + .. + }) = &item.identity + { + widgets::wide_card( + ui, + CardSpec::new(t(Text::OvMessages), |ui| { + widgets::messages(ui, &[(MsgKind::Error, labels::note(error))]); + }), + ); + ui.add_space(12.0); + } + let cards = vec![ + CardSpec::new(t(Text::PendingIdentified), |ui| identity_rows(ui, item)), + CardSpec::new(t(Text::PendingNext), move |ui| { + next_actions(ui, actions, item, not_protected, caps.unpack); + }), + ]; + widgets::card_grid(ui, ("pending-cards", item.id), cards); + }); + }); +} + +fn identity_rows(ui: &mut Ui, item: &Item) { + let Some(identity) = &item.identity else { + ui.spinner(); + return; + }; + let mut rows: Vec<(String, widgets::Body<'_>)> = Vec::new(); + let text_row = |key: Text, value: RichText| -> (String, widgets::Body<'static>) { + ( + t(key).into_owned(), + Box::new(move |ui: &mut Ui| { + widgets::selectable(ui, value); + }), + ) + }; + match identity { + Identity::Package { + container: Ok(container), + .. + } => { + rows.push(text_row( + Text::PkgKind, + RichText::new(container.kind.to_uppercase()), + )); + if let Some(named) = container.manifests.iter().find(|manifest| manifest.named) { + let package = named.package.clone().unwrap_or_default(); + let version = named.version.clone().unwrap_or_default(); + rows.push(( + t(Text::PkgPackage).into_owned(), + Box::new(move |ui: &mut Ui| { + widgets::selectable(ui, widgets::mono(package)); + ui.label(widgets::faint(version)); + }), + )); + } + rows.push(text_row( + Text::PkgEntries, + RichText::new(format::num(container.entry_count as u64)), + )); + rows.push(text_row( + Text::PkgCandidates, + RichText::new(format::num(container.candidate_entries.len() as u64)), + )); + } + Identity::Windows { + size, + profile, + companion, + companion_path, + } => { + rows.push(text_row( + Text::OvPlatform, + RichText::new(tv("platform", &profile.observed.platform)), + )); + rows.push(text_row( + Text::OvFormat, + widgets::mono(format_label(profile.observed.format)), + )); + if let Some(kind) = profile.observed.kind { + rows.push(text_row(Text::OvKind, RichText::new(tv("kind", &kind)))); + } + rows.push(text_row( + Text::OvSource, + RichText::new(format::bytes(*size)), + )); + if *companion != CompanionState::Absent { + let state = if *companion == CompanionState::Spliced { + t(Text::CompanionPaired).into_owned() + } else { + tv("companion", companion).into_owned() + }; + let name = companion_path + .as_deref() + .map(|path| format::base_name(path).to_owned()); + rows.push(( + t(Text::OvCompanion).into_owned(), + Box::new(move |ui: &mut Ui| { + ui.label(state); + if let Some(name) = name { + ui.label("·"); + widgets::selectable(ui, widgets::mono(name)); + } + }), + )); + } + } + Identity::Metadata { size, identity } => { + rows.push(text_row( + Text::OvPlatform, + RichText::new(tv("platform", &Platform::Il2cppMetadata)), + )); + if let Some(identity) = identity { + rows.push(text_row( + Text::OvMetadataVersion, + RichText::new(identity.raw_version.to_string()), + )); + } + rows.push(text_row( + Text::OvSource, + RichText::new(format::bytes(*size)), + )); + } + Identity::AndroidLibrary { size } => { + rows.push(text_row( + Text::OvPlatform, + RichText::new(tv("platform", &Platform::AndroidElf)), + )); + rows.push(text_row(Text::OvFormat, widgets::mono("ELF64 AArch64"))); + rows.push(text_row( + Text::OvSource, + RichText::new(format::bytes(*size)), + )); + } + Identity::NotTarget { size } => { + rows.push(text_row( + Text::OvSource, + RichText::new(format::bytes(*size)), + )); + } + Identity::Package { + container: Err(_), + size, + } => { + rows.push(text_row( + Text::OvSource, + RichText::new(format::bytes(*size)), + )); + } + Identity::Unreadable(_) | Identity::NotAFile => {} + } + let keys: Vec = rows.iter().map(|(key, _)| key.clone()).collect(); + let refs: Vec<&str> = keys.iter().map(String::as_str).collect(); + widgets::kv(ui, &refs, |kv| { + for (key, value) in rows { + kv.row(key, value); + } + }); +} + +fn next_actions( + ui: &mut Ui, + actions: &mut Vec, + item: &Item, + not_protected: bool, + can_unpack: bool, +) { + let choices = [ + (Mode::Unpack, Text::TbUnpack, Text::PendingUnpackDesc, true), + (Mode::DryRun, Text::TbDryRun, Text::PendingDryRunDesc, false), + ( + Mode::Inspect, + Text::TbInspect, + Text::PendingInspectDesc, + false, + ), + ]; + for (index, (mode, label, desc, primary)) in choices.into_iter().enumerate() { + if index > 0 { + widgets::rule(ui); + } + ui.add_space(6.0); + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = 10.0; + let enabled = !not_protected && (mode != Mode::Unpack || can_unpack); + let clicked = ui + .allocate_ui_with_layout( + vec2(110.0, 24.0), + Layout::top_down_justified(Align::Min), + |ui| { + if primary { + widgets::primary_button(ui, t(label), enabled).clicked() + } else { + ui.add_enabled( + enabled, + egui::Button::new(t(label)).min_size(vec2(110.0, 24.0)), + ) + .clicked() + } + }, + ) + .inner; + if clicked { + actions.push(Action::RunItem(mode, item.id)); + } + ui.add(egui::Label::new(widgets::dim(t(desc))).wrap()); + }); + ui.add_space(6.0); + } + if not_protected { + ui.add_space(8.0); + widgets::note(ui, t(Text::PendingNotProtectedNote)); + } +} + +// --------------------------------------------------------- running inputs + +fn run_detail<'a>(ui: &mut Ui, draw: &mut Draw<'a>, view: &mut ViewState, item: &'a Item) { + let (label, tone) = match item.run { + RunState::Running => (t(Text::RunRunning), Tone::Info), + RunState::Queued => (t(Text::RunQueued), Tone::Skip), + _ => (t(Text::RunWillNotRun), Tone::Skip), + }; + let head = Head { + title: item.name.clone(), + tag: Some(kind_tag(item)), + pills: vec![(label.into_owned(), tone)], + path: item.path.display().to_string(), + tabs: Vec::new(), + export: None, + }; + let running = draw + .jobs + .running + .as_ref() + .filter(|running| running.current == Some(item.id)); + let state = item.run; + shell(ui, draw, view, head, |ui, _, view| match state { + RunState::Running => { + padded(ui, ("running", item.id), |ui| { + widgets::wide_card( + ui, + CardSpec::new(t(Text::RunProgress), |ui| { + let step = running.and_then(|running| running.step.as_ref()); + progress_stages(ui, step); + }), + ); + ui.add_space(12.0); + let lines = running + .map(|running| running.live.as_slice()) + .unwrap_or_default(); + widgets::wide_card( + ui, + CardSpec::new(t(Text::TabLog), |ui| { + logview::log_box(ui, view.log_filter, lines); + }), + ); + }); + } + RunState::Queued => {} + _ => padded(ui, ("will-not-run", item.id), |ui| { + widgets::note(ui, t(Text::RunCancelledNote)); + }), + }); +} + +/// The step a running input is on, as the status bar and progress card show it. +pub fn step_text(step: &(Option<(u8, u8)>, senbei_i18n::Step)) -> String { + let (position, step) = step; + match position { + Some((index, total)) => t(Text::RunStep { + i: index.to_string(), + n: total.to_string(), + s: step_title(step).into_owned(), + }) + .into_owned(), + None => step_title(step).into_owned(), + } +} + +fn progress_stages(ui: &mut Ui, step: Option<&(Option<(u8, u8)>, senbei_i18n::Step)>) { + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(6.0, 6.0); + let detection_done = step.is_some(); + stage_chip( + ui, + if detection_done { + ("✓", Tone::Ok) + } else { + ("●", Tone::Info) + }, + &tv("stage", &Stage::Detection), + None, + if detection_done { + (tv("stageStatus", &StageStatus::Ok).into_owned(), Tone::Ok) + } else { + (t(Text::RunRunning).into_owned(), Tone::Info) + }, + None, + false, + ); + arrow(ui); + stage_chip( + ui, + ("●", Tone::Info), + &tv("stage", &Stage::Recovery), + None, + (step.map(step_text).unwrap_or_default(), Tone::Info), + None, + !detection_done, + ); + arrow(ui); + stage_chip_dimmed(ui, &tv("stage", &Stage::StaticValidation)); + arrow(ui); + stage_chip_dimmed(ui, &tv("stage", &Stage::OutputWrite)); + }); +} + +fn arrow(ui: &mut Ui) { + ui.label(widgets::faint("→")); +} + +fn stage_frame() -> Frame { + Frame::new() + .fill(theme::PANEL) + .stroke(Stroke::new(1.0, theme::BORDER)) + .corner_radius(CornerRadius::same(4)) + .inner_margin(Margin::symmetric(10, 5)) +} + +#[allow(clippy::too_many_arguments)] +fn stage_chip( + ui: &mut Ui, + icon: (&str, Tone), + name: &str, + duration: Option, + status: (String, Tone), + detail: Option, + dimmed: bool, +) { + let opacity = if dimmed { 0.5 } else { 1.0 }; + ui.scope(|ui| { + ui.multiply_opacity(opacity); + stage_frame().show(ui, |ui| { + ui.set_min_width(120.0); + ui.spacing_mut().item_spacing.y = 1.0; + ui.vertical(|ui| { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + ui.label(widgets::toned(icon.0, icon.1).font(theme::strong(12.5))); + ui.label(widgets::strong(name, 12.5)); + if let Some(duration) = duration + && duration > 0 + { + ui.label(widgets::faint(format::ms(duration)).font(theme::small())); + } + }); + if !status.0.is_empty() { + ui.label(widgets::toned(status.0, status.1).font(theme::small())); + } + if let Some(detail) = detail { + ui.scope(|ui| { + ui.set_max_width(360.0); + ui.add(egui::Label::new(widgets::dim(detail).font(theme::small())).wrap()); + }); + } + }); + }); + }); +} + +fn stage_chip_dimmed(ui: &mut Ui, name: &str) { + ui.scope(|ui| { + ui.multiply_opacity(0.5); + stage_frame().show(ui, |ui| { + ui.set_min_width(120.0); + ui.label(widgets::strong(name, 12.5)); + }); + }); +} + +// ------------------------------------------------------------ results + +fn item_detail<'a>( + ui: &mut Ui, + draw: &mut Draw<'a>, + view: &mut ViewState, + item: &'a Item, + result: &'a ItemResult, +) { + let input = &result.report; + let verdict = result.verdict(); + let mut pills = vec![(verdict.label().into_owned(), verdict.tone())]; + if input + .companion + .as_ref() + .is_some_and(|companion| companion.state == CompanionState::Spliced) + { + pills.push((t(Text::CompanionSplicedPill).into_owned(), Tone::Info)); + } + let mut tabs = vec![ + tab(Tab::Overview, Text::TabOverview), + tab(Tab::Research, Text::TabResearch), + tab(Tab::Hex, Text::TabHex), + ]; + if comparable(input) { + tabs.push(tab(Tab::Compare, Text::TabCompare)); + } + tabs.push(tab(Tab::Log, Text::TabLog)); + let head = Head { + title: item.name.clone(), + tag: Some(kind_tag(item)), + pills, + path: last_run_line(item, result), + tabs, + export: Some(Sel::Item(item.id)), + }; + shell(ui, draw, view, head, |ui, draw, view| match view.tab { + Tab::Research => research::tab(ui, draw, view, research::Subject::item(item, result)), + Tab::Hex => hex::tab(ui, draw, view, hex::Subject::Item(item)), + Tab::Compare => super::compare::tab(ui, draw, view, item, result), + Tab::Log => logview::log_view(ui, view, ("item-log", item.id), &result.log), + _ => overview(ui, draw, item, result), + }); +} + +/// True when both the input and its restored image have PE headers. +pub fn comparable(input: &InputReport) -> bool { + input.research.as_ref().is_some_and(|research| { + research.input.pe.is_some() + && research + .restored + .as_ref() + .is_some_and(|restored| restored.pe.is_some()) + }) +} + +/// Every message an input reports, each once, where a reader looks for it. +struct Plan<'a> { + top: Vec<(MsgKind, &'a Message)>, + validation: Vec<(MsgKind, &'a Message)>, + shown: HashSet<&'a str>, +} + +fn message_plan(input: &InputReport) -> Plan<'_> { + let profile = input.profile.as_ref(); + let validation_status = profile.map(|profile| profile.static_validation); + let mut validation: Vec<(MsgKind, &Message)> = Vec::new(); + if matches!( + validation_status, + Some(ValidationStatus::Warnings | ValidationStatus::Failed) + ) && let Some(profile) = profile + { + let errors = profile + .errors + .iter() + .map(|message| (MsgKind::Error, message)); + let warnings = profile + .warnings + .iter() + .map(|message| (MsgKind::Warning, message)); + validation.extend( + errors + .chain(warnings) + .filter(|(_, message)| !message.text().trim().is_empty()), + ); + } + let mut shown: HashSet<&str> = validation + .iter() + .map(|(_, message)| message.text()) + .collect(); + let mut top = Vec::new(); + let mut add = |kind: MsgKind, message| { + let message: &Message = message; + if !message.text().trim().is_empty() + && shown.insert(message.text()) + && !labels::message(message).quiet + { + top.push((kind, message)); + } + }; + for message in &input.errors { + add(MsgKind::Error, message); + } + for message in &input.warnings { + add(MsgKind::Warning, message); + } + if validation.is_empty() + && let Some(profile) = profile + { + for message in &profile.errors { + add(MsgKind::Error, message); + } + for message in &profile.warnings { + add(MsgKind::Warning, message); + } + } + Plan { + top, + validation, + shown, + } +} + +/// Size and hash of produced bytes. +fn identity_value(ui: &mut Ui, size: Option, sha256: Option<&str>) { + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = 2.0; + match (size, sha256) { + (None, None) => { + ui.label("—"); + } + _ => { + if let Some(size) = size { + ui.label(format::bytes(size)); + } + if let Some(sha256) = sha256 { + hash_row(ui, sha256); + } + } + } + }); +} + +pub fn hash_row(ui: &mut Ui, sha256: &str) { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + widgets::selectable(ui, widgets::mono(format::short_hash(sha256))) + .on_hover_text(sha256.to_owned()); + widgets::copy_button(ui, sha256); + }); +} + +fn json_str<'v>(value: &'v Value, key: &str) -> Option<&'v str> { + value.get(key)?.as_str() +} + +fn json_u64(value: &Value, key: &str) -> Option { + value.get(key)?.as_u64() +} + +fn overview<'a>(ui: &mut Ui, draw: &mut Draw<'a>, item: &'a Item, result: &'a ItemResult) { + let input = &result.report; + let caps = draw.caps; + let actions = &mut *draw.actions; + padded(ui, ("overview", item.id), |ui| { + let profile = input.profile.as_ref(); + let plan = message_plan(input); + let skipped = input.status == InputStatus::Skipped; + if !plan.top.is_empty() { + let blocks: Vec<(MsgKind, Shown)> = plan + .top + .iter() + .map(|(kind, message)| { + ( + if skipped { MsgKind::Info } else { *kind }, + labels::message(message), + ) + }) + .collect(); + widgets::wide_card( + ui, + CardSpec::new(t(Text::OvMessages), move |ui| { + widgets::messages(ui, &blocks) + }), + ); + ui.add_space(12.0); + } + let shown = &plan.shown; + // A run that stopped before it read the format still has the format + // the file's header showed when it was added. + let header_format = item.identity.as_ref().and_then(identity_format); + widgets::card_grid( + ui, + ("overview-top", item.id), + vec![ + CardSpec::new(t(Text::OvRecognition), move |ui| { + recognition(ui, profile, header_format.as_deref()) + }) + .aside(move |ui| { + let text = profile + .map(|profile| tv("recognition", &profile.recognition)) + .unwrap_or_else(|| "—".into()); + ui.label(widgets::faint(text).font(theme::small())); + }), + CardSpec::new(t(Text::OvRoutes), |ui| routes(ui, profile, shown)), + ], + ); + if !input.stages.is_empty() { + widgets::wide_card( + ui, + CardSpec::new(t(Text::OvStages), |ui| stages(ui, input, shown)), + ); + ui.add_space(12.0); + } + let mut lower: Vec> = Vec::new(); + if let Some(card) = validation_card(input, &plan) { + lower.push(card); + } + let digests = Digests::of(input); + if !digests.is_empty() { + lower.push(CardSpec::new(t(Text::OvIdentity), move |ui| { + identity_card(ui, actions, caps.reveal, input, digests); + })); + } + if let Some(metadata) = &input.metadata { + lower.push(CardSpec::new(t(Text::OvMetadata), move |ui| { + metadata_card(ui, metadata, &input.provenance); + })); + } + if let Some(valid) = input + .android_research + .as_ref() + .and_then(|research| research.restoration.as_ref()) + .and_then(|restoration| restoration.get("validation")) + .filter(|valid| valid.is_object()) + { + lower.push(CardSpec::new(t(Text::OvRestoredElf), move |ui| { + elf_card(ui, valid); + })); + } + widgets::card_grid(ui, ("overview-lower", item.id), lower); + }); +} + +fn recognition(ui: &mut Ui, profile: Option<&ProtectionProfile>, header_format: Option<&str>) { + let observed = profile.map(|profile| &profile.observed); + let known = profile.is_some_and(|profile| { + profile.recognition != RecognitionStatus::NotAttempted || profile.observed.format.is_some() + }); + let metadata = observed.is_some_and(|observed| observed.platform == Platform::Il2cppMetadata); + let keys = [ + t(Text::OvPlatform), + t(Text::OvFormat), + t(Text::OvKind), + t(Text::OvEvidence), + ]; + let refs: Vec<&str> = keys.iter().map(|key| key.as_ref()).collect(); + widgets::kv(ui, &refs, |rows| { + rows.text( + &keys[0], + match observed { + Some(observed) if known => tv("platform", &observed.platform).into_owned(), + _ => "—".into(), + }, + ); + if !metadata { + let format = match observed.and_then(|observed| observed.format) { + Some(format) => format_label(Some(format)), + None => header_format.map_or_else(|| format_label(None), str::to_owned), + }; + rows.text(&keys[1], widgets::mono(format)); + } + if let Some(kind) = observed.and_then(|observed| observed.kind) { + rows.text(&keys[2], tv("kind", &kind).into_owned()); + } + rows.row(&keys[3], |ui| { + let evidence = profile + .map(|profile| profile.evidence.as_slice()) + .unwrap_or_default(); + if evidence.is_empty() { + ui.label(widgets::faint(t(Text::OvNoEvidence))); + } + for item in evidence { + widgets::pill(ui, tv("evidence", item), Tone::Skip); + } + }); + }); +} + +fn routes(ui: &mut Ui, profile: Option<&ProtectionProfile>, shown: &HashSet<&str>) { + let candidates = profile + .map(|profile| profile.candidates.as_slice()) + .unwrap_or_default(); + if candidates.is_empty() { + ui.label(widgets::faint(t(Text::OvNoRoutes))); + return; + } + for (index, attempt) in candidates.iter().enumerate() { + if index > 0 { + widgets::rule(ui); + } + ui.add_space(6.0); + let tone = match attempt.outcome { + senbei_engine::AttemptOutcome::Succeeded => Tone::Ok, + senbei_engine::AttemptOutcome::NotAttempted => Tone::Skip, + _ => Tone::Err, + }; + ui.horizontal(|ui| { + ui.label(tv("layout", &attempt.layout)); + if profile.and_then(|profile| profile.selected) == Some(attempt.layout) { + ui.label( + widgets::toned(format!("★ {}", t(Text::OvSelected)), Tone::Warn) + .font(theme::small()), + ); + } + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + widgets::pill(ui, tv("outcome", &attempt.outcome), tone); + }); + }); + let reasons: Vec<(MsgKind, Shown)> = attempt + .errors + .iter() + .map(|message| (MsgKind::Error, message)) + .chain( + attempt + .warnings + .iter() + .map(|message| (MsgKind::Warning, message)), + ) + .filter(|(_, message)| !shown.contains(message.text())) + .map(|(kind, message)| (kind, labels::message(message))) + .collect(); + if !reasons.is_empty() { + ui.add_space(4.0); + widgets::messages(ui, &reasons); + } + ui.add_space(6.0); + } +} + +fn stages(ui: &mut Ui, input: &InputReport, shown: &HashSet<&str>) { + let skipped = input.status == InputStatus::Skipped; + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(6.0, 6.0); + for (index, stage) in input.stages.iter().enumerate() { + if index > 0 { + arrow(ui); + } + let status = if skipped && stage.status == StageStatus::Failed { + StageStatus::Skipped + } else { + stage.status + }; + let (icon, tone) = match status { + StageStatus::Ok => ("✓", Tone::Ok), + StageStatus::Skipped => ("–", Tone::Skip), + StageStatus::Failed => ("✕", Tone::Err), + StageStatus::Blocked => ("⏸", Tone::Warn), + }; + let detail = stage.detail.as_ref().and_then(|detail| { + let hidden = shown.contains(detail.text()) + || detail.text().contains('\\') + || labels::message(detail).quiet; + (!hidden).then(|| labels::message(detail).text) + }); + stage_chip( + ui, + (icon, tone), + &tv("stage", &stage.stage), + stage.duration_ms, + (tv("stageStatus", &status).into_owned(), tone), + detail, + false, + ); + } + }); +} + +fn validation_card<'a>(input: &'a InputReport, plan: &Plan<'a>) -> Option> { + let profile = input.profile.as_ref()?; + let status = profile.static_validation; + let metadata = profile.observed.platform == Platform::Il2cppMetadata; + let note = match status { + ValidationStatus::Warnings => t(Text::OvValidationWarnings), + ValidationStatus::Failed => t(Text::OvValidationFailed), + _ if metadata && status != ValidationStatus::Clean => t(Text::OvValidationMetadata), + _ => return None, + }; + let tone = match status { + ValidationStatus::Clean => Tone::Ok, + ValidationStatus::Warnings => Tone::Warn, + ValidationStatus::Failed => Tone::Err, + ValidationStatus::NotRun => Tone::Skip, + }; + let blocks: Vec<(MsgKind, Shown)> = plan + .validation + .iter() + .map(|(kind, message)| (*kind, labels::message(message))) + .collect(); + Some( + CardSpec::new(t(Text::OvValidation), move |ui| { + widgets::note(ui, note); + if !blocks.is_empty() { + ui.add_space(8.0); + widgets::messages(ui, &blocks); + } + }) + .aside(move |ui| { + widgets::pill(ui, tv("validation", &status), tone); + }), + ) +} + +/// Size and hash of the bytes an input read and recovered, from the report or +/// else from the Android restoration record. +struct Digests { + source: (Option, Option), + recovered: (Option, Option), + companion: bool, + outputs: bool, +} + +impl Digests { + fn of(input: &InputReport) -> Self { + let restoration = input + .android_research + .as_ref() + .and_then(|research| research.restoration.as_ref()); + let source = match (&input.source, restoration) { + (Some(digest), _) => (Some(digest.size), Some(digest.sha256.clone())), + (None, Some(restoration)) => ( + None, + json_str(restoration, "input_sha256").map(str::to_owned), + ), + (None, None) => (None, None), + }; + let recovered = match (&input.recovered, restoration) { + (Some(digest), _) => (Some(digest.size), Some(digest.sha256.clone())), + (None, Some(restoration)) => ( + json_u64(restoration, "output_size"), + json_str(restoration, "output_sha256").map(str::to_owned), + ), + (None, None) => (None, None), + }; + Self { + source, + recovered, + companion: input.companion.is_some(), + outputs: !input.outputs.is_empty(), + } + } + + fn is_empty(&self) -> bool { + self.source == (None, None) + && self.recovered == (None, None) + && !self.companion + && !self.outputs + } +} + +fn identity_card( + ui: &mut Ui, + actions: &mut Vec, + reveal: bool, + input: &InputReport, + digests: Digests, +) { + let Digests { + source, recovered, .. + } = digests; + let keys = [ + t(Text::OvSource), + t(Text::OvCompanion), + t(Text::OvRecovered), + t(Text::OvOutput), + ]; + let refs: Vec<&str> = keys.iter().map(|key| key.as_ref()).collect(); + widgets::kv(ui, &refs, |rows| { + if source != (None, None) { + rows.row(&keys[0], |ui| { + identity_value(ui, source.0, source.1.as_deref()); + }); + } + if let Some(companion) = &input.companion { + rows.row(&keys[1], |ui| { + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = 2.0; + // State and size on one line, the hash under them. + let state = tv("companion", &companion.state); + match &companion.source { + Some(source) => { + ui.label(format!("{state} · {}", format::bytes(source.size))); + hash_row(ui, &source.sha256); + } + None => { + ui.label(state); + } + } + if let Some(detail) = &companion.detail { + let shown = labels::message(detail); + if !shown.quiet { + widgets::code_spans(ui, &shown.text); + } + } + if let Some(path) = &companion.path { + widgets::selectable( + ui, + widgets::mono(format::base_name(path)).color(theme::FAINT), + ); + } + }); + }); + } + if recovered != (None, None) { + rows.row(&keys[2], |ui| { + identity_value(ui, recovered.0, recovered.1.as_deref()); + }); + } + for output in &input.outputs { + rows.row(&keys[3], |ui| { + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = 2.0; + widgets::selectable(ui, widgets::mono(&output.path)); + ui.horizontal(|ui| { + ui.label(format::bytes(output.size)); + if reveal && widgets::ghost_button(ui, t(Text::OvOpenFolder)).clicked() { + actions.push(Action::Reveal(output.path.clone().into())); + } + }); + }); + }); + } + }); +} + +fn metadata_card(ui: &mut Ui, metadata: &senbei_metadata::MetadataIdentity, provenance: &[String]) { + let keys = [ + t(Text::OvMetadataVersion), + t(Text::OvMetadataLayout), + t(Text::OvCapSeeded), + t(Text::OvCapStructural), + t(Text::OvCapIndices), + t(Text::OvCapContext), + t(Text::OvProvenance), + ]; + let refs: Vec<&str> = keys.iter().map(|key| key.as_ref()).collect(); + let caps = metadata.capabilities; + widgets::kv(ui, &refs, |rows| { + rows.text(&keys[0], metadata.raw_version.to_string()); + rows.text(&keys[1], tv("metaLayout", &metadata.layout).into_owned()); + rows.row(&keys[2], |ui| { + widgets::yes_no(ui, caps.seeded_method_tokens) + }); + rows.row(&keys[3], |ui| { + widgets::yes_no(ui, caps.structural_method_tokens) + }); + rows.row(&keys[4], |ui| { + widgets::yes_no(ui, caps.method_index_restore) + }); + rows.row(&keys[5], |ui| { + widgets::yes_no(ui, caps.method_index_requires_context); + }); + if !provenance.is_empty() { + rows.text(&keys[6], widgets::mono(provenance.join("\n"))); + } + }); +} + +fn elf_card(ui: &mut Ui, valid: &Value) { + let keys = [ + t(Text::OvFormat), + t(Text::OvElfSections), + t(Text::OvElfSymbols), + t(Text::OvElfRelocs), + ]; + let refs: Vec<&str> = keys.iter().map(|key| key.as_ref()).collect(); + let text = |key: &str| json_str(valid, key).unwrap_or_default().to_owned(); + let count = |key: &str| { + json_u64(valid, key) + .map(format::num) + .unwrap_or_else(|| "—".into()) + }; + widgets::kv(ui, &refs, |rows| { + // The engine spells the machine in capitals; the pair this tool + // restores reads the same as everywhere else in the window. + let format = match (text("format").as_str(), text("machine").as_str()) { + ("ELF64", "AARCH64") => format_label(Some(senbei_engine::TargetFormat::Elf64Aarch64)), + (format, machine) => format!("{format} {machine}"), + }; + rows.text(&keys[0], widgets::mono(format)); + rows.text( + &keys[1], + format!("{} · {}", count("sections"), count("segments")), + ); + rows.text(&keys[2], count("dynamic_symbols")); + rows.text( + &keys[3], + format!( + "{} · {}", + count("dynamic_relocations"), + count("pltgot_relocations") + ), + ); + }); +} + +// ------------------------------------------------------------- packages + +fn package_detail<'a>( + ui: &mut Ui, + draw: &mut Draw<'a>, + view: &mut ViewState, + item: &'a Item, + result: &'a ItemResult, +) { + let input = &result.report; + let verdict = result.verdict(); + let named = input + .container + .as_ref() + .and_then(|container| container.manifests.iter().find(|manifest| manifest.named)) + .and_then(|manifest| manifest.package.clone()); + let mut pills = vec![(verdict.label().into_owned(), verdict.tone())]; + if let Some(named) = named { + pills.push((named, Tone::Skip)); + } + let head = Head { + title: item.name.clone(), + tag: Some(kind_tag(item)), + pills, + path: last_run_line(item, result), + tabs: vec![ + tab(Tab::Overview, Text::TabOverview), + TabSpec { + tab: Tab::Entries, + label: t(Text::TabEntries).into_owned(), + badge: Some(input.entries.len()), + }, + tab(Tab::Log, Text::TabLog), + ], + export: Some(Sel::Item(item.id)), + }; + shell(ui, draw, view, head, |ui, draw, view| match view.tab { + Tab::Entries => package_entries(ui, draw, view, item, input), + Tab::Log => logview::log_view(ui, view, ("item-log", item.id), &result.log), + _ => package_overview(ui, draw, item, input), + }); +} + +fn package_overview<'a>(ui: &mut Ui, draw: &mut Draw<'a>, item: &'a Item, input: &'a InputReport) { + let actions = &mut *draw.actions; + padded(ui, ("package", item.id), |ui| { + let blocks: Vec<(MsgKind, Shown)> = input + .errors + .iter() + .map(|message| (MsgKind::Error, labels::message(message))) + .chain( + input + .warnings + .iter() + .map(|message| (MsgKind::Warning, labels::message(message))), + ) + .filter(|(_, shown)| !shown.quiet) + .collect(); + if !blocks.is_empty() { + widgets::wide_card( + ui, + CardSpec::new(t(Text::OvMessages), move |ui| { + widgets::messages(ui, &blocks) + }), + ); + ui.add_space(12.0); + } + let Some(container) = &input.container else { + return; + }; + let mut counts: Vec<(EntryStatus, usize)> = Vec::new(); + for status in [ + EntryStatus::Restored, + EntryStatus::Unchanged, + EntryStatus::Duplicate, + EntryStatus::Error, + EntryStatus::NotTarget, + ] { + let count = input + .entries + .iter() + .filter(|entry| entry.status == status) + .count(); + if count > 0 { + counts.push((status, count)); + } + } + widgets::card_grid( + ui, + ("package-cards", item.id), + vec![ + CardSpec::new(t(Text::PkgTitle), move |ui| { + let keys = [ + t(Text::PkgKind), + t(Text::PkgEntries), + t(Text::PkgCandidates), + t(Text::PkgNested), + ]; + let refs: Vec<&str> = keys.iter().map(|key| key.as_ref()).collect(); + widgets::kv(ui, &refs, |rows| { + rows.text(&keys[0], container.kind.to_uppercase()); + rows.text(&keys[1], format::num(container.entry_count as u64)); + rows.text( + &keys[2], + format::num(container.candidate_entries.len() as u64), + ); + if !container.nested_packages.is_empty() { + rows.text( + &keys[3], + widgets::mono(container.nested_packages.join("\n")), + ); + } + }); + ui.add_space(8.0); + widgets::note(ui, t(Text::PkgNote)); + }), + CardSpec::new(t(Text::PkgResult), move |ui| { + let labels: Vec = counts + .iter() + .map(|(status, _)| tv("entryStatus", status).into_owned()) + .collect(); + let refs: Vec<&str> = labels.iter().map(String::as_str).collect(); + widgets::kv(ui, &refs, |rows| { + for ((status, count), label) in counts.iter().zip(&labels) { + let text = match status { + EntryStatus::Error => widgets::toned(count.to_string(), Tone::Err), + EntryStatus::Restored => { + widgets::toned(count.to_string(), Tone::Ok) + } + _ => RichText::new(count.to_string()), + }; + rows.text(label, text); + } + }); + }), + ], + ); + widgets::wide_card( + ui, + CardSpec::new(t(Text::PkgManifests), move |ui| { + let cols = [ + col(t(Text::ColSource)).width(220.0), + col(t(Text::PkgPackage)).width(260.0), + col(t(Text::PkgVersion)), + ]; + let manifests = &container.manifests; + table::table( + ui, + ("manifests", item.id), + &cols, + manifests.len(), + |_| table::lines(1), + |index, row| { + let manifest = &manifests[index]; + table::mono(row, format::base_name(&manifest.source).to_owned()); + match &manifest.package { + Some(package) => table::mono(row, package.clone()), + None => table::text(row, widgets::faint(t(Text::PkgUnnamed))), + } + table::mono(row, manifest.version.clone().unwrap_or_default()); + }, + ); + }) + .aside(move |ui| { + ui.label( + widgets::faint(container.manifests.len().to_string()).font(theme::small()), + ); + }), + ); + ui.add_space(12.0); + let targets: Vec = input + .entries + .iter() + .enumerate() + .filter(|(_, entry)| is_target_entry(entry)) + .map(|(index, _)| index) + .collect(); + if targets.is_empty() { + widgets::wide_card( + ui, + CardSpec::untitled(|ui| widgets::note(ui, t(Text::PkgNoTargets))), + ); + } else { + widgets::wide_card( + ui, + CardSpec::new(t(Text::PkgTargets), |ui| { + entry_table(ui, actions, item, &input.entries, &targets); + }), + ); + } + }); +} + +fn entry_table( + ui: &mut Ui, + actions: &mut Vec, + item: &Item, + entries: &[EntryReport], + shown: &[usize], +) { + // A column no shown entry has a value for is left out: Android entries + // carry no route, and only Unpack keeps outputs. + let routes = shown.iter().any(|index| { + let entry = &entries[*index]; + entry.layout.is_some() || entry.remapped.is_some() + }); + let outputs = shown.iter().any(|index| entries[*index].output.is_some()); + let mut cols = vec![ + col("").width(18.0), + col(t(Text::ColName)).width(240.0), + col(t(Text::ColType)).width(120.0), + col(t(Text::ColStatus)).width(110.0), + ]; + if routes { + cols.push(col(t(Text::ColRoute)).width(170.0)); + } + if outputs { + cols.push(col(t(Text::OvOutput))); + } + let mut clicked = None; + table::table_clickable( + ui, + ("entries", item.id, shown.len(), routes, outputs), + &cols, + shown.len(), + |_| table::lines(2), + |index, row| { + let entry = &entries[shown[index]]; + let verdict = Verdict::of_entry(entry); + table::cell(row, |ui| { + widgets::dot(ui, Some(verdict.tone())); + }); + let inner = entry_inner(&entry.name); + let source = entry_source(&entry.name); + let folder = inner + .replace('/', "\\") + .rsplit_once('\\') + .map(|(folder, _)| format!("{folder}\\")) + .unwrap_or_default(); + let place = if source.is_empty() { + folder + } else { + format!("{} › {folder}", format::base_name(source)) + }; + table::cell(row, |ui| { + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = 0.0; + ui.add( + egui::Label::new( + RichText::new(format::base_name(inner)).font(theme::mono_small()), + ) + .truncate(), + ); + ui.add(egui::Label::new(widgets::faint(place).font(theme::small())).truncate()); + }); + }); + table::cell(row, |ui| { + widgets::tag(ui, entry_tag(entry)); + }); + table::text(row, widgets::toned(verdict.label(), verdict.tone())); + if routes { + table::cell(row, |ui| { + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = 0.0; + if let Some(layout) = entry.layout { + ui.add(egui::Label::new(tv("layout", &layout)).truncate()); + } + if let Some(remapped) = entry.remapped { + ui.add( + egui::Label::new( + widgets::faint(t(Text::EntriesRemapped { + n: format::num(remapped as u64), + })) + .font(theme::small()), + ) + .truncate(), + ); + } + }); + }); + } + if outputs { + table::mono( + row, + entry + .output + .as_ref() + .map(|output| output.path.clone()) + .unwrap_or_default(), + ); + } + }, + |index| clicked = Some(index), + ); + if let Some(index) = clicked { + actions.push(Action::Select { + sel: Sel::Entry(item.id, shown[index]), + toggle: false, + }); + } +} + +fn package_entries<'a>( + ui: &mut Ui, + draw: &mut Draw<'a>, + view: &mut ViewState, + item: &'a Item, + input: &'a InputReport, +) { + let actions = &mut *draw.actions; + let entries = &input.entries; + let non_targets = entries + .iter() + .filter(|entry| !is_target_entry(entry)) + .count(); + padded(ui, ("package-entries", item.id), |ui| { + ui.checkbox( + &mut view.show_non_targets, + widgets::dim(t(Text::EntriesShowNonTargets { + n: non_targets.to_string(), + })), + ); + ui.add_space(8.0); + let mut shown: Vec = entries + .iter() + .enumerate() + .filter(|(_, entry)| view.show_non_targets || is_target_entry(entry)) + .map(|(index, _)| index) + .collect(); + if shown.is_empty() { + shown = (0..entries.len()).collect(); + } + entry_table(ui, actions, item, entries, &shown); + if let Some(container) = &input.container { + ui.add_space(12.0); + egui::CollapsingHeader::new(widgets::dim(t(Text::PkgInventory { + n: container.candidate_entries.len().to_string(), + }))) + .id_salt(("inventory", item.id)) + .show(ui, |ui| { + Frame::new() + .fill(theme::WELL) + .corner_radius(CornerRadius::same(4)) + .inner_margin(Margin::symmetric(10, 8)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ScrollArea::vertical() + .id_salt(("inventory-list", item.id)) + .max_height(280.0) + .show(ui, |ui| { + widgets::selectable( + ui, + widgets::mono(container.candidate_entries.join("\n")), + ); + }); + }); + }); + } + }); +} + +fn entry_detail<'a>( + ui: &mut Ui, + draw: &mut Draw<'a>, + view: &mut ViewState, + item: &'a Item, + index: usize, + entry: &'a EntryReport, +) { + let verdict = Verdict::of_entry(entry); + let mut tabs = vec![tab(Tab::Overview, Text::TabOverview)]; + if entry.android_research.is_some() || entry.metadata_research.is_some() { + tabs.push(tab(Tab::Research, Text::TabResearch)); + } + tabs.push(tab(Tab::Hex, Text::TabHex)); + let inner = entry_inner(&entry.name); + let head = Head { + title: format::base_name(inner).to_owned(), + tag: Some(entry_tag(entry)), + pills: vec![(verdict.label().into_owned(), verdict.tone())], + path: super::inputs::entry_path(item, entry), + tabs, + export: None, + }; + let mode = item.result.as_ref().map(|result| result.mode); + let reveal = draw.caps.reveal; + shell(ui, draw, view, head, |ui, draw, view| match view.tab { + Tab::Research => research::tab( + ui, + draw, + view, + research::Subject::entry(item, index, entry, mode), + ), + Tab::Hex => hex::tab(ui, draw, view, hex::Subject::Entry { item, entry }), + _ => { + let actions = &mut *draw.actions; + padded(ui, ("entry", item.id, index), |ui| { + let blocks: Vec<(MsgKind, Shown)> = entry + .errors + .iter() + .map(|message| (MsgKind::Error, labels::message(message))) + .chain( + entry + .warnings + .iter() + .map(|message| (MsgKind::Warning, labels::message(message))), + ) + .filter(|(_, shown)| !shown.quiet) + .collect(); + if !blocks.is_empty() { + widgets::wide_card( + ui, + CardSpec::new(t(Text::OvMessages), move |ui| { + widgets::messages(ui, &blocks) + }), + ); + ui.add_space(12.0); + } + let restoration = entry + .android_research + .as_ref() + .and_then(|research| research.restoration.as_ref()); + let mut cards = vec![CardSpec::new(t(Text::EntriesTitle), move |ui| { + entry_rows(ui, actions, reveal, item, entry, verdict, restoration); + })]; + if let Some(valid) = restoration + .and_then(|restoration| restoration.get("validation")) + .filter(|valid| valid.is_object()) + { + cards.push(CardSpec::new(t(Text::OvRestoredElf), move |ui| { + elf_card(ui, valid); + })); + } + widgets::card_grid(ui, ("entry-cards", item.id, index), cards); + }); + } + }); +} + +fn entry_rows( + ui: &mut Ui, + actions: &mut Vec, + reveal: bool, + item: &Item, + entry: &EntryReport, + verdict: Verdict, + restoration: Option<&Value>, +) { + let keys = [ + t(Text::ColStatus), + t(Text::ColType), + t(Text::ColRoute), + t(Text::OvMetadataVersion), + t(Text::EntriesRemappedLabel), + t(Text::OvProvenance), + t(Text::OvSource), + t(Text::OvRecovered), + t(Text::OvOutput), + ]; + let refs: Vec<&str> = keys.iter().map(|key| key.as_ref()).collect(); + widgets::kv(ui, &refs, |rows| { + rows.text(&keys[0], widgets::toned(verdict.label(), verdict.tone())); + if let Some(kind) = entry.kind { + rows.text(&keys[1], tv("entryKind", &kind).into_owned()); + } + if let Some(layout) = entry.layout { + rows.text(&keys[2], tv("layout", &layout).into_owned()); + } + if let Some(version) = entry.metadata_version { + rows.text(&keys[3], version.to_string()); + } + if let Some(remapped) = entry.remapped { + rows.text(&keys[4], format::num(remapped as u64)); + } + if !entry.provenance.is_empty() { + rows.text(&keys[5], widgets::mono(entry.provenance.join("\n"))); + } + if let Some(restoration) = restoration { + rows.row(&keys[6], |ui| match json_str(restoration, "input_sha256") { + Some(sha256) => hash_row(ui, sha256), + None => { + ui.label("—"); + } + }); + rows.row(&keys[7], |ui| { + identity_value( + ui, + json_u64(restoration, "output_size"), + json_str(restoration, "output_sha256"), + ); + }); + } + if let Some(output) = &entry.output { + rows.row(&keys[8], |ui| { + widgets::selectable(ui, widgets::mono(&output.path)); + if reveal && widgets::ghost_button(ui, t(Text::OvOpenFolder)).clicked() { + actions.push(Action::Reveal(output.path.clone().into())); + } + }); + } + }); + let _ = item; +} + +/// The output-location label of the top bar. +pub fn output_label(output: &Output) -> String { + match output { + Output::Beside => t(Text::TbOutputBeside).into_owned(), + Output::Folder(folder) => folder.display().to_string(), + } +} diff --git a/senbei-gui/src/ui/dialogs.rs b/senbei-gui/src/ui/dialogs.rs new file mode 100644 index 0000000..fb9997e --- /dev/null +++ b/senbei-gui/src/ui/dialogs.rs @@ -0,0 +1,964 @@ +//! The window's frame and overlays: top bar, banner, status bar, the empty +//! session, the drop overlay, and the legal, settings, and close dialogs. + +use egui::text::LayoutJob; +use egui::{ + Align, Align2, Color32, ComboBox, Context, CornerRadius, Frame, Id, Layout, Margin, Modal, + Order, Popup, Rect, Response, RichText, Sense, Shape, Stroke, TextFormat, TextureHandle, Ui, + pos2, vec2, +}; +use senbei_i18n::Lang; +use senbei_io::report::Mode; + +use super::{Action, Draw, SettingsTab, ViewState, widgets}; +use crate::backend::{Output, Pick}; +use crate::format; +use crate::model::mode_action; +use crate::settings::Settings; +use crate::text::{Text, strong_runs, t}; +use crate::theme::{self, Tone}; + +fn icon_image(icon: Option<&TextureHandle>, size: f32) -> Option> { + icon.map(|texture| egui::Image::new((texture.id(), vec2(size, size)))) +} + +// ---------------------------------------------------------------- top bar + +pub struct TopBar<'a> { + pub targets: usize, + pub has_selection: bool, + pub icon: Option<&'a TextureHandle>, +} + +fn run_label(mode: Mode, has_selection: bool, targets: usize) -> String { + let n = targets.to_string(); + t(match (mode, has_selection) { + (Mode::Unpack, true) => Text::TbUnpackN { n }, + (Mode::Unpack, false) => Text::TbUnpackAll, + (Mode::DryRun, true) => Text::TbDryRunN { n }, + (Mode::DryRun, false) => Text::TbDryRunAll, + (Mode::Inspect, true) => Text::TbInspectN { n }, + (Mode::Inspect, false) => Text::TbInspectAll, + }) + .into_owned() +} + +pub fn topbar(ui: &mut Ui, draw: &mut Draw<'_>, view: &mut ViewState, bar: TopBar<'_>) { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 8.0; + if let Some(image) = icon_image(bar.icon, 26.0) { + ui.add(image); + } + ui.label(RichText::new("Senbei").font(theme::title(19.0))); + ui.label( + RichText::new(env!("CARGO_PKG_VERSION")) + .font(theme::tiny()) + .color(theme::FAINT), + ); + ui.add_space(6.0); + if ui + .button(t(Text::TbAddFiles)) + .on_hover_text("Ctrl+O") + .clicked() + { + draw.act(Action::Pick(Pick::Files)); + } + if draw.caps.folders && ui.button(t(Text::TbAddFolder)).clicked() { + draw.act(Action::Pick(Pick::Folder)); + } + separator(ui); + let enabled = !draw.session.is_empty() && bar.targets > 0; + let unpack = widgets::primary_button( + ui, + format!( + "▶ {}", + run_label(Mode::Unpack, bar.has_selection, bar.targets) + ), + enabled && draw.caps.unpack, + ) + .on_hover_text(t(Text::TbUnpackTip)); + if unpack.clicked() { + draw.act(Action::Run(Mode::Unpack)); + } + for (mode, tip) in [ + (Mode::DryRun, Text::TbDryRunTip), + (Mode::Inspect, Text::TbInspectTip), + ] { + let button = ui + .add_enabled( + enabled, + egui::Button::new(run_label(mode, bar.has_selection, bar.targets)), + ) + .on_hover_text(t(tip)); + if button.clicked() { + draw.act(Action::Run(mode)); + } + } + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let settings = ui + .add(egui::Button::new(RichText::new("⚙").size(15.0))) + .on_hover_text(t(Text::TbSettings)); + if settings.clicked() { + view.settings_open = true; + } + if draw.caps.unpack { + output_chip(ui, draw); + } + }); + }); +} + +fn separator(ui: &mut Ui) { + let (rect, _) = ui.allocate_exact_size(vec2(1.0, 22.0), Sense::hover()); + ui.painter().rect_filled(rect, 0, theme::BORDER); +} + +fn output_chip(ui: &mut Ui, draw: &mut Draw<'_>) { + let label = super::detail::output_label(&draw.settings.output); + let prefix = + ui.painter() + .layout_no_wrap(t(Text::TbOutput).into_owned(), theme::body(), theme::DIM); + let caret = ui + .painter() + .layout_no_wrap("▾".into(), theme::body(), theme::FAINT); + let mut job = LayoutJob::simple_singleline(label, theme::body(), theme::TEXT); + job.wrap = egui::text::TextWrapping::truncate_at_width( + 340.0 - prefix.size().x - caret.size().x - 28.0, + ); + let value = ui.painter().layout_job(job); + let size = vec2( + prefix.size().x + value.size().x + caret.size().x + 12.0 + 16.0, + 24.0, + ); + let (rect, response) = ui.allocate_exact_size(size, Sense::click()); + widgets::describe(&response, egui::Role::Button, &t(Text::TbOutput), None); + let stroke = if response.hovered() { + theme::HOVER_STROKE + } else { + theme::BORDER + }; + ui.painter().rect( + rect, + CornerRadius::same(4), + Color32::TRANSPARENT, + Stroke::new(1.0, stroke), + egui::StrokeKind::Inside, + ); + let mut x = rect.left() + 8.0; + let y = |galley: &std::sync::Arc| rect.center().y - galley.size().y / 2.0; + let prefix_width = prefix.size().x; + let prefix_y = y(&prefix); + ui.painter().galley(pos2(x, prefix_y), prefix, theme::DIM); + x += prefix_width + 6.0; + let value_width = value.size().x; + let value_y = y(&value); + ui.painter().galley(pos2(x, value_y), value, theme::TEXT); + x += value_width + 6.0; + let caret_y = y(&caret); + ui.painter().galley(pos2(x, caret_y), caret, theme::FAINT); + let response = response.on_hover_text(t(Text::TbOutputTip)); + let current = draw.settings.output.clone(); + let recent = draw.settings.recent_output.clone(); + Popup::menu(&response).width(330.0).show(|ui| { + let choice = |ui: &mut Ui, on: bool, label: String, sub: Option| -> bool { + let mut clicked = false; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + ui.label(widgets::toned(if on { "●" } else { "○" }, Tone::Warn)); + ui.vertical(|ui| { + clicked = ui + .add(egui::Button::new(label).frame_when_inactive(false)) + .clicked(); + if let Some(sub) = sub { + ui.label(widgets::faint(sub).font(theme::mono_small())); + } + }); + }); + clicked + }; + if choice( + ui, + current == Output::Beside, + t(Text::TbOutputBeside).into_owned(), + None, + ) { + draw.act(Action::SetOutput(Output::Beside)); + ui.close(); + } + if let Some(recent) = recent { + let on = current == Output::Folder(recent.clone()); + if choice( + ui, + on, + t(Text::SettingsOutputRecent).into_owned(), + Some(recent.display().to_string()), + ) { + draw.act(Action::SetOutput(Output::Folder(recent))); + ui.close(); + } + } + ui.separator(); + if ui + .add(egui::Button::new(t(Text::SettingsOutputChoose)).frame_when_inactive(false)) + .clicked() + { + draw.act(Action::Pick(Pick::Output)); + ui.close(); + } + }); +} + +pub fn banner(ui: &mut Ui, vars: &[String]) { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 8.0; + ui.label(widgets::toned("⚠", Tone::Warn)); + let names = vars + .iter() + .map(|name| format!("`{name}`")) + .collect::>() + .join(", "); + let text = t(Text::BannerEnv { vars: names }); + let mut job = LayoutJob::default(); + for (index, part) in text.split('`').enumerate() { + let code = index % 2 == 1; + job.append( + part, + 0.0, + TextFormat { + font_id: if code { theme::mono() } else { theme::body() }, + color: if code { theme::TEXT } else { theme::WARN }, + ..Default::default() + }, + ); + } + ui.label(job); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + ui.label(widgets::faint(t(Text::BannerEnvHint))); + }); + }); +} + +// ------------------------------------------------------------- status bar + +pub fn statusbar(ui: &mut Ui, draw: &mut Draw<'_>, notice: Option<&super::Notice>) { + ui.horizontal(|ui| { + ui.set_min_height(22.0); + ui.spacing_mut().item_spacing.x = 14.0; + let small = |text: String| RichText::new(text).font(theme::small()).color(theme::DIM); + if let Some(running) = &draw.jobs.running { + ui.label(widgets::toned("●", Tone::Info)); + ui.label(widgets::strong(mode_action(running.plan.mode), 12.5).color(theme::TEXT)); + let total = running.total.max(running.done); + let fraction = if total == 0 { + 0.0 + } else { + running.done as f32 / total as f32 + }; + progress(ui, fraction); + ui.label(small(format!("{} / {}", running.done, total))); + if let Some((_, item)) = running.current.and_then(|id| draw.session.item(id)) { + ui.scope(|ui| { + ui.set_max_width(420.0); + ui.add( + egui::Label::new( + RichText::new(&item.name) + .font(theme::mono_small()) + .color(theme::TEXT), + ) + .truncate(), + ); + }); + } + if let Some(step) = &running.step { + ui.label(small(super::detail::step_text(step))); + } + ui.label( + RichText::new(format::clock( + running.input_started.elapsed().as_millis() as u64 + )) + .font(theme::small()) + .color(theme::FAINT), + ); + if !draw.jobs.queued.is_empty() { + ui.label( + RichText::new(t(Text::RunQueue { + n: draw.jobs.queued.len().to_string(), + })) + .font(theme::small()) + .color(theme::FAINT), + ); + } + let stopping = running.cancel_requested; + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let cancel = ui.add_enabled( + !stopping, + egui::Button::new(RichText::new(t(Text::RunCancel)).color(theme::ERR)), + ); + if cancel.clicked() { + draw.act(Action::Cancel); + } + if stopping { + ui.label( + RichText::new(t(Text::RunStopping)) + .font(theme::small()) + .color(theme::WARN), + ); + } + }); + return; + } + if let Some(group) = draw + .session + .groups + .iter() + .find(|group| group.scanning.is_some()) + { + ui.label(widgets::toned("●", Tone::Info)); + ui.label(small( + t(Text::ScanStatus { + p: group.title().into_owned(), + n: group.scanning.unwrap_or_default().to_string(), + }) + .into_owned(), + )); + return; + } + ui.label(widgets::toned("●", Tone::Ok)); + ui.label(small(t(Text::StatusReady).into_owned())); + if let Some(notice) = notice { + ui.add( + egui::Label::new( + RichText::new(¬ice.text) + .font(theme::small()) + .color(notice.tone.color()), + ) + .truncate(), + ); + } + }); +} + +fn progress(ui: &mut Ui, fraction: f32) { + let (rect, _) = ui.allocate_exact_size(vec2(220.0, 8.0), Sense::hover()); + ui.painter().rect( + rect, + CornerRadius::same(4), + theme::WELL, + Stroke::new(1.0, theme::BORDER), + egui::StrokeKind::Inside, + ); + let filled = Rect::from_min_size( + rect.min, + vec2(rect.width() * fraction.clamp(0.0, 1.0), rect.height()), + ); + ui.painter() + .rect_filled(filled, CornerRadius::same(4), theme::ACCENT); +} + +// ------------------------------------------------------------ empty state + +fn dashed_rect(ui: &Ui, rect: Rect, color: Color32, width: f32) { + let points = [ + rect.left_top(), + rect.right_top(), + rect.right_bottom(), + rect.left_bottom(), + rect.left_top(), + ]; + ui.painter().extend(Shape::dashed_line( + &points, + Stroke::new(width, color), + 6.0, + 4.0, + )); +} + +pub fn empty_state(ui: &mut Ui, draw: &mut Draw<'_>, icon: Option<&TextureHandle>) { + let full = ui.available_rect_before_wrap(); + let width = (full.width() - 60.0).clamp(200.0, 640.0); + let height = 330.0; + let rect = Rect::from_center_size(full.center(), vec2(width, height)); + ui.painter() + .rect_filled(rect, CornerRadius::same(10), theme::BG); + dashed_rect(ui, rect, theme::BORDER_STRONG, 1.5); + ui.scope_builder( + egui::UiBuilder::new().max_rect(rect.shrink2(vec2(30.0, 30.0))), + |ui| { + ui.vertical_centered(|ui| { + ui.spacing_mut().item_spacing.y = 6.0; + if let Some(image) = icon_image(icon, 84.0) { + ui.add(image); + } + ui.add_space(6.0); + ui.label(RichText::new(t(Text::EmptyTitle)).font(theme::title(21.0))); + ui.add_space(8.0); + let kinds = [ + ".exe".to_owned(), + ".dll".to_owned(), + ".exe._ / .dll._".to_owned(), + "global-metadata.dat".to_owned(), + ".so".to_owned(), + ".apk".to_owned(), + ".apks".to_owned(), + ".xapk".to_owned(), + t(Text::EmptyFolders).into_owned(), + ]; + centered_wrap(ui, &kinds); + ui.add_space(12.0); + widgets::centered_row(ui, "empty-buttons", |ui| { + if widgets::primary_button(ui, t(Text::TbAddFiles), true).clicked() { + draw.act(Action::Pick(Pick::Files)); + } + if draw.caps.folders && ui.button(t(Text::TbAddFolder)).clicked() { + draw.act(Action::Pick(Pick::Folder)); + } + }); + ui.add_space(14.0); + ui.label(widgets::faint(t(Text::EmptyLocal))); + }); + }, + ); +} + +/// Tags laid out in centred rows. +fn centered_wrap(ui: &mut Ui, tags: &[String]) { + let max = ui.available_width(); + let widths: Vec = tags + .iter() + .map(|tag| { + ui.painter() + .layout_no_wrap(tag.clone(), egui::FontId::monospace(11.0), theme::DIM) + .size() + .x + + 10.0 + }) + .collect(); + let gap = 6.0; + let mut rows: Vec> = vec![Vec::new()]; + let mut width = 0.0; + for (index, tag_width) in widths.iter().enumerate() { + if width + tag_width > max && !rows.last().is_some_and(Vec::is_empty) { + rows.push(Vec::new()); + width = 0.0; + } + rows.last_mut().expect("a row").push(index); + width += tag_width + gap; + } + for row in rows { + let row_width: f32 = row.iter().map(|index| widths[*index]).sum::() + + gap * row.len().saturating_sub(1) as f32; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = gap; + ui.add_space(((max - row_width) / 2.0).max(0.0)); + for index in row { + widgets::mono_tag(ui, &tags[index]); + } + }); + } +} + +// --------------------------------------------------------------- overlays + +pub struct Overlays<'a> { + pub legal_pending: bool, + pub icon: Option<&'a TextureHandle>, + pub detected: Lang, +} + +pub fn overlays( + ctx: &Context, + draw: &mut Draw<'_>, + view: &mut ViewState, + settings: &mut Settings, + overlays: Overlays<'_>, +) { + if ctx.input(|input| !input.raw.hovered_files.is_empty()) { + drop_overlay(ctx); + } + if view.settings_open { + settings_modal(ctx, draw, view, settings, &overlays); + } + if view.close_confirm { + close_modal(ctx, draw, view); + } + if overlays.legal_pending || view.legal_open { + legal_modal(ctx, draw, view, settings, &overlays); + } +} + +fn drop_overlay(ctx: &Context) { + egui::Area::new(Id::unique("drop-overlay")) + .order(Order::Foreground) + .fixed_pos(pos2(0.0, 0.0)) + .show(ctx, |ui| { + let screen = ctx.content_rect(); + ui.painter() + .rect_filled(screen, 0, Color32::from_rgba_unmultiplied(12, 14, 17, 199)); + let galley = ui.painter().layout_no_wrap( + t(Text::DragTitle).into_owned(), + theme::title(22.0), + theme::ACCENT, + ); + let size = galley.size() + vec2(140.0, 80.0); + let rect = Rect::from_center_size(screen.center(), size); + ui.painter() + .rect_filled(rect, CornerRadius::same(12), theme::BG); + dashed_rect(ui, rect, theme::ACCENT, 2.0); + ui.painter() + .galley(rect.center() - galley.size() / 2.0, galley, theme::ACCENT); + }); +} + +fn modal_frame() -> Frame { + Frame::new() + .fill(theme::PANEL) + .stroke(Stroke::new(1.0, theme::BORDER_STRONG)) + .corner_radius(CornerRadius::same(8)) +} + +fn modal_section(ui: &mut Ui, margin: Margin, add: impl FnOnce(&mut Ui)) { + Frame::new().inner_margin(margin).show(ui, |ui| { + ui.set_width(ui.available_width()); + add(ui); + }); +} + +fn language_combo(ui: &mut Ui, id: &str, settings: &mut Settings, detected: Lang) -> Response { + let current = settings.lang(detected); + ComboBox::from_id_salt(id) + .selected_text(current.native_name()) + .show_ui(ui, |ui| { + for lang in Lang::ALL { + if ui + .selectable_label(lang == current, lang.native_name()) + .clicked() + { + settings.language = Some(lang.tag().to_owned()); + } + } + }) + .response + .accessible_name(t(Text::SettingsLanguage)) +} + +fn legal_modal( + ctx: &Context, + draw: &mut Draw<'_>, + view: &mut ViewState, + settings: &mut Settings, + overlays: &Overlays<'_>, +) { + Modal::new(Id::unique("legal")) + .frame(modal_frame()) + .backdrop_color(theme::backdrop()) + .show(ctx, |ui| { + ui.set_width(620.0_f32.min(ctx.content_rect().width() - 40.0)); + ui.spacing_mut().item_spacing.y = 0.0; + modal_section(ui, Margin::symmetric(16, 12), |ui| { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 10.0; + if let Some(image) = icon_image(overlays.icon, 24.0) { + ui.add(image); + } + ui.label(RichText::new(t(Text::LegalTitle)).font(theme::title(17.0))); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + language_combo(ui, "legal-language", settings, overlays.detected); + }); + }); + }); + widgets::rule(ui); + modal_section(ui, Margin::symmetric(16, 14), |ui| { + ui.spacing_mut().item_spacing.y = 10.0; + for text in [Text::LegalP1, Text::LegalP2, Text::LegalP3, Text::LegalP4] { + let text = t(text); + let mut job = LayoutJob::default(); + for (strong, run) in strong_runs(&text) { + job.append( + run, + 0.0, + TextFormat { + font_id: if strong { + theme::strong(13.5) + } else { + theme::body() + }, + color: if strong { theme::TEXT } else { theme::DIM }, + ..Default::default() + }, + ); + } + job.wrap.max_width = ui.available_width(); + ui.add(egui::Label::new(job).wrap()); + } + }); + widgets::rule(ui); + modal_section(ui, Margin::symmetric(16, 10), |ui| { + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = 8.0; + if widgets::primary_button(ui, t(Text::LegalAccept), true).clicked() { + draw.act(Action::AcceptLegal); + settings.legal_accepted = true; + view.legal_open = false; + } + if ui.button(t(Text::LegalQuit)).clicked() { + if overlays.legal_pending { + draw.act(Action::Quit); + } else { + view.legal_open = false; + } + } + }); + }); + }); +} + +fn close_modal(ctx: &Context, draw: &mut Draw<'_>, view: &mut ViewState) { + let response = Modal::new(Id::unique("close-confirm")) + .frame(modal_frame()) + .backdrop_color(theme::backdrop()) + .show(ctx, |ui| { + ui.set_width(520.0); + ui.spacing_mut().item_spacing.y = 0.0; + modal_section(ui, Margin::symmetric(16, 12), |ui| { + ui.label(RichText::new(t(Text::CloseTitle)).font(theme::title(17.0))); + }); + widgets::rule(ui); + modal_section(ui, Margin::symmetric(16, 14), |ui| { + ui.add(egui::Label::new(widgets::dim(t(Text::CloseBody))).wrap()); + }); + widgets::rule(ui); + modal_section(ui, Margin::symmetric(16, 10), |ui| { + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = 8.0; + if widgets::primary_button(ui, t(Text::CloseStop), true).clicked() { + draw.act(Action::StopAndClose); + } + if ui.button(t(Text::CloseKeep)).clicked() { + view.close_confirm = false; + } + }); + }); + }); + if response.should_close() { + view.close_confirm = false; + } +} + +// ---------------------------------------------------------------- settings + +/// A settings row: its label, its control, and an optional help line. The +/// control returns its main widget, which the label names for screen readers. +fn field(ui: &mut Ui, label: Text, help: Option, control: impl FnOnce(&mut Ui) -> Response) { + labelled_row(ui, label, help, |ui, label| { + control(ui).labelled_by(label); + }); +} + +/// A row that only shows a value beside its label, such as a link, which +/// keeps its own name. +fn info_row(ui: &mut Ui, label: Text, value: impl FnOnce(&mut Ui)) { + labelled_row(ui, label, None, |ui, _| value(ui)); +} + +fn labelled_row(ui: &mut Ui, label: Text, help: Option, add: impl FnOnce(&mut Ui, Id)) { + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = 14.0; + let label = ui + .allocate_ui_with_layout( + vec2(210.0, 24.0), + Layout::left_to_right(Align::Center), + |ui| { + ui.set_width(210.0); + ui.add(egui::Label::new(t(label)).wrap()) + }, + ) + .inner; + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = 4.0; + ui.horizontal(|ui| add(ui, label.id)); + if let Some(help) = help { + ui.add(egui::Label::new(widgets::faint(t(help)).font(theme::small())).wrap()); + } + }); + }); +} + +fn mib(ui: &mut Ui, value: &mut u64) -> Response { + let response = ui.add(egui::DragValue::new(value).range(1..=1_048_576).speed(16.0)); + ui.label("MiB"); + response +} + +fn settings_modal( + ctx: &Context, + draw: &mut Draw<'_>, + view: &mut ViewState, + settings: &mut Settings, + overlays: &Overlays<'_>, +) { + let response = Modal::new(Id::unique("settings")) + .frame(modal_frame()) + .backdrop_color(theme::backdrop()) + .show(ctx, |ui| { + ui.set_width(760.0_f32.min(ctx.content_rect().width() - 40.0)); + ui.spacing_mut().item_spacing.y = 0.0; + modal_section(ui, Margin::symmetric(16, 12), |ui| { + ui.horizontal(|ui| { + ui.label(RichText::new(t(Text::SettingsTitle)).font(theme::title(17.0))); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if widgets::ghost_button(ui, "✕").clicked() { + view.settings_open = false; + } + }); + }); + }); + widgets::rule(ui); + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + ui.allocate_ui_with_layout( + vec2(160.0, 380.0), + Layout::top_down(Align::Min), + |ui| { + ui.set_min_size(vec2(160.0, 380.0)); + modal_section(ui, Margin::symmetric(6, 8), |ui| { + ui.spacing_mut().item_spacing.y = 2.0; + for (tab, text) in [ + (SettingsTab::General, Text::SettingsTabGeneral), + (SettingsTab::Processing, Text::SettingsTabProcessing), + (SettingsTab::Android, Text::SettingsTabAndroid), + (SettingsTab::Memory, Text::SettingsTabMemory), + (SettingsTab::About, Text::SettingsTabAbout), + ] { + if nav_item(ui, &t(text), view.settings_tab == tab) { + view.settings_tab = tab; + } + } + }); + }, + ); + let line = ui.available_rect_before_wrap(); + ui.painter().vline( + line.left(), + line.top()..=line.top() + 380.0, + Stroke::new(1.0, theme::BORDER), + ); + ui.vertical(|ui| { + modal_section(ui, Margin::symmetric(16, 12), |ui| { + ui.spacing_mut().item_spacing.y = 12.0; + settings_pane(ui, draw, view, settings, overlays); + }); + }); + }); + widgets::rule(ui); + modal_section(ui, Margin::symmetric(16, 10), |ui| { + ui.horizontal(|ui| { + if widgets::ghost_button(ui, t(Text::SettingsReset)).clicked() { + settings.reset(); + } + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if widgets::primary_button(ui, t(Text::SettingsDone), true).clicked() { + view.settings_open = false; + } + }); + }); + }); + }); + if response.should_close() { + view.settings_open = false; + } +} + +fn nav_item(ui: &mut Ui, label: &str, on: bool) -> bool { + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 26.0), Sense::click()); + widgets::describe(&response, egui::Role::Tab, label, Some(on)); + if on { + ui.painter() + .rect_filled(rect, CornerRadius::same(4), theme::selection()); + } else if response.hovered() { + ui.painter() + .rect_filled(rect, CornerRadius::same(4), theme::row_hover()); + } + ui.painter().text( + pos2(rect.left() + 10.0, rect.center().y), + Align2::LEFT_CENTER, + label, + theme::body(), + if on { theme::TEXT } else { theme::DIM }, + ); + response.clicked() +} + +fn settings_pane( + ui: &mut Ui, + draw: &mut Draw<'_>, + view: &mut ViewState, + settings: &mut Settings, + overlays: &Overlays<'_>, +) { + match view.settings_tab { + SettingsTab::General => { + field(ui, Text::SettingsLanguage, None, |ui| { + language_combo(ui, "settings-language", settings, overlays.detected) + }); + if draw.caps.unpack { + field( + ui, + Text::SettingsOutput, + Some(Text::SettingsOutputHelp), + |ui| { + let label = super::detail::output_label(&settings.output); + ComboBox::from_id_salt("settings-output") + .selected_text(label) + .width(260.0) + .show_ui(ui, |ui| { + if ui + .selectable_label( + settings.output == Output::Beside, + t(Text::TbOutputBeside), + ) + .clicked() + { + settings.output = Output::Beside; + } + if let Some(recent) = settings.recent_output.clone() { + let on = settings.output == Output::Folder(recent.clone()); + if ui + .selectable_label(on, recent.display().to_string()) + .clicked() + { + settings.output = Output::Folder(recent); + } + } + if ui + .selectable_label(false, t(Text::SettingsOutputChoose)) + .clicked() + { + draw.act(Action::Pick(Pick::Output)); + } + }) + .response + }, + ); + field(ui, Text::SettingsLog, Some(Text::SettingsLogHelp), |ui| { + ui.checkbox(&mut settings.write_log, "") + }); + } + } + SettingsTab::Processing => { + let cores = std::thread::available_parallelism().map_or(1, usize::from); + field(ui, Text::SettingsThreads, None, |ui| { + let label = |threads: usize| { + if threads == 0 { + t(Text::SettingsThreadsAuto { + n: cores.to_string(), + }) + .into_owned() + } else { + threads.to_string() + } + }; + ComboBox::from_id_salt("settings-threads") + .selected_text(label(settings.threads)) + .show_ui(ui, |ui| { + let mut choices = vec![0, 1, 2, 4, 8, 16, 32, 64]; + choices.retain(|count| *count == 0 || *count <= cores); + if !choices.contains(&cores) { + choices.push(cores); + } + for count in choices { + ui.selectable_value(&mut settings.threads, count, label(count)); + } + }) + .response + }); + field( + ui, + Text::SettingsScanAll, + Some(Text::SettingsScanAllHelp), + |ui| ui.checkbox(&mut settings.scan_all, ""), + ); + } + SettingsTab::Android => { + widgets::note(ui, t(Text::SettingsAndroidNote)); + field( + ui, + Text::SettingsMaxEntry, + Some(Text::SettingsMaxEntryHelp), + |ui| mib(ui, &mut settings.max_entry_mib), + ); + field( + ui, + Text::SettingsMaxTotal, + Some(Text::SettingsMaxTotalHelp), + |ui| mib(ui, &mut settings.max_total_mib), + ); + field( + ui, + Text::SettingsMaxEntries, + Some(Text::SettingsMaxEntriesHelp), + |ui| { + ui.add( + egui::DragValue::new(&mut settings.max_entries) + .range(1..=100_000_000) + .speed(100.0), + ) + }, + ); + field( + ui, + Text::SettingsMaxDepth, + Some(Text::SettingsMaxDepthHelp), + |ui| ui.add(egui::DragValue::new(&mut settings.max_depth).range(0..=1024)), + ); + } + SettingsTab::Memory => { + field( + ui, + Text::SettingsKeepBytes, + Some(Text::SettingsKeepBytesHelp), + |ui| ui.checkbox(&mut settings.keep_bytes, ""), + ); + field( + ui, + Text::SettingsKeepCap, + Some(Text::SettingsKeepCapHelp), + |ui| { + ui.add_enabled_ui(settings.keep_bytes, |ui| { + mib(ui, &mut settings.keep_cap_mib) + }) + .inner + }, + ); + } + SettingsTab::About => about(ui, view, overlays), + } +} + +fn about(ui: &mut Ui, view: &mut ViewState, overlays: &Overlays<'_>) { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 14.0; + if let Some(image) = icon_image(overlays.icon, 72.0) { + ui.add(image); + } + ui.vertical(|ui| { + ui.label(RichText::new("Senbei").font(theme::title(22.0))); + ui.label(widgets::dim(t(Text::AboutVersion { + v: env!("CARGO_PKG_VERSION").to_owned(), + }))); + }); + }); + ui.add(egui::Label::new(widgets::dim(t(Text::AboutDesc))).wrap()); + info_row(ui, Text::AboutLicense, |ui| { + ui.label("AGPL-3.0-only"); + }); + info_row(ui, Text::AboutSource, |ui| { + ui.hyperlink_to( + RichText::new("github.com/Momoko-Ayase/Senbei").font(theme::mono()), + "https://github.com/Momoko-Ayase/Senbei", + ); + }); + if ui.button(t(Text::AboutLegal)).clicked() { + view.settings_open = false; + view.legal_open = true; + } +} diff --git a/senbei-gui/src/ui/hex.rs b/senbei-gui/src/ui/hex.rs new file mode 100644 index 0000000..7f8356f --- /dev/null +++ b/senbei-gui/src/ui/hex.rs @@ -0,0 +1,1132 @@ +//! The hex view: the original file, its spliced view, or the restored image, +//! with regions, a byte inspector, go-to, and find. + +use std::collections::HashMap; +use std::sync::Arc; + +use egui::text::LayoutJob; +use egui::{ + Align, Color32, CornerRadius, FontId, Key, Layout, Margin, Rect, RichText, ScrollArea, Sense, + Stroke, StrokeKind, TextFormat, Ui, UiBuilder, pos2, vec2, +}; +use senbei_engine::windows::PeInspection; +use senbei_io::report::{CompanionState, EntryReport, ResearchInputView}; +use serde_json::Value; + +use super::{Action, Draw, HexState, HexView, Loaded, Session, ViewState, widgets}; +use crate::backend::{Identity, Produced, Source}; +use crate::format; +use crate::labels::{self, tv}; +use crate::model::{Item, Sel}; +use crate::text::{Text, t}; +use crate::theme; + +/// What the hex view shows bytes of. +#[derive(Clone, Copy)] +pub enum Subject<'a> { + Item(&'a Item), + Entry { + item: &'a Item, + entry: &'a EntryReport, + }, +} + +impl<'a> Subject<'a> { + fn item(&self) -> &'a Item { + match self { + Subject::Item(item) | Subject::Entry { item, .. } => item, + } + } + + fn windows(&self) -> Option<&'a senbei_io::report::WindowsResearchReport> { + match self { + Subject::Item(item) => item.result.as_ref()?.report.research.as_ref(), + Subject::Entry { .. } => None, + } + } + + fn android(&self) -> Option<&'a senbei_io::report::AndroidResearchReport> { + match self { + Subject::Item(item) => item.result.as_ref()?.report.android_research.as_ref(), + Subject::Entry { entry, .. } => entry.android_research.as_ref(), + } + } + + /// The `._` file this loader is spliced with, when it is. + fn companion(&self) -> Option { + let Subject::Item(item) = self else { + return None; + }; + match (&item.result, &item.identity) { + (Some(result), _) => { + let companion = result.report.companion.as_ref()?; + (companion.state == CompanionState::Spliced) + .then(|| companion.path.clone().map(Into::into)) + .flatten() + } + ( + None, + Some(Identity::Windows { + companion: CompanionState::Spliced, + companion_path: Some(path), + .. + }), + ) => Some(path.into()), + _ => None, + } + } + + fn restored(&self) -> Option<&'a Produced> { + match self { + Subject::Item(item) => item.result.as_ref()?.restored.as_ref(), + Subject::Entry { item, entry, .. } => item.result.as_ref()?.entry_bytes(&entry.name), + } + } +} + +/// The subject a selection shows, if it has bytes. +fn subject_of(session: &Session, sel: Option) -> Option> { + match sel? { + Sel::Group(_) => None, + Sel::Item(id) => session.item(id).map(|(_, item)| Subject::Item(item)), + Sel::Entry(id, index) => { + let (_, item) = session.item(id)?; + let entry = item.entries().get(index)?; + Some(Subject::Entry { item, entry }) + } + } +} + +/// Where a view's bytes come from. +enum Origin { + Bytes(Arc<[u8]>), + Load(Source), + Note(Text), +} + +fn views(subject: &Subject<'_>) -> Vec { + let mut views = vec![HexView::Original]; + if subject.companion().is_some() { + views.push(HexView::Spliced); + } + if matches!( + subject.restored(), + Some(Produced::Kept(_) | Produced::OnDisk(_) | Produced::TooLarge(_)) + ) { + views.push(HexView::Restored); + } + views +} + +fn origin(subject: &Subject<'_>, view: HexView) -> Option { + match view { + HexView::Original => Some(Origin::Load(match subject { + Subject::Item(item) => Source::File(item.path.clone()), + Subject::Entry { item, entry, .. } => Source::Entry { + package: item.path.clone(), + label: entry.name.clone(), + }, + })), + HexView::Spliced => Some(Origin::Load(Source::Spliced { + stub: subject.item().path.clone(), + companion: subject.companion()?, + })), + HexView::Restored => match subject.restored()? { + Produced::Kept(bytes) => Some(Origin::Bytes(bytes.clone())), + Produced::OnDisk(path) => Some(Origin::Load(Source::File(path.clone()))), + Produced::TooLarge(_) => Some(Origin::Note(Text::SettingsKeepCapHelp)), + Produced::NotKept => None, + }, + } +} + +fn current_view(subject: &Subject<'_>, state: &HexState) -> HexView { + let views = views(subject); + match state.view { + Some(view) if views.contains(&view) => view, + _ if views.contains(&HexView::Spliced) => HexView::Spliced, + _ => HexView::Original, + } +} + +/// The bytes the hex view shows for the selection, when they are loaded. +pub fn current_bytes( + session: &Session, + loaded: &HashMap, + view: &ViewState, +) -> Option> { + let subject = subject_of(session, view.selected)?; + match origin(&subject, current_view(&subject, &view.hex))? { + Origin::Bytes(bytes) => Some(bytes), + Origin::Load(source) => match loaded.get(&source)? { + Loaded::Ready(bytes) => Some(bytes.clone()), + _ => None, + }, + Origin::Note(_) => None, + } +} + +/// Find the needle after the cursor. +pub fn find(bytes: &[u8], state: &mut HexState) { + let needle = format::parse_needle(&state.find); + if needle.is_empty() { + return; + } + let from = state + .focus + .map_or(0, |focus| (focus as usize).saturating_add(1)); + let found = bytes.get(from..).and_then(|rest| { + rest.windows(needle.len()) + .position(|window| window == needle) + }); + match found { + Some(position) => { + let at = (from + position) as u64; + state.focus = Some(at); + state.highlight = Some((at, at + needle.len() as u64)); + state.note = None; + state.reveal = true; + } + None => state.note = Some(t(Text::HexFindNone).into_owned()), + } +} + +// ------------------------------------------------------------- addresses + +/// The file offset of `rva` in an image, if a section or the headers back it. +pub fn rva_to_offset(pe: Option<&PeInspection>, rva: u64) -> Option { + let pe = pe?; + for section in &pe.sections { + let start = u64::from(section.virtual_address); + let span = u64::from(section.virtual_size.max(section.raw_size)); + if rva >= start && rva < start + span { + let delta = rva - start; + return (delta < u64::from(section.raw_size)) + .then(|| u64::from(section.raw_offset) + delta); + } + } + (rva < u64::from(pe.size_of_headers.unwrap_or(0))).then_some(rva) +} + +/// The RVA a file offset maps to, with its section's name. +pub fn offset_to_rva(pe: Option<&PeInspection>, offset: u64) -> Option<(u64, Option<&str>)> { + let pe = pe?; + for section in &pe.sections { + let start = u64::from(section.raw_offset); + if offset >= start && offset < start + u64::from(section.raw_size) { + return Some(( + u64::from(section.virtual_address) + (offset - start), + Some(section.name.as_str()), + )); + } + } + (offset < u64::from(pe.size_of_headers.unwrap_or(0))).then_some((offset, None)) +} + +/// The PE headers that describe a view's bytes. +fn view_pe<'a>(subject: &Subject<'a>, view: HexView) -> Option<&'a PeInspection> { + let research = subject.windows()?; + match view { + HexView::Restored => research.restored.as_ref()?.pe.as_ref(), + // The research offsets address the spliced view; the bare loader + // shares only its header page with it. + HexView::Original if research.input_view == ResearchInputView::SplicedCompanion => None, + _ => research.input.pe.as_ref(), + } +} + +// --------------------------------------------------------------- regions + +pub struct Region { + pub name: String, + pub start: u64, + pub end: u64, + pub color: Color32, +} + +fn le_u16(bytes: &[u8], at: usize) -> Option { + Some(u16::from_le_bytes(bytes.get(at..at + 2)?.try_into().ok()?)) +} + +fn le_u32(bytes: &[u8], at: usize) -> Option { + Some(u32::from_le_bytes(bytes.get(at..at + 4)?.try_into().ok()?)) +} + +fn le_u64(bytes: &[u8], at: usize) -> Option { + Some(u64::from_le_bytes(bytes.get(at..at + 8)?.try_into().ok()?)) +} + +fn json_u64(value: &Value, key: &str) -> Option { + value.get(key)?.as_u64() +} + +fn elf_regions(subject: &Subject<'_>, view: HexView, bytes: &[u8]) -> Vec { + let mut regions = Vec::new(); + if bytes.len() >= 0x40 && bytes.starts_with(b"\x7fELF") { + let program_headers = le_u64(bytes, 0x20).unwrap_or(0); + let entry_size = u64::from(le_u16(bytes, 0x36).unwrap_or(0)); + let count = u64::from(le_u16(bytes, 0x38).unwrap_or(0)); + regions.push(Region { + name: t(Text::HexRElfHeader).into_owned(), + start: 0, + end: 0x40, + color: theme::REGION_HEADERS, + }); + regions.push(Region { + name: t(Text::HexRProgramHeaders).into_owned(), + start: program_headers, + end: program_headers + entry_size * count, + color: theme::REGION_OTHER, + }); + let mut load = 0; + for index in 0..count { + let Ok(at) = usize::try_from(program_headers + index * entry_size) else { + break; + }; + if at + 0x38 > bytes.len() { + break; + } + if le_u32(bytes, at) != Some(1) { + continue; + } + let start = le_u64(bytes, at + 8).unwrap_or(0); + let size = le_u64(bytes, at + 0x20).unwrap_or(0); + regions.push(Region { + name: t(Text::HexRLoad { + n: load.to_string(), + }) + .into_owned(), + start, + end: start + size, + color: theme::SECTION_COLORS[load % theme::SECTION_COLORS.len()], + }); + load += 1; + } + } + if view == HexView::Original + && let Some(stage1) = subject + .android() + .and_then(|research| research.extraction.get("stage1")) + { + let span = |offset: &str, size: &str| -> Option<(u64, u64)> { + let start = json_u64(stage1, offset)?; + Some((start, start + json_u64(stage1, size)?)) + }; + for (name, offset, size, color) in [ + ( + Text::HexRPrivateSection, + "section_offset", + "section_size", + theme::REGION_PROTECTION, + ), + ( + Text::HexRStage2, + "stage2_file_offset", + "stage2_size", + theme::REGION_PREFIX, + ), + ( + Text::HexRStreams, + "remaining_file_offset", + "remaining_size", + theme::REGION_TAIL, + ), + ] { + if let Some((start, end)) = span(offset, size) { + regions.push(Region { + name: t(name).into_owned(), + start, + end, + color, + }); + } + } + } + regions +} + +fn regions(subject: &Subject<'_>, view: HexView, bytes: &[u8]) -> Vec { + if subject.android().is_some() || bytes.starts_with(b"\x7fELF") { + return elf_regions(subject, view, bytes); + } + let mut regions = Vec::new(); + let Some(research) = subject.windows() else { + return regions; + }; + let section_regions = |regions: &mut Vec, pe: &PeInspection, restored: bool| { + for (index, section) in pe.sections.iter().enumerate() { + let start = u64::from(section.raw_offset); + regions.push(Region { + name: section.name.clone(), + start, + end: if restored { + start + u64::from(section.raw_size) + } else { + section.raw_end + }, + color: theme::SECTION_COLORS[index % theme::SECTION_COLORS.len()], + }); + } + }; + if view == HexView::Restored { + if let Some(pe) = research + .restored + .as_ref() + .and_then(|restored| restored.pe.as_ref()) + { + regions.push(Region { + name: t(Text::HexRHeaders).into_owned(), + start: 0, + end: u64::from(pe.size_of_headers.unwrap_or(0x1000)), + color: theme::REGION_HEADERS, + }); + section_regions(&mut regions, pe, true); + } + return regions; + } + let spliced = research.input_view == ResearchInputView::SplicedCompanion; + if view == HexView::Original && spliced { + regions.push(Region { + name: t(Text::HexRStubPage).into_owned(), + start: 0, + end: 0x1000, + color: theme::REGION_HEADERS, + }); + return regions; + } + let Some(pe) = research.input.pe.as_ref() else { + return regions; + }; + regions.push(Region { + name: t(Text::HexRHeaders).into_owned(), + start: 0, + end: 0x1000, + color: theme::REGION_HEADERS, + }); + if let Some(protection) = &research.input.protection { + if let (Some(first), Some(last)) = ( + protection.header_words.first(), + protection.header_words.last(), + ) { + regions.push(Region { + name: t(Text::HexRHeaderTable).into_owned(), + start: first.source_file_offset, + end: last.source_file_offset + 4, + color: theme::REGION_PROTECTION, + }); + } + if let Some(payload) = &protection.payload { + for check in payload + .checks + .iter() + .filter(|check| check.name.starts_with("source_")) + { + regions.push(Region { + name: crate::labels::tv_str("check", check.name).into_owned(), + start: check.start, + end: check.end, + color: if check.name == "source_prefix" { + theme::REGION_PREFIX + } else { + theme::REGION_TAIL + }, + }); + } + } + } + section_regions(&mut regions, pe, false); + if let Some(overlay) = &pe.overlay { + regions.push(Region { + name: tv("region", &senbei_engine::windows::FileRegionKind::Overlay).into_owned(), + start: overlay.offset, + end: overlay.offset + overlay.length, + color: theme::REGION_OTHER, + }); + } + regions +} + +/// The narrowest region holding `offset`, so a table inside a section shows. +fn region_at(regions: &[Region], offset: u64) -> Option<&Region> { + regions + .iter() + .filter(|region| offset >= region.start && offset < region.end) + .min_by_key(|region| region.end - region.start) +} + +// ------------------------------------------------------------------- tab + +const ROW: f32 = 19.0; +const SIDE: f32 = 250.0; + +/// The bytes of one view: ready, still loading (`Err(None)`), or a reason +/// they cannot be shown. Asks the backend for bytes it has not loaded. +pub fn view_bytes( + draw: &mut Draw<'_>, + subject: &Subject<'_>, + view: HexView, +) -> Result, Option> { + match origin(subject, view) { + Some(Origin::Bytes(bytes)) => Ok(bytes), + Some(Origin::Load(source)) => match draw.bytes.get(&source) { + Some(Loaded::Ready(bytes)) => Ok(bytes.clone()), + Some(Loaded::Failed(error)) => Err(Some(labels::load_error(error))), + Some(Loaded::Loading) => Err(None), + None => { + draw.act(Action::Load(source)); + Err(None) + } + }, + Some(Origin::Note(text)) => Err(Some(t(text).into_owned())), + None => Err(None), + } +} + +pub fn tab(ui: &mut Ui, draw: &mut Draw<'_>, view: &mut ViewState, subject: Subject<'_>) { + let full = ui.available_rect_before_wrap(); + let views = views(&subject); + let current = current_view(&subject, &view.hex); + view.hex.view = Some(current); + let bytes = view_bytes(draw, &subject, current); + let pe = view_pe(&subject, current); + let state = &mut view.hex; + + hex_bar(ui, state, &views, current, bytes.as_ref().ok(), pe); + widgets::rule(ui); + if current == HexView::Spliced { + egui::Frame::new() + .inner_margin(Margin::symmetric(12, 6)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + widgets::note(ui, t(Text::ResearchSplicedNote)); + }); + widgets::rule(ui); + } + let status_height = 24.0; + let top = ui.cursor().top(); + let main = Rect::from_min_max( + pos2(full.left(), top), + pos2( + full.right(), + (full.bottom() - status_height).max(top + 40.0), + ), + ); + let rows_rect = Rect::from_min_max(main.min, pos2(main.right() - SIDE, main.bottom())); + let side_rect = Rect::from_min_max(pos2(main.right() - SIDE, main.top()), main.max); + ui.painter().rect_filled(rows_rect, 0, theme::WELL); + ui.painter().rect_filled(side_rect, 0, theme::PANEL); + ui.painter().vline( + side_rect.left() + 0.5, + side_rect.y_range(), + Stroke::new(1.0, theme::BORDER), + ); + + let regions = match &bytes { + Ok(bytes) => regions(&subject, current, bytes), + Err(_) => Vec::new(), + }; + match &bytes { + Ok(bytes) => rows(ui, rows_rect, state, bytes, ®ions), + Err(message) => { + ui.scope_builder( + UiBuilder::new().max_rect(rows_rect.shrink(16.0)), + |ui| match message { + Some(message) => widgets::note(ui, message.clone()), + None => { + ui.spinner(); + } + }, + ); + } + } + ui.scope_builder( + UiBuilder::new().max_rect(side_rect.shrink2(vec2(10.0, 8.0))), + |ui| { + ScrollArea::vertical() + .id_salt("hex-side") + .auto_shrink([false, false]) + .show(ui, |ui| { + side_panel(ui, state, bytes.as_ref().ok(), pe, ®ions, current, draw); + }); + }, + ); + let status_rect = Rect::from_min_max(pos2(full.left(), main.bottom()), full.max); + ui.painter().hline( + status_rect.x_range(), + status_rect.top() + 0.5, + Stroke::new(1.0, theme::BORDER), + ); + ui.scope_builder( + UiBuilder::new().max_rect(status_rect.shrink2(vec2(12.0, 4.0))), + |ui| { + ui.horizontal_centered(|ui| { + ui.spacing_mut().item_spacing.x = 16.0; + status(ui, state, bytes.as_ref().ok(), ®ions, current); + }); + }, + ); + ui.allocate_rect( + Rect::from_min_max(pos2(full.left(), top), full.max), + Sense::hover(), + ); +} + +fn hex_bar( + ui: &mut Ui, + state: &mut HexState, + views: &[HexView], + current: HexView, + bytes: Option<&Arc<[u8]>>, + pe: Option<&PeInspection>, +) { + egui::Frame::new() + .inner_margin(Margin::symmetric(12, 8)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = 8.0; + let labels: Vec = views + .iter() + .map(|view| { + t(match view { + HexView::Original => Text::HexVOriginal, + HexView::Spliced => Text::HexVSpliced, + HexView::Restored => Text::HexVRestored, + }) + .into_owned() + }) + .collect(); + let index = views.iter().position(|view| *view == current).unwrap_or(0); + if let Some(chosen) = widgets::segmented(ui, &labels, index) { + state.view = Some(views[chosen]); + state.focus = None; + state.highlight = None; + state.note = None; + state.top = 0; + } + let goto_label = ui.label(widgets::dim(t(Text::HexGoto))); + let goto = ui + .add( + egui::TextEdit::singleline(&mut state.goto) + .font(theme::mono()) + .hint_text("0x14E0") + .desired_width(104.0), + ) + .labelled_by(goto_label.id); + if goto.lost_focus() && ui.input(|input| input.key_pressed(Key::Enter)) { + go_to(state, pe); + } + egui::ComboBox::from_id_salt("hex-goto-space") + .selected_text(t(if state.goto_rva { + Text::HexAsRva + } else { + Text::HexAsFile + })) + .show_ui(ui, |ui| { + ui.selectable_value(&mut state.goto_rva, false, t(Text::HexAsFile)); + ui.selectable_value(&mut state.goto_rva, true, t(Text::HexAsRva)); + }) + .response + .labelled_by(goto_label.id); + let (rect, _) = ui.allocate_exact_size(vec2(1.0, 20.0), Sense::hover()); + ui.painter().rect_filled(rect, 0, theme::BORDER); + let find_label = ui.label(widgets::dim(t(Text::HexFind))); + let find = ui + .add( + egui::TextEdit::singleline(&mut state.find) + .font(theme::mono()) + .hint_text(t(Text::HexFindHint)) + .desired_width(150.0), + ) + .labelled_by(find_label.id); + let enter = find.lost_focus() && ui.input(|input| input.key_pressed(Key::Enter)); + let next = widgets::ghost_button(ui, t(Text::HexFindNext)).on_hover_text("F3"); + if (enter || next.clicked()) + && let Some(bytes) = bytes + { + self::find(bytes, state); + if enter { + find.request_focus(); + } + } + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let selection = state.highlight.filter(|_| bytes.is_some()); + let copy = ui + .add_enabled_ui(selection.is_some(), |ui| { + widgets::ghost_button(ui, t(Text::HexCopySel)) + }) + .inner; + if copy.clicked() + && let (Some((start, end)), Some(bytes)) = (selection, bytes) + { + ui.ctx().copy_text(selection_text(bytes, start, end)); + } + }); + }); + }); +} + +fn selection_text(bytes: &[u8], start: u64, end: u64) -> String { + const MAX: u64 = 1024 * 1024; + let start = start.min(bytes.len() as u64) as usize; + let end = end.min(start as u64 + MAX).min(bytes.len() as u64) as usize; + bytes[start..end] + .iter() + .map(|byte| format!("{byte:02X}")) + .collect::>() + .join(" ") +} + +fn go_to(state: &mut HexState, pe: Option<&PeInspection>) { + let Some(value) = format::parse_hex(&state.goto) else { + return; + }; + let target = if state.goto_rva { + match rva_to_offset(pe, value) { + Some(offset) => offset, + None => { + state.note = Some( + t(Text::HexRvaUnmapped { + o: format::hex(value), + }) + .into_owned(), + ); + return; + } + } + } else { + value + }; + state.focus = Some(target); + state.highlight = Some((target, target + 16)); + state.note = None; + state.reveal = true; +} + +/// The byte rows, scrolled by row index so files of any size scroll exactly. +fn rows(ui: &mut Ui, rect: Rect, state: &mut HexState, bytes: &[u8], regions: &[Region]) { + let id = ui.scope_id().with("hex-rows"); + let response = ui.interact(rect, id, Sense::click()); + let len = bytes.len() as u64; + let total = len.div_ceil(16).max(1); + let visible = (((rect.height() - 12.0) / ROW).floor().max(1.0)) as u64; + let max_top = total.saturating_sub(visible); + if state.reveal { + if let Some(focus) = state.focus { + state.top = (focus / 16).saturating_sub(visible / 2).min(max_top); + } + state.reveal = false; + } + // Wheel and keys scroll whole rows; fractions carry over between frames. + if ui.rect_contains_pointer(rect) { + let delta = ui.input(|input| input.smooth_scroll_delta.y); + if delta != 0.0 { + let carry: f32 = ui + .data(|data| data.get_temp(id.with("carry"))) + .unwrap_or(0.0); + let rows = carry - delta / ROW; + let whole = rows.trunc(); + ui.data_mut(|data| data.insert_temp(id.with("carry"), rows - whole)); + state.top = (state.top as i64 + whole as i64).clamp(0, max_top as i64) as u64; + } + let (page_down, page_up, home, end) = ui.input(|input| { + ( + input.key_pressed(Key::PageDown), + input.key_pressed(Key::PageUp), + input.key_pressed(Key::Home) && input.modifiers.command, + input.key_pressed(Key::End) && input.modifiers.command, + ) + }); + if page_down { + state.top = (state.top + visible).min(max_top); + } + if page_up { + state.top = state.top.saturating_sub(visible); + } + if home { + state.top = 0; + } + if end { + state.top = max_top; + } + } + state.top = state.top.min(max_top); + + let font = theme::mono(); + let char_width = ui + .painter() + .layout_no_wrap("0".into(), font.clone(), theme::TEXT) + .size() + .x; + let strip_x = rect.left(); + let offset_right = rect.left() + 4.0 + 10.0 + 92.0; + let hex_x = offset_right + 10.0; + let hex_col = |index: usize| (index * 3 + usize::from(index >= 8)) as f32 * char_width; + let ascii_x = hex_x + hex_col(15) + 2.0 * char_width + 18.0; + let painter = ui.painter_at(rect); + + // Click and shift-click on a byte. + if response.clicked() + && let Some(pos) = response.interact_pointer_pos() + { + let row = state.top + ((pos.y - rect.top() - 6.0) / ROW).floor().max(0.0) as u64; + let column = if pos.x >= ascii_x { + Some(((pos.x - ascii_x) / char_width).floor() as i64) + } else if pos.x >= hex_x { + (0..16) + .find(|index| { + let left = hex_x + hex_col(*index); + pos.x >= left && pos.x < left + 2.5 * char_width + }) + .map(|index| index as i64) + } else { + None + }; + if let Some(column) = column.filter(|column| (0..16).contains(column)) { + let offset = row * 16 + column as u64; + if offset < len { + let extend = ui.input(|input| input.modifiers.shift); + match (extend, state.focus) { + (true, Some(focus)) => { + state.highlight = Some((focus.min(offset), focus.max(offset) + 1)); + } + _ => { + state.focus = Some(offset); + state.highlight = Some((offset, offset + 1)); + } + } + state.note = None; + } + } + } + + for line in 0..=visible { + let row = state.top + line; + if row >= total { + break; + } + let base = row * 16; + let y = rect.top() + 6.0 + line as f32 * ROW; + if let Some(region) = region_at(regions, base) { + painter.rect_filled( + Rect::from_min_size(pos2(strip_x, y), vec2(4.0, ROW)), + 0, + region.color, + ); + } + let focus_row = state.focus.is_some_and(|focus| focus / 16 == row); + let offset_text = format!("{base:08X}"); + let offset = painter.layout_no_wrap( + offset_text, + font.clone(), + if focus_row { + theme::ACCENT + } else { + theme::FAINT + }, + ); + painter.galley( + pos2(offset_right - offset.size().x, y + 1.0), + offset, + theme::FAINT, + ); + let end = (base + 16).min(len); + let chunk = &bytes[base as usize..end as usize]; + let mut hex_job = LayoutJob::default(); + let mut ascii_job = LayoutJob::default(); + for (index, byte) in chunk.iter().enumerate() { + let at = base + index as u64; + let lit = state + .highlight + .is_some_and(|(start, end)| at >= start && at < end); + let cursor = state.focus == Some(at); + if lit { + painter.rect_filled( + Rect::from_min_size( + pos2(hex_x + hex_col(index) - 1.0, y), + vec2(2.0 * char_width + 2.0, ROW), + ), + 0, + theme::highlight(), + ); + painter.rect_filled( + Rect::from_min_size( + pos2(ascii_x + index as f32 * char_width, y), + vec2(char_width, ROW), + ), + 0, + theme::highlight(), + ); + } + if cursor { + let stroke = Stroke::new(1.0, theme::ACCENT); + painter.rect_stroke( + Rect::from_min_size( + pos2(hex_x + hex_col(index) - 1.0, y), + vec2(2.0 * char_width + 2.0, ROW), + ), + CornerRadius::ZERO, + stroke, + StrokeKind::Inside, + ); + painter.rect_stroke( + Rect::from_min_size( + pos2(ascii_x + index as f32 * char_width, y), + vec2(char_width, ROW), + ), + CornerRadius::ZERO, + stroke, + StrokeKind::Inside, + ); + } + let color = if lit || cursor { + theme::HIGHLIGHT_TEXT + } else if *byte == 0 { + theme::ZERO_BYTE + } else { + theme::TEXT + }; + let gap = if index == 7 { " " } else { " " }; + let format = TextFormat { + font_id: font.clone(), + color, + ..Default::default() + }; + hex_job.append(&format!("{byte:02X}"), 0.0, format.clone()); + if index + 1 < chunk.len() { + hex_job.append(gap, 0.0, format); + } + let character = if (0x20..0x7f).contains(byte) { + char::from(*byte) + } else { + '.' + }; + ascii_job.append( + &character.to_string(), + 0.0, + TextFormat { + font_id: font.clone(), + color: if lit || cursor { + theme::HIGHLIGHT_TEXT + } else { + theme::DIM + }, + ..Default::default() + }, + ); + } + let hex = painter.layout_job(hex_job); + painter.galley(pos2(hex_x, y + 1.0), hex, theme::TEXT); + let ascii = painter.layout_job(ascii_job); + painter.galley(pos2(ascii_x, y + 1.0), ascii, theme::DIM); + } + scrollbar(ui, rect, id, state, total, visible, max_top); +} + +fn scrollbar( + ui: &mut Ui, + rect: Rect, + id: egui::Id, + state: &mut HexState, + total: u64, + visible: u64, + max_top: u64, +) { + if max_top == 0 { + return; + } + let bar = Rect::from_min_max(pos2(rect.right() - 10.0, rect.top()), rect.max); + let response = ui.interact(bar, id.with("bar"), Sense::click_and_drag()); + let thumb_height = (bar.height() * visible as f32 / total as f32).clamp(24.0, bar.height()); + let travel = (bar.height() - thumb_height).max(1.0); + if (response.dragged() || response.clicked()) + && let Some(pos) = response.interact_pointer_pos() + { + let fraction = ((pos.y - bar.top() - thumb_height / 2.0) / travel).clamp(0.0, 1.0); + state.top = (f64::from(fraction) * max_top as f64).round() as u64; + } + let fraction = state.top as f64 / max_top as f64; + let thumb = Rect::from_min_size( + pos2( + bar.left() + 2.0, + bar.top() + (fraction * f64::from(travel)) as f32, + ), + vec2(6.0, thumb_height), + ); + let color = if response.hovered() || response.dragged() { + theme::HOVER_STROKE + } else { + Color32::from_rgb(0x35, 0x3a, 0x44) + }; + ui.painter() + .rect_filled(thumb, CornerRadius::same(3), color); +} + +fn side_panel( + ui: &mut Ui, + state: &HexState, + bytes: Option<&Arc<[u8]>>, + pe: Option<&PeInspection>, + regions: &[Region], + current: HexView, + draw: &mut Draw<'_>, +) { + let heading = |ui: &mut Ui, text: Text| { + ui.add_space(4.0); + ui.label( + RichText::new(t(text).to_uppercase()) + .font(theme::small()) + .color(theme::FAINT), + ); + ui.add_space(2.0); + }; + heading(ui, Text::HexInspector); + match (state.focus, bytes) { + (Some(focus), Some(bytes)) => inspector(ui, bytes, focus, pe), + _ => { + ui.label(widgets::faint(t(Text::HexInspectorHint))); + } + } + ui.add_space(10.0); + heading(ui, Text::HexRegions); + if regions.is_empty() { + ui.label(widgets::faint(t(Text::HexNoRegions))); + return; + } + for region in regions { + let (rect, response) = + ui.allocate_exact_size(vec2(ui.available_width(), 38.0), Sense::click()); + widgets::describe(&response, egui::Role::Button, ®ion.name, None); + if response.hovered() { + ui.painter() + .rect_filled(rect, CornerRadius::same(4), theme::row_hover()); + } + ui.painter().rect_filled( + Rect::from_min_size(rect.min + vec2(6.0, 8.0), vec2(10.0, 10.0)), + CornerRadius::same(2), + region.color, + ); + let name = ui + .painter() + .layout_no_wrap(region.name.clone(), theme::body(), theme::TEXT); + ui.painter() + .galley(rect.min + vec2(24.0, 4.0), name, theme::TEXT); + let range = ui.painter().layout_no_wrap( + format!( + "{} – {}", + format::hex(region.start), + format::hex(region.end) + ), + FontId::monospace(11.5), + theme::FAINT, + ); + ui.painter() + .galley(rect.min + vec2(24.0, 22.0), range, theme::FAINT); + if response + .on_hover_cursor(egui::CursorIcon::PointingHand) + .clicked() + { + draw.act(Action::JumpView { + view: current, + offset: region.start, + }); + } + } +} + +fn inspector(ui: &mut Ui, bytes: &[u8], focus: u64, pe: Option<&PeInspection>) { + let Ok(at) = usize::try_from(focus) else { + return; + }; + let Some(&byte) = bytes.get(at) else { + return; + }; + let mut rows: Vec<(&str, String, String)> = + vec![("u8", format::hex_w(u64::from(byte), 2), byte.to_string())]; + if let Some(value) = le_u16(bytes, at) { + rows.push(( + "u16 LE", + format::hex_w(u64::from(value), 4), + format::num(u64::from(value)), + )); + } + if let Some(value) = le_u32(bytes, at) { + rows.push(( + "u32 LE", + format::hex_w(u64::from(value), 8), + format::num(u64::from(value)), + )); + } + if let Some(value) = le_u64(bytes, at) { + rows.push(("u64 LE", format::hex_w(value, 16), String::new())); + } + if let Some((rva, section)) = offset_to_rva(pe, focus) { + rows.push(( + "RVA", + format::hex(rva), + section.unwrap_or_default().to_owned(), + )); + } + egui::Grid::new("hex-inspector") + .num_columns(2) + .spacing(vec2(10.0, 1.0)) + .show(ui, |ui| { + for (key, value, aside) in rows { + ui.label( + RichText::new(key) + .font(FontId::monospace(11.5)) + .color(theme::DIM), + ); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + widgets::selectable(ui, RichText::new(value).font(FontId::monospace(11.5))); + if !aside.is_empty() { + ui.label(widgets::faint(aside).font(FontId::monospace(11.5))); + } + }); + ui.end_row(); + } + }); +} + +fn status( + ui: &mut Ui, + state: &HexState, + bytes: Option<&Arc<[u8]>>, + regions: &[Region], + current: HexView, +) { + let small = |text: String| RichText::new(text).font(theme::small()).color(theme::DIM); + if let Some(bytes) = bytes { + ui.label(small( + t(Text::HexSize { + s: format::bytes(bytes.len() as u64), + }) + .into_owned(), + )); + } + if let Some(focus) = state.focus { + let mut text = t(Text::HexAt { + o: format::hex(focus), + }) + .into_owned(); + if let Some(region) = region_at(regions, focus) { + text.push_str(" · "); + text.push_str(®ion.name); + } + ui.label(small(text)); + if current == HexView::Spliced { + ui.label(small(if focus >= 0x1000 { + t(Text::HexInCompanion { + o: format::hex(focus - 0x1000), + }) + .into_owned() + } else { + t(Text::HexInStub).into_owned() + })); + } + } + if let Some(note) = &state.note { + ui.label(RichText::new(note).font(theme::small()).color(theme::WARN)); + } +} diff --git a/senbei-gui/src/ui/inputs.rs b/senbei-gui/src/ui/inputs.rs new file mode 100644 index 0000000..9a88e12 --- /dev/null +++ b/senbei-gui/src/ui/inputs.rs @@ -0,0 +1,656 @@ +//! The inputs panel: groups, the inputs in them, and package entries. + +use egui::text::{LayoutJob, TextWrapping}; +use egui::{ + Align, Align2, Color32, CornerRadius, FontId, Frame, Layout, Margin, Pos2, Rect, Response, + RichText, ScrollArea, Sense, Stroke, Ui, pos2, vec2, +}; +use senbei_io::report::{EntryReport, Mode}; + +use super::{Action, Draw, ViewState, widgets}; +use crate::format; +use crate::labels::tv; +use crate::model::{ + Counts, Filter, Group, GroupKind, Item, RunState, Sel, Verdict, entry_inner, entry_tag, + is_target_entry, kind_tag, mode_label, +}; +use crate::text::{Text, t}; +use crate::theme::{self, Tone}; + +const ROW_HEIGHT: f32 = 44.0; +const GROUP_HEIGHT: f32 = 26.0; +const GROUP_SUB_HEIGHT: f32 = 16.0; + +pub fn panel(ui: &mut Ui, draw: &mut Draw<'_>, view: &mut ViewState) { + let idle = draw.jobs.running.is_none() && draw.jobs.queued.is_empty(); + let any_result = draw.session.items().any(|item| item.result.is_some()); + Frame::new() + .inner_margin(Margin { + left: 10, + right: 10, + top: 8, + bottom: 6, + }) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.spacing_mut().item_spacing.y = 6.0; + ui.horizontal(|ui| { + ui.label(RichText::new(t(Text::InputsTitle)).font(theme::title(15.0))); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let clear = ui + .add_enabled_ui(idle, |ui| widgets::ghost_button(ui, t(Text::InputsClear))) + .inner; + if clear.clicked() { + draw.act(Action::Clear); + } + }); + }); + if any_result { + let counts = counts(draw); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(4.0, 4.0); + for filter in Filter::ALL { + let on = view.filter == filter; + if widgets::chip(ui, &filter.label(), counts.get(filter), on).clicked() { + view.filter = filter; + } + } + }); + } + ui.add( + egui::TextEdit::singleline(&mut view.search) + .hint_text(t(Text::InputsSearch)) + .desired_width(f32::INFINITY), + ); + }); + widgets::rule(ui); + let rows = RowCtx { + idle, + caps: draw.caps, + }; + let session = draw.session; + let actions = &mut *draw.actions; + ScrollArea::vertical() + .id_salt("inputs-list") + .auto_shrink([false, false]) + .show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + ui.add_space(4.0); + let mut shown = 0; + for group in &session.groups { + shown += group_rows(ui, actions, &rows, group, view); + } + if shown == 0 { + ui.add_space(6.0); + ui.horizontal(|ui| { + ui.add_space(10.0); + ui.label(widgets::faint(t(Text::InputsNone))); + }); + } + ui.add_space(8.0); + }); +} + +/// What every row needs to know about the window. +struct RowCtx { + idle: bool, + caps: crate::backend::Capabilities, +} + +fn counts(draw: &Draw<'_>) -> Counts { + let mut counts = Counts::default(); + for item in draw.session.items() { + counts.inputs += 1; + if let Some(verdict) = item.verdict() { + counts.add(verdict); + } + } + counts +} + +fn name_matches(name: &str, search: &str) -> bool { + search.is_empty() || name.to_lowercase().contains(&search.to_lowercase()) +} + +fn visible(item: &Item, view: &ViewState) -> bool { + if view.filter != Filter::All + && let Some(verdict) = item.verdict() + && verdict.filter() != view.filter + { + return false; + } + if !view.search.is_empty() + && !name_matches(&item.name, &view.search) + && !item + .entries() + .iter() + .any(|entry| name_matches(format::base_name(entry_inner(&entry.name)), &view.search)) + { + return false; + } + true +} + +/// Draw one group; returns how many rows it showed. +fn group_rows( + ui: &mut Ui, + actions: &mut Vec, + rows: &RowCtx, + group: &Group, + view: &ViewState, +) -> usize { + let visible_items: Vec<&Item> = group + .items + .iter() + .filter(|item| visible(item, view)) + .collect(); + let filtering = view.filter != Filter::All || !view.search.is_empty(); + if visible_items.is_empty() && group.scanning.is_none() && filtering { + return 0; + } + group_header(ui, actions, group, view, visible_items.len()); + let mut shown = 1; + if !group.folded { + for item in visible_items { + item_row(ui, actions, rows, item, view); + shown += 1; + if !item.entries().is_empty() && !item.folded { + shown += entry_rows(ui, actions, rows, item, view); + } + } + } + shown +} + +/// A single-line galley cut to `width` with an ellipsis. +fn line( + ui: &Ui, + text: &str, + font: FontId, + color: Color32, + width: f32, +) -> std::sync::Arc { + let mut job = LayoutJob::simple_singleline(text.to_owned(), font, color); + job.wrap = TextWrapping::truncate_at_width(width.max(8.0)); + ui.painter().layout_job(job) +} + +fn caret(ui: &Ui, at: Pos2, folded: bool) -> Rect { + let rect = Rect::from_center_size(at, vec2(14.0, 14.0)); + ui.painter().text( + rect.center(), + Align2::CENTER_CENTER, + if folded { "▶" } else { "▼" }, + FontId::proportional(9.0), + theme::FAINT, + ); + rect +} + +/// Paint a row's background; returns the row's rect and response. +fn row_base(ui: &mut Ui, height: f32, selected: bool) -> (Rect, Response) { + let width = ui.available_width(); + let (rect, response) = ui.allocate_exact_size(vec2(width, height), Sense::click()); + if selected { + ui.painter().rect_filled(rect, 0, theme::selection()); + } else if response.hovered() { + ui.painter().rect_filled(rect, 0, theme::row_hover()); + } + (rect, response) +} + +fn toggle_pressed(ui: &Ui) -> bool { + ui.input(|input| input.modifiers.command) +} + +fn group_header( + ui: &mut Ui, + actions: &mut Vec, + group: &Group, + view: &ViewState, + visible: usize, +) { + let selected = view.selected == Some(Sel::Group(group.id)); + let sub = match (&group.kind, group.scanning) { + (_, Some(found)) => Some(( + t(Text::GroupScanning { + n: found.to_string(), + }) + .into_owned(), + theme::INFO, + )), + (GroupKind::Folder(root), None) => Some(( + match &group.last_run { + Some(run) => format!("{} · {}", mode_label(run.mode), root.display()), + None => root.display().to_string(), + }, + if selected { theme::DIM } else { theme::FAINT }, + )), + (GroupKind::Files, None) => None, + }; + ui.add_space(4.0); + let height = GROUP_HEIGHT + if sub.is_some() { GROUP_SUB_HEIGHT } else { 0.0 }; + let (rect, response) = row_base(ui, height, selected); + widgets::describe( + &response, + egui::Role::TreeItem, + &group.title(), + Some(selected), + ); + let left = rect.left() + 10.0; + let top = rect.top() + 5.0; + let caret_rect = caret(ui, pos2(left + 7.0, top + 8.0), group.folded); + let count = group.scanning.unwrap_or(visible).to_string(); + let count_galley = ui + .painter() + .layout_no_wrap(count, theme::small(), theme::FAINT); + let count_pos = pos2(rect.right() - 10.0 - count_galley.size().x, top); + let name_x = left + 20.0; + let name = line( + ui, + &group.title(), + theme::strong(12.5), + theme::TEXT, + count_pos.x - name_x - 6.0, + ); + ui.painter().galley(pos2(name_x, top), name, theme::TEXT); + ui.painter().galley(count_pos, count_galley, theme::FAINT); + if let Some((text, color)) = sub { + let galley = line( + ui, + &text, + theme::small(), + color, + rect.right() - 10.0 - name_x, + ); + ui.painter().galley(pos2(name_x, top + 17.0), galley, color); + } + let response = match group.root() { + Some(root) => response.on_hover_text(root.display().to_string()), + None => response, + }; + if response.clicked() { + let on_caret = response + .interact_pointer_pos() + .is_some_and(|pos| caret_rect.expand(3.0).contains(pos)); + if on_caret { + actions.push(Action::Fold(Sel::Group(group.id))); + } else { + actions.push(Action::Select { + sel: Sel::Group(group.id), + toggle: false, + }); + } + } +} + +/// The dot, label, and label colour of a row. +pub(super) struct RowState { + pub dot: Option, + pub label: String, + pub color: Color32, + pub extra: Option, + pub time: Option, +} + +pub(super) fn row_state(item: &Item) -> RowState { + let plain = |label: String, color: Color32| RowState { + dot: None, + label, + color, + extra: None, + time: None, + }; + match (item.run, &item.result) { + (RunState::Running, _) => RowState { + dot: Some(Tone::Info), + ..plain(t(Text::RunRunning).into_owned(), theme::INFO) + }, + (RunState::Queued, _) => plain(t(Text::RunQueued).into_owned(), theme::FAINT), + (RunState::WillNotRun, None) => plain(t(Text::RunWillNotRun).into_owned(), theme::FAINT), + (_, Some(result)) => { + let verdict = result.verdict(); + RowState { + dot: Some(verdict.tone()), + label: verdict.label().into_owned(), + color: verdict.tone().color(), + extra: Some(mode_label(result.mode).into_owned()), + time: Some(format::ms(result.report.duration_ms)), + } + } + (_, None) => { + let not_protected = item + .identity + .as_ref() + .is_some_and(crate::backend::Identity::not_protected); + plain( + t(if not_protected { + Text::PendingNotProtected + } else { + Text::PendingNotRun + }) + .into_owned(), + theme::FAINT, + ) + } + } +} + +/// Paint the two lines of an input or entry row. +#[allow(clippy::too_many_arguments)] +fn paint_row( + ui: &Ui, + rect: Rect, + indent: f32, + selected: bool, + name: &str, + tag: &str, + state: &RowState, + nested: bool, +) { + if selected { + ui.painter().rect_filled( + Rect::from_min_size(rect.min, vec2(2.0, rect.height())), + 0, + theme::BLUE, + ); + } + let top = rect.top() + 4.0; + let dot_center = pos2(rect.left() + indent + 4.0, top + 10.0); + widgets::paint_dot(ui, dot_center, state.dot); + let name_x = dot_center.x + 12.0; + let tag_galley = + ui.painter() + .layout_no_wrap(tag.to_owned(), FontId::proportional(11.0), theme::DIM); + let tag_size = tag_galley.size() + vec2(10.0, 1.0); + let tag_rect = Rect::from_min_size( + pos2( + rect.right() - 10.0 - tag_size.x, + top + 10.0 - tag_size.y / 2.0, + ), + tag_size, + ); + let name_galley = line( + ui, + name, + theme::body(), + theme::TEXT, + tag_rect.left() - name_x - 8.0, + ); + ui.painter() + .galley(pos2(name_x, top + 1.0), name_galley, theme::TEXT); + ui.painter().rect( + tag_rect, + CornerRadius::same(3), + Color32::TRANSPARENT, + Stroke::new(1.0, theme::BORDER), + egui::StrokeKind::Inside, + ); + ui.painter() + .galley(tag_rect.min + vec2(5.0, 0.5), tag_galley, theme::DIM); + + let meta_font = FontId::proportional(if nested { 11.0 } else { 11.5 }); + let meta_y = top + 21.0; + let faint = if selected { theme::DIM } else { theme::FAINT }; + let mut x = name_x; + let right = rect.right() - 10.0; + if let Some(time) = &state.time { + let galley = ui + .painter() + .layout_no_wrap(time.clone(), meta_font.clone(), faint); + let pos = pos2(right - galley.size().x, meta_y); + ui.painter().galley(pos, galley, faint); + } + let label_color = if state.dot.is_none() { + faint + } else { + state.color + }; + let label = line( + ui, + &state.label, + meta_font.clone(), + label_color, + right - x - 60.0, + ); + let width = label.size().x; + ui.painter().galley(pos2(x, meta_y), label, label_color); + x += width + 6.0; + if let Some(extra) = &state.extra { + let dot = ui + .painter() + .layout_no_wrap("·".to_owned(), meta_font.clone(), faint); + let dot_width = dot.size().x; + ui.painter().galley(pos2(x, meta_y), dot, faint); + x += dot_width + 6.0; + let extra = line(ui, extra, meta_font, faint, right - x - 60.0); + ui.painter().galley(pos2(x, meta_y), extra, faint); + } +} + +fn item_row(ui: &mut Ui, actions: &mut Vec, rows: &RowCtx, item: &Item, view: &ViewState) { + let sel = Sel::Item(item.id); + let selected = view.selected == Some(sel) || view.multi.contains(&sel); + let (rect, response) = row_base(ui, ROW_HEIGHT, selected); + widgets::describe(&response, egui::Role::TreeItem, &item.name, Some(selected)); + let has_entries = !item.entries().is_empty(); + let caret_rect = + has_entries.then(|| caret(ui, pos2(rect.left() + 16.0, rect.top() + 14.0), item.folded)); + paint_row( + ui, + rect, + 26.0, + selected, + &item.name, + &kind_tag(item), + &row_state(item), + false, + ); + let response = response.on_hover_text(item.path.display().to_string()); + if response.clicked() { + let on_caret = caret_rect.is_some_and(|caret| { + response + .interact_pointer_pos() + .is_some_and(|pos| caret.expand(3.0).contains(pos)) + }); + if on_caret { + actions.push(Action::Fold(sel)); + } else { + actions.push(Action::Select { + sel, + toggle: toggle_pressed(ui), + }); + } + } + row_menu(&response, actions, rows, item); +} + +fn entry_rows( + ui: &mut Ui, + actions: &mut Vec, + rows: &RowCtx, + item: &Item, + view: &ViewState, +) -> usize { + let entries = item.entries(); + let searching = !view.search.is_empty(); + let mut shown = 0; + for (index, entry) in entries.iter().enumerate() { + let name = format::base_name(entry_inner(&entry.name)); + let keep = if searching { + name_matches(name, &view.search) + } else { + is_target_entry(entry) + }; + if !keep { + continue; + } + entry_row(ui, actions, rows, item, index, entry, view); + shown += 1; + } + let others = entries + .iter() + .filter(|entry| !is_target_entry(entry)) + .count(); + if others > 0 && !searching { + let (rect, response) = row_base(ui, 24.0, false); + let text = t(Text::EntriesOthers { + n: others.to_string(), + }); + widgets::describe(&response, egui::Role::Button, &text, None); + let galley = line(ui, &text, theme::tiny(), theme::FAINT, rect.width() - 54.0); + ui.painter().galley( + pos2(rect.left() + 44.0 + 12.0, rect.top() + 2.0), + galley, + theme::FAINT, + ); + if response + .on_hover_cursor(egui::CursorIcon::PointingHand) + .clicked() + { + actions.push(Action::ShowEntries(item.id)); + } + shown += 1; + } + shown +} + +fn entry_row( + ui: &mut Ui, + actions: &mut Vec, + rows: &RowCtx, + item: &Item, + index: usize, + entry: &EntryReport, + view: &ViewState, +) { + let sel = Sel::Entry(item.id, index); + let selected = view.selected == Some(sel) || view.multi.contains(&sel); + let (rect, response) = row_base(ui, ROW_HEIGHT - 2.0, selected); + widgets::describe( + &response, + egui::Role::TreeItem, + format::base_name(entry_inner(&entry.name)), + Some(selected), + ); + let verdict = Verdict::of_entry(entry); + let state = RowState { + dot: Some(verdict.tone()), + label: verdict.label().into_owned(), + color: verdict.tone().color(), + extra: entry + .layout + .map(|layout| tv("layout", &layout).into_owned()), + time: None, + }; + let inner = entry_inner(&entry.name); + paint_row( + ui, + rect, + 44.0, + selected, + format::base_name(inner), + &entry_tag(entry), + &state, + true, + ); + let response = response.on_hover_text(entry_path(item, entry)); + if response.clicked() { + actions.push(Action::Select { + sel, + toggle: toggle_pressed(ui), + }); + } + row_menu_entry(&response, actions, rows, item, entry); +} + +/// `package › inner\path` for an entry. +pub fn entry_path(item: &Item, entry: &EntryReport) -> String { + format!( + "{} › {}", + item.path.display(), + entry_inner(&entry.name).replace('/', "\\") + ) +} + +fn run_items( + ui: &mut Ui, + actions: &mut Vec, + id: crate::backend::ItemId, + enabled: bool, + unpack: bool, +) { + for (mode, text) in [ + (Mode::Unpack, Text::TbUnpack), + (Mode::DryRun, Text::TbDryRun), + (Mode::Inspect, Text::TbInspect), + ] { + let allowed = enabled && (mode != Mode::Unpack || unpack); + if ui + .add_enabled(allowed, egui::Button::new(t(text))) + .clicked() + { + actions.push(Action::RunItem(mode, id)); + ui.close(); + } + } +} + +fn row_menu(response: &Response, actions: &mut Vec, rows: &RowCtx, item: &Item) { + let idle = rows.idle; + let protected = !item + .identity + .as_ref() + .is_some_and(crate::backend::Identity::not_protected); + let unpack = rows.caps.unpack; + let reveal = rows.caps.reveal; + response.context_menu(|ui| { + ui.set_min_width(200.0); + run_items(ui, actions, item.id, protected, unpack); + ui.separator(); + if reveal && ui.button(t(Text::OvOpenFolder)).clicked() { + actions.push(Action::Reveal(item.path.clone())); + ui.close(); + } + if ui.button(t(Text::MenuCopyPath)).clicked() { + ui.ctx().copy_text(item.path.display().to_string()); + ui.close(); + } + ui.separator(); + if ui + .add_enabled( + idle, + egui::Button::new(t(Text::MenuRemove)).shortcut_text("Del"), + ) + .clicked() + { + actions.push(Action::Remove(item.id)); + ui.close(); + } + }); +} + +fn row_menu_entry( + response: &Response, + actions: &mut Vec, + rows: &RowCtx, + item: &Item, + entry: &EntryReport, +) { + let path = entry_path(item, entry); + let reveal = rows.caps.reveal; + let unpack = rows.caps.unpack; + response.context_menu(|ui| { + ui.set_min_width(200.0); + run_items(ui, actions, item.id, true, unpack); + ui.separator(); + if reveal && ui.button(t(Text::OvOpenFolder)).clicked() { + actions.push(Action::Reveal(item.path.clone())); + ui.close(); + } + if ui.button(t(Text::MenuCopyPath)).clicked() { + ui.ctx().copy_text(path.clone()); + ui.close(); + } + }); +} diff --git a/senbei-gui/src/ui/logview.rs b/senbei-gui/src/ui/logview.rs new file mode 100644 index 0000000..68ab0ad --- /dev/null +++ b/senbei-gui/src/ui/logview.rs @@ -0,0 +1,201 @@ +//! The log tab: structured log lines in the display language. + +use egui::{Align, Layout, Margin, RichText, ScrollArea, Ui, vec2}; + +use super::{LogFilter, ViewState, widgets}; +use crate::format; +use crate::labels::{self, step_title}; +use crate::model::{Level, LogBody, LogLine, mode_action}; +use crate::text::{Text, t}; +use crate::theme; + +/// The text of one log line. +pub fn line_text(line: &LogLine) -> String { + match &line.body { + LogBody::RunStarted { mode, inputs } => t(Text::LogRunStarted { + mode: mode_action(*mode).into_owned(), + n: inputs.to_string(), + }) + .into_owned(), + LogBody::Scan { + candidates, + skipped, + } => t(Text::LogScan { + n: candidates.to_string(), + s: skipped.to_string(), + }) + .into_owned(), + LogBody::ScanIncomplete => t(Text::BatchScanIncomplete).into_owned(), + LogBody::InputStarted { index, total, path } => t(Text::LogInputStarted { + i: index.to_string(), + n: total.to_string(), + p: path.clone(), + }) + .into_owned(), + LogBody::Companion { name } => t(Text::LogCompanion { p: name.clone() }).into_owned(), + LogBody::Step { position, step } => match position { + Some((index, total)) => t(Text::LogStep { + i: index.to_string(), + n: total.to_string(), + s: step_title(step).into_owned(), + }) + .into_owned(), + None => step_title(step).into_owned(), + }, + LogBody::Detail(text) => text.clone(), + LogBody::Stage { + stage, + status, + duration, + detail, + } => { + let mut text = format!( + "{}: {}", + labels::tv("stage", stage), + labels::tv("stageStatus", status) + ); + if let Some(duration) = duration.filter(|duration| *duration > 0) { + text.push_str(&format!(" ({})", format::ms(duration))); + } + if let Some(detail) = detail { + let shown = labels::message(detail); + if !shown.quiet { + text.push_str(" — "); + text.push_str(&shown.text); + } + } + text + } + LogBody::Message(message) => labels::message(message).text, + LogBody::Entry { label, verdict } => t(Text::LogEntry { + p: label.replace('/', "\\"), + o: verdict.label().into_owned(), + }) + .into_owned(), + LogBody::Finished { verdict, duration } => t(Text::LogInputFinished { + o: verdict.label().into_owned(), + t: format::ms(*duration), + }) + .into_owned(), + LogBody::Summary(counts) => t(Text::LogSummary { + ok: counts.recovered.to_string(), + suspect: counts.suspect.to_string(), + failed: counts.failed.to_string(), + skipped: counts.skipped.to_string(), + }) + .into_owned(), + } +} + +fn level_label(level: Level) -> (String, egui::Color32) { + match level { + Level::Info => (t(Text::LogLvInfo).into_owned(), theme::SKIP), + Level::Step => (t(Text::LogLvStep).into_owned(), theme::INFO), + Level::Detail => (String::new(), theme::SKIP), + Level::Warn => (t(Text::LogLvWarn).into_owned(), theme::WARN), + Level::Error => (t(Text::LogLvError).into_owned(), theme::ERR), + } +} + +fn keep(filter: LogFilter, level: Level) -> bool { + match filter { + LogFilter::All => true, + LogFilter::NoSteps => !matches!(level, Level::Step | Level::Detail), + LogFilter::Problems => matches!(level, Level::Warn | Level::Error), + } +} + +/// The log as plain text, for the clipboard. +pub fn plain(lines: &[LogLine], filter: LogFilter) -> String { + let mut out = String::new(); + for line in lines.iter().filter(|line| keep(filter, line.level)) { + let (level, _) = level_label(line.level); + out.push_str(&format!("{} {:<6} {}\n", line.at, level, line_text(line))); + } + out +} + +/// Log lines without a bar or scroll of their own. +pub fn log_box(ui: &mut Ui, filter: LogFilter, lines: &[LogLine]) { + ui.scope(|ui| { + ui.spacing_mut().item_spacing.y = 1.0; + for line in lines.iter().filter(|line| keep(filter, line.level)) { + log_line(ui, line); + } + }); +} + +fn log_line(ui: &mut Ui, line: &LogLine) { + let detail = line.level == Level::Detail; + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = 10.0; + let font = if detail { + theme::mono_small() + } else { + theme::mono() + }; + ui.allocate_ui_with_layout(vec2(96.0, 16.0), Layout::left_to_right(Align::Min), |ui| { + ui.set_width(96.0); + ui.label( + RichText::new(&line.at) + .font(font.clone()) + .color(theme::FAINT), + ); + }); + let (level, color) = level_label(line.level); + ui.allocate_ui_with_layout(vec2(56.0, 16.0), Layout::left_to_right(Align::Min), |ui| { + ui.set_width(56.0); + ui.label(RichText::new(level).font(theme::tiny()).color(color)); + }); + if detail { + ui.add_space(14.0); + } + let text = RichText::new(line_text(line)).font(font).color(if detail { + theme::DIM + } else { + theme::TEXT + }); + ui.add(egui::Label::new(text).wrap().selectable(true)); + }); +} + +/// The log tab: a filter bar and the lines below it. +pub fn log_view(ui: &mut Ui, view: &mut ViewState, id: impl egui::AsIdSalt, lines: &[LogLine]) { + egui::Frame::new() + .inner_margin(Margin::symmetric(12, 8)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + let options = [ + t(Text::LogFAll).into_owned(), + t(Text::LogFNosteps).into_owned(), + t(Text::LogFProblems).into_owned(), + ]; + let filters = [LogFilter::All, LogFilter::NoSteps, LogFilter::Problems]; + let current = filters + .iter() + .position(|filter| *filter == view.log_filter) + .unwrap_or(0); + if let Some(index) = widgets::segmented(ui, &options, current) { + view.log_filter = filters[index]; + } + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if widgets::ghost_button(ui, t(Text::LogCopy)).clicked() { + ui.ctx().copy_text(plain(lines, view.log_filter)); + } + }); + }); + }); + widgets::rule(ui); + ScrollArea::both() + .id_salt(id) + .auto_shrink([false, false]) + .show(ui, |ui| { + egui::Frame::new() + .inner_margin(Margin::symmetric(12, 6)) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + log_box(ui, view.log_filter, lines); + }); + }); +} diff --git a/senbei-gui/src/ui/mod.rs b/senbei-gui/src/ui/mod.rs new file mode 100644 index 0000000..7377c2d --- /dev/null +++ b/senbei-gui/src/ui/mod.rs @@ -0,0 +1,1727 @@ +//! The workbench window: inputs on the left, the selected input on the right. + +use std::collections::{HashMap, HashSet, VecDeque}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Instant; + +use egui::{Context, Frame, Margin, Panel, Ui}; +use senbei_i18n::{Lang, Message, Step}; +use senbei_io::report::{CompanionState, InputReport, Mode, Report, StageStatus}; + +use crate::backend::{ + Backend, Capabilities, Event, GroupId, ItemId, Job, JobId, Output, Pick, Produced, Request, + Source, Unit, +}; +use crate::model::{ + Counts, Filter, Group, GroupKind, GroupRun, Item, ItemResult, Level, LogBody, LogLine, + RunState, Sel, Verdict, is_target_entry, +}; +use crate::settings::Settings; +use crate::theme::{self, FontSet, Tone}; + +mod compare; +mod detail; +mod dialogs; +mod hex; +mod inputs; +mod logview; +mod research; +mod table; +mod widgets; + +// ------------------------------------------------------------------ state + +/// Every added input, grouped as it was added. +#[derive(Default)] +pub struct Session { + pub groups: Vec, + next_id: u64, +} + +impl Session { + fn next(&mut self) -> u64 { + self.next_id += 1; + self.next_id + } + + pub fn group(&self, id: GroupId) -> Option<&Group> { + self.groups.iter().find(|group| group.id == id) + } + + fn group_mut(&mut self, id: GroupId) -> Option<&mut Group> { + self.groups.iter_mut().find(|group| group.id == id) + } + + pub fn item(&self, id: ItemId) -> Option<(&Group, &Item)> { + self.groups.iter().find_map(|group| { + group + .items + .iter() + .find(|item| item.id == id) + .map(|item| (group, item)) + }) + } + + fn item_mut(&mut self, id: ItemId) -> Option<&mut Item> { + self.groups + .iter_mut() + .flat_map(|group| group.items.iter_mut()) + .find(|item| item.id == id) + } + + fn items(&self) -> impl Iterator { + self.groups.iter().flat_map(|group| group.items.iter()) + } + + fn is_empty(&self) -> bool { + self.groups.is_empty() + } +} + +/// The detail pane's tabs. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Tab { + #[default] + Overview, + Research, + Hex, + Compare, + Log, + Entries, +} + +/// Which bytes the hex view shows. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum HexView { + #[default] + Original, + Spliced, + Restored, +} + +#[derive(Debug, Clone, Default)] +pub struct HexState { + pub view: Option, + pub focus: Option, + pub highlight: Option<(u64, u64)>, + pub goto: String, + pub goto_rva: bool, + pub find: String, + pub note: Option, + /// Scroll the focus into view on the next frame. + pub reveal: bool, + /// The first row on screen. + pub top: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum LogFilter { + #[default] + All, + NoSteps, + Problems, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum SettingsTab { + #[default] + General, + Processing, + Android, + Memory, + About, +} + +/// What the window shows, apart from the session itself. +#[derive(Default)] +pub struct ViewState { + pub selected: Option, + pub multi: Vec, + pub filter: Filter, + pub search: String, + pub tab: Tab, + pub research_section: Option, + pub hex: HexState, + pub compare_section: Option, + pub compare_diff: Option, + pub log_filter: LogFilter, + pub show_non_targets: bool, + pub settings_open: bool, + pub settings_tab: SettingsTab, + pub legal_open: bool, + pub close_confirm: bool, +} + +impl ViewState { + fn select(&mut self, sel: Sel) { + if self.selected != Some(sel) { + self.hex = HexState::default(); + self.research_section = None; + self.compare_diff = None; + } + self.selected = Some(sel); + } +} + +/// The job that is running and the jobs waiting behind it. +#[derive(Default)] +pub struct Jobs { + pub running: Option, + pub queued: VecDeque, + next_id: JobId, +} + +#[derive(Debug, Clone)] +pub struct JobPlan { + pub id: JobId, + pub mode: Mode, + pub units: Vec, +} + +#[derive(Debug, Clone)] +pub struct UnitPlan { + pub group: GroupId, + pub items: Vec, + pub folder: bool, +} + +pub struct RunningJob { + pub plan: JobPlan, + pub total: usize, + pub done: usize, + pub current: Option, + pub step: Option<(Option<(u8, u8)>, Step)>, + pub input_started: Instant, + pub cancel_requested: bool, + /// Lines of the input being processed. + pub live: Vec, + /// Bytes produced for each finished input, by its path. + produced: HashMap, + /// Group-level logs and run facts of this job. + group_runs: HashMap, + /// When the running folder unit's scan finished, for its log line. + scan_at: Option, + /// Inputs this job finished, by group. + finished: Vec<(GroupId, ItemId)>, +} + +/// The restored image and entry outputs of one input. +type ProducedBytes = (Option, Vec<(String, Produced)>); + +/// Bytes loaded for the hex view. +#[derive(Debug, Clone)] +pub enum Loaded { + Loading, + Ready(Arc<[u8]>), + Failed(crate::backend::LoadError), +} + +/// A message for the status bar. +#[derive(Debug, Clone)] +pub struct Notice { + pub text: String, + pub tone: Tone, +} + +/// What a drawing pass asks to change. +#[derive(Debug, Clone)] +pub enum Action { + Pick(Pick), + Run(Mode), + RunItem(Mode, ItemId), + Cancel, + Select { + sel: Sel, + toggle: bool, + }, + Fold(Sel), + ShowEntries(ItemId), + Tab(Tab), + /// Show `offset` of an address space in the hex view. + Jump { + space: String, + offset: u64, + }, + /// Show `offset` of one hex view. + JumpView { + view: HexView, + offset: u64, + }, + Load(Source), + Reveal(PathBuf), + Remove(ItemId), + Clear, + Export { + sel: Sel, + json: bool, + }, + SetOutput(Output), + SetLanguage(Option), + AcceptLegal, + Quit, + StopAndClose, +} + +/// Read-only state a drawing pass needs. +pub struct Draw<'a> { + pub session: &'a Session, + pub jobs: &'a Jobs, + pub bytes: &'a HashMap, + pub settings: &'a Settings, + pub caps: Capabilities, + pub actions: &'a mut Vec, +} + +impl Draw<'_> { + fn act(&mut self, action: Action) { + self.actions.push(action); + } +} + +/// A [`Draw`] over the workbench's parts, so the view state can be borrowed +/// mutably beside it. +fn draw_of<'a>( + session: &'a Session, + jobs: &'a Jobs, + bytes: &'a HashMap, + settings: &'a Settings, + caps: Capabilities, + actions: &'a mut Vec, +) -> Draw<'a> { + Draw { + session, + jobs, + bytes, + settings, + caps, + actions, + } +} + +pub struct Workbench { + backend: Box, + caps: Capabilities, + session: Session, + view: ViewState, + pub settings: Settings, + detected_lang: Lang, + fonts: Option FontSet>>, + font_lang: Option, + debug_vars: Vec, + jobs: Jobs, + bytes: HashMap, + notice: Option, + close_after_job: bool, + closing: bool, + styled: bool, + icon: Option, + icon_texture: Option, +} + +impl Workbench { + /// A workbench on `backend`. `fonts` returns the system fonts for a + /// language; `debug_vars` names set debug environment variables. + pub fn new( + backend: Box, + settings: Settings, + detected_lang: Lang, + fonts: Option FontSet>>, + debug_vars: Vec, + icon: Option, + ) -> Self { + let caps = backend.capabilities(); + let mut settings = settings; + if !caps.unpack { + settings.output = Output::Beside; + } + Self { + backend, + caps, + session: Session::default(), + view: ViewState::default(), + settings, + detected_lang, + fonts, + font_lang: None, + debug_vars, + jobs: Jobs::default(), + bytes: HashMap::new(), + notice: None, + close_after_job: false, + closing: false, + styled: false, + icon, + icon_texture: None, + } + } + + pub fn lang(&self) -> Lang { + self.settings.lang(self.detected_lang) + } + + /// True while the window waits on the backend: a job, a folder scan, an + /// identification, or bytes for the hex view. + pub fn is_busy(&self) -> bool { + self.jobs.running.is_some() + || !self.jobs.queued.is_empty() + || self + .session + .groups + .iter() + .any(|group| group.scanning.is_some()) + || self + .session + .items() + .any(|item| item.identity.is_none() && item.result.is_none()) + || self + .bytes + .values() + .any(|loaded| matches!(loaded, Loaded::Loading)) + } + + /// Work that does not paint: events, language, window close. + pub fn logic(&mut self, ctx: &Context) { + let lang = self.lang(); + senbei_i18n::set_current(lang); + if self.font_lang != Some(lang) { + self.apply_fonts(ctx, lang); + } + if !self.styled { + ctx.global_style_mut(|style| *style = theme::style(style)); + self.styled = true; + } + while let Some(event) = self.backend.poll() { + self.on_event(ctx, event); + } + self.guard_close(ctx); + if self.jobs.running.is_some() || self.session.groups.iter().any(|g| g.scanning.is_some()) { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } + } + + fn apply_fonts(&mut self, ctx: &Context, lang: Lang) { + let set = match &mut self.fonts { + Some(load) => load(lang), + None => FontSet::default(), + }; + ctx.set_fonts(theme::font_definitions(&set)); + self.font_lang = Some(lang); + } + + fn guard_close(&mut self, ctx: &Context) { + if !ctx.input(|input| input.viewport().close_requested()) || self.closing { + return; + } + if self.jobs.running.is_some() || !self.jobs.queued.is_empty() { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + self.view.close_confirm = true; + } else { + self.closing = true; + } + } + + /// Draw the whole window. + pub fn ui(&mut self, ui: &mut Ui) { + let ctx = ui.ctx().clone(); + if self.icon_texture.is_none() + && let Some(image) = self.icon.take() + { + self.icon_texture = + Some(ctx.load_texture("senbei-icon", image, egui::TextureOptions::LINEAR)); + } + self.take_drops(&ctx); + self.shortcuts(&ctx); + let mut actions = Vec::new(); + let legal_pending = !self.settings.legal_accepted; + let bar = dialogs::TopBar { + targets: self.target_count(), + has_selection: !self.view.multi.is_empty() || self.view.selected.is_some(), + icon: self.icon_texture.as_ref(), + }; + let icon = self.icon_texture.as_ref(); + + Panel::top("topbar") + .frame( + Frame::new() + .fill(theme::PANEL) + .inner_margin(Margin::symmetric(10, 6)), + ) + .show(ui, |ui| { + let mut draw = draw_of( + &self.session, + &self.jobs, + &self.bytes, + &self.settings, + self.caps, + &mut actions, + ); + dialogs::topbar(ui, &mut draw, &mut self.view, bar); + }); + if !self.debug_vars.is_empty() { + Panel::top("banner") + .frame( + Frame::new() + .fill(theme::accent_soft()) + .inner_margin(Margin::symmetric(12, 5)), + ) + .show(ui, |ui| dialogs::banner(ui, &self.debug_vars)); + } + Panel::bottom("statusbar") + .frame( + Frame::new() + .fill(theme::PANEL) + .inner_margin(Margin::symmetric(12, 4)), + ) + .show(ui, |ui| { + let mut draw = draw_of( + &self.session, + &self.jobs, + &self.bytes, + &self.settings, + self.caps, + &mut actions, + ); + dialogs::statusbar(ui, &mut draw, self.notice.as_ref()); + }); + if self.session.is_empty() { + egui::CentralPanel::default() + .frame(Frame::new().fill(theme::BG)) + .show(ui, |ui| { + let mut draw = draw_of( + &self.session, + &self.jobs, + &self.bytes, + &self.settings, + self.caps, + &mut actions, + ); + dialogs::empty_state(ui, &mut draw, icon); + }); + } else { + let narrow = ui.available_width() < 1360.0; + Panel::left("inputs") + .resizable(true) + .default_size(if narrow { 300.0 } else { 340.0 }) + .size_range(220.0..=640.0) + .frame(Frame::new().fill(theme::PANEL)) + .show(ui, |ui| { + let mut draw = draw_of( + &self.session, + &self.jobs, + &self.bytes, + &self.settings, + self.caps, + &mut actions, + ); + inputs::panel(ui, &mut draw, &mut self.view); + }); + egui::CentralPanel::default() + .frame(Frame::new().fill(theme::BG)) + .show(ui, |ui| { + let mut draw = draw_of( + &self.session, + &self.jobs, + &self.bytes, + &self.settings, + self.caps, + &mut actions, + ); + detail::pane(ui, &mut draw, &mut self.view); + }); + } + + let mut settings = self.settings.clone(); + { + let mut draw = draw_of( + &self.session, + &self.jobs, + &self.bytes, + &self.settings, + self.caps, + &mut actions, + ); + dialogs::overlays( + &ctx, + &mut draw, + &mut self.view, + &mut settings, + dialogs::Overlays { + legal_pending, + icon, + detected: self.detected_lang, + }, + ); + } + if settings != self.settings { + self.settings = settings; + } + for action in actions { + self.apply(&ctx, action); + } + } + + // ------------------------------------------------------------ input + + fn take_drops(&mut self, ctx: &Context) { + let dropped: Vec = ctx.input(|input| { + input + .raw + .dropped_files + .iter() + .map(|file| file.path().to_path_buf()) + .collect() + }); + if !dropped.is_empty() && self.settings.legal_accepted { + self.add_paths(dropped); + } + } + + fn shortcuts(&mut self, ctx: &Context) { + if !self.settings.legal_accepted { + return; + } + let open = egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::O); + if ctx.input_mut(|input| input.consume_shortcut(&open)) { + self.backend.send(Request::Pick(Pick::Files)); + } + let typing = ctx.egui_wants_keyboard_input(); + if !typing + && ctx.input(|input| input.key_pressed(egui::Key::Delete)) + && let Some(Sel::Item(id)) = self.view.selected + && self.jobs.running.is_none() + { + self.remove_item(id); + } + if ctx.input(|input| input.key_pressed(egui::Key::F3)) { + self.find_next(); + } + } + + /// Add files and folders: files join "Added files", each folder is a + /// group of its own. + pub fn add_paths(&mut self, paths: Vec) { + let mut identify = Vec::new(); + for path in paths { + if path.is_dir() { + if !self.caps.folders { + continue; + } + if self + .session + .groups + .iter() + .any(|group| group.root() == Some(path.as_path())) + { + continue; + } + let id = self.session.next(); + let mut group = Group::new(id, GroupKind::Folder(path.clone())); + group.scanning = Some(0); + self.session.groups.push(group); + self.backend.send(Request::Scan { + group: id, + root: path, + scan_all: self.settings.scan_all, + limits: self.settings.limits(), + }); + self.view.select(Sel::Group(id)); + continue; + } + // A dropped `x.exe._` stands for its loader `x.exe`. + let path = match companion_stub(&path) { + Some(stub) => stub, + None => path, + }; + let files = match self + .session + .groups + .iter() + .position(|group| group.kind == GroupKind::Files) + { + Some(index) => index, + None => { + let id = self.session.next(); + self.session + .groups + .insert(0, Group::new(id, GroupKind::Files)); + 0 + } + }; + if self.session.groups[files] + .items + .iter() + .any(|item| item.path == path) + { + continue; + } + let id = self.session.next(); + self.session.groups[files] + .items + .push(Item::new(id, path.clone())); + identify.push((id, path)); + if self.view.selected.is_none() { + self.view.select(Sel::Item(id)); + } + } + if let Some((first, _)) = identify.first() + && !matches!(self.view.selected, Some(Sel::Item(_))) + { + self.view.select(Sel::Item(*first)); + } + if !identify.is_empty() { + self.backend.send(Request::Identify(identify)); + } + } + + fn remove_item(&mut self, id: ItemId) { + for group in &mut self.session.groups { + group.items.retain(|item| item.id != id); + } + self.session + .groups + .retain(|group| !(group.kind == GroupKind::Files && group.items.is_empty())); + if matches!(self.view.selected, Some(Sel::Item(item) | Sel::Entry(item, _)) if item == id) { + self.view.selected = None; + } + self.view + .multi + .retain(|sel| !matches!(sel, Sel::Item(item) | Sel::Entry(item, _) if *item == id)); + } + + // ------------------------------------------------------------- runs + + /// The inputs an action applies to: the multi-selection, else the + /// selection, else everything. An entry stands for its package. + fn targets(&self) -> Vec<(GroupId, Vec, bool)> { + let picked: Vec = if !self.view.multi.is_empty() { + self.view.multi.clone() + } else if let Some(sel) = self.view.selected { + vec![sel] + } else { + self.session + .groups + .iter() + .map(|group| Sel::Group(group.id)) + .collect() + }; + let mut out: Vec<(GroupId, Vec, bool)> = Vec::new(); + let mut entry = |group: GroupId, item: Option| { + let index = match out.iter().position(|(id, _, _)| *id == group) { + Some(index) => index, + None => { + out.push((group, Vec::new(), false)); + out.len() - 1 + } + }; + match item { + None => out[index].2 = true, + Some(item) if !out[index].1.contains(&item) => out[index].1.push(item), + Some(_) => {} + } + }; + for sel in picked { + match sel { + Sel::Group(group) => entry(group, None), + Sel::Item(item) | Sel::Entry(item, _) => { + if let Some((group, _)) = self.session.item(item) { + entry(group.id, Some(item)); + } + } + } + } + for (group, items, whole) in &mut out { + let Some(group) = self.session.group(*group) else { + continue; + }; + if *whole || (group.root().is_some() && items.len() == group.items.len()) { + *whole = true; + *items = group.items.iter().map(|item| item.id).collect(); + } + } + out + } + + /// How many inputs a run of the current targets covers. + pub fn target_count(&self) -> usize { + self.targets().iter().map(|(_, items, _)| items.len()).sum() + } + + fn plan_units(&self) -> Vec<(Unit, UnitPlan)> { + let mut units = Vec::new(); + for (group_id, items, whole) in self.targets() { + let Some(group) = self.session.group(group_id) else { + continue; + }; + if let (Some(root), true) = (group.root(), whole) { + if group.scanning.is_some() { + continue; + } + units.push(( + Unit::Folder { + root: root.to_path_buf(), + out_dir: self.out_dir(group, None), + }, + UnitPlan { + group: group_id, + items: items.clone(), + folder: true, + }, + )); + continue; + } + for id in items { + let Some(item) = group.items.iter().find(|item| item.id == id) else { + continue; + }; + units.push(( + Unit::File { + path: item.path.clone(), + out_dir: self.out_dir(group, Some(&item.path)), + }, + UnitPlan { + group: group_id, + items: vec![id], + folder: false, + }, + )); + } + } + units + } + + /// Where an unpack of `item` (or of the whole group) writes. + fn out_dir(&self, group: &Group, item: Option<&Path>) -> PathBuf { + let relative = |root: &Path, path: &Path| -> PathBuf { + path.parent() + .and_then(|parent| parent.strip_prefix(root).ok()) + .map(Path::to_path_buf) + .unwrap_or_default() + }; + match (&self.settings.output, group.root(), item) { + (Output::Beside, Some(root), None) => senbei_io::job::default_out_root_for_folder(root), + (Output::Beside, Some(root), Some(path)) => { + senbei_io::job::default_out_root_for_folder(root).join(relative(root, path)) + } + (Output::Beside, None, Some(path)) => senbei_io::job::default_out_root_for_file(path), + (Output::Folder(dir), Some(root), Some(path)) => dir.join(relative(root, path)), + (Output::Folder(dir), _, _) => dir.clone(), + (Output::Beside, None, None) => PathBuf::from("unpack"), + } + } + + fn start(&mut self, mode: Mode, units: Vec<(Unit, UnitPlan)>) { + if units.is_empty() || (mode == Mode::Unpack && !self.caps.unpack) { + return; + } + self.jobs.next_id += 1; + let id = self.jobs.next_id; + let (units, plans): (Vec, Vec) = units.into_iter().unzip(); + for plan in &plans { + for item in &plan.items { + if let Some(item) = self.session.item_mut(*item) { + item.run = RunState::Queued; + } + } + } + self.jobs.queued.push_back(JobPlan { + id, + mode, + units: plans, + }); + self.backend.send(Request::Run(Box::new(Job { + id, + mode, + units, + options: self.settings.run_options(), + }))); + } + + fn run_item(&mut self, mode: Mode, id: ItemId) { + let Some((group, item)) = self.session.item(id) else { + return; + }; + let unit = Unit::File { + path: item.path.clone(), + out_dir: self.out_dir(group, Some(&item.path)), + }; + let plan = UnitPlan { + group: group.id, + items: vec![id], + folder: false, + }; + self.start(mode, vec![(unit, plan)]); + } + + // ----------------------------------------------------------- events + + fn on_event(&mut self, ctx: &Context, event: Event) { + match event { + Event::Identified(id, identity) => { + if let Some(item) = self.session.item_mut(id) { + item.identity = Some(*identity); + } + } + Event::ScanProgress { group, found } => { + if let Some(group) = self.session.group_mut(group) + && group.scanning.is_some() + { + group.scanning = Some(found); + } + } + Event::Scanned { + group, + targets, + scan, + } => { + let ids: Vec = targets.iter().map(|_| self.session.next()).collect(); + if let Some(group) = self.session.group_mut(group) { + group.scanning = None; + group.scan = Some(scan); + for ((path, identity), id) in targets.into_iter().zip(ids) { + let mut item = Item::new(id, path); + item.identity = Some(*identity); + group.items.push(item); + } + } + } + Event::UnitStarted { job, unit, at } => self.unit_started(job, unit, at), + Event::UnitScanned { + job, + unit, + inputs, + at, + } => { + if let Some(running) = &mut self.jobs.running + && running.plan.id == job + && let Some(plan) = running.plan.units.get(unit) + { + let planned = plan.items.len(); + running.total = running.total + inputs - planned.min(running.total); + running.scan_at = Some(at); + // The run's own scan is the count the log reports. + if let Some(group_run) = running.group_runs.get_mut(&plan.group) + && let Some(LogBody::RunStarted { inputs: total, .. }) = + group_run.log.first_mut().map(|line| &mut line.body) + { + *total = *total + inputs - planned.min(*total); + } + } + } + Event::InputStarted { + job, + unit, + path, + at, + } => self.input_started(job, unit, &path, at), + Event::Step { + job, + step, + position, + at, + } => { + if let Some(running) = self.running(job) { + running.live.push(LogLine::new( + at, + Level::Step, + LogBody::Step { + position, + step: step.clone(), + }, + )); + if !matches!(step, Step::WriteTo { .. }) { + running.step = Some((position, step)); + } + } + } + Event::Detail { job, text, at } => { + if let Some(running) = self.running(job) { + running + .live + .push(LogLine::new(at, Level::Detail, LogBody::Detail(text))); + } + } + Event::Produced { + job, + path, + restored, + entries, + } => { + if let Some(running) = self.running(job) { + running.produced.insert(path, (restored, entries)); + } + } + Event::InputFinished { + job, + unit, + report, + at, + } => self.input_finished(job, unit, *report, at), + Event::UnitFinished { + job, + unit, + report, + at, + } => self.unit_finished(job, unit, *report, at), + Event::JobFinished { job, cancelled } => self.job_finished(ctx, job, cancelled), + Event::Loaded { source, result } => { + self.bytes.insert( + source, + match result { + Ok(bytes) => Loaded::Ready(bytes), + Err(error) => Loaded::Failed(error), + }, + ); + } + Event::Picked(pick, paths) => match pick { + Pick::Files | Pick::Folder => self.add_paths(paths), + Pick::Output => { + if let Some(folder) = paths.into_iter().next() { + self.settings.recent_output = Some(folder.clone()); + self.settings.output = Output::Folder(folder); + } + } + }, + Event::Saved(result) => { + self.notice = Some(match result { + Ok(path) => Notice { + text: path.display().to_string(), + tone: Tone::Ok, + }, + Err(error) => Notice { + text: error, + tone: Tone::Err, + }, + }); + } + Event::Failed(error) => { + self.notice = Some(Notice { + text: error, + tone: Tone::Err, + }); + } + } + } + + fn running(&mut self, job: JobId) -> Option<&mut RunningJob> { + self.jobs + .running + .as_mut() + .filter(|running| running.plan.id == job) + } + + fn unit_started(&mut self, job: JobId, unit: usize, at: String) { + if self.jobs.running.as_ref().map(|running| running.plan.id) != Some(job) { + let Some(index) = self.jobs.queued.iter().position(|plan| plan.id == job) else { + return; + }; + let plan = self.jobs.queued.remove(index).expect("index"); + let total = plan.units.iter().map(|unit| unit.items.len()).sum(); + self.jobs.running = Some(RunningJob { + plan, + total, + done: 0, + current: None, + step: None, + input_started: Instant::now(), + cancel_requested: false, + live: Vec::new(), + produced: HashMap::new(), + group_runs: HashMap::new(), + scan_at: None, + finished: Vec::new(), + }); + } + let Some(running) = self.jobs.running.as_mut() else { + return; + }; + let Some(plan) = running.plan.units.get(unit).cloned() else { + return; + }; + let mode = running.plan.mode; + let inputs = running + .plan + .units + .iter() + .filter(|unit| unit.group == plan.group) + .map(|unit| unit.items.len()) + .sum(); + running + .group_runs + .entry(plan.group) + .or_insert_with(|| GroupRun { + mode, + duration_ms: 0, + errors: Vec::new(), + cancelled: false, + log: vec![LogLine::new( + at.clone(), + Level::Info, + LogBody::RunStarted { mode, inputs }, + )], + report: None, + }); + } + + fn input_started(&mut self, job: JobId, unit: usize, path: &Path, at: String) { + let Some(running) = self + .jobs + .running + .as_ref() + .filter(|running| running.plan.id == job) + else { + return; + }; + let Some(plan) = running.plan.units.get(unit).cloned() else { + return; + }; + let mode = running.plan.mode; + // A folder run may find inputs the add-time scan did not. + let item_id = match self.find_in_group(plan.group, path) { + Some(id) => id, + None => { + let id = self.session.next(); + if let Some(group) = self.session.group_mut(plan.group) { + group.items.push(Item::new(id, path.to_path_buf())); + } + id + } + }; + if let Some(item) = self.session.item_mut(item_id) { + item.run = RunState::Running; + } + let Some(running) = self.jobs.running.as_mut() else { + return; + }; + // Inputs are numbered across their group, as one run of it, even + // when each added file runs as a unit of its own. + let (index, total) = running + .group_runs + .get(&plan.group) + .map_or((1, 1), |group_run| next_position(&group_run.log)); + running.current = Some(item_id); + running.step = None; + running.input_started = Instant::now(); + let started = LogLine::new( + at.clone(), + Level::Info, + LogBody::InputStarted { + index, + total, + path: path.display().to_string(), + }, + ); + running.live = vec![ + LogLine::new( + at, + Level::Info, + LogBody::RunStarted { + mode, + inputs: total, + }, + ), + started.clone(), + ]; + if let Some(group_run) = running.group_runs.get_mut(&plan.group) { + group_run.log.push(started); + } + } + + fn find_in_group(&self, group: GroupId, path: &Path) -> Option { + self.session + .group(group)? + .items + .iter() + .find(|item| item.path == path) + .map(|item| item.id) + } + + fn input_finished(&mut self, job: JobId, unit: usize, report: InputReport, at: String) { + let Some(running) = self + .jobs + .running + .as_ref() + .filter(|running| running.plan.id == job) + else { + return; + }; + let Some(plan) = running.plan.units.get(unit).cloned() else { + return; + }; + let mode = running.plan.mode; + let path = PathBuf::from(&report.path); + let item_id = match running.current { + Some(current) + if self + .session + .item(current) + .is_some_and(|(_, item)| item.path == path) => + { + Some(current) + } + _ => self.find_in_group(plan.group, &path), + }; + let item_id = match item_id { + Some(id) => id, + None => { + let id = self.session.next(); + if let Some(group) = self.session.group_mut(plan.group) { + group.items.push(Item::new(id, path.clone())); + } + id + } + }; + let running = self.jobs.running.as_mut().expect("running"); + let mut log = std::mem::take(&mut running.live); + if log.is_empty() { + // Finished without a start event: number it like the others. + let (index, total) = running + .group_runs + .get(&plan.group) + .map_or((1, 1), |group_run| next_position(&group_run.log)); + let started = LogLine::new( + at.clone(), + Level::Info, + LogBody::InputStarted { + index, + total, + path: report.path.clone(), + }, + ); + if let Some(group_run) = running.group_runs.get_mut(&plan.group) { + group_run.log.push(started.clone()); + } + log.push(started); + } + finish_log(&mut log, &report, &at); + let verdict = Verdict::of_input(&report); + if let Some(group_run) = running.group_runs.get_mut(&plan.group) { + group_run.log.push(LogLine::new( + at, + level_of(verdict), + LogBody::Finished { + verdict, + duration: report.duration_ms, + }, + )); + } + let (restored, entries) = running.produced.remove(&path).unwrap_or_default(); + running.done += 1; + running.finished.push((plan.group, item_id)); + if running.current == Some(item_id) { + running.current = None; + running.step = None; + } + if let Some(item) = self.session.item_mut(item_id) { + item.run = RunState::Idle; + item.result = Some(ItemResult { + mode, + report, + log, + restored, + entries, + }); + } + // New bytes replace what the hex view had for these paths. + self.bytes.retain( + |source, _| !matches!(source, Source::Entry { package, .. } if *package == path), + ); + } + + fn unit_finished(&mut self, job: JobId, unit: usize, report: Report, at: String) { + let Some(running) = self + .jobs + .running + .as_mut() + .filter(|running| running.plan.id == job) + else { + return; + }; + let Some(plan) = running.plan.units.get(unit).cloned() else { + return; + }; + if let Some(group_run) = running.group_runs.get_mut(&plan.group) { + group_run.duration_ms += report.duration_ms; + group_run.cancelled |= report.cancelled; + for error in &report.errors { + group_run.log.push(LogLine::new( + at.clone(), + Level::Error, + LogBody::Message(error.clone()), + )); + } + group_run.errors.extend(report.errors.iter().cloned()); + if plan.folder { + if let Some(scan) = report.scan { + group_run.log.insert( + 1.min(group_run.log.len()), + LogLine::new( + running.scan_at.take().unwrap_or_else(|| at.clone()), + Level::Info, + LogBody::Scan { + candidates: report.summary.inputs, + skipped: scan.non_target_skipped, + }, + ), + ); + if scan.walk_errors > 0 || scan.probe_errors > 0 { + group_run.log.push(LogLine::new( + at.clone(), + Level::Warn, + LogBody::ScanIncomplete, + )); + } + } + group_run.report = Some(report.clone()); + } + } + if plan.folder + && let Some(scan) = report.scan + && let Some(group) = self.session.group_mut(plan.group) + { + group.scan = Some(scan); + } + } + + fn job_finished(&mut self, ctx: &Context, job: JobId, cancelled: bool) { + let (units, group_runs, finished) = match self.jobs.running.take() { + Some(running) if running.plan.id == job => { + (running.plan.units, running.group_runs, running.finished) + } + other => { + self.jobs.running = other; + // A job cancelled before it started. + match self.jobs.queued.iter().position(|plan| plan.id == job) { + Some(index) => match self.jobs.queued.remove(index) { + Some(plan) => (plan.units, HashMap::new(), Vec::new()), + None => return, + }, + None => return, + } + } + }; + for plan in &units { + for id in &plan.items { + if let Some(item) = self.session.item_mut(*id) + && matches!( + item.run, + RunState::Queued | RunState::Running | RunState::WillNotRun + ) + { + // An earlier result still stands for an input the + // cancelled job never reached. + item.run = if cancelled && item.result.is_none() { + RunState::WillNotRun + } else { + RunState::Idle + }; + } + } + } + for (group_id, mut group_run) in group_runs { + let Some(group) = self.session.group_mut(group_id) else { + continue; + }; + let mut counts = Counts::default(); + for (_, id) in finished.iter().filter(|(group, _)| *group == group_id) { + if let Some(verdict) = group + .items + .iter() + .find(|item| item.id == *id) + .and_then(Item::verdict) + { + counts.inputs += 1; + counts.add(verdict); + } + } + group_run.cancelled |= cancelled; + group_run.log.push(LogLine::new( + senbei_io::logfile::local_clock(), + Level::Info, + LogBody::Summary(counts), + )); + group.last_run = Some(group_run); + } + if self.close_after_job && self.jobs.running.is_none() && self.jobs.queued.is_empty() { + self.closing = true; + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + } + + // ---------------------------------------------------------- actions + + fn apply(&mut self, ctx: &Context, action: Action) { + match action { + Action::Pick(pick) => self.backend.send(Request::Pick(pick)), + Action::Run(mode) => { + let units = self.plan_units(); + self.start(mode, units); + } + Action::RunItem(mode, id) => self.run_item(mode, id), + Action::Cancel => { + if let Some(running) = &mut self.jobs.running { + running.cancel_requested = true; + } + // Queued jobs still start, see the cancelled token, and end + // at once; their inputs will not run. + for plan in &self.jobs.queued { + for unit in &plan.units { + for id in &unit.items { + if let Some(item) = self.session.item_mut(*id) + && item.result.is_none() + { + item.run = RunState::WillNotRun; + } + } + } + } + self.backend.send(Request::Cancel); + } + Action::Select { sel, toggle } => { + if toggle { + if let Some(current) = self.view.selected + && !self.view.multi.contains(¤t) + && !matches!(current, Sel::Group(_)) + { + self.view.multi.push(current); + } + if let Some(index) = self.view.multi.iter().position(|known| *known == sel) { + self.view.multi.remove(index); + } else { + self.view.multi.push(sel); + } + } else { + self.view.multi.clear(); + } + self.view.select(sel); + } + Action::Fold(sel) => match sel { + Sel::Group(id) => { + if let Some(group) = self.session.group_mut(id) { + group.folded = !group.folded; + } + } + Sel::Item(id) | Sel::Entry(id, _) => { + if let Some(item) = self.session.item_mut(id) { + item.folded = !item.folded; + } + } + }, + Action::ShowEntries(id) => { + self.view.multi.clear(); + self.view.select(Sel::Item(id)); + self.view.tab = Tab::Entries; + self.view.show_non_targets = true; + } + Action::Tab(tab) => self.view.tab = tab, + Action::Jump { space, offset } => self.jump(&space, offset), + Action::JumpView { view, offset } => { + self.view.hex.view = Some(view); + self.view.hex.focus = Some(offset); + self.view.hex.highlight = Some((offset, offset + 16)); + self.view.hex.note = None; + self.view.hex.reveal = true; + self.view.tab = Tab::Hex; + } + Action::Load(source) => { + if !self.bytes.contains_key(&source) { + self.bytes.insert(source.clone(), Loaded::Loading); + self.backend.send(Request::Load { + source, + limits: self.settings.limits(), + }); + } + } + Action::Reveal(path) => self.backend.send(Request::Reveal(path)), + Action::Remove(id) => { + if self.jobs.running.is_none() { + self.remove_item(id); + } + } + Action::Clear => { + if self.jobs.running.is_none() && self.jobs.queued.is_empty() { + self.session.groups.clear(); + self.view = ViewState { + settings_open: self.view.settings_open, + ..ViewState::default() + }; + self.bytes.clear(); + } + } + Action::Export { sel, json } => self.export(sel, json), + Action::SetOutput(output) => { + if let Output::Folder(folder) = &output { + self.settings.recent_output = Some(folder.clone()); + } + self.settings.output = output; + } + Action::SetLanguage(lang) => { + self.settings.language = lang.map(|lang| lang.tag().to_owned()); + senbei_i18n::set_current(self.lang()); + } + Action::AcceptLegal => { + self.settings.legal_accepted = true; + self.view.legal_open = false; + } + Action::Quit => { + self.closing = true; + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + Action::StopAndClose => { + self.view.close_confirm = false; + self.close_after_job = true; + self.apply(ctx, Action::Cancel); + } + } + } + + /// Show an address in the hex view. Working-image RVAs address the image + /// being rebuilt, so they open the restored image when one exists. + fn jump(&mut self, space: &str, offset: u64) { + let id = match self.view.selected { + Some(Sel::Item(id)) => id, + // Entry offsets address the extracted entry. + Some(Sel::Entry(..)) => { + self.view.hex.view = Some(HexView::Original); + self.view.hex.focus = Some(offset); + self.view.hex.highlight = Some((offset, offset + 16)); + self.view.hex.note = None; + self.view.hex.reveal = true; + self.view.tab = Tab::Hex; + return; + } + _ => return, + }; + let Some((_, item)) = self.session.item(id) else { + return; + }; + let research = item + .result + .as_ref() + .and_then(|result| result.report.research.as_ref()); + let rva = match space { + "working_image_rva" => Some(offset), + "decoded_payload_offset" => research + .and_then(|research| research.input.protection.as_ref()) + .and_then(|protection| protection.payload.as_ref()) + .map(|payload| u64::from(payload.destination_rva) + offset), + _ => None, + }; + let (view, target) = match rva { + Some(rva) => match research.and_then(|research| research.restored.as_ref()) { + Some(restored) => ( + HexView::Restored, + hex::rva_to_offset(restored.pe.as_ref(), rva).unwrap_or(rva), + ), + None => ( + HexView::Original, + research + .and_then(|research| hex::rva_to_offset(research.input.pe.as_ref(), rva)) + .unwrap_or(rva), + ), + }, + None => ( + if research.is_some_and(|research| { + research.input_view == senbei_io::report::ResearchInputView::SplicedCompanion + }) { + HexView::Spliced + } else { + HexView::Original + }, + offset, + ), + }; + self.view.hex.view = Some(view); + self.view.hex.focus = Some(target); + self.view.hex.highlight = Some((target, target + 16)); + self.view.hex.note = None; + self.view.hex.reveal = true; + self.view.tab = Tab::Hex; + } + + fn find_next(&mut self) { + if self.view.tab != Tab::Hex { + return; + } + let draw_bytes = hex::current_bytes(&self.session, &self.bytes, &self.view); + if let Some(bytes) = draw_bytes { + hex::find(&bytes, &mut self.view.hex); + } + } + + fn export(&mut self, sel: Sel, json: bool) { + let Some((report, name)) = self.export_report(sel) else { + return; + }; + let contents = if json { + report.to_json() + } else { + report.render_text_in(senbei_io::ui::Palette::plain(), self.lang()) + }; + let extension = if json { "json" } else { "txt" }; + self.backend.send(Request::Save { + name: format!("{name}.senbei.{extension}"), + contents: contents.into_bytes(), + }); + } + + /// A versioned report of the selection, as `--json` would write it. + fn export_report(&self, sel: Sel) -> Option<(Report, String)> { + let (group, items, run): (&Group, Vec<&Item>, Option<&GroupRun>) = match sel { + Sel::Group(id) => { + let group = self.session.group(id)?; + (group, group.items.iter().collect(), group.last_run.as_ref()) + } + Sel::Item(id) | Sel::Entry(id, _) => { + let (group, item) = self.session.item(id)?; + (group, vec![item], None) + } + }; + let results: Vec<&ItemResult> = items + .iter() + .filter_map(|item| item.result.as_ref()) + .collect(); + let mode = run + .map(|run| run.mode) + .or_else(|| results.first().map(|result| result.mode))?; + let inputs: Vec = results.iter().map(|result| result.report.clone()).collect(); + let mut report = match run.and_then(|run| run.report.clone()) { + Some(report) => report, + None => { + let mut collector = senbei_io::report::Collector::new(mode); + for input in &inputs { + collector.push(input.clone()); + } + let mut report = collector.finish(); + report.duration_ms = inputs.iter().map(|input| input.duration_ms).sum(); + report + } + }; + report.inputs = inputs; + let name = match sel { + Sel::Group(_) => group.title().into_owned(), + _ => items + .first() + .map(|item| item.name.clone()) + .unwrap_or_default(), + }; + Some((report, name)) + } +} + +/// `x.exe` for a dropped `x.exe._` whose loader exists. +fn companion_stub(path: &Path) -> Option { + let name = path.file_name()?.to_str()?; + let stub = name.strip_suffix("._")?; + let stub = path.with_file_name(stub); + stub.is_file().then_some(stub) +} + +fn level_of(verdict: Verdict) -> Level { + match verdict.tone() { + Tone::Err => Level::Error, + Tone::Warn => Level::Warn, + _ => Level::Info, + } +} + +/// The next input's position in its group's run and the run's input count. +fn next_position(log: &[LogLine]) -> (usize, usize) { + let index = 1 + log + .iter() + .filter(|line| matches!(line.body, LogBody::InputStarted { .. })) + .count(); + let total = log + .iter() + .find_map(|line| match line.body { + LogBody::RunStarted { inputs, .. } => Some(inputs), + _ => None, + }) + .unwrap_or(index); + (index, total.max(index)) +} + +/// Close an input's log: companion, stages, messages, entries, outcome. +fn finish_log(log: &mut Vec, report: &InputReport, at: &str) { + if let Some(companion) = &report.companion + && companion.state == CompanionState::Spliced + { + let name = companion + .path + .as_deref() + .map(crate::format::base_name) + .unwrap_or_default() + .to_owned(); + let at_companion = log.get(1).map_or(at.to_owned(), |line| line.at.clone()); + log.insert( + 2.min(log.len()), + LogLine::new(at_companion, Level::Info, LogBody::Companion { name }), + ); + } + let skipped = report.status == senbei_io::report::InputStatus::Skipped; + for stage in &report.stages { + let status = if skipped && stage.status == StageStatus::Failed { + StageStatus::Skipped + } else { + stage.status + }; + log.push(LogLine::new( + at, + if status == StageStatus::Failed { + Level::Error + } else { + Level::Info + }, + LogBody::Stage { + stage: stage.stage, + status, + duration: stage.duration_ms, + detail: stage.detail.clone(), + }, + )); + } + let mut seen: HashSet = HashSet::new(); + let mut push = |log: &mut Vec, level: Level, message: &Message| { + if seen.insert(message.text().to_owned()) && !crate::labels::message(message).quiet { + log.push(LogLine::new(at, level, LogBody::Message(message.clone()))); + } + }; + for message in &report.errors { + push(log, Level::Error, message); + } + for message in &report.warnings { + push(log, Level::Warn, message); + } + if let Some(profile) = &report.profile { + for message in &profile.errors { + push(log, Level::Error, message); + } + for message in &profile.warnings { + push(log, Level::Warn, message); + } + } + for entry in report.entries.iter().filter(|entry| is_target_entry(entry)) { + let verdict = Verdict::of_entry(entry); + log.push(LogLine::new( + at, + if verdict.tone() == Tone::Err { + Level::Error + } else { + Level::Info + }, + LogBody::Entry { + label: crate::model::entry_inner(&entry.name).to_owned(), + verdict, + }, + )); + } + let verdict = Verdict::of_input(report); + log.push(LogLine::new( + at, + level_of(verdict), + LogBody::Finished { + verdict, + duration: report.duration_ms, + }, + )); +} diff --git a/senbei-gui/src/ui/research.rs b/senbei-gui/src/ui/research.rs new file mode 100644 index 0000000..a3fc63d --- /dev/null +++ b/senbei-gui/src/ui/research.rs @@ -0,0 +1,1907 @@ +//! The research tab: the structural evidence a run collected, by section. + +use egui::{ + Align, CornerRadius, Frame, Layout, Margin, Rect, RichText, ScrollArea, Sense, Stroke, Ui, + UiBuilder, pos2, vec2, +}; +use senbei_engine::windows::{ + AddressSpace, DirectoryMapping, PeInspection, ResearchEvent, SectionBacking, TraceValue, +}; +use senbei_engine::{ProtectionProfile, ResearchTrace}; +use senbei_io::report::{ + AndroidResearchReport, EntryReport, Mode, ResearchInputView, WindowsResearchReport, +}; +use serde_json::Value; + +use super::table::{self, col, num_col}; +use super::widgets::{self, CardSpec}; +use super::{Action, Draw, HexView, Tab, ViewState}; +use crate::backend::ItemId; +use crate::format; +use crate::labels::{self, tv, tv_str, wire}; +use crate::model::{Item, ItemResult, format_label}; +use crate::text::{Text, t}; +use crate::theme::{self, Tone}; + +/// The research a subject carries. +pub struct Subject<'a> { + pub item: ItemId, + pub entry: Option, + pub windows: Option<&'a WindowsResearchReport>, + pub android: Option<&'a AndroidResearchReport>, + pub metadata: Option<&'a Value>, + pub profile: Option<&'a ProtectionProfile>, + pub mode: Option, + pub comparable: bool, +} + +impl<'a> Subject<'a> { + pub fn item(item: &'a Item, result: &'a ItemResult) -> Self { + let input = &result.report; + Self { + item: item.id, + entry: None, + windows: input.research.as_ref(), + android: input.android_research.as_ref(), + metadata: input.metadata_research.as_ref(), + profile: input.profile.as_ref(), + mode: Some(result.mode), + comparable: super::detail::comparable(input), + } + } + + pub fn entry(item: &'a Item, index: usize, entry: &'a EntryReport, mode: Option) -> Self { + Self { + item: item.id, + entry: Some(index), + windows: None, + android: entry.android_research.as_ref(), + metadata: entry.metadata_research.as_ref(), + profile: None, + mode, + comparable: false, + } + } +} + +enum Nav { + Group(String), + Section { + key: String, + label: String, + count: Option, + }, +} + +fn section(key: &str, text: Text, count: Option) -> Nav { + Nav::Section { + key: key.to_owned(), + label: t(text).into_owned(), + count, + } +} + +fn group(text: Text) -> Nav { + Nav::Group(t(text).into_owned()) +} + +const RESTORATION: [(&str, Text); 7] = [ + ("descriptor", Text::RsARDescriptor), + ("static_config", Text::RsARStaticConfig), + ("primary", Text::RsARPrimary), + ("auxiliary", Text::RsARAuxiliary), + ("elf_materialization", Text::RsARElfMaterialization), + ("cleaning", Text::RsARCleaning), + ("validation", Text::RsARValidation), +]; + +fn array_len(value: Option<&Value>) -> Option { + Some(value.and_then(Value::as_array).map_or(0, Vec::len)) +} + +/// The issues worth showing for the protected input. +fn input_issues(research: &WindowsResearchReport) -> Vec<&senbei_engine::windows::InspectionIssue> { + research + .input + .issues + .iter() + .filter(|issue| !labels::is_quiet(&issue.message)) + .collect() +} + +/// The issues worth showing for the restored image, which has no protection +/// header to explain. +fn restored_issues( + restored: &senbei_engine::windows::WindowsInspection, +) -> Vec<&senbei_engine::windows::InspectionIssue> { + restored + .issues + .iter() + .filter(|issue| { + !issue + .message + .starts_with("header table decoded but info[1] is ") + }) + .collect() +} + +fn sections(subject: &Subject<'_>) -> Vec