diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml new file mode 100644 index 0000000000..bd23031869 --- /dev/null +++ b/.github/workflows/launcher.yml @@ -0,0 +1,59 @@ +# Builds and tests the optional launcher (launcher/, Rust) when it changes, so a change that breaks its build, its +# lints or its tests shows up in CI. It needs no GPU, no display and no game files: the tests draw the window +# offscreen on the CPU (iced's tiny-skia renderer) and run a stand-in script in place of make_game.py. +name: Launcher + +on: + # What can break it: the launcher itself, the logo it builds in (include_bytes! of assets/logo.png), and this + # workflow. Every other change leaves it alone. + push: + branches: [main] + paths: + - "launcher/**" + - "assets/logo.png" + - ".github/workflows/launcher.yml" + pull_request: + paths: + - "launcher/**" + - "assets/logo.png" + - ".github/workflows/launcher.yml" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + # Each non-PR run has its own group so a queued push or dispatch cannot replace it. + group: launcher-${{ github.event_name }}-${{ github.event.pull_request.number || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + launcher: + name: launcher (${{ matrix.os }}) + strategy: + fail-fast: false + matrix: + # Windows first, as the project is; Linux for Wayland and X11 users and the same tests on another system. + os: [windows-latest, ubuntu-24.04] + runs-on: ${{ matrix.os }} + timeout-minutes: 40 + defaults: + run: + working-directory: launcher + shell: bash + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + # The runners' own rustup, no third-party action: the stable toolchain with its formatter and linter. + - name: Rust toolchain + run: | + rustup toolchain install stable --profile minimal --component clippy,rustfmt + rustup default stable + rustc --version + - name: Format + run: cargo fmt --check + - name: Lints + run: cargo clippy --locked --all-targets -- -D warnings + - name: Tests (offscreen on the CPU, no GPU, no game data) + run: cargo test --locked diff --git a/launcher/.gitignore b/launcher/.gitignore new file mode 100644 index 0000000000..b83d22266a --- /dev/null +++ b/launcher/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock new file mode 100644 index 0000000000..d1b4ba7cfa --- /dev/null +++ b/launcher/Cargo.lock @@ -0,0 +1,5264 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ab_glyph" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[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", + "version_check", + "zerocopy", +] + +[[package]] +name = "aligned" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685" +dependencies = [ + "as-slice", +] + +[[package]] +name = "aligned-vec" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b" +dependencies = [ + "equator", +] + +[[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-build" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9fc9904ad2ad097c3c1cfe2eacaaf0fc24710936fa9ed941cb310b7c6ed2ab7" +dependencies = [ + "windows-sys 0.52.0", +] + +[[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 = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" + +[[package]] +name = "arg_enum_proc_macro" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + +[[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 = "as-slice" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516" +dependencies = [ + "stable_deref_trait", +] + +[[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 = "ashpd" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f3f79755c74fd155000314eb349864caa787c6592eace6c6882dad873d9c39" +dependencies = [ + "async-fs", + "async-net", + "enumflags2", + "futures-channel", + "futures-util", + "rand", + "raw-window-handle", + "serde", + "serde_repr", + "url", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "zbus", +] + +[[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-fs" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8034a681df4aed8b8edbd7fbe472401ecf009251c8b40556b304567052e294c5" +dependencies = [ + "async-lock", + "blocking", + "futures-lite", +] + +[[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-net" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b948000fad4873c1c9339d60f2623323a0cfd3816e5181033c6a5cb68b2accf7" +dependencies = [ + "async-io", + "blocking", + "futures-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.10", +] + +[[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.10", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "av-scenechange" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394" +dependencies = [ + "aligned", + "anyhow", + "arg_enum_proc_macro", + "arrayvec", + "log", + "num-rational", + "num-traits", + "pastey", + "rayon", + "thiserror 2.0.21", + "v_frame", + "y4m", +] + +[[package]] +name = "av1-grain" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8" +dependencies = [ + "anyhow", + "arrayvec", + "log", + "nom", + "num-rational", + "v_frame", +] + +[[package]] +name = "avif-serialize" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7178fe5f7d460b13895ebb9dcb28a3a6216d2df2574a0806cb51b555d297f38" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + +[[package]] +name = "bit_field" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1" + +[[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" + +[[package]] +name = "bitstream-io" +version = "4.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eff00be299a18769011411c9def0d827e8f2d7bf0c3dbf53633147a8867fd1f" +dependencies = [ + "no_std_io2", +] + +[[package]] +name = "block" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" + +[[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 = "built" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4ad8f11f288f48ca24471bbd51ac257aaeaaa07adae295591266b792902ae64" + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[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.10", +] + +[[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.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[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.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dbf9978365bac10f54d1d4b04f7ce4427e51f71d61f2fe15e3fed5166474df7" +dependencies = [ + "bitflags 2.13.2", + "polling", + "rustix 1.1.6", + "slab", + "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.4", + "rustix 1.1.6", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[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 = "clipboard_macos" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b7f4aaa047ba3c3630b080bb9860894732ff23e2aee290a418909aa6d5df38f" +dependencies = [ + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "clipboard_wayland" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "003f886bc4e2987729d10c1db3424e7f80809f3fc22dbc16c685738887cb37b8" +dependencies = [ + "smithay-clipboard", +] + +[[package]] +name = "clipboard_x11" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd63e33452ffdafd39924c4f05a5dd1e94db646c779c6bd59148a3d95fff5ad4" +dependencies = [ + "thiserror 2.0.21", + "x11rb", +] + +[[package]] +name = "codespan-reporting" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe6d2e5af09e8c8ad56c969f2157a3d4238cebc7c55f0a517728c38f7b200f81" +dependencies = [ + "serde", + "termcolor", + "unicode-width", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[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 = "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" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +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 0.9.4", + "core-graphics-types 0.1.3", + "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 0.9.4", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "libc", +] + +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + +[[package]] +name = "cosmic-text" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173852283a9a57a3cbe365d86e74dc428a09c50421477d5ad6fe9d9509e37737" +dependencies = [ + "bitflags 2.13.2", + "fontdb", + "harfrust", + "linebender_resource_handle", + "log", + "rangemap", + "rustc-hash 1.1.0", + "self_cell", + "skrifa 0.37.0", + "smol_str", + "swash", + "sys-locale", + "unicode-bidi", + "unicode-linebreak", + "unicode-script", + "unicode-segmentation", +] + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[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 = "cryoglyph" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08bc795bdbccdbd461736fb163930a009da6597b226d6f6fce33e7a8eb6ec519" +dependencies = [ + "cosmic-text", + "etagere", + "lru", + "rustc-hash 2.1.3", + "wgpu", +] + +[[package]] +name = "ctor" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83cf0d42651b16c6dfe68685716d18480d18a9c39c62d76e8cf3eb6ed5d8bcbf" +dependencies = [ + "dtor", +] + +[[package]] +name = "cursor-icon" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" + +[[package]] +name = "dirs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", +] + +[[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.10", +] + +[[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 = "dtor" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edf234dd1594d6dd434a8fb8cada51ddbbc593e40e4a01556a0b31c62da2775b" + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[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 = "equator" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc" +dependencies = [ + "equator-macro", +] + +[[package]] +name = "equator-macro" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "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 = "etagere" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc89bf99e5dc15954a60f707c1e09d7540e5cd9af85fa75caa0b510bc08c5342" +dependencies = [ + "euclid", + "svg_fmt", +] + +[[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]] +name = "exr" +version = "1.74.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide 0.8.9", + "multiversion", + "rayon-core", + "smallvec", + "zune-inflate", +] + +[[package]] +name = "fastrand" +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 = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "float_next_after" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[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.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39a654f404bbcbd48ea58c617c2993ee91d1cb63727a37bf2323a4edeed1b8c5" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "font-types" +version = "0.12.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "fontconfig-parser" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646" +dependencies = [ + "roxmltree", +] + +[[package]] +name = "fontdb" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905" +dependencies = [ + "fontconfig-parser", + "log", + "memmap2", + "slotmap", + "tinyvec", + "ttf-parser", +] + +[[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.10", +] + +[[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.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[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.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + +[[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 = "glam" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "151665d9be52f9bb40fc7966565d39666f2d1e69233571b71b87791c7e0528b3" + +[[package]] +name = "glow" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5e5ea60d70410161c8bf5da3fdfeaa1c72ed2c15f8bbb9d19fe3a4fad085f08" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + +[[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 = "gpu-alloc" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45cf04b2726f02df5508c6de726acdc90cdf97ac771a9a0ffd8ba10a6e696bf9" +dependencies = [ + "bitflags 2.13.2", + "gpu-alloc-types", +] + +[[package]] +name = "gpu-alloc-types" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2bbed164dd10ed526c2e4fe3e721ca4a71c61730e5aafac6844b417b3227058" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "gpu-allocator" +version = "0.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c151a2a5ef800297b4e79efa4f4bec035c5f51d5ae587287c9b952bdf734cacd" +dependencies = [ + "log", + "presser", + "thiserror 1.0.69", + "windows 0.58.0", +] + +[[package]] +name = "gpu-descriptor" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b89c83349105e3732062a895becfc71a8f921bb71ecbbdd8ff99263e3b53a0ca" +dependencies = [ + "bitflags 2.13.2", + "gpu-descriptor-types", + "hashbrown 0.15.5", +] + +[[package]] +name = "gpu-descriptor-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdf242682df893b86f33a73828fb09ca4b2d3bb6cc95249707fc684d27484b91" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "guillotiere" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b62d5865c036cb1393e23c50693df631d3f5d7bcca4c04fe4cc0fd592e74a782" +dependencies = [ + "euclid", + "svg_fmt", +] + +[[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.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92c020db12c71d8a12a3fe7607873cade3a01a6287e29d540c8723276221b9d8" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "core_maths", + "read-fonts 0.35.0", + "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 = [ + "foldhash 0.2.0", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[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 = "hexf-parse" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df" + +[[package]] +name = "iced" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "000e01026c93ba643f8357a3db3ada0e6555265a377f6f9291c472f6dd701fb3" +dependencies = [ + "iced_core", + "iced_debug", + "iced_futures", + "iced_renderer", + "iced_runtime", + "iced_widget", + "iced_winit", + "image", + "thiserror 2.0.21", +] + +[[package]] +name = "iced_core" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91ab1937d699403e7e69252ae743a902bcee9f4ab2052cc4c9a46fcf34729d85" +dependencies = [ + "bitflags 2.13.2", + "bytes", + "glam", + "lilt", + "log", + "num-traits", + "rustc-hash 2.1.3", + "smol_str", + "thiserror 2.0.21", + "web-time", +] + +[[package]] +name = "iced_debug" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25035ab0215a620e53f4103e36fc4e59a1fb2817e4bfc38a30ad27b4202ea0be" +dependencies = [ + "iced_core", + "iced_futures", + "log", +] + +[[package]] +name = "iced_futures" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c0c85ccad42dfbec7293c36c018af0ea0dbcc52d137a4a9a0b0f6822a3fdf0a" +dependencies = [ + "futures", + "iced_core", + "log", + "rustc-hash 2.1.3", + "wasm-bindgen-futures", + "wasmtimer", +] + +[[package]] +name = "iced_graphics" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "234ca1c2cec4155055f68fa5fad1b5242c496ac8238d80a259bca382fb44a102" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "cosmic-text", + "half", + "iced_core", + "iced_futures", + "image", + "kamadak-exif", + "log", + "lyon_path", + "raw-window-handle", + "rustc-hash 2.1.3", + "thiserror 2.0.21", + "unicode-segmentation", +] + +[[package]] +name = "iced_program" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dfafec2947cda688d8eb00dac337ba11aa60f9ef6335aed343e189d26e4a673" +dependencies = [ + "iced_graphics", + "iced_runtime", +] + +[[package]] +name = "iced_renderer" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "250cc0802408e8c077986ec56c7d07c65f423ee658a4b9fd795a1f2aae5dac05" +dependencies = [ + "iced_graphics", + "iced_tiny_skia", + "iced_wgpu", + "log", + "thiserror 2.0.21", +] + +[[package]] +name = "iced_runtime" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1889b819ce4c06674183242e336c8d49465665441396914dc07cc86f44fa8d4" +dependencies = [ + "bytes", + "iced_core", + "iced_futures", + "raw-window-handle", + "thiserror 2.0.21", +] + +[[package]] +name = "iced_tiny_skia" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c267596d742714b1853cc10c3983a367762816fc4836bd3b79f76ce76787d6f8" +dependencies = [ + "bytemuck", + "cosmic-text", + "iced_debug", + "iced_graphics", + "kurbo", + "log", + "rustc-hash 2.1.3", + "softbuffer", + "tiny-skia", +] + +[[package]] +name = "iced_wgpu" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff144a999b0ca0f8a10257934500060240825c42e950ec0ebee9c8ae30561c13" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "cryoglyph", + "futures", + "glam", + "guillotiere", + "iced_debug", + "iced_graphics", + "log", + "lyon", + "rustc-hash 2.1.3", + "thiserror 2.0.21", + "wgpu", +] + +[[package]] +name = "iced_widget" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1596afa0d3109c2618e8bc12bae6c11d3064df8f95c42dfce570397dbe957ab" +dependencies = [ + "iced_renderer", + "log", + "num-traits", + "rustc-hash 2.1.3", + "thiserror 2.0.21", + "unicode-segmentation", +] + +[[package]] +name = "iced_winit" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7589888c8e951899cc688247a69933bb7a0511f0b4b2e122ac3fcd5dacb37f72" +dependencies = [ + "iced_debug", + "iced_program", + "log", + "mundy", + "rustc-hash 2.1.3", + "thiserror 2.0.21", + "tracing", + "wasm-bindgen-futures", + "web-sys", + "window_clipboard", + "winit", +] + +[[package]] +name = "icu_collections" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +dependencies = [ + "displaydoc", + "potential_utf", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" + +[[package]] +name = "icu_properties" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af" + +[[package]] +name = "icu_provider" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +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.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6506c6c10786659413faa717ceebcb8f70731c0a60cbae39795fdf114519c1a" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "exr", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png", + "qoi", + "ravif", + "rayon", + "rgb", + "tiff", + "zune-core 0.5.3", + "zune-jpeg 0.5.15", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error 2.0.1", +] + +[[package]] +name = "imgref" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e44b0a4eaa4c82f441d50a963f2d5f05a787240aeee097597033e72accfd22f" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", +] + +[[package]] +name = "interpolate_name" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "kamadak-exif" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8772c92c0f41c4a672cbdee6728253e5ae8fcc1c5eb5c6c676579565684bbf68" +dependencies = [ + "mutate_once", +] + +[[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.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1618d4ebd923e97d67e7cd363d80aef35fe961005cbbbb3d2dad8bdd1bc63440" +dependencies = [ + "arrayvec", + "smallvec", +] + +[[package]] +name = "lebe" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" + +[[package]] +name = "leonida-launcher" +version = "0.1.0" +dependencies = [ + "dirs", + "iced", + "iced_runtime", + "iced_wgpu", + "png", + "proptest", + "rfd", + "serde", + "serde_json", + "tiny-skia", + "unicode-segmentation", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libfuzzer-sys" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2" +dependencies = [ + "arbitrary", + "cc", +] + +[[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 = "lilt" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "337d4c256f7d9f2dbd633891d48ace853efa5b1554122d9220b172ad9c03c3a9" +dependencies = [ + "web-time", +] + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "loop9" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062" +dependencies = [ + "imgref", +] + +[[package]] +name = "lru" +version = "0.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39" + +[[package]] +name = "lyon" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0578bdecb7d6d88987b8b2b1e3a4e2f81df9d0ece1078623324a567904e7b7" +dependencies = [ + "lyon_algorithms", + "lyon_tessellation", +] + +[[package]] +name = "lyon_algorithms" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a6b9d4e8b48acd531fbf1241ad9b270df6e60b6b92bdea1469f4f40899d805" +dependencies = [ + "lyon_path", + "num-traits", +] + +[[package]] +name = "lyon_geom" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d82dd26aa4dc0b5b70b9115de59824842bcb43cf4a28e1b1e6d0ad148c93f93e" +dependencies = [ + "arrayvec", + "euclid", + "num-traits", +] + +[[package]] +name = "lyon_path" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c463f9c428b7fc5ec885dcd39ce4aa61e29111d0e33483f6f98c74e89d8621e" +dependencies = [ + "lyon_geom", + "num-traits", +] + +[[package]] +name = "lyon_tessellation" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd4872650e70dc907dd4f7ebc449d7d657a0d2658e423b2e724970870bbbf75b" +dependencies = [ + "float_next_after", + "lyon_path", + "num-traits", +] + +[[package]] +name = "malloc_buf" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb" +dependencies = [ + "libc", +] + +[[package]] +name = "maybe-rayon" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" +dependencies = [ + "cfg-if", + "rayon", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +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 = "metal" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00c15a6f673ff72ddcc22394663290f870fb224c1bfce55734a75c414150e605" +dependencies = [ + "bitflags 2.13.2", + "block", + "core-graphics-types 0.2.0", + "foreign-types", + "log", + "objc", + "paste", +] + +[[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.7.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac9557c559cd6fc9867e122e20d2cbefc9ca29d80d027a8e39310920ed2f0a97" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "multiversion" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076" +dependencies = [ + "multiversion-macros", + "target-features", +] + +[[package]] +name = "multiversion-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "target-features", +] + +[[package]] +name = "mundy" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f32eb0db40f2df2bcfb05c93b8f73938d4c26ce9ac8881f1df0c8d3296921a73" +dependencies = [ + "android-build", + "async-io", + "cfg-if", + "dispatch", + "futures-channel", + "futures-lite", + "jni", + "ndk-context", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "pin-project-lite", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows 0.62.2", + "zbus", +] + +[[package]] +name = "mutate_once" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13d2233c9842d08cfe13f9eac96e207ca6a2ea10b80259ebe8ad0268be27d2af" + +[[package]] +name = "naga" +version = "27.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "066cf25f0e8b11ee0df221219010f213ad429855f57c494f995590c861a9a7d8" +dependencies = [ + "arrayvec", + "bit-set", + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "codespan-reporting", + "half", + "hashbrown 0.16.1", + "hexf-parse", + "indexmap", + "libm", + "log", + "num-traits", + "once_cell", + "rustc-hash 1.1.0", + "spirv", + "thiserror 2.0.21", + "unicode-ident", +] + +[[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 = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "no_std_io2" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418abd1b6d34fbf6cae440dc874771b0525a604428704c76e48b29a5e67b8003" +dependencies = [ + "memchr", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "noop_proc_macro" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[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" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1" +dependencies = [ + "malloc_buf", +] + +[[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 0.2.2", + "objc2-core-image 0.2.2", + "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", + "libc", + "objc2 0.6.5", + "objc2-cloud-kit 0.3.2", + "objc2-core-data 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-image 0.3.2", + "objc2-core-text", + "objc2-core-video", + "objc2-foundation 0.3.2", + "objc2-quartz-core 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-cloud-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-foundation 0.3.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-data" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-foundation 0.3.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", +] + +[[package]] +name = "objc2-core-image" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006" +dependencies = [ + "objc2 0.6.5", + "objc2-foundation 0.3.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 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", +] + +[[package]] +name = "objc2-core-video" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-io-surface", +] + +[[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", + "libc", + "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-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", +] + +[[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-foundation 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 0.2.2", + "objc2-core-data 0.2.2", + "objc2-core-image 0.2.2", + "objc2-core-location", + "objc2-foundation 0.2.2", + "objc2-link-presentation", + "objc2-quartz-core 0.2.2", + "objc2-symbols", + "objc2-uniform-type-identifiers", + "objc2-user-notifications", +] + +[[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-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 = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[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.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c860fd3227ca4ac3cc032e2cd20cba3f02ccdf4b610538f8ee6584d56bb62e96" +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 = "owned_ttf_parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" +dependencies = [ + "ttf-parser", +] + +[[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 = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pastey" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6c2123f4708bbd422630a6dae7c03f678b1ce1f1c99e4c4b3beac69c8174cc9" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "358938fd6df944c1e44bb328b60fb275f13c804aac47ba26a1165d45a3f87756" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[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 = "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 = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3" + +[[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 = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +dependencies = [ + "profiling-procmacros", +] + +[[package]] +name = "profiling-procmacros" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "proptest" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744" +dependencies = [ + "bit-set", + "bit-vec", + "bitflags 2.13.2", + "num-traits", + "rand", + "rand_chacha", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "qoi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +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 = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_xorshift" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a" +dependencies = [ + "rand_core", +] + +[[package]] +name = "range-alloc" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" + +[[package]] +name = "rangemap" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d" + +[[package]] +name = "rav1e" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b" +dependencies = [ + "aligned-vec", + "arbitrary", + "arg_enum_proc_macro", + "arrayvec", + "av-scenechange", + "av1-grain", + "bitstream-io", + "built", + "cfg-if", + "interpolate_name", + "itertools", + "libc", + "libfuzzer-sys", + "log", + "maybe-rayon", + "new_debug_unreachable", + "noop_proc_macro", + "num-derive", + "num-traits", + "paste", + "profiling", + "rand", + "rand_chacha", + "simd_helpers", + "thiserror 2.0.21", + "v_frame", + "wasm-bindgen", +] + +[[package]] +name = "ravif" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef69c1990ceef18a116855938e74793a5f7496ee907562bd0857b6ac734ab285" +dependencies = [ + "avif-serialize", + "imgref", + "loop9", + "quick-error 2.0.1", + "rav1e", + "rayon", + "rgb", +] + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "read-fonts" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6717cf23b488adf64b9d711329542ba34de147df262370221940dfabc2c91358" +dependencies = [ + "bytemuck", + "core_maths", + "font-types 0.10.1", +] + +[[package]] +name = "read-fonts" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" +dependencies = [ + "bytemuck", + "font-types 0.12.7", + "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 = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror 2.0.21", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[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.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2bee61e6cffa4635c72d7d81a84294e28f0930db0ddcb0f66d10244674ebed" +dependencies = [ + "ashpd", + "block2 0.6.2", + "dispatch2", + "js-sys", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "pollster", + "raw-window-handle", + "urlencoding", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows-sys 0.59.0", +] + +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" + +[[package]] +name = "roxmltree" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" + +[[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 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error 1.2.3", + "tempfile", + "wait-timeout", +] + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +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 = "sctk-adwaita" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec" +dependencies = [ + "ab_glyph", + "log", + "memmap2", + "smithay-client-toolkit 0.19.2", + "tiny-skia", +] + +[[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 = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "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.10", +] + +[[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 = "simd_helpers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6" +dependencies = [ + "quote", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "skrifa" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c31071dedf532758ecf3fed987cdb4bd9509f900e026ab684b4ecb81ea49841" +dependencies = [ + "bytemuck", + "read-fonts 0.35.0", +] + +[[package]] +name = "skrifa" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" +dependencies = [ + "bytemuck", + "read-fonts 0.41.0", +] + +[[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.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[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.4", + "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 = "softbuffer" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aac18da81ebbf05109ab275b157c22a653bb3c12cf884450179942f81bcbf6c3" +dependencies = [ + "as-raw-xcb-connection", + "bytemuck", + "fastrand", + "js-sys", + "memmap2", + "ndk", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", + "raw-window-handle", + "redox_syscall 0.5.18", + "rustix 1.1.6", + "tiny-xlib", + "tracing", + "wasm-bindgen", + "wayland-backend", + "wayland-client", + "wayland-sys", + "web-sys", + "windows-sys 0.61.2", + "x11rb", +] + +[[package]] +name = "spirv" +version = "0.3.0+sdk-1.3.268.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eda41003dc44290527a59b13432d4a0379379fa074b70174882adfbdfd917844" +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 = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" + +[[package]] +name = "svg_fmt" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0193cc4331cfd2f3d2011ef287590868599a2f33c3e69bc22c1a3d3acf9e02fb" + +[[package]] +name = "swash" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c2499c2d826531388872b2268718aed907a39bd785ab0dcfe57fab26283f92e" +dependencies = [ + "skrifa 0.44.0", + "yazi", + "zeno", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "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.10", +] + +[[package]] +name = "sys-locale" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4" +dependencies = [ + "libc", +] + +[[package]] +name = "target-features" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "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]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "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]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tiff" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af9605de7fee8d9551863fd692cce7637f548dbd9db9180fcc07ccc6d26c336f" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error 2.0.1", + "weezl", + "zune-jpeg 0.4.21", +] + +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "tiny-xlib" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a90a0ca3ee6a69f2ad28fd11621a4c3f03b371f366be500b64df260c4ffbafb4" +dependencies = [ + "as-raw-xcb-connection", + "ctor", + "libloading", + "pkg-config", + "tracing", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[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.20+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e76360e201d6dbd6583e17795ba71a88f47365a9139c8450a7979c32303b8e73" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow 1.0.5", +] + +[[package]] +name = "toml_parser" +version = "1.1.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31" +dependencies = [ + "winnow 1.0.5", +] + +[[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 = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +dependencies = [ + "core_maths", +] + +[[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 = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-linebreak" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", + "serde_derive", +] + +[[package]] +name = "urlencoding" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + +[[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.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" +dependencies = [ + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "v_frame" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2" +dependencies = [ + "aligned-vec", + "num-traits", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[package]] +name = "walkdir" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasip2" +version = "1.0.1+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasmtimer" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c62b7f338e4397a45d054c15a2b36a93d57cccdda7be11a7d7b045d47b5e70ce" +dependencies = [ + "futures", + "js-sys", + "parking_lot", + "pin-project-lite", + "slab", + "wasm-bindgen", +] + +[[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.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "563a85523cade2429938e790815fd7319062103b9f4a2dc806e9b53b95982d8f" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "wgpu" +version = "27.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfe68bac7cde125de7a731c3400723cadaaf1703795ad3f4805f187459cd7a77" +dependencies = [ + "arrayvec", + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "document-features", + "hashbrown 0.16.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 = "27.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27a75de515543b1897b26119f93731b385a19aea165a1ec5f0e3acecc229cae7" +dependencies = [ + "arrayvec", + "bit-set", + "bit-vec", + "bitflags 2.13.2", + "bytemuck", + "cfg_aliases", + "document-features", + "hashbrown 0.16.1", + "indexmap", + "log", + "naga", + "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-windows-linux-android", + "wgpu-hal", + "wgpu-types", +] + +[[package]] +name = "wgpu-core-deps-apple" +version = "27.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0772ae958e9be0c729561d5e3fd9a19679bcdfb945b8b1a1969d9bfe8056d233" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-emscripten" +version = "27.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b06ac3444a95b0813ecfd81ddb2774b66220b264b3e2031152a4a29fda4da6b5" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-windows-linux-android" +version = "27.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71197027d61a71748e4120f05a9242b2ad142e3c01f8c1b47707945a879a03c3" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-hal" +version = "27.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b21cb61c57ee198bc4aff71aeadff4cbb80b927beb912506af9c780d64313ce" +dependencies = [ + "android_system_properties", + "arrayvec", + "ash", + "bit-set", + "bitflags 2.13.2", + "block", + "bytemuck", + "cfg-if", + "cfg_aliases", + "core-graphics-types 0.2.0", + "glow", + "glutin_wgl_sys", + "gpu-alloc", + "gpu-allocator", + "gpu-descriptor", + "hashbrown 0.16.1", + "js-sys", + "khronos-egl", + "libc", + "libloading", + "log", + "metal", + "naga", + "ndk-sys", + "objc", + "once_cell", + "ordered-float", + "parking_lot", + "portable-atomic", + "portable-atomic-util", + "profiling", + "range-alloc", + "raw-window-handle", + "renderdoc-sys", + "smallvec", + "thiserror 2.0.21", + "wasm-bindgen", + "web-sys", + "wgpu-types", + "windows 0.58.0", + "windows-core 0.58.0", +] + +[[package]] +name = "wgpu-types" +version = "27.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afdcf84c395990db737f2dd91628706cb31e86d72e53482320d368e52b5da5eb" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "js-sys", + "log", + "thiserror 2.0.21", + "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 0.61.2", +] + +[[package]] +name = "window_clipboard" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5654226305eaf2dde8853fb482861d28e5dcecbbd40cb88e8393d94bb80d733" +dependencies = [ + "clipboard-win", + "clipboard_macos", + "clipboard_wayland", + "clipboard_x11", + "raw-window-handle", + "thiserror 2.0.21", +] + +[[package]] +name = "windows" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6" +dependencies = [ + "windows-core 0.58.0", + "windows-targets", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core 0.62.2", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core 0.62.2", +] + +[[package]] +name = "windows-core" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99" +dependencies = [ + "windows-implement 0.58.0", + "windows-interface 0.58.0", + "windows-result 0.2.0", + "windows-strings 0.1.0", + "windows-targets", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement 0.60.2", + "windows-interface 0.59.3", + "windows-link", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core 0.62.2", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core 0.62.2", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" +dependencies = [ + "windows-result 0.2.0", + "windows-targets", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +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 0.9.4", + "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", + "orbclient", + "percent-encoding", + "pin-project", + "raw-window-handle", + "redox_syscall 0.4.1", + "rustix 0.38.44", + "sctk-adwaita", + "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 = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[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.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" + +[[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 = "y4m" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" + +[[package]] +name = "yazi" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac366ea532fa8ee6a992cec9dea525b1dc284e69702f36c2ab5fbebadc81ec86" + +[[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.10", + "synstructure", +] + +[[package]] +name = "zbus" +version = "5.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfeff997a0aaa3eb20c4652baf788d2dfa6d2839a0ead0b3ff69ce2f9c4bdd1" +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 0.7.15", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bbd5a90dbe8feee5b13def448427ae314ccd26a49cac47905cafefb9ff846f1" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffd8af6d5b78619bab301ff3c560a5bd22426150253db278f164d6cf3b72c50f" +dependencies = [ + "serde", + "winnow 0.7.15", + "zvariant", +] + +[[package]] +name = "zeno" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524" + +[[package]] +name = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +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.10", + "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.10", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-inflate" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "zune-jpeg" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713" +dependencies = [ + "zune-core 0.4.12", +] + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core 0.5.3", +] + +[[package]] +name = "zvariant" +version = "5.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68b64ef4f40c7951337ddc7023dd03528a57a3ce3408ee9da5e948bd29b232c4" +dependencies = [ + "endi", + "enumflags2", + "serde", + "url", + "winnow 0.7.15", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "484d5d975eb7afb52cc6b929c13d3719a20ad650fea4120e6310de3fc55e415c" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75c23a64ef8f40f13a6989991e643554d9bef1d682a281160cf0c1bc389c5e9" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 2.0.119", + "winnow 0.7.15", +] diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml new file mode 100644 index 0000000000..5923441751 --- /dev/null +++ b/launcher/Cargo.toml @@ -0,0 +1,56 @@ +[package] +name = "leonida-launcher" +description = "A small desktop launcher for Leonida: check your copy, build the port, start the loader" +version = "0.1.0" +edition = "2024" +rust-version = "1.88" +# The launcher is under the repository's licence; its bundled fonts (fonts/) under the SIL Open +# Font License. +license = "GPL-3.0-or-later AND OFL-1.1" +publish = false +default-run = "leonida-launcher" + +[lib] +name = "leonida_launcher" +path = "src/lib.rs" + +[[bin]] +name = "leonida-launcher" +path = "src/main.rs" + +[dependencies] +# Stock iced 0.14 from crates.io with its default features (wgpu and tiny-skia renderers, X11 and +# Wayland); advanced for the ported widgets, image for the logo, canvas for the window icons. +iced = { version = "0.14", features = ["advanced", "image", "canvas"] } +# iced's wgpu renderer, at iced's exact version, for the one custom primitive (shape.rs: the +# window's rounded corners and the close button's cross) through its public primitive API. +iced_wgpu = "=0.14.0" +# Grapheme clusters: a label's letters, spaced out, and the text field's caret steps. +unicode-segmentation = "1" +# The Play page's scene: its shore and palms, filled as anti-aliased paths. The version iced's +# software renderer already uses, so nothing new is compiled. +tiny-skia = { version = "0.11", default-features = false, features = ["std"] } +# The native folder picker: the Windows dialog, and on Linux the desktop portal (X11 and Wayland). +rfd = "0.15" +# The platform's per-user configuration folder. +dirs = "6" +serde = { version = "1", features = ["derive"] } +serde_json = "1" + +[dev-dependencies] +# Draws a view offscreen, as a window would, for the screenshot and keyboard tests. +iced_runtime = "=0.14.0" +png = "0.18" +# The text editing rules' property tests (src/ui/edit.rs). +proptest = "1" + +[lints.rust] +unsafe_code = "forbid" + +[lints.clippy] +all = { level = "warn", priority = -1 } + +[profile.release] +lto = true +codegen-units = 1 +strip = true diff --git a/launcher/README.md b/launcher/README.md new file mode 100644 index 0000000000..a35bd7abda --- /dev/null +++ b/launcher/README.md @@ -0,0 +1,188 @@ +# Leonida launcher + +A small desktop window over the repository's own commands. It checks your copy of the game with +`make_game.py`, builds the port, and starts the loader as [docs/boot.md](../docs/boot.md) (section 2) +and the [README](../README.md) ("How to build", "Running the loader on Linux") describe. It +draws nothing from the game, reads no game file itself, and never goes online: no telemetry, no +update check. + +## Build and run + +Rust 1.88 or newer, from this folder: + +```sh +cargo build --release +cargo run --release # finds the repository above itself or the current folder +cargo run --release -- --repo PATH # or names it: the folder that holds make_game.py +``` + +The release build is a window without a console on Windows. It needs a GPU with Vulkan, DX12 +(Windows) or, failing those, draws on the CPU (iced's tiny-skia renderer; `ICED_BACKEND=tiny-skia` +forces it). + +## The window + +A sidebar with five pages, and the light and dark pill in the header bar: click a side, or drag +its highlight across, which follows the pointer and slides into place, the mode changing as it's +let go; the window then crossfades into the other mode. Buttons' glows fade in and out with the +pointer. + +- **Play**: the logo, the launcher's version and the game copy's version once a check has run, + one status line, and one big main button whose meaning follows what exists: + **Check** (`make_game.py --game --check`), **Build** (`make_game.py --game + --out [--work ]` and the options below), **Play** (the loader, below), and + **Cancel** while something runs. Play is enabled only when the output folder holds the built + loader and the package holds the game's executable; today's package has no executable, so + "Not bootable yet" is the normal state after a build. While a command runs, the loader turns, + the bar follows the build's stages (from make_game.py's `HH:MM:SS : …` lines; it also + reads `@@stage`, `@@progress`, `@@eta`, `@@check`, `@@done` and `@@error` lines if a later + make_game.py prints them), and the output's last lines show below. A failure shows its exit + code and last words. +- **Game files**: the game package, output and work folders (a field and a folder picker each), + and the full check. +- **Build**: the stages and the WAV audio. +- **Performance**: the GPU filter, the Vulkan validation layer, wave64 translation and jobs. +- **Diagnostics**: the loader's D3D12 trace, what it does with unimplemented imports, and where + the game's writes go. + +| Control | Page | What it drives | +|---|---|---| +| Game package | Game files | `--game` (Check, Build); `--run`, `--game-dir` (Play) | +| Output folder | Game files | `--out` (Build); where the loader is looked for (Play) | +| Work folder | Game files | `--work` (Build); left out when empty | +| Compare every file's SHA-256 | Game files | `--full-check` (Check) | +| Shaders, Assets, Runtime, Pipelines | Build | `--stages` (Build); left out when all are on; none is `--stages check` | +| Also decode audio to WAV | Build | `--wav` (Build) | +| GPU | Performance | `LEONIDA_VK_DEVICE` (Build, for make_game.py's GPU probe, and Play) | +| Vulkan validation | Performance | `LEONIDA_VK_VALIDATION=1` (Play) | +| Choose wave64 translation automatically; Emulate or Native | Performance | `--wave64-emulate auto`, `on` or `off` (Build); `auto` is left out, as it's the default | +| Jobs | Performance | `--jobs N` (Build); left out when empty | +| Trace D3D12 calls | Diagnostics | `gta6rt --trace-d3d12` (Play) | +| Unimplemented imports: Log, Fail, Stop | Diagnostics | `LEONIDA_UNIMPLEMENTED=fail` or `stop` (Play); `log`, the default, is left out | +| Writes folder | Diagnostics | `gta6rt --overlay DIR` (Play; Wine's `Z:` path on Linux); left out when empty | + +On/off settings are switches; a three-way one is a choice. + +make_game.py runs as `python -I -u make_game.py …` (`python3` off Windows) in the repository, +with no input, so a question it would ask ends it instead of waiting. Play runs +`gta6rt.exe --run \game_scarlett_master.exe --game-dir ` from the output folder +with `LEONIDA_D3D12=vulkan`; on Linux the output folder's `gta6rt.sh` (Wine) runs in the package +folder, `--run ./game_scarlett_master.exe --game-dir Z:\`. The executable's name is +the version manifest's `expected_exe` (`game/*.json`). + +Settings are saved to `launcher.json` in `%APPDATA%\Leonida` (Windows) or `~/.config/leonida` +(Linux), with a version; a missing, broken or newer file gives the defaults. + +## Keys + +| Keys | | +|---|---| +| Tab, Shift+Tab | Move focus through the header bar, the sidebar and the page | +| Enter, Space | Press the focused button; Space toggles a switch or checkbox | +| Up, Down | Choose a page in the focused sidebar | +| Left, Right | Choose in the focused light and dark pill (or drag across it) | +| Ctrl+Page Down, Ctrl+Page Up | The next and previous page | +| Ctrl+L | Light and dark | + +The window draws its own decorations: drag the header bar to move it, double-click it to +maximize or restore, drag inside its edges to resize. Narrower than 640 pixels, the sidebar folds +and the header bar shows a back button. + +`LEONIDA_WINDOW_FRAME`, read at start, says who draws the frame: unset or `1`, the launcher (see +below); `0`, nobody: an opaque, square window, for a desktop that draws its own or a driver that +misbehaves with a transparent window; anything else is as unset, with one line on stderr. + +- **Linux (Wayland, X11)**: a transparent window, its corners rounded (14 px) and a 1 px line + drawn by the launcher while it floats, square when maximized. +- **Windows**: stock iced can't present a transparent window there (iced_wgpu makes its DX12 + swapchain from the window's HWND, which presents opaque only, and tiny-skia's softbuffer has no + alpha), so the window is opaque and asks Windows 11 for its own rounded corners + (`CornerPreference::Round`), and the launcher draws its 1 px line at their 8 px radius. **Not + tested on a real Windows machine**; it builds with `cargo check --target x86_64-pc-windows-gnu`. + Windows 10 shows square corners. + +## Tests + +```sh +cargo test # everything; no game files, no GPU, no window +LEONIDA_LAUNCHER_SCREENSHOTS=/tmp/shots cargo test --test screenshots +cargo clippy --all-targets -- -D warnings +cargo fmt --check +``` + +Unit tests cover the command lines on Windows and Linux, the state machine, the settings file, +finding the repository, reading the output, the window's frame, the Play page's scene, and every +palette's contrast. The process tests run a stand-in shell script. `tests/keyboard.rs` drives the +window by keys alone, `tests/backdrop.rs` counts the scene's generations, and +`tests/screenshots.rs` draws every page offscreen on tiny-skia (on the CPU), writing PNGs to +`$LEONIDA_LAUNCHER_SCREENSHOTS` or `target/tmp/screenshots`. +`cargo test --release --lib scene::tests::timing -- --ignored --nocapture` times the scene. + +## The Play page's scene + +Behind the Play page: a dusk (dark) or a morning (light) over water, with a shore and two palms +in silhouette, generated by the launcher (`src/scene.rs`) from the theme alone: its gradient's six +stops, its background, its mode, and its outline and shadow colors. There are no image files. +The scene is one RGBA picture of the page's size in physical pixels, its soft layers computed per +pixel and the silhouettes filled as anti-aliased paths (tiny-skia), in a 16:10 frame that covers +the page from its bottom right (horizon at 0.66 of the frame's height, sun at 0.805 of its width). + +- Over the text column on the left (its padding, its 420-pixel content and 24 pixels), the + page's background lies at 0.97 opacity, then fades out across at most 40% of the page; the + tests check that the `muted` ink keeps 4.5:1 on every pixel there, in both modes, at three + sizes. Text sits on the page only in that column; the progress bar and the output lie on an + opaque panel. However narrow the window, folded too, the scene stays: the column's background + covers what lies under the text, and the fade takes at least 48 pixels beside it. +- It's generated off the interface's thread, once per page size, scale, theme, mode and column, + after the size has held for 150 ms, and cached: drawing a frame only shows the cached picture, + and while a resize is under way the last picture shows, scaled to cover. Both modes' pictures + stay cached for the current size. +- About 30–34 ms for a 1040×754 page and 123–132 ms for 2320×1394 in a release build on the + machine it was written on. + +## The design system + +`src/ui/` is the launcher's UI kit: the design language's tokens (colors, type, spacing, radii, +motion, glow), the theme, text roles, fonts and focus model, and the widgets the window shows, +each with its states, focus and keys: button, text field and its editing rules, checkbox, choice, +switch, toggle group (the header bar's pill), loader, progress bar, status chip, scroll area, +sidebar list, settings groups, form, the window's own decorations and the folded window. + +- **Palettes**: Sunset dark and light, from the logo's pixels. Its light orange and dark purple + are the two colors: in light, orange is the main one (the main button's fill, selection, the + brand) and purple the secondary (focus, switches, every glow); in dark, the other way round, + except that the main button stays orange, with an orange glow, to stand out on the purple + page. It is filled with the logo's orange and its shadow as ink; as text or a line, each + color keeps its hue but is darkened (light) or lightened (dark) only as far as 4.5:1 needs. + Information is the logo's blue, errors its coral, warnings a gold. The logo's near-black + purple shadow is dark's background and light's text, its deep purple outline dark's lines. A + running progress bar goes from the purple to the orange. The tests check every ink on every + surface in both. +- **Stock iced 0.14** from crates.io, with no patched crates. iced reads the system's fonts at + start; text names only the launcher's own, so that changes nothing drawn. +- **Rounded corners**: `shape.rs` draws the window's corners and the close button's cross with + one custom primitive through iced_wgpu's public primitive API. On the tiny-skia renderer, which + can't draw one, the frame's and header bar's fills are rounded quads, the line a rounded quad's + border, and the cross canvas strokes. Windows: the frame described above. +- **Fonts**: the four faces the text roles use (Chakra Petch SemiBold and Bold, IBM Plex Sans + Regular, JetBrains Mono Regular), compiled in from `fonts/`. +- `LEONIDA_REDUCE_MOTION=1` stills what moves (the loader, a busy bar, the theme's crossfade); + `LEONIDA_BATTERY_SAVER=1` halves animations and softens glow. +- One test is ignored: the text field's right-to-left caret positions, as with stock iced a + system Hebrew font shapes the line and an unbounded right-to-left line lays out at infinity. + +## Licence + +The launcher is under the repository's licence, GPLv3 or later; the fonts in `fonts/` are under +the SIL Open Font License 1.1, with their licence files beside them. + +## Not done + +- Run in a real window on Linux only (Wayland, an RX 7900 XTX), not yet on Windows or macOS, and + not through a complete build or a real launch: the tests use a stand-in script and offscreen + drawing. +- The translator's fallback flags (`--no-float-controls`, `--bary-fallback`, + `--texel-offset-fallback`, `--f16-interp-fallback`, `--mesh-compute`, `--pc-tail-ubo`) and + `--runtime-build` have no controls yet; they are real options and could go on a Compatibility + page. +- No translations; no high-contrast palette. diff --git a/launcher/fonts/ChakraPetch-Bold.ttf b/launcher/fonts/ChakraPetch-Bold.ttf new file mode 100644 index 0000000000..76369fffa4 Binary files /dev/null and b/launcher/fonts/ChakraPetch-Bold.ttf differ diff --git a/launcher/fonts/ChakraPetch-OFL.txt b/launcher/fonts/ChakraPetch-OFL.txt new file mode 100644 index 0000000000..9cee5a5b7f --- /dev/null +++ b/launcher/fonts/ChakraPetch-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2018 The Chakra Petch Project Authors (https://github.com/m4rc1e/Chakra-Petch.git) + +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/launcher/fonts/ChakraPetch-SemiBold.ttf b/launcher/fonts/ChakraPetch-SemiBold.ttf new file mode 100644 index 0000000000..802d59875a Binary files /dev/null and b/launcher/fonts/ChakraPetch-SemiBold.ttf differ diff --git a/launcher/fonts/IBMPlexSans-OFL.txt b/launcher/fonts/IBMPlexSans-OFL.txt new file mode 100644 index 0000000000..01497cc60d --- /dev/null +++ b/launcher/fonts/IBMPlexSans-OFL.txt @@ -0,0 +1,93 @@ +Copyright © 2017 IBM Corp. with Reserved Font Name "Plex" + +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/launcher/fonts/IBMPlexSans-Regular.ttf b/launcher/fonts/IBMPlexSans-Regular.ttf new file mode 100644 index 0000000000..bd6817d520 Binary files /dev/null and b/launcher/fonts/IBMPlexSans-Regular.ttf differ diff --git a/launcher/fonts/JetBrainsMono-OFL.txt b/launcher/fonts/JetBrainsMono-OFL.txt new file mode 100644 index 0000000000..8bee4148c1 --- /dev/null +++ b/launcher/fonts/JetBrainsMono-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) + +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: +https://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/launcher/fonts/JetBrainsMono-Regular.ttf b/launcher/fonts/JetBrainsMono-Regular.ttf new file mode 100644 index 0000000000..dff66cc507 Binary files /dev/null and b/launcher/fonts/JetBrainsMono-Regular.ttf differ diff --git a/launcher/fonts/SHA256SUMS b/launcher/fonts/SHA256SUMS new file mode 100644 index 0000000000..3d0240bacc --- /dev/null +++ b/launcher/fonts/SHA256SUMS @@ -0,0 +1,4 @@ +65fbf76d95651697275e19db4d717c0e95a789ddd3476478b05292104db278a0 ChakraPetch-Bold.ttf +45264de3204ddbd5fb3e14a2402acd5c630d16650ae5fc221d2c52da46a6734b ChakraPetch-SemiBold.ttf +975dcda37d80f038dcd143c22e33ca2d97a0cc5a929aace1c749153b0fe1afa5 IBMPlexSans-Regular.ttf +a0bf60ef0f83c5ed4d7a75d45838548b1f6873372dfac88f71804491898d138f JetBrainsMono-Regular.ttf diff --git a/launcher/src/app.rs b/launcher/src/app.rs new file mode 100644 index 0000000000..fd7ef73ade --- /dev/null +++ b/launcher/src/app.rs @@ -0,0 +1,1169 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! The launcher's window: a sidebar with three pages (Play, Settings, Performance) in the +//! design language's browsing window, the light and dark pill in the header bar, and the commands run from it. + +use std::path::{Path, PathBuf}; + +use std::time::{Duration, Instant}; + +use iced::keyboard::{self, key::Named}; +use iced::widget::image; +use iced::{Size, Subscription, Task}; + +use crate::backdrop::{self, Backdrop, Key}; +use crate::scene::{self, Picture}; +use crate::ui::chrome::Corners; +use crate::ui::tokens::window as decorations; + +use crate::commands::{self, Command, Missing, Platform}; +use crate::config::{self, Checked, STAGES, Settings, Shade, Unimplemented, Wave64}; +use crate::output::Tracker; +use crate::process; +use crate::repo; +use crate::state::{self, Action, Facts, Kind, Outcome, Tone}; +use crate::ui::chrome::header; +use crate::ui::settings::{group, row}; +use crate::ui::text; +use crate::ui::theme::{Emphasis, Frame, Status}; +use crate::ui::tokens::{Mode, Palette, Surface, size, space}; +use crate::ui::widget::{Column, Row, column, container, row as across, space as gap}; +use crate::ui::window::{Chrome, ChromeMessage, FrameSetting}; +use crate::ui::{ + Center, Element, Fill, Ink, Theme, button, choice, form, loader, navigation, progress, + scroll_area, status, switch, text_field, toggle_group, +}; + +/// The launcher's version, from its Cargo.toml. +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); + +/// The window's size when it opens, and the least it takes. +pub const SIZE: Size = Size::new(980.0, 680.0); +pub const LEAST: Size = Size::new(420.0, 480.0); + +/// How many of the output's last lines the Play page shows. +const SHOWN_LINES: usize = 200; + +/// The pages, in the sidebar's order. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Page { + #[default] + Play, + GameFiles, + Build, + Performance, + Diagnostics, +} + +impl Page { + pub const ALL: [Self; 5] = [ + Self::Play, + Self::GameFiles, + Self::Build, + Self::Performance, + Self::Diagnostics, + ]; + + pub const fn title(self) -> &'static str { + match self { + Self::Play => "Play", + Self::GameFiles => "Game files", + Self::Build => "Build", + Self::Performance => "Performance", + Self::Diagnostics => "Diagnostics", + } + } + + fn index(self) -> usize { + Self::ALL.iter().position(|page| *page == self).unwrap_or(0) + } + + /// The page after this one, or before it, round the ends. + pub fn step(self, forwards: bool) -> Self { + let count = Self::ALL.len(); + let at = self.index(); + Self::ALL[if forwards { + (at + 1) % count + } else { + (at + count - 1) % count + }] + } +} + +/// One of the folders the settings name. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Folder { + Package, + Output, + Work, + /// Where the game's writes go (`gta6rt --overlay`). + Overlay, +} + +#[derive(Debug, Clone)] +pub enum Message { + Chrome(ChromeMessage), + /// A page chosen in the sidebar. + Show(Page), + /// Ctrl+Page Down and Ctrl+Page Up. + Step(bool), + Shade(Shade), + /// Ctrl+L. + ToggleShade, + Folder(Folder, String), + Pick(Folder), + Picked(Folder, Option), + Stage(&'static str, bool), + Wav(bool), + FullCheck(bool), + Gpu(String), + AutoWave64(bool), + Wave64(Wave64), + Jobs(String), + Validation(bool), + TraceD3d12(bool), + Unimplemented(Unimplemented), + Act(Action), + Process(process::Event), + /// The window's scale factor. + Scale(f32), + /// A wait for the scene's key ended: generate it if it held. + SceneTick(Instant), + /// A scene was generated for this key. + SceneReady(Key, Option), + /// A frame, while the scene fades in. + SceneFrame(Instant), +} + +/// A command under way. +#[derive(Debug, Clone)] +pub struct Running { + pub kind: Kind, + pub command: Command, + pub pid: Option, + pub tracker: Tracker, + pub cancelled: bool, +} + +/// What exists on disk, as last looked. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct OnDisk { + pub package: bool, + pub loader: bool, + pub exe: bool, +} + +/// The launcher's state. +pub struct Launcher { + pub repo: Result, + pub platform: Platform, + pub exe: String, + pub settings_path: Option, + pub settings: Settings, + /// Something to say about the settings file, once. + pub note: Option, + pub page: Page, + pub chrome: Chrome, + pub disk: OnDisk, + pub running: Option, + /// The last command that finished: how it ended, its command line and its output. + pub last: Option<(Outcome, Command, Tracker)>, + /// The Play page's scene, cached. + pub backdrop: Backdrop, + /// Generate scenes on the interface's thread, at once: for the tests, which run no tasks. + pub synchronous: bool, + /// Physical pixels to a logical one. + pub scale: f32, + /// The logo, decoded once: a handle made anew in every view would be a new image every frame, + /// uploaded again while anything animates. + logo: image::Handle, + /// The veil over the Play page's scene, one per palette by its name, made once + /// ([`crate::scene::veil`]). + veils: Vec<(&'static str, image::Handle)>, +} + +/// The Play page's text column: its padding either side of its content, and its content's width, +/// in logical pixels. Text sits on the page only inside it; the scene's fade keeps it readable. +pub const COLUMN_PAD: f32 = space::XXL; +pub const COLUMN_CONTENT: f32 = 420.0; + +impl Launcher { + /// The launcher for a repository, with its settings file (none: not saved). + pub fn new( + repo: Result, + settings_path: Option, + frame: FrameSetting, + ) -> Self { + let loaded = settings_path + .as_deref() + .map_or(config::Loaded::Missing, config::load); + let exe = repo + .as_deref() + .map_or_else(|_| repo::DEFAULT_EXE.to_owned(), repo::expected_exe); + let mut launcher = Self { + repo, + platform: Platform::current(), + exe, + settings_path, + settings: loaded.settings(), + note: loaded.note(), + page: Page::Play, + chrome: Chrome::new(SIZE, frame), + disk: OnDisk::default(), + running: None, + last: None, + backdrop: Backdrop::default(), + synchronous: false, + scale: 1.0, + logo: image::Handle::from_bytes(include_bytes!("../../assets/logo.png").as_slice()), + veils: Palette::ALL + .iter() + .map(|palette| { + let picture = crate::scene::veil(palette.veil()); + ( + palette.name, + image::Handle::from_rgba(picture.width, picture.height, picture.rgba), + ) + }) + .collect(), + }; + launcher.refresh(); + let wanted = launcher.scene_wanted(); + launcher.backdrop.want(wanted, Instant::now()); + launcher + } + + /// The Play page's size, in logical pixels: the window less its frame, header bar and, + /// unless it's folded, sidebar. + pub fn page_size(&self) -> Size { + let window = self.chrome.size(); + let inset = if self.chrome.corners() == Corners::Square { + 0.0 + } else { + decorations::BORDER + }; + let sidebar = if self.chrome.folded() { + 0.0 + } else { + decorations::SIDEBAR_WIDTH + decorations::BORDER + }; + Size::new( + (window.width - 2.0 * inset - sidebar).max(0.0), + (window.height - 2.0 * inset - decorations::BAR_HEIGHT).max(0.0), + ) + } + + /// The scene's pictures the page wants now, the current mode's first, then the other's, so + /// a switch never waits. + pub fn scene_wanted(&self) -> Vec<(Key, scene::Input)> { + let page = self.page_size(); + let current = self.chosen_theme(); + let other = Theme::new(match self.settings.shade { + Shade::Dark => Palette::SUNSET_LIGHT, + Shade::Light => Palette::SUNSET_DARK, + }); + [current, other] + .into_iter() + .map(|theme| { + let input = scene::Input { + colors: scene::Colors::of(theme.palette()), + width: (page.width * self.scale).round() as u32, + height: (page.height * self.scale).round() as u32, + scale: self.scale, + corner: (self.chrome.corners() == Corners::Drawn) + .then_some(decorations::CORNER_RADIUS - decorations::BORDER), + }; + (Key::of(&input, theme.name()), input) + }) + .collect() + } + + /// The launcher as `main` boots it, and its first task: the window found, and the scene's + /// first tick, at once, so the Play page's pictures are made as the window opens. + pub fn boot( + repo: Result, + settings_path: Option, + frame: FrameSetting, + ) -> (Self, Task) { + let mut launcher = Self::new(repo, settings_path, frame); + let scene = launcher.scene_next(Instant::now()); + ( + launcher, + Task::batch([Chrome::boot().map(Message::Chrome), scene]), + ) + } + + /// Handles a message, then notes the scene's pictures the page wants now and schedules the + /// tick that makes the next, if one is needed and none is due: none is ever left waiting. + pub fn update(&mut self, message: Message) -> Task { + let task = self.handle(message); + let scene = self.scene_next(Instant::now()); + Task::batch([task, scene]) + } + + fn scene_next(&mut self, now: Instant) -> Task { + self.backdrop.want(self.scene_wanted(), now); + match self.backdrop.schedule(now) { + Some(delay) => wait(delay), + None => Task::none(), + } + } + + /// Generates the picture that's due, if one is: off this thread, or at once when synchronous + /// (then every one that's due). + fn generate_scene(&mut self, now: Instant) -> Task { + let generator = self.backdrop.generator; + if self.synchronous { + while let Some((key, input)) = self.backdrop.due(now) { + self.backdrop.finished(key, generator(&input)); + if self.backdrop.schedule(now).is_none() { + break; + } + } + return Task::none(); + } + let Some((key, input)) = self.backdrop.due(now) else { + return Task::none(); + }; + let (sender, receiver) = iced::futures::channel::oneshot::channel(); + std::thread::spawn(move || { + let _ = sender.send(generator(&input)); + }); + Task::perform(receiver, move |picture| { + Message::SceneReady(key, picture.ok().flatten()) + }) + } + + /// Looks again at what exists: the package, the built loader, the game's executable. + pub fn refresh(&mut self) { + let package = self.settings.package.trim(); + let output = self.settings.output.trim(); + let is_dir = |path: &str| !path.is_empty() && Path::new(path).is_dir(); + let is_file = |path: PathBuf| path.is_file(); + self.disk = OnDisk { + package: is_dir(package), + loader: !output.is_empty() && is_file(Path::new(output).join(self.platform.loader())), + exe: !package.is_empty() && is_file(Path::new(package).join(&self.exe)), + }; + } + + /// What the state machine reads. + pub fn facts(&self) -> Facts { + let package = self.settings.package.trim().to_owned(); + Facts { + checked: self + .settings + .checked + .as_ref() + .is_some_and(|checked| checked.package == package), + package, + package_exists: self.disk.package, + output: self.settings.output.trim().to_owned(), + loader_exists: self.disk.loader, + loader: self.platform.loader().to_owned(), + exe_exists: self.disk.exe, + exe: self.exe.clone(), + running: self.running.as_ref().map(|running| running.kind), + last: self.last.as_ref().map(|(outcome, ..)| outcome.clone()), + } + } + + /// The theme the window draws in now: the chosen one, or while it fades in, on the way. + pub fn theme(&self) -> Theme { + self.chrome.theme(self.chosen_theme()) + } + + /// The theme the settings choose. + pub fn chosen_theme(&self) -> Theme { + Theme::new(match self.settings.shade { + Shade::Dark => Palette::SUNSET_DARK, + Shade::Light => Palette::SUNSET_LIGHT, + }) + } + + /// Light or dark, fading from what shows into it. + fn set_shade(&mut self, shade: Shade) { + if shade == self.settings.shade { + return; + } + let before = self.chosen_theme(); + self.settings.shade = shade; + self.chrome.theme_changed(before, Instant::now()); + self.save(); + } + + fn save(&mut self) { + if let Some(path) = &self.settings_path + && let Err(error) = config::save(path, &self.settings) + { + self.note = Some(format!("Settings couldn't be saved: {error}")); + } + } + + /// The command for an action, or why there's none. + fn command(&self, kind: Kind) -> Result { + let repo = self.repo.as_ref().map_err(Clone::clone)?; + let repo = repo.display().to_string(); + let made = match kind { + Kind::Check => commands::check(self.platform, &repo, &self.settings), + Kind::Build => commands::build(self.platform, &repo, &self.settings), + Kind::Play => commands::play(self.platform, &self.exe, &self.settings), + }; + made.map_err(|missing| match missing { + Missing::Package => "Choose the game package folder on the Game files page.".to_owned(), + Missing::Output => "Choose an output folder on the Game files page.".to_owned(), + }) + } + + fn handle(&mut self, message: Message) -> Task { + match message { + Message::Chrome(message) => { + // Once the window's known, its scale factor too. + let scale = match &message { + ChromeMessage::Opened(id) | ChromeMessage::Resized(id, _) => { + iced::window::scale_factor(*id).map(Message::Scale) + } + _ => Task::none(), + }; + return Task::batch([self.chrome.update(message).map(Message::Chrome), scale]); + } + Message::Scale(scale) => { + if scale > 0.0 { + self.scale = scale; + } + } + Message::SceneTick(now) => return self.generate_scene(now), + // The next picture, if one is wanted, is scheduled after every message (`update`). + Message::SceneReady(key, picture) => self.backdrop.finished(key, picture), + Message::SceneFrame(at) => self.backdrop.frame(at), + Message::Show(page) => { + self.page = page; + self.chrome.show_page(); + } + Message::Step(forwards) => { + self.page = self.page.step(forwards); + self.chrome.show_page(); + } + Message::Shade(shade) => self.set_shade(shade), + Message::ToggleShade => self.set_shade(match self.settings.shade { + Shade::Dark => Shade::Light, + Shade::Light => Shade::Dark, + }), + Message::Folder(folder, value) => { + *self.folder_mut(folder) = value; + self.refresh(); + self.save(); + } + Message::Pick(folder) => { + let start = self.folder(folder).trim().to_owned(); + let title = match folder { + Folder::Package => "Choose your game package folder", + Folder::Output => "Choose the output folder", + Folder::Work => "Choose the work folder", + Folder::Overlay => "Choose the folder for the game's writes", + }; + let mut dialog = rfd::AsyncFileDialog::new().set_title(title); + if !start.is_empty() && Path::new(&start).is_dir() { + dialog = dialog.set_directory(&start); + } + return Task::perform(dialog.pick_folder(), move |picked| { + Message::Picked(folder, picked.map(|handle| handle.path().to_path_buf())) + }); + } + Message::Picked(folder, Some(path)) => { + *self.folder_mut(folder) = path.display().to_string(); + self.refresh(); + self.save(); + } + Message::Picked(_, None) => {} + Message::Stage(stage, on) => { + self.settings.stages.retain(|chosen| chosen != stage); + if on { + self.settings.stages.push(stage.to_owned()); + } + self.save(); + } + Message::Wav(on) => { + self.settings.wav = on; + self.save(); + } + Message::FullCheck(on) => { + self.settings.full_check = on; + self.save(); + } + Message::Gpu(value) => { + self.settings.gpu = value; + self.save(); + } + Message::AutoWave64(auto) => { + self.settings.wave64 = if auto { Wave64::Auto } else { Wave64::On }; + self.save(); + } + Message::Wave64(mode) => { + self.settings.wave64 = mode; + self.save(); + } + Message::Jobs(value) => { + self.settings.jobs = value.chars().filter(char::is_ascii_digit).take(4).collect(); + self.save(); + } + Message::TraceD3d12(on) => { + self.settings.trace_d3d12 = on; + self.save(); + } + Message::Unimplemented(policy) => { + self.settings.unimplemented = policy; + self.save(); + } + Message::Validation(on) => { + self.settings.validation = on; + self.save(); + } + Message::Act(Action::Cancel) => { + if let Some(running) = &mut self.running { + running.cancelled = true; + if let Some(pid) = running.pid { + process::cancel(pid); + } + } + } + Message::Act(Action::Run(kind)) => return self.start(kind), + Message::Process(event) => self.follow(event), + } + Task::none() + } + + fn folder(&self, folder: Folder) -> &str { + match folder { + Folder::Package => &self.settings.package, + Folder::Output => &self.settings.output, + Folder::Work => &self.settings.work, + Folder::Overlay => &self.settings.overlay, + } + } + + fn folder_mut(&mut self, folder: Folder) -> &mut String { + match folder { + Folder::Package => &mut self.settings.package, + Folder::Output => &mut self.settings.output, + Folder::Work => &mut self.settings.work, + Folder::Overlay => &mut self.settings.overlay, + } + } + + /// Starts a command, unless one runs. + fn start(&mut self, kind: Kind) -> Task { + if self.running.is_some() { + return Task::none(); + } + self.refresh(); + let command = match self.command(kind) { + Ok(command) => command, + Err(why) => { + self.last = Some(( + Outcome { + kind, + code: None, + cancelled: false, + words: Some(why), + }, + Command { + program: String::new(), + args: Vec::new(), + env: Vec::new(), + cwd: String::new(), + }, + Tracker::plain(), + )); + return Task::none(); + } + }; + let tracker = match kind { + Kind::Build => Tracker::build(commands::stages(&self.settings).as_deref()), + Kind::Check | Kind::Play => Tracker::plain(), + }; + let stream = process::run(&command); + self.running = Some(Running { + kind, + command, + pid: None, + tracker, + cancelled: false, + }); + Task::run(stream, Message::Process) + } + + /// What a running command said. + pub fn follow(&mut self, event: process::Event) { + let Some(running) = &mut self.running else { + return; + }; + let ended = match event { + process::Event::Started(pid) => { + running.pid = Some(pid); + // Cancel pressed before the process said it had started had nothing to stop yet: + // stop it now that there is. + if running.cancelled { + process::cancel(pid); + } + None + } + process::Event::Line(line) => { + running.tracker.feed(&line); + None + } + process::Event::Exited(code) => Some((code, None)), + process::Event::Failed(why) => Some((None, Some(why))), + }; + let Some((code, why)) = ended else { + return; + }; + let Some(running) = self.running.take() else { + return; + }; + let succeeded = code == Some(0) && !running.cancelled; + let outcome = Outcome { + kind: running.kind, + code, + cancelled: running.cancelled, + words: why.or_else(|| (!succeeded).then(|| running.tracker.last_words()).flatten()), + }; + if running.kind == Kind::Check { + let package = self.settings.package.trim().to_owned(); + if succeeded { + let game = running + .tracker + .game + .clone() + .unwrap_or_else(|| "a supported version".to_owned()); + self.settings.checked = Some(Checked { package, game }); + } else if !running.cancelled { + self.settings.checked = None; + } + self.save(); + } + self.last = Some((outcome, running.command, running.tracker)); + self.refresh(); + } + + pub fn subscription(&self) -> Subscription { + let keys = keyboard::listen().filter_map(|event| match event { + keyboard::Event::KeyPressed { key, modifiers, .. } + if modifiers.control() && !modifiers.alt() => + { + match key.as_ref() { + keyboard::Key::Named(Named::PageDown) => Some(Message::Step(true)), + keyboard::Key::Named(Named::PageUp) => Some(Message::Step(false)), + keyboard::Key::Character("l" | "L") => Some(Message::ToggleShade), + _ => None, + } + } + _ => None, + }); + let fading = if self.chrome.is_fading() { + iced::window::frames().map(|at| Message::Chrome(ChromeMessage::Frame(at))) + } else { + Subscription::none() + }; + // Frames while the scene fades in, and none once it's whole. + let scene = if self.backdrop.is_fading() { + iced::window::frames().map(Message::SceneFrame) + } else { + Subscription::none() + }; + Subscription::batch([ + keys, + Chrome::subscription().map(Message::Chrome), + fading, + scene, + ]) + } + + /// The window: header bar, sidebar and the page. + pub fn view(&self) -> Element<'_, Message> { + let shade = usize::from(self.settings.shade == Shade::Light); + let pill = toggle_group(["Dark", "Light"], shade) + .pill(true) + .on_choose(|at| Message::Shade(if at == 1 { Shade::Light } else { Shade::Dark })); + let bar = header().start(text::brand("Leonida")).end(pill); + let sidebar = navigation( + Page::ALL.iter().map(|page| page.title()), + Some(self.page.index()), + ) + .on_choose(|at| Message::Show(Page::ALL[at])); + let page = match self.page { + Page::Play => self.play_page(), + Page::GameFiles => self.game_files_page(), + Page::Build => self.build_page(), + Page::Diagnostics => self.diagnostics_page(), + Page::Performance => self.performance_page(), + }; + let scrolled: Element<'_, Message> = + scroll_area(container(page).padding(COLUMN_PAD).width(Fill)).into(); + // The Play page's scene, under it: cached pictures, never made here. The one it replaces + // under the one fading in; while a resize is under way, the last one, scaled to cover and + // kept to the bottom right. + let content = if self.page == Page::Play { + let page = self.page_size(); + let layer = |shown: &backdrop::Shown, opacity: f32| -> Option> { + let handle = shown.handle.clone()?; + let size = backdrop::cover(shown.size, page); + let picture = image(handle) + .width(size.width) + .height(size.height) + .content_fit(iced::ContentFit::Fill) + .opacity(opacity); + Some( + container(picture) + .width(Fill) + .height(Fill) + .align_x(iced::alignment::Horizontal::Right) + .align_y(iced::alignment::Vertical::Bottom) + .clip(true) + .into(), + ) + }; + let (previous, shown) = self.backdrop.layers(); + let mut layers: Vec> = Vec::new(); + layers.extend(previous.and_then(|previous| layer(previous, 1.0))); + layers.extend(shown.and_then(|(shown, at)| layer(shown, at))); + // The veil over the scene, stretched to the page, so it follows a resize at once; + // while the mode changes, the old one fading out as the new one fades in. Both are + // see-through, so the old one must go as the new one comes: left whole under it, it + // would show through to the end and then vanish at once. + if !layers.is_empty() { + let veil = |palette: &Palette, opacity: f32| -> Option> { + let (_, handle) = self.veils.iter().find(|(name, _)| *name == palette.name)?; + Some( + image(handle.clone()) + .width(Fill) + .height(Fill) + .content_fit(iced::ContentFit::Fill) + .filter_method(image::FilterMethod::Linear) + .opacity(opacity) + .into(), + ) + }; + let chosen = self.chosen_theme(); + match self.chrome.theme_fade() { + Some((from, share)) => { + layers.extend(veil(from.palette(), 1.0 - share)); + layers.extend(veil(chosen.palette(), share)); + } + None => layers.extend(veil(chosen.palette(), 1.0)), + } + } + layers.push(scrolled); + iced::widget::Stack::with_children(layers).into() + } else { + scrolled + }; + // One focus scope round the whole window, as every window has it: Tab goes through the + // header bar, the sidebar and the page. + crate::ui::focus::scope(self.chrome.view( + bar, + Some(sidebar.into()), + content, + Message::Chrome, + )) + .into() + } + + fn page_title<'a>(&self, words: &'a str) -> Element<'a, Message> { + text::heading(words).into() + } + + fn play_page(&self) -> Element<'_, Message> { + let facts = self.facts(); + let running = self.running.as_ref(); + let tracker = running + .map(|running| &running.tracker) + .or(self.last.as_ref().map(|(_, _, tracker)| tracker)); + let under_way = running.and_then(|running| running.tracker.stage()); + let line = state::status(&facts, under_way.as_deref()); + let game = self + .settings + .checked + .as_ref() + .filter(|checked| checked.package == self.settings.package.trim()) + .map_or_else( + || "not checked yet".to_owned(), + |checked| checked.game.clone(), + ); + let logo = image(self.logo.clone()).width(96).height(96); + let identity = across![ + logo, + column![ + text::title("Leonida"), + text::meta(format!("Launcher {VERSION}")), + text::meta(format!("Game copy: {game}")), + ] + .spacing(space::XS), + ] + .spacing(space::XL) + .align_y(Center); + + let tone = match line.tone { + Tone::Waiting => Status::Waiting, + Tone::Running => Status::Running, + Tone::Passed => Status::Passed, + Tone::Info => Status::Info, + Tone::Failed => Status::Failed, + }; + let status_line = across![ + status(tone, line.word), + text::interface(line.text).class(match line.tone { + Tone::Failed => Ink::Text, + _ => Ink::Body, + }), + ] + .spacing(space::L) + .align_y(Center); + + let primary = state::primary(&facts); + let mut actions = Row::new().spacing(space::L).align_y(Center); + let main = button(primary.action.label()) + .large() + .emphasis(match primary.action { + Action::Cancel => Emphasis::Danger, + Action::Run(_) => Emphasis::Primary, + }) + .on_press_maybe(primary.enabled().then_some(Message::Act(primary.action))); + actions = actions.push(main); + // The others beside it, large as the main button is, so the row lines up. + for (action, enabled) in state::secondary(&facts) { + actions = actions.push( + button(action.label()) + .large() + .on_press_maybe(enabled.then_some(Message::Act(action))), + ); + } + if running.is_some() { + actions = actions.push(loader().size(size::LOADER_SMALL)); + } + + // The text column: text sits on the page only here, where the scene's fade keeps it + // readable. + let mut column_content = Column::new() + .spacing(space::XL) + .width(Fill) + .push(identity) + .push(status_line) + .push(actions); + if let Some(note) = &self.note { + column_content = column_content.push(text::meta(note.clone())); + } + if let Err(why) = &self.repo { + column_content = column_content + .push(text::interface(why.clone()).class(Ink::Accent(crate::ui::Accent::Red))); + } + let text_column = container(column_content).max_width(COLUMN_CONTENT); + // Everything else lies on an opaque surface. + let bar: Option> = match (running, &self.last) { + (Some(running), _) => Some(match running.tracker.progress() { + Some(done) if running.kind == Kind::Build => progress(done).into(), + _ => crate::ui::progress::busy().into(), + }), + (None, Some((outcome, _, tracker))) + if !outcome.succeeded() && outcome.kind == Kind::Build => + { + Some(progress(tracker.progress().unwrap_or(1.0)).failed().into()) + } + (None, Some((outcome, _, _))) if outcome.succeeded() && outcome.kind == Kind::Build => { + Some(progress(1.0).done().into()) + } + _ => None, + }; + let command = running + .map(|running| &running.command) + .or(self.last.as_ref().map(|(_, command, _)| command)) + .filter(|command| !command.program.is_empty()); + let bar_or_output = bar.is_some() || tracker.is_some(); + let mut surface = Column::new().spacing(space::M).width(Fill); + if let Some(bar) = bar { + surface = surface.push(bar); + } + if let Some(tracker) = tracker { + let lines = tracker.lines.iter().rev().take(SHOWN_LINES).rev(); + let log = Column::with_children( + lines.map(|line| text::meta(line.clone()).class(Ink::Body).into()), + ) + .spacing(space::XXS) + .width(Fill); + surface = surface.push(text::label("Output")); + if let Some(command) = command { + surface = surface.push(text::meta(command.display())); + } + surface = surface.push( + container(scroll_area(container(log).padding(space::L).width(Fill))) + .height(220) + .width(Fill) + .class(Frame::Card(Surface::Sunk)), + ); + } + let mut page = Column::new().spacing(space::XL).push(text_column); + if bar_or_output { + page = page.push( + container(surface) + .padding(space::L) + .width(Fill) + .class(Frame::Card(Surface::Panel)), + ); + } + page.max_width(760).into() + } + + fn folder_field(&self, folder: Folder) -> Element<'_, Message> { + let (name, help, placeholder) = match folder { + Folder::Package => ( + "Game package", + "Your own copy: the folder that holds MicrosoftGame.Config and the .rpf archives.", + "The package folder", + ), + Folder::Output => ( + "Output folder", + "Where the build puts the port and the loader (make_game.py --out).", + "Documents/Leonida", + ), + Folder::Work => ( + "Work folder", + "Hundreds of GB of intermediate files (--work); empty puts them in the output \ + folder's work.", + "/work", + ), + Folder::Overlay => ( + "Writes folder", + "Where the game's writes go instead of the package (gta6rt --overlay); empty is \ + the package's overlay folder. Needed for a read-only package.", + "/overlay", + ), + }; + let missing = folder == Folder::Package + && !self.settings.package.trim().is_empty() + && !self.disk.package; + let field = text_field(placeholder, self.folder(folder)) + .on_input(move |value| Message::Folder(folder, value)) + .invalid(missing); + let control = across![field, button("Browse…").on_press(Message::Pick(folder))] + .spacing(space::M) + .align_y(Center); + let error = missing.then(|| "There's no folder there.".to_owned()); + form::field(name, control).help(help).error(error).into() + } + + fn game_files_page(&self) -> Element<'_, Message> { + let folders = group("Folders") + .description("The folders the build uses. Nothing is copied into the repository.") + .item( + form::form([ + self.folder_field(Folder::Package), + self.folder_field(Folder::Output), + self.folder_field(Folder::Work), + ]) + .padding([space::L, space::XL]), + ); + let check = group("Checking your copy").row( + row("Compare every file's SHA-256") + .description("Slow: reads the whole package (make_game.py --full-check).") + .control(switch(self.settings.full_check).on_toggle(Message::FullCheck)), + ); + column![self.page_title("Game files"), folders, check] + .spacing(space::XL) + .max_width(760) + .into() + } + + fn build_page(&self) -> Element<'_, Message> { + let stage_words = |stage: &'static str| match stage { + "shaders" => ( + "Shaders", + "Carve, disassemble and translate them to SPIR-V: the longest step.", + ), + "assets" => ( + "Assets", + "Export the models, textures and audio: hundreds of GB.", + ), + "runtime" => ("Runtime", "Build the loader, gta6rt."), + "pipelines" => ( + "Pipelines", + "Create every translated shader on this GPU's driver and save its cache.", + ), + _ => (stage, ""), + }; + let mut stages = group("Stages").description( + "What Build runs after checking your copy (make_game.py --stages). A stopped build \ + continues where it left off.", + ); + for stage in STAGES { + let on = self.settings.stages.iter().any(|chosen| chosen == stage); + let (title, words) = stage_words(stage); + stages = stages.row( + row(title) + .description(words) + .control(switch(on).on_toggle(move |on| Message::Stage(stage, on))), + ); + } + let audio = group("Audio").row( + row("Also decode audio to WAV") + .description( + "16-bit PCM WAV beside the Ogg Opus files: several times larger (--wav).", + ) + .control(switch(self.settings.wav).on_toggle(Message::Wav)), + ); + column![self.page_title("Build"), stages, audio] + .spacing(space::XL) + .max_width(760) + .into() + } + + fn diagnostics_page(&self) -> Element<'_, Message> { + let loader = group("The loader") + .description("For finding what stops the game: docs/boot.md has the triage.") + .row( + row("Trace D3D12 calls") + .description( + "Every D3D12 call and its outcome in the output (gta6rt --trace-d3d12).", + ) + .control(switch(self.settings.trace_d3d12).on_toggle(Message::TraceD3d12)), + ) + .item( + container( + form::field( + "Unimplemented imports", + choice(Some(self.settings.unimplemented)) + .option( + Unimplemented::Log, + "Log", + "Log each once and return 0: the loader's default.", + ) + .option( + Unimplemented::Fail, + "Fail", + "Return E_NOTIMPL, to see how the game's own failure path reacts.", + ) + .option( + Unimplemented::Stop, + "Stop", + "End at the first, with its caller (exit code 3).", + ) + .on_choose(Message::Unimplemented), + ) + .help("LEONIDA_UNIMPLEMENTED"), + ) + .padding([space::L, space::XL]), + ) + .item(container(self.folder_field(Folder::Overlay)).padding([space::L, space::XL])); + column![self.page_title("Diagnostics"), loader] + .spacing(space::XL) + .max_width(760) + .into() + } + + fn performance_page(&self) -> Element<'_, Message> { + let gpu = group("Graphics") + .row( + row("GPU") + .description( + "Part of the GPU's name, such as 5070 or radeon: the loader and the \ + build's GPU checks use the first that matches (LEONIDA_VK_DEVICE). \ + Empty lets the runtime choose.", + ) + .control( + text_field("Any", &self.settings.gpu) + .on_input(Message::Gpu) + .width(180), + ), + ) + .row( + row("Vulkan validation") + .description( + "The Khronos validation layer at play, a diagnostic: slower to start and \ + to run (LEONIDA_VK_VALIDATION=1).", + ) + .control(switch(self.settings.validation).on_toggle(Message::Validation)), + ); + let auto = self.settings.wave64 == Wave64::Auto; + let mode = if auto { + None + } else { + Some(self.settings.wave64) + }; + let mut wave = choice(mode) + .option( + Wave64::On, + "Emulate", + "Exact on any GPU; needed where subgroups are 32 wide (NVIDIA, Intel).", + ) + .option( + Wave64::Off, + "Native", + "64-wide subgroups as the console runs them (AMD).", + ); + if !auto { + wave = wave.on_choose(Message::Wave64); + } + let build = group("Build") + .row( + row("Choose wave64 translation automatically") + .description( + "Asks the GPU whether it runs 64-wide subgroups (--wave64-emulate auto). \ + Changing it translates the shaders again.", + ) + .control(switch(auto).on_toggle(Message::AutoWave64)), + ) + .item(container(wave).padding([space::L, space::XL])) + .row( + row("Jobs") + .description( + "Processes the shader translation runs on (--jobs). Empty is half the \ + CPU threads.", + ) + .control( + text_field("Auto", &self.settings.jobs) + .on_input(Message::Jobs) + .max_len(4) + .width(96), + ), + ); + column![ + self.page_title("Performance"), + gpu, + build, + gap().height(space::XL) + ] + .spacing(space::XL) + .max_width(760) + .into() + } + + /// The window's background: clear where the launcher rounds its own corners. + pub fn style(&self, theme: &Theme) -> iced::theme::Style { + self.chrome.style(theme) + } + + /// For the window's events: the scale-free size the page is drawn at, in a test. + pub fn resize(&mut self, size: Size) { + self.chrome.resize(size); + } + + /// The mode, for the screenshots' names. + pub fn mode(&self) -> Mode { + match self.settings.shade { + Shade::Dark => Mode::Dark, + Shade::Light => Mode::Light, + } + } +} + +/// The end of a scene key's wait, `delay` from now, from a thread that sleeps: no timer runs once +/// it has fired. +fn wait(delay: Duration) -> Task { + let (sender, receiver) = iced::futures::channel::oneshot::channel(); + std::thread::spawn(move || { + std::thread::sleep(delay); + let _ = sender.send(Instant::now()); + }); + Task::perform(receiver, |at| { + Message::SceneTick(at.unwrap_or_else(|_| Instant::now())) + }) +} diff --git a/launcher/src/backdrop.rs b/launcher/src/backdrop.rs new file mode 100644 index 0000000000..f95a1717c5 --- /dev/null +++ b/launcher/src/backdrop.rs @@ -0,0 +1,381 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! The Play page's scene, generated once per key and cached: never in `view`, never per frame. +//! +//! A key is a page (its size in physical pixels, the scale, the text column, the window's corner) +//! and a theme with its mode. For the page in use, both modes' pictures are made, the current +//! mode's first, each off the interface's thread, so switching the mode never waits. At start, +//! with nothing shown yet, they're made at once; after a resize, only once the size has held for +//! [`DEBOUNCE`], while the last picture shows, scaled to cover. +//! +//! A picture fades in when it's ready ([`motion::SCENE_IN`]), crossfades with the one it +//! replaces, and then nothing moves. Whenever a wanted picture isn't made, isn't being made and +//! no tick is due, [`Backdrop::schedule`] says when to tick, so none is ever stranded. + +use std::time::{Duration, Instant}; + +use iced::widget::image; + +use crate::scene::{self, Input, Picture}; +use crate::ui::tokens::motion; +use crate::ui::transition::Transition; + +/// How long a resized page's size must hold before its pictures are made. +pub const DEBOUNCE: Duration = Duration::from_millis(150); + +/// A page, as its pictures depend on it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Page { + pub width: u32, + pub height: u32, + scale: u32, + corner: Option, +} + +/// What a picture depends on: its page and its theme. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Key { + pub page: Page, + /// The palette's name, which says its theme and mode. + pub theme: &'static str, +} + +impl Key { + pub fn of(input: &Input, theme: &'static str) -> Self { + Self { + page: Page { + width: input.width, + height: input.height, + scale: input.scale.to_bits(), + corner: input.corner.map(f32::to_bits), + }, + theme, + } + } +} + +/// The generator: [`scene::generate`], or a stand-in in the tests. +pub type Generator = fn(&Input) -> Option; + +/// A generated picture, ready to show, or none where it couldn't be made. +#[derive(Debug, Clone)] +pub struct Shown { + pub handle: Option, + /// Its size, in logical pixels. + pub size: iced::Size, +} + +/// The pictures made, the ones wanted, and the one showing. +pub struct Backdrop { + made: Vec<(Key, Shown)>, + /// The pictures wanted, the current mode's first, and since when their page has held. + wanted: Vec<(Key, Input)>, + since: Option, + in_flight: Option, + tick_pending: bool, + /// The picture showing, the one it replaces while they crossfade, and how far the fade is. + shown: Option, + previous: Option, + fade: Option, + fade_at: f32, + /// How many pictures have been generated: what the tests count. + pub generations: usize, + pub generator: Generator, +} + +impl Default for Backdrop { + fn default() -> Self { + Self { + made: Vec::new(), + wanted: Vec::new(), + since: None, + in_flight: None, + tick_pending: false, + shown: None, + previous: None, + fade: None, + fade_at: 1.0, + generations: 0, + generator: scene::generate, + } + } +} + +impl Backdrop { + /// The pictures the page wants now, the current mode's first, noted at `now`. A new page + /// starts its wait; a current picture that's made and isn't showing crossfades in. + pub fn want(&mut self, wanted: Vec<(Key, Input)>, now: Instant) { + let page = |list: &[(Key, Input)]| list.first().map(|(key, _)| key.page); + if page(&wanted) != page(&self.wanted) { + // A resize, with a picture showing, waits for the size to hold; at start, nothing does. + self.since = self.shown.map(|_| now); + } + self.wanted = wanted; + if let Some(current) = self.current() + && self.is_made(¤t) + && self.shown != Some(current) + { + let duration = if self.shown.is_some() { + motion::SLOW + } else { + motion::SCENE_IN + }; + self.show(current, duration); + } + } + + /// The key the page should show: the current mode's for the page in use. + fn current(&self) -> Option { + self.wanted.first().map(|(key, _)| *key) + } + + fn is_made(&self, key: &Key) -> bool { + self.made.iter().any(|(made, _)| made == key) + } + + /// Whether a wanted picture isn't made yet. + fn missing(&self) -> bool { + self.wanted.iter().any(|(key, _)| !self.is_made(key)) + } + + /// If a wanted picture isn't made, isn't being made and no tick is due, how long from `now` + /// a tick should come: at once while nothing shows (at start), else when the page's size has + /// held for [`DEBOUNCE`]. The caller schedules it; until it comes, no other is asked for. + pub fn schedule(&mut self, now: Instant) -> Option { + if !self.missing() || self.in_flight.is_some() || self.tick_pending { + return None; + } + self.tick_pending = true; + Some(self.wait_left(now)) + } + + /// What's left of the page's wait: none while nothing shows. + fn wait_left(&self, now: Instant) -> Duration { + match (self.shown, self.since) { + (Some(_), Some(since)) => DEBOUNCE.saturating_sub(now.saturating_duration_since(since)), + _ => Duration::ZERO, + } + } + + /// A tick at `now`: the picture to generate, if one is wanted, its wait is over and nothing + /// is being made. Counted as a generation. + pub fn due(&mut self, now: Instant) -> Option<(Key, Input)> { + self.tick_pending = false; + if self.in_flight.is_some() || !self.wait_left(now).is_zero() { + return None; + } + let (key, input) = *self.wanted.iter().find(|(key, _)| !self.is_made(key))?; + self.in_flight = Some(key); + self.generations += 1; + Some((key, input)) + } + + /// A picture was generated for `key`. Pictures of another page go, but for what's showing; + /// the current one fades in, or crossfades with what showed. + pub fn finished(&mut self, key: Key, picture: Option) { + if self.in_flight == Some(key) { + self.in_flight = None; + } + let scale = f32::from_bits(key.page.scale); + let shown = match picture { + Some(picture) => Shown { + size: iced::Size::new(picture.width as f32 / scale, picture.height as f32 / scale), + handle: Some(image::Handle::from_rgba( + picture.width, + picture.height, + picture.rgba, + )), + }, + None => Shown { + handle: None, + size: iced::Size::ZERO, + }, + }; + let page = self.current().map(|current| current.page); + let keep = [self.shown, self.previous]; + self.made.retain(|(made, _)| { + *made != key && (Some(made.page) == page || keep.contains(&Some(*made))) + }); + self.made.push((key, shown)); + if Some(key) == self.current() && self.shown != Some(key) { + let duration = if self.shown.is_some() { + motion::NORMAL + } else { + motion::SCENE_IN + }; + self.show(key, duration); + } + } + + /// `key` comes in over `duration`, from nothing or over what showed. + fn show(&mut self, key: Key, duration: Duration) { + self.previous = self.shown.take(); + self.shown = Some(key); + self.fade = Transition::start(0.0, 1.0, duration); + self.fade_at = if self.fade.is_some() { 0.0 } else { 1.0 }; + if self.fade.is_none() { + self.previous = None; + } + } + + /// A frame at `now`, while a picture fades in: once it's whole, what it replaced goes. + pub fn frame(&mut self, now: Instant) { + if let Some(fade) = &mut self.fade { + let going = fade.frame(now); + self.fade_at = fade.at(); + if !going { + self.fade = None; + self.fade_at = 1.0; + self.previous = None; + } + } + } + + /// Whether a picture is fading in: it wants every frame until it's whole, and none after. + pub fn is_fading(&self) -> bool { + self.fade.is_some() + } + + fn get(&self, key: Option) -> Option<&Shown> { + let key = key?; + self.made + .iter() + .find(|(made, _)| *made == key) + .map(|(_, shown)| shown) + } + + /// What to draw: the picture it replaces, whole, and the picture showing, at how far it has + /// faded in. + pub fn layers(&self) -> (Option<&Shown>, Option<(&Shown, f32)>) { + ( + self.get(self.previous), + self.get(self.shown).map(|shown| (shown, self.fade_at)), + ) + } +} + +/// The size that covers `page` with a picture of `picture`'s, keeping its shape. +pub fn cover(picture: iced::Size, page: iced::Size) -> iced::Size { + if picture.width <= 0.0 || picture.height <= 0.0 { + return page; + } + let k = (page.width / picture.width).max(page.height / picture.height); + iced::Size::new(picture.width * k, picture.height * k) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::scene::Colors; + use crate::ui::tokens::Palette; + + fn wanted(width: u32, dark_first: bool) -> Vec<(Key, Input)> { + let input = |palette: &Palette| Input { + colors: Colors::of(palette), + width, + height: 600, + scale: 1.0, + corner: None, + }; + let dark = input(&Palette::SUNSET_DARK); + let light = input(&Palette::SUNSET_LIGHT); + let pair = [ + (Key::of(&dark, "sunset-dark"), dark), + (Key::of(&light, "sunset-light"), light), + ]; + if dark_first { + pair.to_vec() + } else { + vec![pair[1], pair[0]] + } + } + + fn tiny(input: &Input) -> Option { + Some(Picture { + width: input.width, + height: input.height, + rgba: vec![0; 4], + }) + } + + /// Ticks and makes pictures as the window would, at `now`, until nothing more is due. + fn make_all(backdrop: &mut Backdrop, now: Instant) { + while backdrop.schedule(now).is_some_and(|wait| wait.is_zero()) { + if let Some((key, input)) = backdrop.due(now) { + backdrop.finished(key, tiny(&input)); + } + } + } + + #[test] + fn at_start_both_modes_are_made_at_once_and_the_current_fades_in() { + let mut backdrop = Backdrop::default(); + let start = Instant::now(); + backdrop.want(wanted(900, true), start); + assert_eq!( + backdrop.schedule(start), + Some(Duration::ZERO), + "no wait at start" + ); + assert_eq!(backdrop.schedule(start), None, "one tick at a time"); + let (key, input) = backdrop.due(start).unwrap(); + assert_eq!(key.theme, "sunset-dark", "the current mode first"); + assert!( + !backdrop.is_fading(), + "nothing fades before a picture is ready" + ); + backdrop.finished(key, tiny(&input)); + assert!(backdrop.is_fading()); + assert_eq!(backdrop.layers().1.unwrap().1, 0.0); + make_all(&mut backdrop, start); + assert_eq!(backdrop.generations, 2); + // The fade ends, and then nothing moves. + backdrop.frame(start); + backdrop.frame(start + motion::SCENE_IN); + assert!(!backdrop.is_fading()); + assert_eq!(backdrop.layers().1.unwrap().1, 1.0); + assert_eq!(backdrop.schedule(start + motion::SCENE_IN), None); + } + + #[test] + fn a_mode_switch_crossfades_without_making_anything() { + let mut backdrop = Backdrop::default(); + let start = Instant::now(); + backdrop.want(wanted(900, true), start); + make_all(&mut backdrop, start); + backdrop.frame(start + motion::SLOW * 4); + backdrop.want(wanted(900, false), start); + assert!(backdrop.is_fading()); + assert_eq!(backdrop.schedule(start), None); + assert_eq!(backdrop.generations, 2); + } + + #[test] + fn a_resize_waits_shows_the_last_picture_then_makes_both() { + let mut backdrop = Backdrop::default(); + let start = Instant::now(); + backdrop.want(wanted(900, true), start); + make_all(&mut backdrop, start); + backdrop.want(wanted(1000, true), start); + let wait = backdrop.schedule(start).unwrap(); + assert_eq!(wait, DEBOUNCE, "a resize waits"); + assert_eq!(backdrop.due(start), None, "too soon"); + assert_eq!( + backdrop.layers().1.unwrap().0.size.width, + 900.0, + "the last picture" + ); + let later = start + DEBOUNCE; + assert!(backdrop.schedule(later).is_some()); + let (key, input) = backdrop.due(later).unwrap(); + backdrop.finished(key, tiny(&input)); + make_all(&mut backdrop, later); + assert_eq!(backdrop.generations, 4); + assert_eq!(backdrop.layers().1.unwrap().0.size.width, 1000.0); + let covering = cover( + iced::Size::new(900.0, 600.0), + iced::Size::new(1000.0, 600.0), + ); + assert!((covering.width - 1000.0).abs() < 0.01 && covering.height >= 600.0); + } +} diff --git a/launcher/src/commands.rs b/launcher/src/commands.rs new file mode 100644 index 0000000000..7cc339be3b --- /dev/null +++ b/launcher/src/commands.rs @@ -0,0 +1,533 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! The command lines the launcher runs: `make_game.py`'s check and build, and the loader, as +//! `README.md` ("How to build", "Running the loader on Linux") and `docs/boot.md` (section 2) +//! give them. Each is built for a [`Platform`], so the tests check Windows' and Linux's alike. + +use crate::config::{STAGES, Settings, Unimplemented, Wave64}; + +/// Which system the commands are for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Platform { + Windows, + Linux, +} + +impl Platform { + /// The one the launcher is built for. + pub const fn current() -> Self { + if cfg!(windows) { + Self::Windows + } else { + Self::Linux + } + } + + /// The Python the repository runs its tools with: `python` on Windows (as the README's + /// examples), `python3` elsewhere. + pub const fn python(self) -> &'static str { + match self { + Self::Windows => "python", + Self::Linux => "python3", + } + } + + /// The loader the runtime stage writes into the output folder: `gta6rt.exe`, or on Linux the + /// `gta6rt.sh` beside it that starts it with Wine (make_game.py's `WINE_LAUNCHER`). + pub const fn loader(self) -> &'static str { + match self { + Self::Windows => "gta6rt.exe", + Self::Linux => "gta6rt.sh", + } + } + + fn separator(self) -> char { + match self { + Self::Windows => '\\', + Self::Linux => '/', + } + } + + /// `folder` and `name`, joined as this system joins paths. + pub fn join(self, folder: &str, name: &str) -> String { + let separator = self.separator(); + if folder.ends_with(separator) || (self == Self::Windows && folder.ends_with('/')) { + format!("{folder}{name}") + } else { + format!("{folder}{separator}{name}") + } + } +} + +/// A command to run: the program, its arguments, the environment it adds, and where it runs. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Command { + pub program: String, + pub args: Vec, + pub env: Vec<(String, String)>, + pub cwd: String, +} + +impl Command { + /// As a shell would show it, for the log: each part quoted where it has a space. + pub fn display(&self) -> String { + let quote = |part: &str| { + if part.is_empty() || part.contains(char::is_whitespace) { + format!("\"{part}\"") + } else { + part.to_owned() + } + }; + let env = self + .env + .iter() + .map(|(name, value)| format!("{name}={} ", quote(value))); + env.chain(std::iter::once(quote(&self.program))) + .chain(self.args.iter().map(|arg| format!(" {}", quote(arg)))) + .collect() + } +} + +/// What's needed and missing to make a command. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Missing { + /// The game package folder isn't set. + Package, + /// The output folder isn't set. + Output, +} + +/// `make_game.py` with the arguments after it: `python -I -u make_game.py …`, in the repository. +/// `-I` as the repository runs it; `-u` so its lines arrive as they're printed, not when a pipe's +/// buffer fills (its `log()` flushes, its other prints don't). +fn make_game( + platform: Platform, + repo: &str, + args: Vec, + env: Vec<(String, String)>, +) -> Command { + let mut all = vec![ + "-I".to_owned(), + "-u".to_owned(), + platform.join(repo, "make_game.py"), + ]; + all.extend(args); + Command { + program: platform.python().to_owned(), + args: all, + env, + cwd: repo.to_owned(), + } +} + +/// `LEONIDA_VK_DEVICE`, when a GPU name filter is set: the runtime and make_game.py's GPU probe +/// (`tools/vk_subgroup_info.py`) take the first Vulkan device whose name holds it. +fn gpu_env(settings: &Settings) -> Vec<(String, String)> { + let gpu = settings.gpu.trim(); + if gpu.is_empty() { + Vec::new() + } else { + vec![("LEONIDA_VK_DEVICE".to_owned(), gpu.to_owned())] + } +} + +/// Checks the copy: `make_game.py --game --check`, and `--full-check` to compare every +/// file's SHA-256. +pub fn check(platform: Platform, repo: &str, settings: &Settings) -> Result { + let package = settings.package.trim(); + if package.is_empty() { + return Err(Missing::Package); + } + let mut args = vec![ + "--game".to_owned(), + package.to_owned(), + "--check".to_owned(), + ]; + if settings.full_check { + args.push("--full-check".to_owned()); + } + Ok(make_game(platform, repo, args, Vec::new())) +} + +/// The stages to ask for: none (make_game.py's default, every stage) when all are chosen. +pub fn stages(settings: &Settings) -> Option { + let chosen: Vec<&str> = STAGES + .iter() + .copied() + .filter(|stage| settings.stages.iter().any(|chosen| chosen == stage)) + .collect(); + if chosen.len() == STAGES.len() { + None + } else if chosen.is_empty() { + // Only the check, which runs before every build anyway. + Some("check".to_owned()) + } else { + Some(chosen.join(",")) + } +} + +/// The jobs to ask for, if a whole number above 0 is set. +pub fn jobs(settings: &Settings) -> Option { + settings + .jobs + .trim() + .parse::() + .ok() + .filter(|jobs| *jobs > 0) +} + +/// Builds the port: `make_game.py --game --out [--work ]` and the +/// build's options. +pub fn build(platform: Platform, repo: &str, settings: &Settings) -> Result { + let package = settings.package.trim(); + let output = settings.output.trim(); + if package.is_empty() { + return Err(Missing::Package); + } + if output.is_empty() { + return Err(Missing::Output); + } + let mut args = vec![ + "--game".to_owned(), + package.to_owned(), + "--out".to_owned(), + output.to_owned(), + ]; + let work = settings.work.trim(); + if !work.is_empty() { + args.extend(["--work".to_owned(), work.to_owned()]); + } + if let Some(stages) = stages(settings) { + args.extend(["--stages".to_owned(), stages]); + } + if settings.wav { + args.push("--wav".to_owned()); + } + if let Some(jobs) = jobs(settings) { + args.extend(["--jobs".to_owned(), jobs.to_string()]); + } + if settings.wave64 != Wave64::Auto { + args.extend([ + "--wave64-emulate".to_owned(), + settings.wave64.flag().to_owned(), + ]); + } + Ok(make_game(platform, repo, args, gpu_env(settings))) +} + +/// A Linux path as Wine sees it, on its `Z:` drive (the whole file system). +pub fn wine_path(path: &str) -> String { + format!("Z:{}", path.replace('/', "\\")) +} + +/// Starts the game: the loader with `--run --game-dir ` and +/// `LEONIDA_D3D12=vulkan`, as `docs/boot.md` section 2 has it; on Linux through the output +/// folder's `gta6rt.sh`, in the package folder, the executable by its name there and the package +/// as Wine's `Z:` path. +pub fn play(platform: Platform, exe_name: &str, settings: &Settings) -> Result { + let package = settings.package.trim(); + let output = settings.output.trim(); + if package.is_empty() { + return Err(Missing::Package); + } + if output.is_empty() { + return Err(Missing::Output); + } + let mut env = vec![("LEONIDA_D3D12".to_owned(), "vulkan".to_owned())]; + env.extend(gpu_env(settings)); + if settings.validation { + env.push(("LEONIDA_VK_VALIDATION".to_owned(), "1".to_owned())); + } + if settings.unimplemented != Unimplemented::Log { + env.push(( + "LEONIDA_UNIMPLEMENTED".to_owned(), + settings.unimplemented.value().to_owned(), + )); + } + let loader = platform.join(output, platform.loader()); + let overlay = settings.overlay.trim(); + let mut command = match platform { + Platform::Windows => Command { + program: loader, + args: vec![ + "--run".to_owned(), + platform.join(package, exe_name), + "--game-dir".to_owned(), + package.to_owned(), + ], + env, + cwd: output.to_owned(), + }, + Platform::Linux => Command { + program: loader, + args: vec![ + "--run".to_owned(), + format!("./{exe_name}"), + "--game-dir".to_owned(), + wine_path(package), + ], + env, + cwd: package.to_owned(), + }, + }; + if !overlay.is_empty() { + command.args.push("--overlay".to_owned()); + command.args.push(match platform { + Platform::Windows => overlay.to_owned(), + Platform::Linux => wine_path(overlay), + }); + } + if settings.trace_d3d12 { + command.args.push("--trace-d3d12".to_owned()); + } + Ok(command) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::Wave64; + + fn windows() -> Settings { + Settings { + package: "D:\\Games\\GTA6 package".to_owned(), + output: "D:\\Games\\Leonida".to_owned(), + ..Settings::default() + } + } + + fn linux() -> Settings { + Settings { + package: "/games/package".to_owned(), + output: "/home/player/Leonida".to_owned(), + ..Settings::default() + } + } + + fn strings(parts: &[&str]) -> Vec { + parts.iter().map(|part| (*part).to_owned()).collect() + } + + #[test] + fn check_runs_make_game_with_the_package() { + let command = check(Platform::Windows, "C:\\src\\Leonida", &windows()).unwrap(); + assert_eq!(command.program, "python"); + assert_eq!( + command.args, + strings(&[ + "-I", + "-u", + "C:\\src\\Leonida\\make_game.py", + "--game", + "D:\\Games\\GTA6 package", + "--check" + ]) + ); + assert_eq!(command.cwd, "C:\\src\\Leonida"); + assert!(command.env.is_empty()); + let full = Settings { + full_check: true, + ..linux() + }; + let command = check(Platform::Linux, "/src/Leonida", &full).unwrap(); + assert_eq!(command.program, "python3"); + assert_eq!(command.args[2], "/src/Leonida/make_game.py"); + assert_eq!(command.args.last().unwrap(), "--full-check"); + assert_eq!( + check(Platform::Linux, "/src", &Settings::default()), + Err(Missing::Package) + ); + } + + #[test] + fn build_takes_the_three_folders() { + let settings = Settings { + work: "E:\\leonida-work".to_owned(), + ..windows() + }; + let command = build(Platform::Windows, "C:\\src\\Leonida", &settings).unwrap(); + assert_eq!( + command.args[3..], + strings(&[ + "--game", + "D:\\Games\\GTA6 package", + "--out", + "D:\\Games\\Leonida", + "--work", + "E:\\leonida-work" + ]) + ); + // No work folder: make_game.py's own, /work. + let command = build(Platform::Linux, "/src/Leonida", &linux()).unwrap(); + assert!(!command.args.contains(&"--work".to_owned())); + assert_eq!(command.args.len(), 7); + let no_output = Settings { + output: " ".to_owned(), + ..linux() + }; + assert_eq!( + build(Platform::Linux, "/src", &no_output), + Err(Missing::Output) + ); + } + + #[test] + fn build_options_become_make_games_flags_and_the_gpu_its_variable() { + let settings = Settings { + stages: strings(&["pipelines", "shaders"]), + wav: true, + jobs: " 6 ".to_owned(), + wave64: Wave64::Off, + gpu: "radeon".to_owned(), + ..linux() + }; + let command = build(Platform::Linux, "/src/Leonida", &settings).unwrap(); + let tail = &command.args[7..]; + assert_eq!( + tail, + strings(&[ + "--stages", + "shaders,pipelines", + "--wav", + "--jobs", + "6", + "--wave64-emulate", + "off" + ]) + ); + assert_eq!( + command.env, + vec![("LEONIDA_VK_DEVICE".to_owned(), "radeon".to_owned())] + ); + // Every stage is the default; none is the check alone; a bad job count is left out. + assert_eq!(stages(&Settings::default()), None); + let none = Settings { + stages: Vec::new(), + jobs: "many".to_owned(), + ..Settings::default() + }; + assert_eq!(stages(&none), Some("check".to_owned())); + assert_eq!(jobs(&none), None); + assert_eq!( + jobs(&Settings { + jobs: "0".to_owned(), + ..Settings::default() + }), + None + ); + // Auto is make_game.py's default: not passed. + let auto = build(Platform::Windows, "C:\\src", &windows()).unwrap(); + assert!(!auto.args.contains(&"--wave64-emulate".to_owned())); + } + + #[test] + fn play_on_windows_runs_the_loader_on_the_executable() { + let settings = Settings { + validation: true, + gpu: "5070".to_owned(), + ..windows() + }; + let command = play(Platform::Windows, "game_scarlett_master.exe", &settings).unwrap(); + assert_eq!(command.program, "D:\\Games\\Leonida\\gta6rt.exe"); + assert_eq!( + command.args, + strings(&[ + "--run", + "D:\\Games\\GTA6 package\\game_scarlett_master.exe", + "--game-dir", + "D:\\Games\\GTA6 package" + ]) + ); + assert_eq!( + command.env, + vec![ + ("LEONIDA_D3D12".to_owned(), "vulkan".to_owned()), + ("LEONIDA_VK_DEVICE".to_owned(), "5070".to_owned()), + ("LEONIDA_VK_VALIDATION".to_owned(), "1".to_owned()), + ] + ); + assert_eq!(command.cwd, "D:\\Games\\Leonida"); + } + + #[test] + fn diagnostics_become_the_loaders_options_and_variables() { + let settings = Settings { + trace_d3d12: true, + unimplemented: Unimplemented::Stop, + overlay: "/scratch/overlay".to_owned(), + ..linux() + }; + let command = play(Platform::Linux, "game_scarlett_master.exe", &settings).unwrap(); + assert_eq!( + command.args[4..], + strings(&["--overlay", "Z:\\scratch\\overlay", "--trace-d3d12"]) + ); + assert!( + command + .env + .contains(&("LEONIDA_UNIMPLEMENTED".to_owned(), "stop".to_owned())) + ); + let on_windows = Settings { + overlay: "E:\\overlay".to_owned(), + unimplemented: Unimplemented::Fail, + ..windows() + }; + let command = play(Platform::Windows, "g.exe", &on_windows).unwrap(); + assert_eq!(command.args[4..], strings(&["--overlay", "E:\\overlay"])); + assert!( + command + .env + .contains(&("LEONIDA_UNIMPLEMENTED".to_owned(), "fail".to_owned())) + ); + // The loader's defaults are left out. + let plain = play(Platform::Windows, "g.exe", &windows()).unwrap(); + assert_eq!(plain.args.len(), 4); + assert!( + plain + .env + .iter() + .all(|(name, _)| name != "LEONIDA_UNIMPLEMENTED") + ); + } + + #[test] + fn play_on_linux_goes_through_wine() { + let command = play(Platform::Linux, "game_scarlett_master.exe", &linux()).unwrap(); + assert_eq!(command.program, "/home/player/Leonida/gta6rt.sh"); + assert_eq!( + command.args, + strings(&[ + "--run", + "./game_scarlett_master.exe", + "--game-dir", + "Z:\\games\\package" + ]) + ); + assert_eq!(command.cwd, "/games/package"); + assert_eq!( + command.env, + vec![("LEONIDA_D3D12".to_owned(), "vulkan".to_owned())] + ); + assert_eq!( + play(Platform::Linux, "x.exe", &Settings::default()), + Err(Missing::Package) + ); + } + + #[test] + fn paths_join_as_each_system_does() { + assert_eq!(Platform::Windows.join("C:\\a", "b"), "C:\\a\\b"); + assert_eq!(Platform::Windows.join("C:\\", "b"), "C:\\b"); + assert_eq!(Platform::Linux.join("/a/", "b"), "/a/b"); + assert_eq!(Platform::Linux.loader(), "gta6rt.sh"); + assert_eq!(wine_path("/a b/c"), "Z:\\a b\\c"); + let command = check(Platform::Linux, "/src", &linux()).unwrap(); + assert_eq!( + command.display(), + "python3 -I -u /src/make_game.py --game /games/package --check" + ); + let spaced = play(Platform::Windows, "g.exe", &windows()).unwrap(); + assert!(spaced.display().starts_with("LEONIDA_D3D12=vulkan ")); + assert!(spaced.display().contains("\"D:\\Games\\GTA6 package\"")); + } +} diff --git a/launcher/src/config.rs b/launcher/src/config.rs new file mode 100644 index 0000000000..92fb0bf331 --- /dev/null +++ b/launcher/src/config.rs @@ -0,0 +1,346 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! The launcher's settings: one small JSON file in the platform's per-user configuration folder +//! (`%APPDATA%\Leonida\launcher.json` on Windows, `$XDG_CONFIG_HOME/leonida/launcher.json` or +//! `~/.config/leonida/launcher.json` on Linux), never in the repository. +//! +//! The file carries a `version`. A missing, unreadable or broken file gives the defaults; so does +//! one from a newer launcher, which is then left alone until something is changed and saved. +//! Fields the file lacks take their defaults, and fields it has that this version doesn't know are +//! dropped on the next save. + +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +/// The settings file's version this launcher writes. +pub const VERSION: u32 = 1; + +/// Where the settings live, under the platform's per-user configuration folder. +pub fn path() -> Option { + let folder = if cfg!(windows) { "Leonida" } else { "leonida" }; + dirs::config_dir().map(|config| config.join(folder).join("launcher.json")) +} + +/// The wave64 translation mode, `make_game.py --wave64-emulate`. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Wave64 { + /// make_game.py's default: it asks the GPU. + #[default] + Auto, + On, + Off, +} + +impl Wave64 { + /// The option's value. + pub const fn flag(self) -> &'static str { + match self { + Self::Auto => "auto", + Self::On => "on", + Self::Off => "off", + } + } +} + +/// What the loader does with a call to an import it doesn't implement +/// (`LEONIDA_UNIMPLEMENTED`, runtime/README.md). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Unimplemented { + /// The loader's default: log it once and return 0. + #[default] + Log, + /// Return `E_NOTIMPL` from the ones that return an `HRESULT`. + Fail, + /// End the process with exit code 3 at the first. + Stop, +} + +impl Unimplemented { + /// The variable's value. + pub const fn value(self) -> &'static str { + match self { + Self::Log => "log", + Self::Fail => "fail", + Self::Stop => "stop", + } + } +} + +/// The light or dark palette. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Shade { + #[default] + Dark, + Light, +} + +/// The stages `make_game.py --stages` chooses among, in order, after its check (which always +/// runs first). +pub const STAGES: [&str; 4] = ["shaders", "assets", "runtime", "pipelines"]; + +/// Every setting, as the file holds it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Settings { + pub version: u32, + /// The game package: the folder that holds `MicrosoftGame.Config` (`--game`). + pub package: String, + /// Where the finished port goes (`--out`). + pub output: String, + /// Intermediate files (`--work`); empty is make_game.py's `/work`. + pub work: String, + /// Which build stages run, by name from [`STAGES`]; all of them is make_game.py's default. + pub stages: Vec, + /// Also decode the audio to WAV (`--wav`). + pub wav: bool, + /// Compare every file's SHA-256 when checking (`--full-check`). + pub full_check: bool, + /// Part of the GPU's name (`LEONIDA_VK_DEVICE`); empty takes the runtime's own choice. + pub gpu: String, + /// `--wave64-emulate`. + pub wave64: Wave64, + /// `--jobs`; empty is make_game.py's default, half the CPU threads. + pub jobs: String, + /// The Khronos validation layer at play (`LEONIDA_VK_VALIDATION=1`). + pub validation: bool, + /// The loader logs every D3D12 call and its outcome (`gta6rt --trace-d3d12`). + pub trace_d3d12: bool, + /// What the loader does with an unimplemented import (`LEONIDA_UNIMPLEMENTED`). + pub unimplemented: Unimplemented, + /// Where the game's writes go instead of the package (`gta6rt --overlay`); empty is the + /// loader's default, `\overlay`. + pub overlay: String, + /// Light or dark. + pub shade: Shade, + /// The package last checked without a fault, and the version make_game.py said it is. + pub checked: Option, +} + +/// A package that passed `make_game.py --check`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Checked { + pub package: String, + /// As make_game.py says it: "Xbox Series package 1.0.2.1". + pub game: String, +} + +impl Default for Settings { + fn default() -> Self { + Self { + version: VERSION, + package: String::new(), + output: String::new(), + work: String::new(), + stages: STAGES.iter().map(|stage| (*stage).to_owned()).collect(), + wav: false, + full_check: false, + gpu: String::new(), + wave64: Wave64::Auto, + jobs: String::new(), + validation: false, + trace_d3d12: false, + unimplemented: Unimplemented::Log, + overlay: String::new(), + shade: Shade::Dark, + checked: None, + } + } +} + +/// What reading the settings found. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Loaded { + /// The file, read. + Read(Box), + /// No file yet: the defaults. + Missing, + /// A file that couldn't be read or parsed, or isn't the settings: the defaults, and why. + Unreadable(String), + /// A newer launcher's file: the defaults, and the file is kept as it is until a save. + Newer(u32), +} + +impl Loaded { + /// The settings to use. + pub fn settings(&self) -> Settings { + match self { + Self::Read(settings) => (**settings).clone(), + _ => Settings::default(), + } + } + + /// What to say of it, if anything. + pub fn note(&self) -> Option { + match self { + Self::Read(_) | Self::Missing => None, + Self::Unreadable(why) => Some(format!( + "Settings couldn't be read ({why}); using defaults." + )), + Self::Newer(version) => Some(format!( + "Settings are from a newer launcher (version {version}); using defaults." + )), + } + } +} + +/// Reads settings from text. +pub fn parse(text: &str) -> Loaded { + let value: serde_json::Value = match serde_json::from_str(text) { + Ok(value) => value, + Err(error) => return Loaded::Unreadable(error.to_string()), + }; + let Some(version) = value.get("version").and_then(serde_json::Value::as_u64) else { + return Loaded::Unreadable("no version".to_owned()); + }; + let version = u32::try_from(version).unwrap_or(u32::MAX); + if version > VERSION { + return Loaded::Newer(version); + } + if version == 0 { + return Loaded::Unreadable("version 0".to_owned()); + } + match serde_json::from_value::(value) { + Ok(settings) => Loaded::Read(Box::new(Settings { + version: VERSION, + ..settings + })), + Err(error) => Loaded::Unreadable(error.to_string()), + } +} + +/// Reads the settings file at `path`. +pub fn load(path: &Path) -> Loaded { + match fs::read_to_string(path) { + Ok(text) => parse(&text), + Err(error) if error.kind() == io::ErrorKind::NotFound => Loaded::Missing, + Err(error) => Loaded::Unreadable(error.to_string()), + } +} + +/// The settings as the file holds them. +pub fn to_text(settings: &Settings) -> String { + let settings = Settings { + version: VERSION, + ..settings.clone() + }; + let mut text = serde_json::to_string_pretty(&settings).unwrap_or_default(); + text.push('\n'); + text +} + +/// Writes the settings to `path`, through a file beside it, so a crash leaves the old one. +pub fn save(path: &Path, settings: &Settings) -> io::Result<()> { + if let Some(folder) = path.parent() { + fs::create_dir_all(folder)?; + } + let partial = path.with_extension("json.partial"); + fs::write(&partial, to_text(settings))?; + fs::rename(&partial, path) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scratch(name: &str) -> PathBuf { + let folder = std::env::temp_dir().join(format!( + "leonida-launcher-test-{}-{name}", + std::process::id() + )); + let _ = fs::remove_dir_all(&folder); + folder + } + + #[test] + fn settings_go_round_the_file() { + let folder = scratch("round"); + let path = folder.join("leonida").join("launcher.json"); + let settings = Settings { + package: "D:\\Games\\package".to_owned(), + output: "/home/player/Leonida".to_owned(), + work: String::new(), + stages: vec!["shaders".to_owned(), "runtime".to_owned()], + wav: true, + full_check: true, + gpu: "radeon".to_owned(), + wave64: Wave64::On, + jobs: "6".to_owned(), + validation: true, + shade: Shade::Light, + checked: Some(Checked { + package: "D:\\Games\\package".to_owned(), + game: "Xbox Series package 1.0.2.1".to_owned(), + }), + ..Settings::default() + }; + assert_eq!(load(&path), Loaded::Missing); + save(&path, &settings).unwrap(); + assert_eq!(load(&path), Loaded::Read(Box::new(settings))); + assert!(!path.with_extension("json.partial").exists()); + let _ = fs::remove_dir_all(folder); + } + + #[test] + fn a_missing_or_broken_file_gives_the_defaults() { + assert_eq!(Loaded::Missing.settings(), Settings::default()); + for text in [ + "", + "{", + "[]", + "{\"package\": \"x\"}", + "{\"version\": \"one\"}", + ] { + let loaded = parse(text); + assert!( + matches!(loaded, Loaded::Unreadable(_)), + "{text}: {loaded:?}" + ); + assert_eq!(loaded.settings(), Settings::default()); + assert!(loaded.note().is_some()); + } + // A field of the wrong kind is a broken file, not half a file. + let loaded = parse("{\"version\": 1, \"wav\": \"yes\"}"); + assert!(matches!(loaded, Loaded::Unreadable(_))); + } + + #[test] + fn a_newer_file_gives_the_defaults_and_says_so() { + let loaded = parse("{\"version\": 7, \"package\": \"x\"}"); + assert_eq!(loaded, Loaded::Newer(7)); + assert_eq!(loaded.settings(), Settings::default()); + assert!(loaded.note().unwrap().contains("version 7")); + assert!(matches!(parse("{\"version\": 0}"), Loaded::Unreadable(_))); + } + + #[test] + fn missing_fields_take_defaults_and_unknown_ones_are_dropped() { + let loaded = parse("{\"version\": 1, \"package\": \"/games/pkg\", \"later\": 3}"); + let Loaded::Read(settings) = loaded else { + panic!("{loaded:?}") + }; + assert_eq!(settings.package, "/games/pkg"); + assert_eq!(settings.stages, Settings::default().stages); + assert_eq!(settings.wave64, Wave64::Auto); + assert!(!to_text(&settings).contains("later")); + assert!(to_text(&settings).contains("\"version\": 1")); + } + + #[test] + fn the_file_is_in_the_users_configuration_folder() { + if let Some(path) = path() { + assert!(path.ends_with("launcher.json")); + assert!(path.parent().unwrap().ends_with(if cfg!(windows) { + "Leonida" + } else { + "leonida" + })); + } + assert_eq!(Wave64::default().flag(), "auto"); + } +} diff --git a/launcher/src/lib.rs b/launcher/src/lib.rs new file mode 100644 index 0000000000..2ad261f5e3 --- /dev/null +++ b/launcher/src/lib.rs @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Leonida's launcher: one window to check the player's copy of the game, build the port with +//! `make_game.py`, and start the loader. Everything it does runs the repository's own commands; +//! nothing goes online. +//! +//! Its look comes from [`ui`], the launcher's own design system on stock iced 0.14, in two +//! palettes taken from Leonida's logo. + +pub mod app; +pub mod backdrop; +pub mod commands; +pub mod config; +pub mod output; +pub mod process; +pub mod repo; +pub mod scene; +pub mod state; +pub mod ui; diff --git a/launcher/src/main.rs b/launcher/src/main.rs new file mode 100644 index 0000000000..132b0c4cb4 --- /dev/null +++ b/launcher/src/main.rs @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +// A window, not a console, on Windows (in release builds; a debug build keeps its console for +// what it prints). +#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] + +//! `leonida-launcher [--repo PATH]`: the launcher's window. Without `--repo`, the repository is +//! the first folder holding `make_game.py` above the launcher's executable, or above the current +//! folder. + +use std::path::PathBuf; + +use leonida_launcher::app::{LEAST, Launcher, SIZE}; +use leonida_launcher::config; +use leonida_launcher::repo; +use leonida_launcher::ui::font; +use leonida_launcher::ui::window::{FrameSetting, settings}; + +const USAGE: &str = "usage: leonida-launcher [--repo PATH] + + --repo PATH the Leonida repository (the folder that holds make_game.py); found by walking up + from the launcher, then from the current folder, when left out + +Keys: Tab and Shift+Tab move focus; Enter and Space press; Ctrl+Page Down and Ctrl+Page Up go to +the next and previous page; Ctrl+L switches light and dark. +Environment: LEONIDA_WINDOW_FRAME=0 for an opaque, square window."; + +fn main() -> iced::Result { + let mut given: Option = None; + let mut args = std::env::args_os().skip(1); + while let Some(arg) = args.next() { + match arg.to_str() { + Some("--repo") => match args.next() { + Some(path) => given = Some(PathBuf::from(path)), + None => usage_error("--repo needs a folder"), + }, + Some("-h" | "--help") => { + println!("{USAGE}"); + return Ok(()); + } + _ => usage_error(&format!("unknown argument {}", arg.to_string_lossy())), + } + } + let exe = std::env::current_exe().ok(); + let cwd = std::env::current_dir().ok(); + let repo = repo::find(given.as_deref(), exe.as_deref(), cwd.as_deref()); + if let Err(why) = &repo { + eprintln!("leonida-launcher: {why}"); + } + let frame = FrameSetting::from_env(); + font::load(); + let boot = move || Launcher::boot(repo.clone(), config::path(), frame); + let mut application = iced::application(boot, Launcher::update, Launcher::view) + .title("Leonida") + .subscription(Launcher::subscription) + .theme(Launcher::theme) + .style(Launcher::style) + .window(settings(SIZE, LEAST, frame)) + .default_font(font::DEFAULT); + for bytes in font::SHIPPED { + application = application.font(bytes); + } + application.run() +} + +fn usage_error(why: &str) -> ! { + eprintln!("leonida-launcher: {why}\n\n{USAGE}"); + std::process::exit(2) +} diff --git a/launcher/src/output.rs b/launcher/src/output.rs new file mode 100644 index 0000000000..dc64e24e99 --- /dev/null +++ b/launcher/src/output.rs @@ -0,0 +1,460 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Reading a command's output as it comes: the last lines for the log, and how far a build is. +//! +//! `make_game.py` prints free text: its `log()` lines are `HH:MM:SS `, and each stage's +//! begin with the stage's name (`shaders: carving shaders.rpf`). Its stages run in a fixed order +//! (check, shaders, assets, runtime, pipelines) after the line `building into …`, so a stage's +//! first line says it has begun and `: done` that it's over; that's what the determinate +//! bar follows. Lines before `building into` that name a stage (the GPU probe's `shaders: …`, the +//! runtime stage `left out` on Linux) only say what's planned. Its failures go to stderr as +//! `ERROR: `. +//! +//! Machine-readable lines, if a later `make_game.py` prints them, take over from the free text: +//! `@@stage `, `@@progress <0..1>`, `@@eta `, `@@check `, +//! `@@done ` and `@@error `. They aren't shown in the log as they are; unknown `@@` +//! words are ignored. + +use std::collections::VecDeque; + +/// How many of the last lines are kept for the log. +pub const KEPT: usize = 400; + +/// The stages of a build, in the order make_game.py runs them. +pub const ORDER: [&str; 5] = ["check", "shaders", "assets", "runtime", "pipelines"]; + +/// A line, read. +#[derive(Debug, Clone, PartialEq)] +pub enum Line { + /// Text for the log. + Text(String), + /// `@@stage `. + Stage { id: String, text: String }, + /// `@@progress <0..1>`. + Progress(f32), + /// `@@eta `. + Eta(f64), + /// `@@check `. + Check { ok: bool, text: String }, + /// `@@done `. + Done(String), + /// `@@error `. + Error(String), + /// An `@@` line this launcher doesn't know, or one it can't read. + Ignored, +} + +/// Reads one line. +pub fn parse(line: &str) -> Line { + let Some(rest) = line.strip_prefix("@@") else { + return Line::Text(line.to_owned()); + }; + let (word, rest) = rest.split_once(' ').unwrap_or((rest, "")); + let rest = rest.trim(); + match word { + "stage" => { + let (id, text) = rest.split_once(' ').unwrap_or((rest, "")); + if id.is_empty() { + return Line::Ignored; + } + Line::Stage { + id: id.to_owned(), + text: text.trim().to_owned(), + } + } + "progress" => rest + .parse::() + .ok() + .filter(|value| value.is_finite()) + .map_or(Line::Ignored, |value| Line::Progress(value.clamp(0.0, 1.0))), + "eta" => rest + .parse::() + .ok() + .filter(|value| value.is_finite() && *value >= 0.0) + .map_or(Line::Ignored, Line::Eta), + "check" => { + let (verdict, text) = rest.split_once(' ').unwrap_or((rest, "")); + match verdict { + "ok" | "bad" => Line::Check { + ok: verdict == "ok", + text: text.trim().to_owned(), + }, + _ => Line::Ignored, + } + } + "done" => Line::Done(rest.to_owned()), + "error" => Line::Error(rest.to_owned()), + _ => Line::Ignored, + } +} + +/// The text after a `log()` line's `HH:MM:SS ` time, if it is one. +fn logged(line: &str) -> Option<&str> { + let bytes = line.as_bytes(); + let time = bytes.get(..10)?; + let digits = [0, 1, 3, 4, 6, 7] + .iter() + .all(|at| time[*at].is_ascii_digit()); + (digits && time[2] == b':' && time[5] == b':' && &time[8..10] == b" ").then(|| &line[10..]) +} + +/// What's known of a running command from its output. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Tracker { + /// The last lines, for the log. + pub lines: VecDeque, + /// Whether `@@` lines have been seen: they take over from the free text. + machine: bool, + /// The build's stages, in order, as planned. + planned: Vec<&'static str>, + /// Whether the stages have begun (`building into …`). + begun: bool, + /// The stage under way, by its place in `planned`, and whether it said it's done. + current: Option, + finished_current: bool, + finished: bool, + /// From `@@` lines: the step and how far it is. + step: Option, + fraction: Option, + /// Seconds left, if said. + pub eta: Option, + /// What went wrong, if said: `ERROR: …` or `@@error`. + pub error: Option, + /// The game copy's version, as the check says it: "Xbox Series package 1.0.2.1". + pub game: Option, + /// `@@check` results that weren't ok. + pub bad: Vec, + /// `@@done`'s folder. + pub done: Option, +} + +impl Tracker { + /// For a build of these stages (`None`: make_game.py's default, every stage). The check + /// always runs first. + pub fn build(stages: Option<&str>) -> Self { + let chosen: Vec<&str> = stages + .map(|stages| stages.split(',').map(str::trim).collect()) + .unwrap_or_else(|| ORDER.to_vec()); + Self { + planned: ORDER + .iter() + .copied() + .filter(|stage| *stage == "check" || chosen.contains(stage)) + .collect(), + ..Self::default() + } + } + + /// For a command that isn't a build: no stages. + pub fn plain() -> Self { + Self::default() + } + + /// Takes one line of output. + pub fn feed(&mut self, line: &str) { + let line = line.trim_end_matches(['\r', '\n']); + match parse(line) { + Line::Text(text) => { + self.read_text(&text); + if self.lines.len() == KEPT { + self.lines.pop_front(); + } + self.lines.push_back(text); + } + other => { + self.machine = true; + self.read_machine(other); + } + } + } + + fn read_machine(&mut self, line: Line) { + match line { + Line::Stage { id, text } => { + self.step = Some(if text.is_empty() { id } else { text }); + self.fraction = Some(0.0); + self.eta = None; + } + Line::Progress(fraction) => self.fraction = Some(fraction), + Line::Eta(seconds) => self.eta = Some(seconds), + Line::Check { ok, text } => { + if !ok { + self.bad.push(text); + } + } + Line::Done(folder) => { + self.done = Some(folder); + self.fraction = Some(1.0); + } + Line::Error(text) => self.error = Some(text), + Line::Text(_) | Line::Ignored => {} + } + } + + fn read_text(&mut self, text: &str) { + if let Some(error) = text.strip_prefix("ERROR: ") { + self.error = Some(error.trim().to_owned()); + } + let Some(said) = logged(text) else { + return; + }; + // The check's first line names the copy: "check: <version>, <n> files". + if let Some(rest) = said.strip_prefix("check: ") + && self.game.is_none() + && let Some((game, files)) = rest.rsplit_once(", ") + && files.ends_with(" files") + { + self.game = Some(game.to_owned()); + } + if self.machine { + return; + } + if said.starts_with("building into ") { + self.begun = true; + self.current = self.current.max(Some(0)); + self.finished_current = true; + return; + } + if said.starts_with("finished in ") { + self.finished = true; + return; + } + let Some((stage, rest)) = said.split_once(':') else { + return; + }; + if stage == "runtime" && rest.trim_start().starts_with("left out") { + self.planned.retain(|planned| *planned != "runtime"); + return; + } + let Some(at) = self.planned.iter().position(|planned| *planned == stage) else { + return; + }; + // Before the stages begin, only the check speaks for itself. + if !self.begun && stage != "check" { + return; + } + if self.current.is_none_or(|current| at > current) { + self.current = Some(at); + self.finished_current = false; + } + if Some(at) == self.current && rest.trim() == "done" { + self.finished_current = true; + } + } + + /// How far it is, from 0 to 1, if its output says: the `@@progress` of the step under way, or + /// the build's stages done of those planned. + pub fn progress(&self) -> Option<f32> { + if self.machine { + return self.fraction; + } + if self.finished { + return Some(1.0); + } + let count = self.planned.len(); + let current = self.current?; + if count == 0 { + return None; + } + let done = current + usize::from(self.finished_current); + Some(done.min(count) as f32 / count as f32) + } + + /// What's under way, in words: the `@@stage`'s, or "Stage 2 of 5: shaders". + pub fn stage(&self) -> Option<String> { + if self.machine { + return self.step.clone(); + } + let current = self.current?; + let count = self.planned.len(); + let index = if self.finished_current && current + 1 < count && self.begun { + current + 1 + } else { + current + }; + let name = self.planned.get(index)?; + Some(format!("Stage {} of {count}: {name}", index + 1)) + } + + /// The last line worth showing with a failure: the error if said, or the last line. + pub fn last_words(&self) -> Option<String> { + self.error.clone().or_else(|| { + self.lines + .iter() + .rev() + .find(|line| !line.trim().is_empty()) + .map(|line| line.trim().to_owned()) + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fed(tracker: &mut Tracker, lines: &[&str]) { + for line in lines { + tracker.feed(line); + } + } + + #[test] + fn machine_lines_are_read() { + assert_eq!( + parse("@@stage shaders Translating shaders"), + Line::Stage { + id: "shaders".to_owned(), + text: "Translating shaders".to_owned() + } + ); + assert_eq!(parse("@@progress 0.25"), Line::Progress(0.25)); + assert_eq!(parse("@@progress 7"), Line::Progress(1.0)); + assert_eq!(parse("@@progress NaN"), Line::Ignored); + assert_eq!(parse("@@eta 90"), Line::Eta(90.0)); + assert_eq!( + parse("@@check bad 3 files missing"), + Line::Check { + ok: false, + text: "3 files missing".to_owned() + } + ); + assert_eq!(parse("@@check maybe x"), Line::Ignored); + assert_eq!(parse("@@done /out"), Line::Done("/out".to_owned())); + assert_eq!( + parse("@@error disk full"), + Line::Error("disk full".to_owned()) + ); + assert_eq!(parse("@@later 1 2"), Line::Ignored); + assert_eq!(parse("@@stage"), Line::Ignored); + assert_eq!(parse("plain"), Line::Text("plain".to_owned())); + } + + #[test] + fn machine_lines_drive_the_bar_and_stay_out_of_the_log() { + let mut tracker = Tracker::build(None); + fed( + &mut tracker, + &[ + "12:00:00 check: Made-up package 9.9, 10 files", + "@@stage shaders Translating shaders", + "@@progress 0.5", + "@@eta 120", + "a tool's own line", + "@@check bad one file", + "@@unknown word", + ], + ); + assert_eq!(tracker.stage().as_deref(), Some("Translating shaders")); + assert_eq!(tracker.progress(), Some(0.5)); + assert_eq!(tracker.eta, Some(120.0)); + assert_eq!(tracker.bad, ["one file"]); + assert_eq!(tracker.game.as_deref(), Some("Made-up package 9.9")); + assert!(tracker.lines.iter().all(|line| !line.starts_with("@@"))); + assert_eq!(tracker.lines.len(), 2); + // Free-text stage lines don't move it once @@ lines have come. + tracker.feed("12:00:01 pipelines: done"); + assert_eq!(tracker.progress(), Some(0.5)); + tracker.feed("@@error the disk is full"); + assert_eq!(tracker.last_words().as_deref(), Some("the disk is full")); + tracker.feed("@@done /out"); + assert_eq!( + (tracker.progress(), tracker.done.as_deref()), + (Some(1.0), Some("/out")) + ); + // A new step starts again from its beginning. + tracker.feed("@@stage assets Exporting"); + assert_eq!(tracker.progress(), Some(0.0)); + } + + #[test] + fn the_free_text_log_gives_the_stages() { + let mut tracker = Tracker::build(None); + assert_eq!(tracker.progress(), None); + fed( + &mut tracker, + &[ + "12:00:00 check: Made-up package 9.9, 10 files", + "12:00:01 check: all files present. Executable found.", + ], + ); + assert_eq!(tracker.game.as_deref(), Some("Made-up package 9.9")); + assert_eq!(tracker.progress(), Some(0.0)); + assert_eq!(tracker.stage().as_deref(), Some("Stage 1 of 5: check")); + // Before the stages begin, a stage's name is only the plan: the GPU probe's line, and + // the runtime stage left out. + fed( + &mut tracker, + &[ + "12:00:02 shaders: smallest maximum subgroup size is 64: wave64 emulation off", + "12:00:02 runtime: left out, the cross-build needs clang-cl (or pass --runtime-build)", + ], + ); + assert_eq!(tracker.progress(), Some(0.0)); + tracker.feed("12:00:03 building into /out (work files in /out/work)"); + assert_eq!(tracker.progress(), Some(0.25)); + assert_eq!(tracker.stage().as_deref(), Some("Stage 2 of 4: shaders")); + fed( + &mut tracker, + &[ + "12:00:04 shaders: carving shaders.rpf", + " a tool's own output", + "12:00:05 shaders: done", + ], + ); + assert_eq!(tracker.progress(), Some(0.5)); + assert_eq!(tracker.stage().as_deref(), Some("Stage 3 of 4: assets")); + // Never backwards. + fed( + &mut tracker, + &["12:00:06 assets: audio banks", "12:00:07 shaders: late"], + ); + assert_eq!(tracker.progress(), Some(0.5)); + tracker.feed("12:00:08 pipelines: creating every shader module"); + assert_eq!(tracker.progress(), Some(0.75)); + tracker.feed("12:00:09 finished in 3 min"); + assert_eq!(tracker.progress(), Some(1.0)); + assert_eq!(tracker.lines.len(), 12); + } + + #[test] + fn chosen_stages_are_the_plan_and_errors_are_kept() { + let mut tracker = Tracker::build(Some("shaders,pipelines")); + fed( + &mut tracker, + &[ + "12:00:00 check: Made-up package 9.9, 10 files", + "12:00:01 building into /out (work files in /w)", + "12:00:02 pipelines: creating", + "", + "ERROR: vk_pipeline_check exited with 3", + ], + ); + assert_eq!(tracker.stage().as_deref(), Some("Stage 3 of 3: pipelines")); + assert_eq!( + tracker.last_words().as_deref(), + Some("vk_pipeline_check exited with 3") + ); + // A command that isn't a build has no stages, and its last line says what happened. + let mut plain = Tracker::plain(); + fed( + &mut plain, + &["first", "Traceback (most recent call last):", " boom", ""], + ); + assert_eq!(plain.progress(), None); + assert_eq!(plain.stage(), None); + assert_eq!(plain.last_words().as_deref(), Some("boom")); + } + + #[test] + fn only_the_last_lines_are_kept() { + let mut tracker = Tracker::plain(); + for n in 0..KEPT + 10 { + tracker.feed(&format!("line {n}\r")); + } + assert_eq!(tracker.lines.len(), KEPT); + assert_eq!(tracker.lines.front().unwrap(), "line 10"); + assert_eq!(logged("12:34:56 x"), Some("x")); + assert_eq!(logged("12:34:56 x"), None); + assert_eq!(logged("short"), None); + } +} diff --git a/launcher/src/process.rs b/launcher/src/process.rs new file mode 100644 index 0000000000..7362d8e05f --- /dev/null +++ b/launcher/src/process.rs @@ -0,0 +1,227 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Running a command off the interface's thread: its output read line by line on background +//! threads and sent on as it comes, then its exit code. Cancelling ends it and what it started +//! (make_game.py's tools, Wine's processes). + +use std::io::{BufRead, BufReader, Read}; +use std::process::{Child, Stdio}; +use std::thread; + +use iced::futures::Stream; +use iced::futures::channel::mpsc; + +use crate::commands::Command; + +/// What a running command says. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Event { + /// It started, as this process. + Started(u32), + /// A line of its output, stdout or stderr, as text (lossily, if it isn't UTF-8). + Line(String), + /// It ended, with its exit code (none if a signal ended it). + Exited(Option<i32>), + /// It couldn't be started, and why. + Failed(String), +} + +/// Starts `command` and returns what it says, ending with [`Event::Exited`] or [`Event::Failed`]. +/// Its input is empty, so a question it asks (make_game.py's "which copy?") ends it instead of +/// waiting forever. +pub fn run(command: &Command) -> impl Stream<Item = Event> + use<> { + let (sender, receiver) = mpsc::unbounded(); + match spawn(command) { + Ok(child) => { + let _ = sender.unbounded_send(Event::Started(child.id())); + watch(child, sender); + } + Err(error) => { + let _ = sender.unbounded_send(Event::Failed(format!( + "{} couldn't be started: {error}", + command.program + ))); + } + } + receiver +} + +fn spawn(command: &Command) -> std::io::Result<Child> { + let mut process = std::process::Command::new(&command.program); + process + .args(&command.args) + .envs(command.env.iter().map(|(name, value)| (name, value))) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + if !command.cwd.is_empty() { + process.current_dir(&command.cwd); + } + #[cfg(unix)] + { + // Its own process group, so cancelling reaches what it starts too. + use std::os::unix::process::CommandExt; + process.process_group(0); + } + #[cfg(windows)] + { + // No console window over the launcher's. + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + process.creation_flags(CREATE_NO_WINDOW); + } + process.spawn() +} + +/// Reads the child's output on two threads and waits for it on a third. +fn watch(mut child: Child, sender: mpsc::UnboundedSender<Event>) { + let readers: Vec<_> = [ + child + .stdout + .take() + .map(|out| Box::new(out) as Box<dyn Read + Send>), + child + .stderr + .take() + .map(|err| Box::new(err) as Box<dyn Read + Send>), + ] + .into_iter() + .flatten() + .map(|stream| { + let sender = sender.clone(); + thread::spawn(move || read_lines(stream, &sender)) + }) + .collect(); + thread::spawn(move || { + let status = child.wait(); + for reader in readers { + let _ = reader.join(); + } + let _ = sender.unbounded_send(match status { + Ok(status) => Event::Exited(status.code()), + Err(error) => Event::Failed(format!("waiting for it failed: {error}")), + }); + }); +} + +fn read_lines(stream: impl Read, sender: &mpsc::UnboundedSender<Event>) { + let mut reader = BufReader::new(stream); + let mut line = Vec::new(); + loop { + line.clear(); + match reader.read_until(b'\n', &mut line) { + Ok(0) | Err(_) => break, + Ok(_) => { + let text = String::from_utf8_lossy(&line); + let text = text.trim_end_matches(['\n', '\r']); + if sender.unbounded_send(Event::Line(text.to_owned())).is_err() { + break; + } + } + } + } +} + +/// Ends the process `pid` and everything it started. +pub fn cancel(pid: u32) { + let mut killer = cancel_command(pid); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + killer.creation_flags(0x0800_0000); + } + let _ = killer + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); +} + +/// The command that ends a process tree: `taskkill /T /F` on Windows, and elsewhere `kill` on the +/// process group the command was started in. +fn cancel_command(pid: u32) -> std::process::Command { + if cfg!(windows) { + let mut command = std::process::Command::new("taskkill"); + command.args(["/PID", &pid.to_string(), "/T", "/F"]); + command + } else { + let mut command = std::process::Command::new("kill"); + command.args(["-TERM", "--", &format!("-{pid}")]); + command + } +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use iced::futures::StreamExt; + use iced::futures::executor::block_on; + + /// A stand-in for make_game.py: prints lines to stdout and stderr and exits with a code. + fn stand_in(script: &str) -> Command { + Command { + program: "sh".to_owned(), + args: vec!["-c".to_owned(), script.to_owned()], + env: vec![("STAND_IN".to_owned(), "yes".to_owned())], + cwd: std::env::temp_dir().display().to_string(), + } + } + + fn events(command: &Command) -> Vec<Event> { + block_on(run(command).collect::<Vec<_>>()) + } + + #[test] + fn lines_come_then_the_exit_code() { + let events = events(&stand_in( + "echo '12:00:00 check: Made-up package 9.9, 10 files'; echo \"env $STAND_IN\"; \ + printf 'no newline'; echo 'ERROR: it broke' >&2; exit 3", + )); + assert!(matches!(events[0], Event::Started(_))); + let lines: Vec<_> = events + .iter() + .filter_map(|event| match event { + Event::Line(line) => Some(line.as_str()), + _ => None, + }) + .collect(); + assert!(lines.contains(&"12:00:00 check: Made-up package 9.9, 10 files")); + assert!(lines.contains(&"env yes")); + assert!(lines.contains(&"no newline")); + assert!(lines.contains(&"ERROR: it broke")); + assert_eq!(events.last(), Some(&Event::Exited(Some(3)))); + } + + #[test] + fn a_question_on_stdin_ends_instead_of_waiting() { + let events = events(&stand_in("read answer || exit 9; exit 0")); + assert_eq!(events.last(), Some(&Event::Exited(Some(9)))); + } + + #[test] + fn a_program_that_isnt_there_fails_to_start() { + let command = Command { + program: "/nonexistent/leonida-stand-in".to_owned(), + args: Vec::new(), + env: Vec::new(), + cwd: String::new(), + }; + let events = events(&command); + assert_eq!(events.len(), 1); + assert!(matches!(&events[0], Event::Failed(why) if why.contains("couldn't be started"))); + } + + #[test] + fn cancelling_ends_it_and_what_it_started() { + let mut stream = Box::pin(run(&stand_in("sleep 30 & sleep 30; exit 0"))); + let Some(Event::Started(pid)) = block_on(stream.next()) else { + panic!("not started"); + }; + let started = std::time::Instant::now(); + cancel(pid); + let rest: Vec<_> = block_on(stream.collect::<Vec<_>>()); + assert_eq!(rest.last(), Some(&Event::Exited(None))); + // The background sleep held stdout open too: it ended with the group. + assert!(started.elapsed() < std::time::Duration::from_secs(10)); + } +} diff --git a/launcher/src/repo.rs b/launcher/src/repo.rs new file mode 100644 index 0000000000..39e86a9af1 --- /dev/null +++ b/launcher/src/repo.rs @@ -0,0 +1,126 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Finding the Leonida repository the launcher runs from, and what it says of the game. + +use std::fs; +use std::path::{Path, PathBuf}; + +/// The file that marks the repository's root. +pub const MARKER: &str = "make_game.py"; + +/// The game's executable when no manifest says otherwise (`game/xbox-1.0.2.1.json`'s +/// `expected_exe`). +pub const DEFAULT_EXE: &str = "game_scarlett_master.exe"; + +/// The repository: `--repo PATH` if given (it must hold `make_game.py`), or the first folder +/// holding it walking up from the launcher's own executable, then from the current folder. +pub fn find( + given: Option<&Path>, + exe: Option<&Path>, + cwd: Option<&Path>, +) -> Result<PathBuf, String> { + if let Some(given) = given { + return if given.join(MARKER).is_file() { + Ok(given.to_path_buf()) + } else { + Err(format!("--repo {}: no {MARKER} there", given.display())) + }; + } + exe.and_then(Path::parent) + .and_then(walk_up) + .or_else(|| cwd.and_then(walk_up)) + .ok_or_else(|| { + format!( + "no Leonida repository found above the launcher or the current folder: run it \ + from inside one, or pass --repo PATH (the folder that holds {MARKER})" + ) + }) +} + +/// The first folder from `start` up that holds `make_game.py`. +fn walk_up(start: &Path) -> Option<PathBuf> { + start + .ancestors() + .find(|folder| folder.join(MARKER).is_file()) + .map(Path::to_path_buf) +} + +/// The executable the loader runs, from the repository's version manifests (`game/*.json`, +/// each with an `expected_exe`); the 1.0.2.1 name if none says. +pub fn expected_exe(repo: &Path) -> String { + let Ok(entries) = fs::read_dir(repo.join("game")) else { + return DEFAULT_EXE.to_owned(); + }; + let mut manifests: Vec<PathBuf> = entries + .filter_map(Result::ok) + .map(|entry| entry.path()) + .filter(|path| { + path.extension() + .is_some_and(|extension| extension == "json") + }) + .collect(); + manifests.sort(); + manifests + .iter() + .rev() + .find_map(|manifest| { + let text = fs::read_to_string(manifest).ok()?; + let value: serde_json::Value = serde_json::from_str(&text).ok()?; + value.get("expected_exe")?.as_str().map(str::to_owned) + }) + .unwrap_or_else(|| DEFAULT_EXE.to_owned()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tree(name: &str) -> PathBuf { + let root = std::env::temp_dir().join(format!( + "leonida-launcher-repo-{}-{name}", + std::process::id() + )); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(root.join("launcher/target/release")).unwrap(); + fs::write(root.join(MARKER), "").unwrap(); + root + } + + #[test] + fn the_repository_is_found_above_the_executable() { + let root = tree("exe"); + let exe = root.join("launcher/target/release/leonida-launcher"); + assert_eq!(find(None, Some(&exe), None), Ok(root.clone())); + // Not above the executable: from the current folder. + let elsewhere = std::env::temp_dir().join("leonida-launcher-nowhere/bin/x"); + let cwd = root.join("launcher"); + assert_eq!(find(None, Some(&elsewhere), Some(&cwd)), Ok(root.clone())); + let _ = fs::remove_dir_all(root); + } + + #[test] + fn repo_given_must_hold_make_game() { + let root = tree("given"); + assert_eq!(find(Some(&root), None, None), Ok(root.clone())); + let wrong = root.join("launcher"); + let error = find(Some(&wrong), None, None).unwrap_err(); + assert!(error.contains("no make_game.py"), "{error}"); + let none = find(None, None, None).unwrap_err(); + assert!(none.contains("--repo")); + let _ = fs::remove_dir_all(root); + } + + #[test] + fn the_executable_comes_from_the_manifest() { + let root = tree("manifest"); + assert_eq!(expected_exe(&root), DEFAULT_EXE); + fs::create_dir_all(root.join("game")).unwrap(); + fs::write( + root.join("game/xbox-9.json"), + "{\"title\": \"t\", \"expected_exe\": \"other.exe\", \"files\": {}}", + ) + .unwrap(); + assert_eq!(expected_exe(&root), "other.exe"); + let _ = fs::remove_dir_all(root); + } +} diff --git a/launcher/src/scene.rs b/launcher/src/scene.rs new file mode 100644 index 0000000000..e697315306 --- /dev/null +++ b/launcher/src/scene.rs @@ -0,0 +1,824 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! The Play page's background: a dusk (dark) or a morning (light) over water, in the theme's +//! gradient, with a shore and two palms in silhouette, generated on the CPU into one RGBA picture +//! of the page's size. Nothing of it is an image file: a theme's colours go in, pixels come out. +//! +//! The scene lives in a 16:10 frame, its horizon at 0.66 of its height and its sun at 0.805 of +//! its width, and covers the page anchored to the page's bottom right. The picture is the scene +//! alone: the window lays its veil over it ([`veil`]), a linear gradient of the +//! page's background from the top left to the bottom right, sized to the page as it is drawn. +//! +//! [`generate`] is a pure function: the same input gives the same bytes. It's slow enough (tens +//! of milliseconds) that the window runs it off its thread, once per size, scale, theme and +//! mode, and shows the cached picture. + +use tiny_skia::{FillRule, Mask, Path, PathBuilder, Stroke, Transform}; + +use crate::ui::tokens::{Color, Palette}; + +/// The scene's frame: 16:10. +pub const ASPECT: f32 = 16.0 / 10.0; +/// The horizon, from the frame's top, as a share of its height. +pub const HORIZON: f32 = 0.66; +/// The sun's centre, as a share of the frame's width. +pub const SUN_X: f32 = 0.805; +/// The sun's radius, as a share of the frame's height. +const SUN_RADIUS: f32 = 0.112; + +/// What the scene takes from a theme. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Colors { + pub dark: bool, + /// The page's background. + pub bg: Color, + /// The theme's gradient, top to bottom: blue, violet, magenta, pink, coral, orange in Sunset. + pub gradient: [Color; 6], + /// The theme's outline color (clouds at dusk, the morning's silhouettes). + pub outline: Color, + /// The theme's deepest color (the dusk's silhouettes). + pub shadow: Color, +} + +impl Colors { + /// A palette's. + pub fn of(palette: &Palette) -> Self { + Self { + dark: palette.mode == crate::ui::tokens::Mode::Dark, + bg: palette.surface(crate::ui::tokens::Surface::Bg), + gradient: palette.gradient(), + outline: palette.outline(), + shadow: palette.shadow(), + } + } +} + +/// Everything a picture depends on. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Input { + pub colors: Colors, + /// The page, in physical pixels. + pub width: u32, + pub height: u32, + /// Physical pixels to a logical one. + pub scale: f32, + /// The window's rounded corner at the page's bottom right, its radius in logical pixels, if + /// the window floats with drawn corners: the picture is clear outside it. + pub corner: Option<f32>, +} + +/// A generated picture: RGBA8, `width` by `height`, straight alpha. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Picture { + pub width: u32, + pub height: u32, + pub rgba: Vec<u8>, +} + +type Rgb = [f32; 3]; + +/// Points of a polygon or a line. +type Points = Vec<(f32, f32)>; + +fn srgb(color: Color) -> Rgb { + color.rgb8().map(|c| f32::from(c) / 255.0) +} + +fn to_linear(c: f32) -> f32 { + if c <= 0.04045 { + c / 12.92 + } else { + ((c + 0.055) / 1.055).powf(2.4) + } +} + +fn to_srgb(c: f32) -> f32 { + let c = c.clamp(0.0, 1.0); + if c <= 0.003_130_8 { + c * 12.92 + } else { + 1.055 * c.powf(1.0 / 2.4) - 0.055 + } +} + +fn lin(c: Rgb) -> Rgb { + c.map(to_linear) +} + +fn oklab(c: Rgb) -> Rgb { + let l = (0.412_221_47 * c[0] + 0.536_332_54 * c[1] + 0.051_445_99 * c[2]).cbrt(); + let m = (0.211_903_5 * c[0] + 0.680_699_5 * c[1] + 0.107_396_96 * c[2]).cbrt(); + let s = (0.088_302_46 * c[0] + 0.281_718_85 * c[1] + 0.629_978_7 * c[2]).cbrt(); + [ + 0.210_454_26 * l + 0.793_617_8 * m - 0.004_072_047 * s, + 1.977_998_5 * l - 2.428_592_2 * m + 0.450_593_7 * s, + 0.025_904_037 * l + 0.782_771_77 * m - 0.808_675_77 * s, + ] +} + +fn from_oklab(c: Rgb) -> Rgb { + let l = (c[0] + 0.396_337_78 * c[1] + 0.215_803_76 * c[2]).powi(3); + let m = (c[0] - 0.105_561_346 * c[1] - 0.063_854_17 * c[2]).powi(3); + let s = (c[0] - 0.089_484_18 * c[1] - 1.291_485_5 * c[2]).powi(3); + [ + 4.076_741_7 * l - 3.307_711_6 * m + 0.230_969_94 * s, + -1.268_438 * l + 2.609_757_4 * m - 0.341_319_38 * s, + -0.004_196_086_3 * l - 0.703_418_6 * m + 1.707_614_7 * s, + ] +} + +fn lerp3(a: Rgb, b: Rgb, t: f32) -> Rgb { + [ + a[0] + (b[0] - a[0]) * t, + a[1] + (b[1] - a[1]) * t, + a[2] + (b[2] - a[2]) * t, + ] +} + +/// Between two sRGB colours, in OKLab; the result is sRGB. +fn mix(a: Rgb, b: Rgb, t: f32) -> Rgb { + from_oklab(lerp3(oklab(lin(a)), oklab(lin(b)), t)).map(to_srgb) +} + +fn smoothstep(a: f32, b: f32, x: f32) -> f32 { + let t = ((x - a) / (b - a)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +fn add(a: &mut Rgb, b: Rgb, k: f32) { + for (a, b) in a.iter_mut().zip(b) { + *a += b * k; + } +} + +fn blend(a: &mut Rgb, b: Rgb, k: f32) { + for (a, b) in a.iter_mut().zip(b) { + *a += (b - *a) * k; + } +} + +/// A colour ramp along stops, in OKLab, sampled into a table of linear RGB. +struct Ramp { + table: Vec<Rgb>, +} + +impl Ramp { + const STEPS: usize = 1024; + + fn new(stops: &[(f32, Rgb)]) -> Self { + let labs: Vec<(f32, Rgb)> = stops.iter().map(|(p, c)| (*p, oklab(lin(*c)))).collect(); + let table = (0..=Self::STEPS) + .map(|i| { + let t = i as f32 / Self::STEPS as f32; + let at = labs + .windows(2) + .position(|pair| t <= pair[1].0) + .unwrap_or(labs.len() - 2); + let ((p0, c0), (p1, c1)) = (labs[at], labs[at + 1]); + let k = ((t - p0) / (p1 - p0).max(1e-6)).clamp(0.0, 1.0); + from_oklab(lerp3(c0, c1, k)) + }) + .collect(); + Self { table } + } + + fn at(&self, t: f32) -> Rgb { + self.table[(t.clamp(0.0, 1.0) * Self::STEPS as f32).round() as usize] + } +} + +/// A small, fixed sequence of numbers in 0..1, the same on every machine. +struct Sequence(u32); + +impl Sequence { + fn next(&mut self) -> f32 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 17; + self.0 ^= self.0 << 5; + (self.0 >> 8) as f32 / 16_777_216.0 + } + + fn between(&mut self, low: f32, high: f32) -> f32 { + low + (high - low) * self.next() + } +} + +/// A pixel's noise, from its place and channel alone: -1..1, triangular, against banding. +fn dither(x: u32, y: u32, channel: u32) -> f32 { + let hash = |mut h: u32| { + h ^= h >> 16; + h = h.wrapping_mul(0x7feb_352d); + h ^= h >> 15; + h = h.wrapping_mul(0x846c_a68b); + h ^= h >> 16; + h + }; + let seed = x.wrapping_mul(0x9e37_79b1) + ^ y.wrapping_mul(0x85eb_ca77) + ^ channel.wrapping_mul(0xc2b2_ae3d); + let a = hash(seed); + let b = hash(a ^ 0x68e3_1da4); + ((a >> 8) as f32 + (b >> 8) as f32) / 16_777_216.0 - 1.0 +} + +/// The six low clouds: centre x and y, spread x and y (shares of the frame), and opacity. +const CLOUDS: [(f32, f32, f32, f32, f32); 6] = [ + (0.8664, 0.4668, 0.0829, 0.00557, 0.3507), + (0.9621, 0.3525, 0.0918, 0.00858, 0.3141), + (0.6991, 0.3908, 0.0764, 0.00727, 0.2803), + (0.6834, 0.4405, 0.1384, 0.00812, 0.3685), + (0.4609, 0.4701, 0.1242, 0.00926, 0.4078), + (0.4577, 0.5154, 0.0953, 0.00812, 0.3729), +]; + +/// How the scene's frame lies on the page, in physical pixels: the frame's size and where its +/// top left is (at or above and left of the page's), covering the page from its bottom right. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Placement { + pub width: f32, + pub height: f32, + pub left: f32, + pub top: f32, +} + +/// The frame covering a page `width` by `height`, anchored to its bottom right. +pub fn placement(width: f32, height: f32) -> Placement { + let frame_width = width.max(height * ASPECT); + let frame_height = frame_width / ASPECT; + Placement { + width: frame_width, + height: frame_height, + left: width - frame_width, + top: height - frame_height, + } +} + +/// The sun's centre on the page, in physical pixels. +pub fn sun(width: f32, height: f32) -> (f32, f32) { + let frame = placement(width, height); + ( + frame.left + SUN_X * frame.width, + frame.top + HORIZON * frame.height, + ) +} + +/// The palms' and the shore's coverage of the page, 0..255 a pixel. +fn silhouettes(frame: &Placement, width: u32, height: u32) -> Option<Mask> { + let mut mask = Mask::new(width, height)?; + let to_page = Transform::from_row(frame.width, 0.0, 0.0, frame.height, frame.left, frame.top); + // The frame's x and y in shares of its width and height; lengths in shares of its width. + let aspect = ASPECT; + let mut fill = |path: Option<Path>| { + if let Some(path) = path { + mask.fill_path(&path, FillRule::Winding, true, to_page); + } + }; + // The shore: a low rise from the middle to the right. + let mut shore = PathBuilder::new(); + shore.move_to(0.40, 1.0); + for i in 0..=160 { + let x = 0.40 + 0.60 * i as f32 / 160.0; + let y = 1.0 + - 0.118 * smoothstep(0.40, 1.0, x).powf(1.25) + - 0.006 * (i as f32 * 0.11).sin() * smoothstep(0.45, 0.6, x); + shore.line_to(x, y); + } + shore.line_to(1.0, 1.0); + shore.close(); + fill(shore.finish()); + let mut sequence = Sequence(0x2545_f491); + for (base, top, bend, size) in [ + ((0.672, 1.02), (0.632, 0.330), 0.034, 0.118), + ((0.945, 1.02), (0.972, 0.205), -0.028, 0.140), + ] { + for path in palm(base, top, bend, size, aspect, &mut sequence) { + fill(Some(path)); + } + } + Some(mask) +} + +/// A quadratic Bézier's points, `n` of them. +fn bezier(p0: (f32, f32), p1: (f32, f32), p2: (f32, f32), n: usize) -> Vec<(f32, f32)> { + (0..n) + .map(|i| { + let t = i as f32 / (n - 1) as f32; + let u = 1.0 - t; + ( + u * u * p0.0 + 2.0 * u * t * p1.0 + t * t * p2.0, + u * u * p0.1 + 2.0 * u * t * p1.1 + t * t * p2.1, + ) + }) + .collect() +} + +fn polygon(points: &[(f32, f32)]) -> Option<Path> { + let mut path = PathBuilder::new(); + let (first, rest) = points.split_first()?; + path.move_to(first.0, first.1); + for (x, y) in rest { + path.line_to(*x, *y); + } + path.close(); + path.finish() +} + +/// One palm, in frame shares (x of the width, y of the height; `size` and `bend` of the width): +/// a tapering, curved trunk, three coconuts and a crown of arching fronds. +fn palm( + base: (f32, f32), + top: (f32, f32), + bend: f32, + size: f32, + aspect: f32, + sequence: &mut Sequence, +) -> Vec<Path> { + // Work in a square space (both axes in shares of the width), then scale y back. + let square = |(x, y): (f32, f32)| (x, y / aspect); + let (base, top) = (square(base), square(top)); + let control = ((base.0 + top.0) / 2.0 + bend, (base.1 + top.1) / 2.0); + let trunk = bezier(base, control, top, 48); + let widths: Vec<f32> = (0..48) + .map(|i| (0.085 * (1.0 - i as f32 / 47.0).powf(1.6) + 0.046) * size) + .collect(); + let mut outline: Vec<(f32, f32)> = trunk + .iter() + .zip(&widths) + .map(|((x, y), w)| (x - w / 2.0, *y)) + .collect(); + outline.extend( + trunk + .iter() + .zip(&widths) + .rev() + .map(|((x, y), w)| (x + w / 2.0, *y)), + ); + let back = |points: Vec<(f32, f32)>| -> Vec<(f32, f32)> { + points.into_iter().map(|(x, y)| (x, y * aspect)).collect() + }; + let mut paths: Vec<Path> = polygon(&back(outline)).into_iter().collect(); + for (ox, oy, r) in [ + (-0.045, 0.050, 0.034), + (0.030, 0.062, 0.036), + (0.0, 0.085, 0.030), + ] { + let (cx, cy) = (top.0 + ox * size, top.1 + oy * size); + let points: Vec<(f32, f32)> = (0..24) + .map(|i| { + let a = std::f32::consts::TAU * i as f32 / 24.0; + (cx + a.cos() * r * size, cy + a.sin() * r * size) + }) + .collect(); + paths.extend(polygon(&back(points))); + } + for degrees in [ + -198.0_f32, -170.0, -143.0, -116.0, -90.0, -64.0, -37.0, -10.0, 18.0, + ] { + let angle = (degrees + sequence.between(-7.0, 7.0)).to_radians(); + let flat = angle.cos().abs(); + let length = size * sequence.between(0.86, 1.06) * (0.74 + 0.30 * flat); + let hang = 0.16 + 0.34 * flat + if angle.sin() > 0.0 { 0.20 } else { 0.0 }; + let droop = hang + sequence.between(-0.04, 0.05); + let (feather, rib) = frond(top, angle, length, droop); + paths.extend(polygon(&back(feather))); + let mut midrib = PathBuilder::new(); + let rib = back(rib); + midrib.move_to(rib[0].0, rib[0].1); + for (x, y) in &rib[1..] { + midrib.line_to(*x, *y); + } + if let Some(line) = midrib.finish() { + // The midrib, stroked in the frame's square space: its width is a share of the width, + // scaled back as the rest. Stroked in shares, which the page's transform scales. + let stroke = Stroke { + width: length * 0.011, + ..Stroke::default() + }; + paths.extend(line.stroke(&stroke, 1.0)); + } + } + paths +} + +/// One frond: a feather (an arching midrib with a saw-toothed edge either side for the +/// leaflets, the lower ones hanging) and its midrib, in the square space. +fn frond(crown: (f32, f32), angle: f32, length: f32, droop: f32) -> (Points, Points) { + let (dx, dy) = (angle.cos(), angle.sin()); + let tip = ( + crown.0 + dx * length, + crown.1 + dy * length * 0.62 + droop * length, + ); + let control = ( + crown.0 + dx * length * 0.50, + crown.1 + dy * length * 0.95 - 0.16 * length, + ); + let rib = bezier(crown, control, tip, 44); + let last = rib.len() - 1; + let mut upper = Vec::with_capacity(rib.len()); + let mut lower = Vec::with_capacity(rib.len()); + for (i, (x, y)) in rib.iter().enumerate() { + let t = i as f32 / last as f32; + let (a, b) = (rib[i.saturating_sub(1)], rib[(i + 1).min(last)]); + let (mut tx, mut ty) = (b.0 - a.0, b.1 - a.1); + let norm = tx.hypot(ty).max(1e-9); + (tx, ty) = (tx / norm, ty / norm); + // The normal that points up (smaller y). + let (nx, ny) = if -tx <= 0.0 { (ty, -tx) } else { (-ty, tx) }; + let envelope = (std::f32::consts::PI * (t.powf(0.85) * 1.04).min(1.0)) + .sin() + .max(0.0) + .powf(0.75) + * (1.0 - 0.25 * t); + let jag = if i % 2 == 0 { 1.0 } else { 0.34 }; + let wu = 0.082 * length * envelope * jag; + let wl = 0.118 * length * envelope * jag; + upper.push((x + nx * wu + tx * wu * 0.55, y + ny * wu + ty * wu * 0.55)); + lower.push(( + x - nx * wl + tx * wl * 0.55, + y - ny * wl + ty * wl * 0.55 + wl * 0.45, + )); + } + upper.extend(lower.into_iter().rev()); + (upper, rib) +} + +/// The picture for `input`, or none if the page is too narrow for a scene. +pub fn generate(input: &Input) -> Option<Picture> { + let (width, height) = (input.width, input.height); + if width == 0 || height == 0 || input.scale <= 0.0 { + return None; + } + let colors = &input.colors; + let dark = colors.dark; + let white = [1.0, 1.0, 1.0]; + let bg = srgb(colors.bg); + let [blue, violet, magenta, pink, coral, orange] = colors.gradient.map(srgb); + let outline = srgb(colors.outline); + let sky = Ramp::new(&if dark { + [ + (0.00, bg), + (0.18, mix(blue, bg, 0.66)), + (0.40, mix(violet, bg, 0.36)), + (0.62, mix(magenta, bg, 0.14)), + (0.80, pink), + (0.92, coral), + (1.00, orange), + ] + } else { + [ + (0.00, bg), + (0.22, mix(blue, white, 0.80)), + (0.44, mix(violet, white, 0.74)), + (0.64, mix(magenta, white, 0.68)), + (0.82, mix(pink, white, 0.58)), + (0.93, mix(coral, white, 0.50)), + (1.00, mix(orange, white, 0.42)), + ] + }); + let (sun_top, sun_bottom) = if dark { + (lin(mix(orange, white, 0.72)), lin(mix(coral, orange, 0.35))) + } else { + (lin(white), lin(mix(orange, white, 0.62))) + }; + let silhouette = lin(if dark { + mix(srgb(colors.shadow), [0.0; 3], 0.35) + } else { + mix(outline, bg, 0.34) + }); + let silhouette_alpha = if dark { 1.0 } else { 0.88 }; + let warm = lin(mix(coral, orange, 0.6)); + let far_color = lin(magenta); + let cloud = lin(mix(outline, magenta, 0.30)); + let pink_light = lin(pink); + let streak_color = lin(mix(orange, white, if dark { 0.38 } else { 0.8 })); + let line_color = lin(mix(orange, white, 0.5)); + let water = lin(if dark { bg } else { mix(bg, blue, 0.10) }); + let (glow_amount, streak_amount) = if dark { (0.50, 1.25) } else { (0.30, 0.80) }; + + let frame = placement(width as f32, height as f32); + let mask = silhouettes(&frame, width, height)?; + let coverage = mask.data(); + + // The reflection's per-row gain: smoothed noise along the frame's height. + let rows = frame.height.ceil() as usize + 3; + let mut sequence = Sequence(0x9e37_79b9); + let raw: Vec<f32> = (0..rows).map(|_| sequence.next()).collect(); + let row_gain = |row: usize| -> f32 { + let at = row.min(rows - 3); + ((raw[at] + raw[at + 1] + raw[at + 2]) / 3.0).powi(2) + }; + let encode: Vec<f32> = (0..=4096).map(|i| to_srgb(i as f32 / 4096.0)).collect(); + let encode = |c: f32| encode[(c.clamp(0.0, 1.0) * 4096.0) as usize]; + let corner = input.corner.map(|radius| radius * input.scale); + + let mut rgba = vec![0u8; width as usize * height as usize * 4]; + for y in 0..height { + let frame_y = y as f32 + 0.5 - frame.top; + let fy = frame_y / frame.height; + let above = fy < HORIZON; + let depth = ((fy - HORIZON) / (1.0 - HORIZON)).clamp(0.0, 1.0); + let base = if above { + sky.at(fy / HORIZON) + } else { + let mut c = sky.at(1.0 - 0.55 * depth.powf(0.75)); + blend(&mut c, water, 0.30 + 0.62 * depth.powf(0.6)); + c + }; + let near = if above { + (fy / HORIZON).clamp(0.0, 1.0).powf(2.2) + } else { + 0.45 + }; + let dy = fy - HORIZON; + let line_y = (-(dy / 0.0016).powi(2)).exp(); + let streak_width = 0.034 + 0.17 * depth; + let streak_y = if above { + 0.0 + } else { + (1.0 - depth).powf(1.3) * row_gain(frame_y.max(0.0) as usize) * streak_amount + }; + let clouds: Vec<_> = CLOUDS + .iter() + .filter(|cloud| (fy - cloud.1).abs() < 4.0 * cloud.3 + 0.01) + .collect(); + let row = y as usize * width as usize; + for x in 0..width { + let fx = (x as f32 + 0.5 - frame.left) / frame.width; + let dx = (fx - SUN_X) * ASPECT; + let r = (dx * dx + dy * dy).sqrt(); + let mut c = base; + let glow = (-(r / 0.36).powf(1.5)).exp() * glow_amount * near; + if dark { + let far = smoothstep(0.08, 0.42, r); + add(&mut c, lerp3(warm, far_color, far), glow); + } else { + add(&mut c, white, glow); + } + for &&(cx, cy, sx, sy, amount) in &clouds { + let ex = ((fx - cx) / sx).powi(2); + let m = (-(ex + ((fy - cy) / sy).powi(2))).exp() * amount; + if dark { + let ly = (fy - cy - sy * 1.2) / (sy * 0.6); + blend(&mut c, cloud, m); + add(&mut c, pink_light, (-(ex + ly * ly)).exp() * 0.16); + } else { + blend(&mut c, white, m * 0.8); + } + } + if above && r < SUN_RADIUS + 0.003 { + let disc = smoothstep(SUN_RADIUS + 0.0022, SUN_RADIUS - 0.0022, r); + let k = ((HORIZON - fy) / SUN_RADIUS).clamp(0.0, 1.0).powf(0.8); + blend(&mut c, lerp3(sun_bottom, sun_top, k), disc); + } + if streak_y > 0.0 { + add( + &mut c, + streak_color, + (-(dx / streak_width).powi(2)).exp() * streak_y, + ); + } + if line_y > 0.001 { + add( + &mut c, + line_color, + line_y * (-(dx / 0.60).powi(2)).exp() * 0.55, + ); + } + let a = f32::from(coverage[row + x as usize]) / 255.0 * silhouette_alpha; + if a > 0.0 { + blend(&mut c, silhouette, a); + } + let s = c.map(encode); + let at = (row + x as usize) * 4; + for (channel, value) in s.iter().enumerate() { + let noise = dither(x, y, channel as u32) * 0.9 / 255.0; + rgba[at + channel] = ((value + noise).clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + } + rgba[at + 3] = 255; + } + } + if let Some(radius) = corner { + clear_corner(&mut rgba, width, height, radius); + } + Some(Picture { + width, + height, + rgba, + }) +} + +/// Clears what lies outside a rounded bottom-right corner of `radius` physical pixels, +/// antialiased. +fn clear_corner(rgba: &mut [u8], width: u32, height: u32, radius: f32) { + let reach = radius.ceil() as u32 + 1; + let (cx, cy) = (width as f32 - radius, height as f32 - radius); + for y in height.saturating_sub(reach)..height { + for x in width.saturating_sub(reach)..width { + let (px, py) = (x as f32 + 0.5, y as f32 + 0.5); + if px < cx || py < cy { + continue; + } + let distance = ((px - cx).powi(2) + (py - cy).powi(2)).sqrt() - radius; + let coverage = (0.5 - distance).clamp(0.0, 1.0); + let at = ((y * width + x) * 4 + 3) as usize; + rgba[at] = (f32::from(rgba[at]) * coverage).round() as u8; + } + } +} + +/// The veil over the scene: the page's background at [`VEIL`], held from the top left to +/// [`VEIL_FROM`] of the way to the bottom right, then thinning on a straight line to nothing at +/// the bottom right corner, the bend between the two rounded over [`VEIL_KNEE`]. "The way" is +/// across and down at once, in shares of the page: the window stretches the picture over the +/// page as it is drawn, so it fits any size at once. +pub const VEIL: f32 = 0.85; +pub const VEIL_FROM: f32 = 0.35; +pub const VEIL_KNEE: f32 = 0.10; +/// The veil's picture is this many pixels square; stretched, it stays smooth. +pub const VEIL_SIZE: u32 = 512; + +/// The veil's opacity `along` the way from the top left (0) to the bottom right (1). +pub fn veil_at(along: f32) -> f32 { + let s = (along - VEIL_FROM) / (1.0 - VEIL_FROM); + let k = VEIL_KNEE / (1.0 - VEIL_FROM); + // Linear past the knee; a parabola through it, meeting the hold and the line at their slopes. + let thinned = if s <= -k { + 0.0 + } else if s < k { + (s + k) * (s + k) / (4.0 * k) + } else { + s + }; + VEIL * (1.0 - thinned.min(1.0)) +} + +/// The veil's picture over a page whose background is `bg`: [`VEIL_SIZE`] square, dithered. +pub fn veil(bg: Color) -> Picture { + let size = VEIL_SIZE; + let mut rgba = Vec::with_capacity((size * size * 4) as usize); + let [r, g, b] = bg.rgb8(); + for y in 0..size { + for x in 0..size { + let across = (x as f32 + 0.5) / size as f32; + let down = (y as f32 + 0.5) / size as f32; + let alpha = veil_at((across + down) / 2.0) * 255.0 + dither(x, y, 3) * 0.9; + rgba.extend_from_slice(&[r, g, b, alpha.round().clamp(0.0, 255.0) as u8]); + } + } + Picture { + width: size, + height: size, + rgba, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ui::tokens::{Mode, Palette}; + + fn input(palette: &Palette, size: (u32, u32), scale: f32) -> Input { + Input { + colors: Colors::of(palette), + width: size.0, + height: size.1, + scale, + corner: None, + } + } + + fn pixel(picture: &Picture, x: u32, y: u32) -> Color { + let at = ((y * picture.width + x) * 4) as usize; + let [r, g, b] = [0, 1, 2].map(|c| u32::from(picture.rgba[at + c])); + Color::hex((r << 16) | (g << 8) | b) + } + + #[test] + fn the_same_input_gives_the_same_bytes() { + let input = input(&Palette::SUNSET_LIGHT, (800, 500), 1.0); + assert_eq!(generate(&input), generate(&input)); + } + + #[test] + fn the_theme_decides_the_sky_and_the_modes_differ() { + let dark = input(&Palette::SUNSET_DARK, (1040, 754), 1.0); + let base = generate(&dark).unwrap(); + let mut changed = dark; + changed.colors.gradient[2] = Color::hex(0x00ff00); + let other = generate(&changed).unwrap(); + // The sky at the magenta stop's height, at the right edge, clear of the fade, changes + // with it. + let frame = placement(1040.0, 754.0); + let (x, y) = (1030, (frame.top + 0.62 * HORIZON * frame.height) as u32); + assert_ne!(pixel(&base, x, y), pixel(&other, x, y)); + let light = generate(&input(&Palette::SUNSET_LIGHT, (1040, 754), 1.0)).unwrap(); + assert_ne!(base.rgba, light.rgba); + assert!(!Colors::of(&Palette::SUNSET_LIGHT).dark); + assert_eq!(Palette::SUNSET_DARK.mode, Mode::Dark); + } + + #[test] + fn the_sun_lands_where_the_mapping_says() { + for (width, height) in [(1040_u32, 754_u32), (1600, 500), (700, 800)] { + let palette = Palette::SUNSET_DARK; + let picture = generate(&input(&palette, (width, height), 1.0)).unwrap(); + let frame = placement(width as f32, height as f32); + // Covering: the frame is at least the page, and its bottom right is the page's. + assert!(frame.width >= width as f32 - 0.01 && frame.height >= height as f32 - 0.01); + assert!((frame.left + frame.width - width as f32).abs() < 0.01); + assert!((frame.top + frame.height - height as f32).abs() < 0.01); + let (sx, sy) = sun(width as f32, height as f32); + assert!((sx - (frame.left + 0.805 * frame.width)).abs() < 0.01); + // Just above the horizon at the sun's centre, the disc is bright; well left of the + // disc, at the same height, the sky is darker. + let radius = SUN_RADIUS * frame.height; + let y = (sy - radius * 0.5) as u32; + let disc = pixel(&picture, sx as u32, y).luminance(); + let beside = pixel(&picture, (sx - radius * 2.2).max(0.0) as u32, y).luminance(); + assert!(disc > beside, "{width}x{height}: {disc} <= {beside}"); + } + } + + #[test] + fn silhouettes_are_darker_than_the_sky_beside_them_at_dusk() { + let picture = generate(&input(&Palette::SUNSET_DARK, (1040, 754), 1.0)).unwrap(); + let frame = placement(1040.0, 754.0); + // The right palm's trunk, low down, and the sky a little left of it. + let trunk_x = frame.left + 0.955 * frame.width; + let y = frame.top + 0.62 * frame.height; + let on = pixel(&picture, trunk_x as u32, y as u32).luminance(); + let beside = pixel(&picture, (trunk_x - 0.06 * frame.width) as u32, y as u32).luminance(); + assert!(on < beside, "{on} >= {beside}"); + } + + /// `cargo test --release --lib scene::tests::timing -- --ignored --nocapture` + #[test] + #[ignore = "a measurement, for an optimised build"] + fn timing() { + for (size, scale) in [((1040, 754), 1.0), ((2320, 1394), 2.0)] { + for palette in Palette::ALL { + let input = input(&palette, size, scale); + let _ = generate(&input); + let start = std::time::Instant::now(); + let runs = 5; + for _ in 0..runs { + let _ = generate(&input); + } + let ms = start.elapsed().as_secs_f64() * 1000.0 / f64::from(runs); + println!("{}x{} {}: {ms:.1} ms", size.0, size.1, palette.name); + } + } + } + + #[test] + fn the_corner_is_clear_outside_its_radius() { + let mut input = input(&Palette::SUNSET_DARK, (900, 600), 1.0); + input.corner = Some(13.0); + let picture = generate(&input).unwrap(); + let alpha = |x: u32, y: u32| picture.rgba[((y * 900 + x) * 4 + 3) as usize]; + assert_eq!(alpha(899, 599), 0); + assert_eq!(alpha(880, 580), 255); + assert_eq!(alpha(0, 0), 255); + } + + #[test] + fn the_veil_holds_then_thins_on_a_straight_line_without_a_step() { + assert_eq!(veil_at(0.0), VEIL); + assert_eq!(veil_at(VEIL_FROM - VEIL_KNEE), VEIL); + assert_eq!(veil_at(1.0), 0.0); + // Past the knee, a straight line: equal steps down. + let from = VEIL_FROM + VEIL_KNEE; + let steps: Vec<f32> = (0..=10) + .map(|i| veil_at(from + (1.0 - from) * i as f32 / 10.0)) + .collect(); + let step = steps[0] - steps[1]; + for pair in steps.windows(2) { + assert!((pair[0] - pair[1] - step).abs() < 1e-5); + } + // Everywhere, falling, and smoothly: no jump between neighbouring pixels of a wide page, + // nor in its slope at the knee. + let n = 4000; + let at: Vec<f32> = (0..=n).map(|i| veil_at(i as f32 / n as f32)).collect(); + let slope = VEIL / (1.0 - VEIL_FROM) / n as f32; + for pair in at.windows(2) { + assert!(pair[1] <= pair[0]); + assert!(pair[0] - pair[1] <= slope * 1.001); + } + } + + #[test] + fn the_veils_picture_is_the_veil_color_at_the_veils_opacity() { + for palette in Palette::ALL { + let bg = palette.veil(); + let picture = veil(bg); + assert_eq!((picture.width, picture.height), (VEIL_SIZE, VEIL_SIZE)); + let pixel = |x: u32, y: u32| { + let at = ((y * VEIL_SIZE + x) * 4) as usize; + &picture.rgba[at..at + 4] + }; + assert_eq!(pixel(0, 0)[..3], bg.rgb8()); + assert!((f32::from(pixel(0, 0)[3]) - VEIL * 255.0).abs() <= 1.5); + assert!(pixel(VEIL_SIZE - 1, VEIL_SIZE - 1)[3] <= 1); + } + } +} diff --git a/launcher/src/state.rs b/launcher/src/state.rs new file mode 100644 index 0000000000..0751f56323 --- /dev/null +++ b/launcher/src/state.rs @@ -0,0 +1,460 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! What the launcher offers, from what exists: the one primary action (Check, Build, Play, or +//! Cancel while something runs), whether it can be taken and why not, the secondary actions, and +//! the status line. Plain logic, from [`Facts`], so the tests cover every state. + +/// What's done or running. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + Check, + Build, + Play, +} + +impl Kind { + /// The button's word. + pub const fn verb(self) -> &'static str { + match self { + Self::Check => "Check", + Self::Build => "Build", + Self::Play => "Play", + } + } + + /// While it runs. + pub const fn running(self) -> &'static str { + match self { + Self::Check => "Checking your copy", + Self::Build => "Building the port", + Self::Play => "The game is running", + } + } +} + +/// An action the window offers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Action { + Run(Kind), + Cancel, +} + +impl Action { + pub const fn label(self) -> &'static str { + match self { + Self::Run(kind) => kind.verb(), + Self::Cancel => "Cancel", + } + } +} + +/// How a finished command ended. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Outcome { + pub kind: Kind, + /// Its exit code; none if it was stopped by a signal, or didn't start. + pub code: Option<i32>, + /// Whether it was cancelled. + pub cancelled: bool, + /// What it said last, or why it didn't start. + pub words: Option<String>, +} + +impl Outcome { + pub fn succeeded(&self) -> bool { + self.code == Some(0) && !self.cancelled + } +} + +/// What exists, as the launcher sees it. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Facts { + /// The package folder, as set; empty if not. + pub package: String, + pub package_exists: bool, + pub output: String, + /// Whether the package set passed a check (this session or saved). + pub checked: bool, + /// Whether the output folder holds the built loader (`gta6rt.exe`, or `gta6rt.sh` on Linux). + pub loader_exists: bool, + /// The loader's file name, for the words. + pub loader: String, + /// Whether the package holds the game's executable, and its name. + pub exe_exists: bool, + pub exe: String, + /// What runs now. + pub running: Option<Kind>, + /// How the last command ended, if one has. + pub last: Option<Outcome>, +} + +/// Why the primary action can't be taken. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Blocked { + NoPackage, + PackageMissing(String), + NoOutput, + /// Built, but the package has no executable: the normal state today. + NotBootable { + exe: String, + }, +} + +impl Blocked { + /// Why, in words for the status line. + pub fn words(&self) -> String { + match self { + Self::NoPackage => { + "Choose your game package folder on the Game files page to begin.".to_owned() + } + Self::PackageMissing(path) => format!("The package folder isn't there: {path}"), + Self::NoOutput => { + "Choose an output folder on the Game files page, then build.".to_owned() + } + Self::NotBootable { exe } => format!( + "Not bootable yet: the loader is built, but {exe} isn't in your package. \ + Today's package doesn't include it, so there is nothing to run yet." + ), + } + } +} + +/// The primary action: what it is, and why it can't be taken, if it can't. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Primary { + pub action: Action, + pub blocked: Option<Blocked>, +} + +impl Primary { + pub fn enabled(&self) -> bool { + self.blocked.is_none() + } +} + +/// The primary action for these facts. +pub fn primary(facts: &Facts) -> Primary { + let blocked = |action, why| Primary { + action, + blocked: Some(why), + }; + let ready = |action| Primary { + action, + blocked: None, + }; + if facts.running.is_some() { + return ready(Action::Cancel); + } + let check = Action::Run(Kind::Check); + let build = Action::Run(Kind::Build); + let play = Action::Run(Kind::Play); + if facts.package.trim().is_empty() { + return blocked(check, Blocked::NoPackage); + } + if !facts.package_exists { + return blocked(check, Blocked::PackageMissing(facts.package.clone())); + } + if facts.loader_exists && facts.exe_exists { + return ready(play); + } + if facts.loader_exists { + return blocked( + play, + Blocked::NotBootable { + exe: facts.exe.clone(), + }, + ); + } + if !facts.checked { + return ready(check); + } + if facts.output.trim().is_empty() { + return blocked(build, Blocked::NoOutput); + } + ready(build) +} + +/// The other actions offered beside the primary one, each with whether it can be taken. +pub fn secondary(facts: &Facts) -> Vec<(Action, bool)> { + if facts.running.is_some() { + return Vec::new(); + } + let package = !facts.package.trim().is_empty() && facts.package_exists; + let output = !facts.output.trim().is_empty(); + match primary(facts).action { + Action::Run(Kind::Check) => Vec::new(), + Action::Run(Kind::Build) => vec![(Action::Run(Kind::Check), package)], + Action::Run(Kind::Play) => vec![ + (Action::Run(Kind::Build), package && output), + (Action::Run(Kind::Check), package), + ], + Action::Cancel => Vec::new(), + } +} + +/// The status line's kind: a status chip's state. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Tone { + Waiting, + Running, + Passed, + Info, + Failed, +} + +/// The status line: its tone, the chip's word, and the line. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StatusLine { + pub tone: Tone, + pub word: &'static str, + pub text: String, +} + +/// The status line for these facts, with what's under way (a stage) while something runs. +pub fn status(facts: &Facts, under_way: Option<&str>) -> StatusLine { + let line = |tone, word, text: String| StatusLine { tone, word, text }; + if let Some(kind) = facts.running { + let text = match under_way { + Some(stage) => format!("{}: {stage}", kind.running()), + None => format!("{}…", kind.running()), + }; + return line(Tone::Running, "Running", text); + } + if let Some(last) = &facts.last { + if last.cancelled { + return line( + Tone::Info, + "Stopped", + format!( + "{} was cancelled. A build continues where it left off next time.", + last.kind.verb() + ), + ); + } + if !last.succeeded() { + let how = match last.code { + Some(code) => format!("exit code {code}"), + None => "it didn't run".to_owned(), + }; + let words = last + .words + .as_deref() + .map(|words| format!(": {words}")) + .unwrap_or_default(); + let what = match last.kind { + Kind::Play => "The loader", + kind => kind.verb(), + }; + return line( + Tone::Failed, + "Failed", + format!("{what} failed ({how}){words}"), + ); + } + } + let primary = primary(facts); + match (&primary.blocked, primary.action) { + (Some(blocked @ Blocked::NotBootable { .. }), _) => { + line(Tone::Info, "Not bootable yet", blocked.words()) + } + (Some(blocked), _) => line(Tone::Waiting, "Setup", blocked.words()), + (None, Action::Run(Kind::Check)) => line( + Tone::Waiting, + "Ready", + "Check your copy of the game before building.".to_owned(), + ), + (None, Action::Run(Kind::Build)) => line( + Tone::Passed, + "Checked", + format!( + "Your copy is checked. Build the port; the loader goes to {}.", + facts.output.trim() + ), + ), + (None, Action::Run(Kind::Play)) => line( + Tone::Passed, + "Ready", + format!("Built, and {} is in your package.", facts.exe), + ), + (None, Action::Cancel) => line(Tone::Running, "Running", String::new()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fresh() -> Facts { + Facts { + loader: "gta6rt.exe".to_owned(), + exe: "game_scarlett_master.exe".to_owned(), + ..Facts::default() + } + } + + fn set_up() -> Facts { + Facts { + package: "D:\\pkg".to_owned(), + package_exists: true, + output: "D:\\out".to_owned(), + ..fresh() + } + } + + #[test] + fn nothing_set_asks_for_the_package() { + let facts = fresh(); + let primary = primary(&facts); + assert_eq!(primary.action, Action::Run(Kind::Check)); + assert_eq!(primary.blocked, Some(Blocked::NoPackage)); + assert!(!primary.enabled()); + let status = status(&facts, None); + assert_eq!(status.tone, Tone::Waiting); + assert!(status.text.contains("package folder")); + // It names a page the window has. + assert!(status.text.contains("Game files")); + assert!(secondary(&facts).is_empty()); + } + + #[test] + fn a_missing_package_folder_says_so() { + let facts = Facts { + package_exists: false, + ..set_up() + }; + assert_eq!( + primary(&facts).blocked, + Some(Blocked::PackageMissing("D:\\pkg".to_owned())) + ); + } + + #[test] + fn a_package_not_yet_checked_is_checked_first() { + let facts = set_up(); + assert_eq!( + primary(&facts), + Primary { + action: Action::Run(Kind::Check), + blocked: None + } + ); + } + + #[test] + fn a_checked_copy_builds_once_there_is_an_output_folder() { + let checked = Facts { + checked: true, + ..set_up() + }; + assert_eq!(primary(&checked).action, Action::Run(Kind::Build)); + assert!(primary(&checked).enabled()); + assert_eq!(secondary(&checked), vec![(Action::Run(Kind::Check), true)]); + assert_eq!(status(&checked, None).tone, Tone::Passed); + let no_output = Facts { + output: String::new(), + ..checked + }; + assert_eq!(primary(&no_output).blocked, Some(Blocked::NoOutput)); + } + + #[test] + fn built_without_the_executable_is_not_bootable_yet_and_reads_as_an_explanation() { + let facts = Facts { + checked: true, + loader_exists: true, + ..set_up() + }; + let primary = primary(&facts); + assert_eq!(primary.action, Action::Run(Kind::Play)); + assert!(!primary.enabled()); + let status = status(&facts, None); + assert_eq!((status.tone, status.word), (Tone::Info, "Not bootable yet")); + assert!( + status + .text + .contains("game_scarlett_master.exe isn't in your package") + ); + assert!(!status.text.to_lowercase().contains("error")); + // Building again and checking stay offered. + assert_eq!( + secondary(&facts), + vec![ + (Action::Run(Kind::Build), true), + (Action::Run(Kind::Check), true) + ] + ); + } + + #[test] + fn built_with_the_executable_plays() { + let facts = Facts { + loader_exists: true, + exe_exists: true, + ..set_up() + }; + assert_eq!(primary(&facts).action, Action::Run(Kind::Play)); + assert!(primary(&facts).enabled()); + assert_eq!(status(&facts, None).tone, Tone::Passed); + } + + #[test] + fn while_running_the_one_action_is_cancel() { + let facts = Facts { + running: Some(Kind::Build), + ..set_up() + }; + assert_eq!(primary(&facts).action, Action::Cancel); + assert!(primary(&facts).enabled()); + assert!(secondary(&facts).is_empty()); + let status = status(&facts, Some("Stage 2 of 5: shaders")); + assert_eq!(status.tone, Tone::Running); + assert_eq!(status.text, "Building the port: Stage 2 of 5: shaders"); + assert_eq!(Action::Cancel.label(), "Cancel"); + } + + #[test] + fn a_failure_shows_its_code_and_last_words_until_the_next_run() { + let facts = Facts { + last: Some(Outcome { + kind: Kind::Build, + code: Some(1), + cancelled: false, + words: Some("3 file(s) missing or different.".to_owned()), + }), + checked: true, + ..set_up() + }; + let line = status(&facts, None); + assert_eq!(line.tone, Tone::Failed); + assert_eq!( + line.text, + "Build failed (exit code 1): 3 file(s) missing or different." + ); + // It can be tried again. + assert!(primary(&facts).enabled()); + let unstarted = Facts { + last: Some(Outcome { + kind: Kind::Play, + code: None, + cancelled: false, + words: Some("gta6rt.sh: not found".to_owned()), + }), + ..set_up() + }; + assert!(status_text(&unstarted).starts_with("The loader failed (it didn't run)")); + let cancelled = Facts { + last: Some(Outcome { + kind: Kind::Build, + code: None, + cancelled: true, + words: None, + }), + ..set_up() + }; + assert_eq!(status(&cancelled, None).word, "Stopped"); + } + + fn status_text(facts: &Facts) -> String { + status(facts, None).text + } +} diff --git a/launcher/src/ui/button.rs b/launcher/src/ui/button.rs new file mode 100644 index 0000000000..d846a45dff --- /dev/null +++ b/launcher/src/ui/button.rs @@ -0,0 +1,448 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Buttons: Next and Back, Install, Erase the disk. + +use std::time::Instant; + +use iced::advanced::layout::{self, Layout}; +use iced::advanced::widget::{Operation, Tree, Widget, tree}; +use iced::advanced::{Clipboard, Shell, mouse, renderer}; +use iced::keyboard::{self, Key, key::Named}; +use iced::{Event, Length, Point, Rectangle, Size, touch}; + +use crate::ui::tokens::{size, space, typography}; + +use crate::ui::focus::Focus; +use crate::ui::input; +use crate::ui::paint::{self, Plain}; +use crate::ui::theme::{Emphasis, Interaction, color}; +use crate::ui::{Element, Renderer, Theme}; + +/// A button with a label. Without a message to send it is disabled. +pub fn button<Message>(label: impl Into<String>) -> Button<Message> { + Button { + label: label.into(), + emphasis: Emphasis::Secondary, + on_press: None, + width: Length::Shrink, + height: size::CONTROL, + role: &typography::INTERFACE, + least: 0.0, + preview: None, + } +} + +/// A button: Enter or Space presses it when it has focus, as a click does. +pub struct Button<Message> { + label: String, + emphasis: Emphasis, + on_press: Option<Message>, + width: Length, + height: f32, + /// Its label's type role. + role: &'static typography::Role, + /// The least it's wide, in logical pixels. + least: f32, + preview: Option<(Interaction, bool)>, +} + +/// A large button's height, and the least it's wide. +pub const LARGE_HEIGHT: f32 = 56.0; +pub const LARGE_LEAST: f32 = 200.0; + +impl<Message> Button<Message> { + /// Large, for the one thing a page is for, such as Play: taller and wider, its label a + /// heading's. + pub fn large(self) -> Self { + Self { + height: LARGE_HEIGHT, + role: &typography::HEADING, + least: LARGE_LEAST, + ..self + } + } + + /// The message it sends when pressed. + pub fn on_press(self, message: Message) -> Self { + Self { + on_press: Some(message), + ..self + } + } + + /// The message it sends, if any; none disables it. + pub fn on_press_maybe(self, message: Option<Message>) -> Self { + Self { + on_press: message, + ..self + } + } + + /// How much it stands out: secondary unless set ([`Button::primary`], [`Button::danger`]). + pub fn emphasis(self, emphasis: Emphasis) -> Self { + Self { emphasis, ..self } + } + + /// The step forward: Next, Install. + pub fn primary(self) -> Self { + self.emphasis(Emphasis::Primary) + } + + /// What can't be undone. + pub fn danger(self) -> Self { + self.emphasis(Emphasis::Danger) + } + + /// Its width: as wide as its words unless set. + pub fn width(self, width: impl Into<Length>) -> Self { + Self { + width: width.into(), + ..self + } + } + + /// Draws it as if in this state, whatever the pointer and focus do: for the gallery. + pub fn preview(self, interaction: Interaction, focused: bool) -> Self { + Self { + preview: Some((interaction, focused)), + ..self + } + } +} + +#[derive(Default)] +struct State { + focus: Focus, + pressed: bool, + label: Plain, + drawn: Option<(Interaction, bool)>, + /// Its glow under the pointer, fading in and out. + lit: crate::ui::transition::Lit, + /// Its focus ring's glow, fading in and out with keyboard focus. + focus_lit: crate::ui::transition::Lit, + /// Which button the state is: iced keeps a widget's state for whatever widget of its kind + /// comes where it was, such as the Erase a wizard's next page puts where Next was. + whose: Option<(Emphasis, String)>, + /// When it came, as this button, or last fired, if it's a danger button. + came: Option<Instant>, + /// It fired, and the view hasn't been built again since: a second press in the same batch of + /// events (a double-click while a frame was slow) doesn't fire it again. + fired: bool, +} + +/// How long a danger button takes no press from the pointer after it comes: a double-click on +/// Next, the second click landing on the Erase the next page puts there, presses nothing. +const DANGER_SETTLES: std::time::Duration = std::time::Duration::from_millis(500); + +impl<Message: Clone> Button<Message> { + /// It fired: not again until the view is built again; and a danger button lets go of focus + /// and settles again, so a second Enter or click can't do what can't be undone twice, as + /// when the next dialog asks the same of another disk. + fn fired(&self, state: &mut State) { + state.fired = true; + // A press under way when Enter or Space fired it doesn't fire it again as it's released. + state.pressed = false; + if self.emphasis == Emphasis::Danger { + state.focus.unfocus(); + state.came = Some(Instant::now()); + } + } + + fn interaction(&self, state: &State, over: bool) -> Interaction { + if self.on_press.is_none() { + Interaction::Disabled + } else if state.pressed { + Interaction::Pressed + } else if over { + Interaction::Hovered + } else { + Interaction::Idle + } + } +} + +impl<Message: Clone> Widget<Message, Theme, Renderer> for Button<Message> { + fn tag(&self) -> tree::Tag { + tree::Tag::of::<State>() + } + + /// Made, it knows whose state it is, and when it came: iced makes a widget's state without + /// calling [`diff`](Widget::diff), and builds the view again only after a message. + fn state(&self) -> tree::State { + tree::State::new(State { + whose: Some((self.emphasis, self.label.clone())), + came: Some(Instant::now()), + ..State::default() + }) + } + + /// A danger button where another button was doesn't get its focus or a press it had under + /// way, and takes no pointer press for a moment, even where another danger button was: the + /// Enter or the click that pressed what was there can't press it too. Any other button keeps + /// them as its words change, as Connect becoming Connecting does. + fn diff(&self, tree: &mut Tree) { + let state = tree.state.downcast_mut::<State>(); + state.fired = false; + let same = state + .whose + .as_ref() + .is_some_and(|(emphasis, label)| *emphasis == self.emphasis && *label == self.label); + if same { + return; + } + if self.emphasis == Emphasis::Danger { + state.focus.unfocus(); + state.pressed = false; + state.came = Some(Instant::now()); + } + state.whose = Some((self.emphasis, self.label.clone())); + } + + fn size(&self) -> Size<Length> { + Size::new(self.width, Length::Shrink) + } + + fn layout( + &mut self, + tree: &mut Tree, + _renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + let state = tree.state.downcast_mut::<State>(); + paint::shape(&mut state.label, self.role, &self.label); + let width = (state.label.min_width().ceil() + 2.0 * space::XL).max(self.least); + let size = limits.resolve(self.width, Length::Shrink, Size::new(width, self.height)); + layout::Node::new(Size::new(size.width, self.height)) + } + + fn operate( + &mut self, + tree: &mut Tree, + layout: Layout<'_>, + _renderer: &Renderer, + operation: &mut dyn Operation, + ) { + if self.on_press.is_some() && self.preview.is_none() { + let state = tree.state.downcast_mut::<State>(); + if self.emphasis == Emphasis::Danger { + operation.custom(None, layout.bounds(), &mut crate::ui::focus::Danger); + } + operation.focusable(None, layout.bounds(), &mut state.focus); + } + } + + fn update( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + _renderer: &Renderer, + _clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + _viewport: &Rectangle, + ) { + // A preview is a picture of a state: it takes no input. + if self.preview.is_some() { + return; + } + let state = tree.state.downcast_mut::<State>(); + state.focus.keep_if(self.on_press.is_some()); + let over = cursor.is_over(layout.bounds()); + if let Some(message) = &self.on_press { + match event { + // A press elsewhere ends one this had under way whose release it never saw, as + // when a dialog coming or going took it: a later release over it isn't a click. + Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerPressed { .. }) + if !over => + { + state.pressed = false; + } + Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerPressed { .. }) + if over => + { + // A danger button just come takes the press, and does nothing with it. + let settling = self.emphasis == Emphasis::Danger + && state + .came + .is_some_and(|came| came.elapsed() < DANGER_SETTLES); + // A press it had under way and never saw end, as when a dialog coming or going + // took the release, doesn't count either. + state.pressed = !settling && !state.fired; + if state.pressed { + state.focus.click(); + } + shell.capture_event(); + } + Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerLifted { .. }) + if state.pressed => + { + state.pressed = false; + if over && !state.fired { + shell.publish(message.clone()); + self.fired(state); + } + shell.capture_event(); + } + Event::Touch(touch::Event::FingerLost { .. }) => state.pressed = false, + // Once a press: a key held down doesn't press it again and again. + Event::Keyboard(keyboard::Event::KeyPressed { + key: Key::Named(Named::Enter | Named::Space), + modifiers, + repeat: false, + .. + }) if state.focus.is_focused() && input::plain(*modifiers) => { + if !state.fired { + state.focus.key(); + shell.publish(message.clone()); + self.fired(state); + } + shell.capture_event(); + } + _ => {} + } + } else { + state.pressed = false; + } + let interaction = self.interaction(state, over); + state.lit.frame(event, shell); + state.focus_lit.frame(event, shell); + state.focus_lit.aim(state.focus.is_shown(), shell); + state.lit.aim( + matches!(interaction, Interaction::Hovered | Interaction::Pressed), + shell, + ); + let now = (interaction, state.focus.is_shown()); + input::redraw_on_change(&mut state.drawn, now, event, shell); + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + _style: &renderer::Style, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + ) { + let state = tree.state.downcast_ref::<State>(); + let bounds = layout.bounds(); + let (interaction, focused) = self.preview.unwrap_or(( + self.interaction(state, cursor.is_over(bounds)), + state.focus.is_shown(), + )); + let mut look = theme.button(self.emphasis, interaction); + if self.preview.is_none() && interaction != Interaction::Disabled { + // The glow fades in and out with the pointer: the hovered or pressed look's, at how + // lit it is. + let lit = if interaction == Interaction::Pressed { + Interaction::Pressed + } else { + Interaction::Hovered + }; + let glow = theme.button(self.emphasis, lit).glow; + look = look.lit(glow, state.lit.share()); + } + paint::boxed(renderer, bounds, &look); + let label = state.label.min_bounds(); + let at = Point::new( + bounds.center_x() - label.width / 2.0, + bounds.center_y() - label.height / 2.0, + ); + // Kept to the button: a label wider than a set width doesn't spill onto its neighbours. + let clip = bounds.intersection(viewport).unwrap_or(bounds); + paint::fill(renderer, &state.label, at, color(look.ink), clip); + // The focus ring fades in and out with keyboard focus, its line and glow together: drawn + // while it's fading out too, after focus has gone. + let ring = if self.preview.is_some() { + f32::from(u8::from(focused)) + } else { + state.focus_lit.share() + }; + paint::outline_lit(renderer, theme, bounds, look.radius, ring); + } + + fn mouse_interaction( + &self, + _tree: &Tree, + layout: Layout<'_>, + cursor: mouse::Cursor, + _viewport: &Rectangle, + _renderer: &Renderer, + ) -> mouse::Interaction { + if self.on_press.is_some() && self.preview.is_none() && cursor.is_over(layout.bounds()) { + mouse::Interaction::Pointer + } else { + mouse::Interaction::default() + } + } +} + +impl<'a, Message: Clone + 'a> From<Button<Message>> for Element<'a, Message> { + fn from(button: Button<Message>) -> Self { + Element::new(button) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use iced::advanced::widget::operation::Focusable; + + fn element(button: Button<()>) -> Element<'static, ()> { + button.into() + } + + fn state(tree: &mut Tree) -> &mut State { + tree.state.downcast_mut::<State>() + } + + #[test] + fn a_danger_button_made_where_another_was_gets_neither_its_focus_nor_its_press() { + // As iced_winit has it: the dialog's buttons made, never diffed, then Continue focused + // and pressed, and the app swaps Erase into its place. + let mut tree = Tree::new(element(button("Continue").primary().on_press(()))); + Focusable::focus(&mut state(&mut tree).focus); + state(&mut tree).pressed = true; + tree.diff(element(button("Erase").danger().on_press(()))); + let erase = state(&mut tree); + assert!(!erase.focus.is_focused()); + assert!(!erase.pressed); + assert!( + erase + .came + .is_some_and(|came| came.elapsed() < DANGER_SETTLES) + ); + } + + #[test] + fn a_danger_button_made_fresh_settles_before_a_click() { + let mut tree = Tree::new(element(button("Erase").danger().on_press(()))); + assert!(state(&mut tree).came.is_some()); + assert!(state(&mut tree).whose.is_some()); + } + + #[test] + fn a_danger_button_where_another_was_settles_again() { + let mut tree = Tree::new(element(button("Erase sda").danger().on_press(()))); + state(&mut tree).came = Some(Instant::now() - DANGER_SETTLES * 2); + tree.diff(element(button("Erase sdb").danger().on_press(()))); + assert!( + state(&mut tree) + .came + .is_some_and(|came| came.elapsed() < DANGER_SETTLES) + ); + } + + #[test] + fn a_button_whose_words_change_keeps_its_focus() { + let mut tree = Tree::new(element(button("Connect").primary().on_press(()))); + Focusable::focus(&mut state(&mut tree).focus); + tree.diff(element(button("Connecting…").primary().on_press(()))); + assert!(state(&mut tree).focus.is_focused()); + } +} diff --git a/launcher/src/ui/checkbox.rs b/launcher/src/ui/checkbox.rs new file mode 100644 index 0000000000..ba7a304334 --- /dev/null +++ b/launcher/src/ui/checkbox.rs @@ -0,0 +1,292 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Checkboxes: a yes or no, such as swap or "I've saved my recovery key". Checked or not, the box +//! and its mark fade from the one to the other. + +use iced::advanced::layout::{self, Layout}; +use iced::advanced::text::{self, Renderer as _}; +use iced::advanced::widget::{Operation, Tree, Widget, tree}; +use iced::advanced::{Clipboard, Shell, mouse, renderer}; +use iced::keyboard::{self, Key, key::Named}; + +use iced::{Event, Length, Pixels, Point, Rectangle, Size, touch, window}; + +use crate::ui::tokens::{motion, size, space, typography}; + +use crate::ui::focus::Focus; +use crate::ui::input; +use crate::ui::paint::{self, Plain}; +use crate::ui::theme::{Interaction, color}; +use crate::ui::transition::Transition; +use crate::ui::{Element, Renderer, Theme}; + +/// A checkbox with a label. Without a message to send it is disabled. +pub fn checkbox<'a, Message>(label: impl Into<String>, checked: bool) -> Checkbox<'a, Message> { + Checkbox { + label: label.into(), + checked, + on_toggle: None, + preview: None, + } +} + +/// A checkbox: a click on it or its label, or Space when it has focus, toggles it. +pub struct Checkbox<'a, Message> { + label: String, + checked: bool, + on_toggle: Option<Box<dyn Fn(bool) -> Message + 'a>>, + preview: Option<(Interaction, bool)>, +} + +impl<'a, Message> Checkbox<'a, Message> { + /// The message it sends with the new value. + pub fn on_toggle(self, on_toggle: impl Fn(bool) -> Message + 'a) -> Self { + Self { + on_toggle: Some(Box::new(on_toggle)), + ..self + } + } + + /// Draws it as if in this state, for the gallery. + pub fn preview(self, interaction: Interaction, focused: bool) -> Self { + Self { + preview: Some((interaction, focused)), + ..self + } + } + + fn interaction(&self, state: &State, over: bool) -> Interaction { + match (&self.on_toggle, state.pressed, over) { + (None, _, _) => Interaction::Disabled, + (Some(_), true, _) => Interaction::Pressed, + (Some(_), false, true) => Interaction::Hovered, + (Some(_), false, false) => Interaction::Idle, + } + } + + fn toggle(&mut self, shell: &mut Shell<'_, Message>) { + if let Some(on_toggle) = &self.on_toggle { + shell.publish(on_toggle(!self.checked)); + // Taken at once, so a second key in the same batch of events starts from it, as the + // app will. + self.checked = !self.checked; + } + } +} + +#[derive(Default)] +struct State { + focus: Focus, + pressed: bool, + label: Plain, + mark: Plain, + drawn: Option<(Interaction, bool, bool)>, + /// The value when last seen, and the fade to a new one under way: how checked it looks, + /// from 0 to 1. + seen: Option<bool>, + fade: Option<Transition>, +} + +impl<Message> Widget<Message, Theme, Renderer> for Checkbox<'_, Message> { + fn tag(&self) -> tree::Tag { + tree::Tag::of::<State>() + } + + fn state(&self) -> tree::State { + tree::State::new(State::default()) + } + + fn size(&self) -> Size<Length> { + Size::new(Length::Shrink, Length::Shrink) + } + + fn layout( + &mut self, + tree: &mut Tree, + _renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + let state = tree.state.downcast_mut::<State>(); + paint::shape(&mut state.label, &typography::INTERFACE, &self.label); + // The check, iced's icon, shaped once rather than at every frame it shows. + let mut glyph = [0; 4]; + state.mark.update(text::Text { + content: Renderer::CHECKMARK_ICON.encode_utf8(&mut glyph), + bounds: Size::new(size::CHECK, size::CHECK), + size: Pixels(size::CHECK * 0.7), + line_height: text::LineHeight::default(), + font: Renderer::ICON_FONT, + align_x: text::Alignment::Center, + align_y: iced::alignment::Vertical::Center, + shaping: text::Shaping::Basic, + wrapping: text::Wrapping::None, + }); + let width = size::CHECK + space::M + state.label.min_width().ceil(); + let size = limits.resolve(Length::Shrink, Length::Shrink, Size::new(width, size::ROW)); + layout::Node::new(size) + } + + fn operate( + &mut self, + tree: &mut Tree, + layout: Layout<'_>, + _renderer: &Renderer, + operation: &mut dyn Operation, + ) { + if self.on_toggle.is_some() && self.preview.is_none() { + let state = tree.state.downcast_mut::<State>(); + operation.focusable(None, layout.bounds(), &mut state.focus); + } + } + + fn update( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + _renderer: &Renderer, + _clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + _viewport: &Rectangle, + ) { + // A preview is a picture of a state: it takes no input. + if self.preview.is_some() { + return; + } + let state = tree.state.downcast_mut::<State>(); + state.focus.keep_if(self.on_toggle.is_some()); + // A new value, whatever set it: the box fades to it, from as far as a fade got. + if let Some(seen) = state.seen + && seen != self.checked + { + let (was, to) = (f32::from(u8::from(seen)), f32::from(u8::from(self.checked))); + Transition::turn(&mut state.fade, was, to, motion::FAST, shell); + } + state.seen = Some(self.checked); + if let Event::Window(window::Event::RedrawRequested(now)) = event { + Transition::advance(&mut state.fade, *now, shell); + } + let over = cursor.is_over(layout.bounds()); + if self.on_toggle.is_some() { + match event { + Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerPressed { .. }) + if over => + { + state.pressed = true; + state.focus.click(); + shell.capture_event(); + } + Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerLifted { .. }) + if state.pressed => + { + state.pressed = false; + if over { + self.toggle(shell); + } + shell.capture_event(); + } + Event::Touch(touch::Event::FingerLost { .. }) => state.pressed = false, + // Space, not Enter: Enter is the form's, such as to go on. Once a press: held + // down, it doesn't flicker. + Event::Keyboard(keyboard::Event::KeyPressed { + key: Key::Named(Named::Space), + modifiers, + repeat: false, + .. + }) if state.focus.is_focused() && input::plain(*modifiers) => { + state.focus.key(); + self.toggle(shell); + shell.capture_event(); + } + _ => {} + } + } else { + state.pressed = false; + } + let now = ( + self.interaction(state, over), + state.focus.is_shown(), + self.checked, + ); + input::redraw_on_change(&mut state.drawn, now, event, shell); + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + _style: &renderer::Style, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + ) { + let state = tree.state.downcast_ref::<State>(); + let bounds = layout.bounds(); + let (interaction, focused) = self.preview.unwrap_or(( + self.interaction(state, cursor.is_over(bounds)), + state.focus.is_shown(), + )); + // How checked it looks: fading, part of the way; else its value. + let checked = match (self.preview, state.fade) { + (None, Some(fade)) => fade.at(), + _ => f32::from(u8::from(self.checked)), + }; + let (off, on) = ( + theme.check(false, interaction), + theme.check(true, interaction), + ); + let check = Rectangle::new( + Point::new(bounds.x, bounds.center_y() - size::CHECK / 2.0), + Size::new(size::CHECK, size::CHECK), + ); + paint::boxed(renderer, check, &off.faded(1.0 - checked)); + paint::boxed(renderer, check, &on.faded(checked)); + let look = if checked >= 0.5 { on } else { off }; + let mark = on.ink.opacity(on.ink.alpha() * checked); + if checked > 0.0 { + // A paragraph's drawn from its top left: its middle at the box's, as text aligned to + // the middle of a point is. + let shaped = state.mark.min_bounds(); + let at = Point::new( + check.center_x() - shaped.width / 2.0, + check.center_y() - shaped.height / 2.0, + ); + renderer.fill_paragraph(state.mark.raw(), at, color(mark), *viewport); + } + let label = state.label.min_bounds(); + let at = Point::new( + check.x + size::CHECK + space::M, + bounds.center_y() - label.height / 2.0, + ); + let ink = theme.label(interaction); + paint::fill(renderer, &state.label, at, color(ink), *viewport); + if focused { + paint::outline(renderer, theme, check, look.radius); + } + } + + fn mouse_interaction( + &self, + _tree: &Tree, + layout: Layout<'_>, + cursor: mouse::Cursor, + _viewport: &Rectangle, + _renderer: &Renderer, + ) -> mouse::Interaction { + if self.on_toggle.is_some() && cursor.is_over(layout.bounds()) { + mouse::Interaction::Pointer + } else { + mouse::Interaction::default() + } + } +} + +impl<'a, Message: 'a> From<Checkbox<'a, Message>> for Element<'a, Message> { + fn from(checkbox: Checkbox<'a, Message>) -> Self { + Element::new(checkbox) + } +} diff --git a/launcher/src/ui/choice.rs b/launcher/src/ui/choice.rs new file mode 100644 index 0000000000..ee31d81213 --- /dev/null +++ b/launcher/src/ui/choice.rs @@ -0,0 +1,476 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! A single choice among a few options, each a card with a title and a description: the Secure +//! Boot mode, the disk to install to. + +use iced::advanced::layout::{self, Layout}; +use iced::advanced::text::Renderer as _; +use iced::advanced::widget::{Operation, Tree, Widget, tree}; +use iced::advanced::{Clipboard, Shell, mouse, renderer}; +use iced::keyboard::{self, Key, key::Named}; +use iced::{Event, Length, Point, Rectangle, Size, touch}; + +use crate::ui::tokens::{size, space, typography}; + +use crate::ui::focus::Focus; +use crate::ui::input; +use crate::ui::paint::{self, Plain}; +use crate::ui::theme::{Interaction, Look, color}; +use crate::ui::transition::Lit; +use crate::ui::{Element, Renderer, Theme}; + +/// A single choice: what's chosen, if anything yet, and the message a new choice sends. Without +/// one it is disabled. +pub fn choice<'a, T: Copy + PartialEq, Message>(chosen: Option<T>) -> Choice<'a, T, Message> { + Choice { + options: Vec::new(), + chosen, + on_choose: None, + preview: None, + } +} + +struct Choosable<T> { + value: T, + title: String, + description: String, + enabled: bool, +} + +/// A single choice. It is one stop for Tab; the arrow keys, Home and End move the choice among +/// the options it can take, and Space takes the one the keyboard is on. +pub struct Choice<'a, T, Message> { + options: Vec<Choosable<T>>, + chosen: Option<T>, + on_choose: Option<Box<dyn Fn(T) -> Message + 'a>>, + preview: Option<(usize, Interaction, bool)>, +} + +impl<'a, T: Copy + PartialEq, Message> Choice<'a, T, Message> { + /// An option, with a title and a line or two saying what it means. + pub fn option( + mut self, + value: T, + title: impl Into<String>, + description: impl Into<String>, + ) -> Self { + self.options.push(Choosable { + value, + title: title.into(), + description: description.into(), + enabled: true, + }); + self + } + + /// An option that can't be taken here, saying why in its description. + pub fn unavailable( + mut self, + value: T, + title: impl Into<String>, + description: impl Into<String>, + ) -> Self { + self = self.option(value, title, description); + if let Some(option) = self.options.last_mut() { + option.enabled = false; + } + self + } + + /// The message for a choice, with the option's value: without one, it's disabled. + pub fn on_choose(self, on_choose: impl Fn(T) -> Message + 'a) -> Self { + Self { + on_choose: Some(Box::new(on_choose)), + ..self + } + } + + /// Draws one option as if in this state, and the focus outline, for the gallery. + pub fn preview(self, option: usize, interaction: Interaction, focused: bool) -> Self { + Self { + preview: Some((option, interaction, focused)), + ..self + } + } + + fn chosen_index(&self) -> Option<usize> { + self.options + .iter() + .position(|option| Some(option.value) == self.chosen) + } + + /// The option the keyboard is on: the chosen one, or the first that can be taken. + fn current(&self) -> Option<usize> { + self.chosen_index() + .or_else(|| self.options.iter().position(|option| option.enabled)) + } + + fn interaction(&self, state: &State, index: usize, over: bool) -> Interaction { + if self.on_choose.is_none() || !self.options[index].enabled { + Interaction::Disabled + } else if state.pressed == Some(index) { + Interaction::Pressed + } else if over { + Interaction::Hovered + } else { + Interaction::Idle + } + } + + fn choose(&mut self, index: usize, shell: &mut Shell<'_, Message>) { + let option = &self.options[index]; + if let Some(on_choose) = &self.on_choose + && option.enabled + && Some(option.value) != self.chosen + { + shell.publish(on_choose(option.value)); + // Taken at once, so a second key in the same batch of events starts from it, as the + // app will. + self.chosen = Some(option.value); + } + } +} + +/// The option an arrow key moves to: the next that can be taken in that direction, or none. +pub(crate) fn step(enabled: &[bool], from: Option<usize>, key: &Named) -> Option<usize> { + let mut indices: Box<dyn Iterator<Item = usize>> = match (key, from) { + (Named::ArrowDown | Named::ArrowRight, Some(at)) => Box::new(at + 1..enabled.len()), + (Named::ArrowUp | Named::ArrowLeft, Some(at)) => Box::new((0..at).rev()), + (Named::Home, _) | (Named::ArrowDown | Named::ArrowRight, None) => { + Box::new(0..enabled.len()) + } + (Named::End, _) | (Named::ArrowUp | Named::ArrowLeft, None) => { + Box::new((0..enabled.len()).rev()) + } + _ => return None, + }; + indices.find(|at| enabled[*at]) +} + +/// What it last drew: the option under the pointer, the pressed one, the outline, the current. +type Drawn = (Option<usize>, Option<usize>, bool, Option<usize>); + +#[derive(Default)] +struct State { + focus: Focus, + pressed: Option<usize>, + titles: Vec<Plain>, + descriptions: Vec<Plain>, + drawn: Option<Drawn>, + /// Each card's glows and focus ring, fading in and out on the glows' own timing: under the + /// pointer, chosen, and the focus ring round the current one. + hover_lit: Vec<Lit>, + chosen_lit: Vec<Lit>, + ring_lit: Vec<Lit>, +} + +/// The card's padding, across and down; the radio's gap to the text is `space::L` too. +const PAD_X: f32 = space::L; +const PAD_Y: f32 = space::M; + +impl<T: Copy + PartialEq, Message> Widget<Message, Theme, Renderer> for Choice<'_, T, Message> { + fn tag(&self) -> tree::Tag { + tree::Tag::of::<State>() + } + + fn state(&self) -> tree::State { + tree::State::new(State::default()) + } + + fn size(&self) -> Size<Length> { + Size::new(Length::Fill, Length::Shrink) + } + + fn layout( + &mut self, + tree: &mut Tree, + _renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + let state = tree.state.downcast_mut::<State>(); + let width = limits.max().width; + let text_width = (width - 2.0 * PAD_X - size::CHECK - space::L).max(0.0); + state.titles.resize_with(self.options.len(), Plain::default); + state + .descriptions + .resize_with(self.options.len(), Plain::default); + let mut cards = Vec::with_capacity(self.options.len()); + let mut y = 0.0; + for (at, option) in self.options.iter().enumerate() { + paint::shape(&mut state.titles[at], &typography::INTERFACE, &option.title); + let mut text = paint::unbounded(&typography::INTERFACE, &option.description); + text.bounds = Size::new(text_width, f32::INFINITY); + text.wrapping = iced::advanced::text::Wrapping::Word; + state.descriptions[at].update(text); + let height = 2.0 * PAD_Y + + state.titles[at].min_height() + + if option.description.is_empty() { + 0.0 + } else { + space::XXS + state.descriptions[at].min_height() + }; + cards.push( + layout::Node::new(Size::new(width, height.ceil())).move_to(Point::new(0.0, y)), + ); + y += height.ceil() + space::S; + } + let height = (y - space::S).max(0.0); + layout::Node::with_children(Size::new(width, height), cards) + } + + fn operate( + &mut self, + tree: &mut Tree, + layout: Layout<'_>, + _renderer: &Renderer, + operation: &mut dyn Operation, + ) { + if self.on_choose.is_some() + && self.preview.is_none() + && self.options.iter().any(|option| option.enabled) + { + let state = tree.state.downcast_mut::<State>(); + operation.focusable(None, layout.bounds(), &mut state.focus); + } + } + + fn update( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + _renderer: &Renderer, + _clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + _viewport: &Rectangle, + ) { + // A preview is a picture of a state: it takes no input. + if self.preview.is_some() { + return; + } + let state = tree.state.downcast_mut::<State>(); + state + .focus + .keep_if(self.on_choose.is_some() && self.options.iter().any(|option| option.enabled)); + let over = layout + .children() + .position(|card| cursor.is_over(card.bounds())); + if self.on_choose.is_some() { + match event { + Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerPressed { .. }) => { + if let Some(at) = over.filter(|at| self.options[*at].enabled) { + state.pressed = Some(at); + state.focus.click(); + shell.capture_event(); + } + } + Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerLifted { .. }) => { + if let Some(at) = state.pressed.take() { + if over == Some(at) { + self.choose(at, shell); + } + shell.capture_event(); + } + } + Event::Touch(touch::Event::FingerLost { .. }) => state.pressed = None, + Event::Keyboard(keyboard::Event::KeyPressed { + key: Key::Named(key), + modifiers, + .. + }) if state.focus.is_focused() && input::plain(*modifiers) => { + let enabled: Vec<_> = self.options.iter().map(|o| o.enabled).collect(); + let target = match key { + Named::Space => self.current(), + _ => step(&enabled, self.chosen_index(), key), + }; + if let Some(at) = target { + state.focus.key(); + self.choose(at, shell); + shell.capture_event(); + } else if matches!( + key, + Named::ArrowUp | Named::ArrowDown | Named::ArrowLeft | Named::ArrowRight + ) { + // At the end: the key stays here rather than scrolling the page. + state.focus.key(); + shell.capture_event(); + } + } + _ => {} + } + } else { + state.pressed = None; + } + // Each card's glows and focus ring fade in and out on the glows' own timing. + let count = self.options.len(); + state.hover_lit.resize_with(count, Lit::default); + state.chosen_lit.resize_with(count, Lit::default); + state.ring_lit.resize_with(count, Lit::default); + let current = self.current(); + let shown = state.focus.is_shown(); + for at in 0..count { + let interaction = self.interaction(state, at, over == Some(at)); + let enabled = interaction != Interaction::Disabled; + let hovered = matches!(interaction, Interaction::Hovered | Interaction::Pressed); + let chosen = Some(self.options[at].value) == self.chosen; + state.hover_lit[at].frame(event, shell); + state.hover_lit[at].aim(hovered, shell); + state.chosen_lit[at].frame(event, shell); + state.chosen_lit[at].aim(chosen && enabled, shell); + state.ring_lit[at].frame(event, shell); + state.ring_lit[at].aim(shown && current == Some(at), shell); + } + let now = (over, state.pressed, state.focus.is_shown(), self.current()); + input::redraw_on_change(&mut state.drawn, now, event, shell); + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + _style: &renderer::Style, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + ) { + let state = tree.state.downcast_ref::<State>(); + let focused = match self.preview { + Some((_, _, focused)) => focused, + None => state.focus.is_shown(), + }; + let current = self.current(); + for (at, card) in layout.children().enumerate() { + let (Some(option), Some(title), Some(description)) = ( + self.options.get(at), + state.titles.get(at), + state.descriptions.get(at), + ) else { + continue; + }; + let bounds = card.bounds(); + let interaction = match self.preview { + Some((shown, interaction, _)) if shown == at => interaction, + _ => self.interaction(state, at, cursor.is_over(bounds)), + }; + let chosen = Some(option.value) == self.chosen; + let look = theme.option(chosen, interaction); + let enabled = interaction != Interaction::Disabled; + let hovered = matches!(interaction, Interaction::Hovered | Interaction::Pressed); + // How lit each glow is: on their fades, or whole in a preview, a picture of a state. + let lit = |lits: &Vec<Lit>, whole: bool| match self.preview { + Some(_) => f32::from(u8::from(whole)), + None => lits.get(at).map_or(0.0, Lit::share), + }; + let chosen_share = lit(&state.chosen_lit, chosen && enabled); + let hover_share = lit(&state.hover_lit, hovered); + let ring_share = lit(&state.ring_lit, focused && current == Some(at)); + // The card: the chosen glow at its share, and under it the pointer's glow, which + // gives way to the chosen one as a card is chosen. + let chosen_glow = theme.option(true, Interaction::Idle).glow; + let hover_glow = theme.option(false, Interaction::Hovered).glow; + if let Some(glow) = hover_glow { + let card_hover = hover_share * (1.0 - chosen_share); + paint::boxed( + renderer, + bounds, + &Look { + fill: None, + line: None, + ..look + } + .lit(Some(glow), card_hover), + ); + } + let look = Look { glow: None, ..look }.lit(chosen_glow, chosen_share); + paint::boxed(renderer, bounds, &look); + // The radio circle glows under the pointer, on the same fade. + let radio = theme.radio(chosen, interaction); + let radio_glow = theme.radio(chosen, Interaction::Hovered).glow; + let radio = Look { + glow: None, + ..radio + } + .lit(radio_glow, hover_share); + let first_line = title.min_height(); + let circle = Rectangle::new( + Point::new( + bounds.x + PAD_X, + bounds.y + PAD_Y + (first_line - size::CHECK) / 2.0, + ), + Size::new(size::CHECK, size::CHECK), + ); + paint::boxed(renderer, circle, &radio); + if chosen { + paint::dot(renderer, circle.center(), size::DOT, color(radio.ink), None); + } + let x = circle.x + size::CHECK + space::L; + let ink = theme.label(interaction); + paint::fill( + renderer, + title, + Point::new(x, bounds.y + PAD_Y), + color(ink), + *viewport, + ); + renderer.fill_paragraph( + description.raw(), + Point::new(x, bounds.y + PAD_Y + first_line + space::XXS), + color(theme.ink(crate::ui::tokens::Ink::Muted)), + *viewport, + ); + // The focus ring round the current card fades in and out, and moves by fading. + paint::outline_lit(renderer, theme, bounds, look.radius, ring_share); + } + } + + fn mouse_interaction( + &self, + _tree: &Tree, + layout: Layout<'_>, + cursor: mouse::Cursor, + _viewport: &Rectangle, + _renderer: &Renderer, + ) -> mouse::Interaction { + let over = layout + .children() + .zip(&self.options) + .any(|(card, option)| option.enabled && cursor.is_over(card.bounds())); + if self.on_choose.is_some() && over { + mouse::Interaction::Pointer + } else { + mouse::Interaction::default() + } + } +} + +impl<'a, T: Copy + PartialEq + 'a, Message: 'a> From<Choice<'a, T, Message>> + for Element<'a, Message> +{ + fn from(choice: Choice<'a, T, Message>) -> Self { + Element::new(choice) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn arrows_skip_what_cant_be_taken() { + let enabled = [true, false, true, true]; + assert_eq!(step(&enabled, Some(0), &Named::ArrowDown), Some(2)); + assert_eq!(step(&enabled, Some(2), &Named::ArrowUp), Some(0)); + assert_eq!(step(&enabled, Some(3), &Named::ArrowRight), None); + assert_eq!(step(&enabled, Some(0), &Named::ArrowLeft), None); + assert_eq!(step(&enabled, None, &Named::ArrowDown), Some(0)); + assert_eq!(step(&enabled, None, &Named::ArrowUp), Some(3)); + assert_eq!(step(&enabled, Some(2), &Named::Home), Some(0)); + assert_eq!(step(&enabled, Some(0), &Named::End), Some(3)); + assert_eq!(step(&enabled, Some(0), &Named::Enter), None); + assert_eq!(step(&[false, false], None, &Named::Home), None); + } +} diff --git a/launcher/src/ui/chrome.rs b/launcher/src/ui/chrome.rs new file mode 100644 index 0000000000..25ab45e5aa --- /dev/null +++ b/launcher/src/ui/chrome.rs @@ -0,0 +1,1111 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! A window's own decorations: the launcher draws them itself (client-side), the same on every +//! desktop. [`crate::ui::window`] puts them round the window, and the app gives what its +//! header bar holds: +//! +//! - [`header_bar`]: the bar at the top. What shows goes in its three slots ([`header`]): the +//! app's name at the start, something in the middle, and the light and dark pill at the end. +//! Dragging the bar moves the window, from its controls too once the pointer goes far enough, +//! and double-clicking its empty area maximizes the window or restores it. +//! - [`close_button`]: the one window button. +//! - [`window_frame`]: the window's fill, and while it floats its rounded corners and line, and +//! the zones inside its edges that resize it ([`resize_edge`]). +//! +//! The widgets only say what was asked, by message; the window module moves, maximizes, resizes and +//! closes the window. Their looks are the theme's ([`Theme::header_bar`], +//! [`Theme::close_button`], [`Theme::window`]), their sizes `crate::ui::tokens::window`'s. + +use iced::advanced::layout::{self, Layout}; +use iced::advanced::renderer::{self, Renderer as _}; +use iced::advanced::widget::{Operation, Tree, Widget, tree}; +use iced::advanced::{Clipboard, Shell, mouse, overlay}; +use iced::gradient::Linear; +use iced::{ + Background, Border, Degrees, Event, Gradient, Length, Point, Rectangle, Shadow, Size, Vector, +}; + +use crate::ui::tokens::{size, window}; + +mod fold; +pub use fold::{Folded, folded}; + +use crate::ui::icon::Icon; +use crate::ui::shape; +use crate::ui::theme::color; +use crate::ui::{Element, Renderer, Theme}; + +/// An edge or a corner of a window, to resize it from. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Edge { + North, + South, + East, + West, + NorthEast, + NorthWest, + SouthEast, + SouthWest, +} + +impl Edge { + /// The direction iced resizes a window in from it. + pub fn direction(self) -> iced::window::Direction { + use iced::window::Direction; + match self { + Self::North => Direction::North, + Self::South => Direction::South, + Self::East => Direction::East, + Self::West => Direction::West, + Self::NorthEast => Direction::NorthEast, + Self::NorthWest => Direction::NorthWest, + Self::SouthEast => Direction::SouthEast, + Self::SouthWest => Direction::SouthWest, + } + } + + /// The pointer's shape over it. + pub fn cursor(self) -> mouse::Interaction { + match self { + Self::North | Self::South => mouse::Interaction::ResizingVertically, + Self::East | Self::West => mouse::Interaction::ResizingHorizontally, + Self::NorthWest | Self::SouthEast => mouse::Interaction::ResizingDiagonallyDown, + Self::NorthEast | Self::SouthWest => mouse::Interaction::ResizingDiagonallyUp, + } + } +} + +/// What a header bar holds: three slots, each optional, each the app's, which always show: the +/// app's name at the start, something in the middle, and what comes last before the close +/// button, such as the light and dark pill. +pub struct Header<'a, Message> { + start: Option<Element<'a, Message>>, + center: Option<Element<'a, Message>>, + end: Option<Element<'a, Message>>, +} + +/// An empty header: fill its slots. +pub fn header<'a, Message>() -> Header<'a, Message> { + Header { + start: None, + center: None, + end: None, + } +} + +impl<'a, Message: 'a> Header<'a, Message> { + /// What comes first: the app's name or brand, the window's title. + pub fn start(self, content: impl Into<Element<'a, Message>>) -> Self { + Self { + start: Some(content.into()), + ..self + } + } + + /// What sits in the middle of the room the others leave. + pub fn center(self, content: impl Into<Element<'a, Message>>) -> Self { + Self { + center: Some(content.into()), + ..self + } + } + + /// What comes last, before the close button. + pub fn end(self, content: impl Into<Element<'a, Message>>) -> Self { + Self { + end: Some(content.into()), + ..self + } + } + + /// The same, sending other messages. + pub fn map<B: 'a>(self, f: impl Fn(Message) -> B + Clone + 'a) -> Header<'a, B> { + let map = |slot: Option<Element<'a, Message>>| slot.map(|slot| slot.map(f.clone())); + Header { + start: map(self.start), + center: map(self.center), + end: map(self.end), + } + } + + /// Whether every slot is empty. + pub fn is_empty(&self) -> bool { + self.start.is_none() && self.center.is_none() && self.end.is_none() + } +} + +/// A header bar holding a header's slots. Without [`on_close`](HeaderBar::on_close) it has no +/// close button. +pub fn header_bar<'a, Message>(header: Header<'a, Message>) -> HeaderBar<'a, Message> { + HeaderBar { + header, + on_drag: None, + on_maximize: None, + on_close: None, + on_back: None, + rounded: false, + } +} + +/// A header bar, made into an [`Element`] once it's set up. +pub struct HeaderBar<'a, Message> { + header: Header<'a, Message>, + on_drag: Option<Message>, + on_maximize: Option<Message>, + on_close: Option<Message>, + on_back: Option<Message>, + rounded: bool, +} + +impl<Message> HeaderBar<'_, Message> { + /// Adds the back button before everything else, which sends this: a folded window showing + /// its page goes back to its sidebar. + pub fn on_back(self, message: Message) -> Self { + Self { + on_back: Some(message), + ..self + } + } + + /// Its top corners rounded as the window's, inside its line: where the frame's own rounding + /// can't be drawn (`shape::round` on a renderer without custom primitives), the bar's fill + /// keeps out of the window's corners itself. + pub fn rounded(self, rounded: bool) -> Self { + Self { rounded, ..self } + } + + /// What pressing its empty area and dragging sends: the window should move with the pointer. + pub fn on_drag(self, message: Message) -> Self { + Self { + on_drag: Some(message), + ..self + } + } + + /// What double-clicking its empty area sends: the window should maximize, or restore. + pub fn on_maximize(self, message: Message) -> Self { + Self { + on_maximize: Some(message), + ..self + } + } + + /// Adds the close button, which sends this. + pub fn on_close(self, message: Message) -> Self { + Self { + on_close: Some(message), + ..self + } + } +} + +impl<'a, Message: Clone + 'a> From<HeaderBar<'a, Message>> for Element<'a, Message> { + fn from(bar: HeaderBar<'a, Message>) -> Self { + let Header { start, center, end } = bar.header; + let close = bar + .on_close + .map(|message| Element::from(close_button(message))); + // In place of an overflow menu (items that move into a menu when they don't fit): the + // three slots in a row, the room between them empty, so it drags the window. + let gap = |width: f32| Element::from(iced::widget::space().width(width)); + let fill = || Element::from(iced::widget::space().width(Length::Fill)); + let mut row = Vec::new(); + match bar.on_back { + Some(message) => { + row.push(gap(window::BAR_PAD_END)); + row.push(Element::from(back_button(message))); + row.push(gap(window::BAR_GAP)); + } + None => row.push(gap(window::BAR_PAD_START)), + } + // The start slot, the app's name in capitals, sits a pixel lower: capitals have no + // descenders, so a centred line box leaves their ink a pixel high. + row.extend(start.map(|start| { + Element::from(iced::widget::container(start).padding(iced::Padding { + top: 2.0, + ..iced::Padding::ZERO + })) + })); + row.push(fill()); + if let Some(center) = center { + row.push(center); + row.push(fill()); + } + if let Some(end) = end { + row.push(end); + row.push(gap(if close.is_some() { + window::BUTTON_MARGIN + } else { + window::BAR_GAP + })); + } + match close { + Some(close) => { + row.push(close); + row.push(gap(window::BAR_PAD_END)); + } + None => row.push(gap(window::BAR_PAD_START)), + } + let content = iced::widget::Row::with_children(row) + .align_y(iced::Alignment::Center) + .height(Length::Fill) + .into(); + Element::new(Bar { + content, + on_drag: bar.on_drag, + on_maximize: bar.on_maximize, + rounded: bar.rounded, + }) + } +} + +/// The bar itself: its fill, tints and line, its items, and drags and double-clicks on what of it +/// no item takes. +struct Bar<'a, Message> { + content: Element<'a, Message>, + on_drag: Option<Message>, + on_maximize: Option<Message>, + rounded: bool, +} + +#[derive(Debug, Default)] +struct Drag { + /// Where the button went down on the bar, until the pointer moves away or it comes up, and + /// whether on an item, such as a button. + pressed: Option<Point>, + on_item: bool, + last: Option<mouse::Click>, +} + +impl<Message: Clone> Widget<Message, Theme, Renderer> for Bar<'_, Message> { + fn tag(&self) -> tree::Tag { + tree::Tag::of::<Drag>() + } + + fn state(&self) -> tree::State { + tree::State::new(Drag::default()) + } + + fn children(&self) -> Vec<Tree> { + vec![Tree::new(&self.content)] + } + + fn diff(&self, tree: &mut Tree) { + tree.diff_children(std::slice::from_ref(&self.content)); + } + + fn size(&self) -> Size<Length> { + Size::new(Length::Fill, Length::Fixed(window::BAR_HEIGHT)) + } + + fn layout( + &mut self, + tree: &mut Tree, + renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + let size = limits.resolve(Length::Fill, Length::Fixed(window::BAR_HEIGHT), Size::ZERO); + // The items sit above the bottom line. + let inside = layout::Limits::new( + Size::ZERO, + Size::new(size.width, size.height - size::BORDER), + ); + let content = self + .content + .as_widget_mut() + .layout(&mut tree.children[0], renderer, &inside); + layout::Node::with_children(size, vec![content]) + } + + fn operate( + &mut self, + tree: &mut Tree, + layout: Layout<'_>, + renderer: &Renderer, + operation: &mut dyn Operation, + ) { + let content = inside(layout); + self.content + .as_widget_mut() + .operate(&mut tree.children[0], content, renderer, operation); + } + + fn update( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + renderer: &Renderer, + clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + viewport: &Rectangle, + ) { + let content = inside(layout); + // A press anywhere on the bar, on an item too, moves the window once the pointer goes + // far enough with it held, as a header bar does in GTK. The items then hear the button + // come up away from them, so the one pressed lets go without acting. + let drag = tree.state.downcast_mut::<Drag>(); + if let Event::Mouse(mouse::Event::CursorMoved { .. }) = event + && let (Some(from), Some(at)) = (drag.pressed, cursor.position()) + && from.distance(at) >= window::DRAG_THRESHOLD + { + drag.pressed = None; + if drag.on_item { + self.content.as_widget_mut().update( + &mut tree.children[0], + &Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)), + content, + mouse::Cursor::Unavailable, + renderer, + clipboard, + shell, + viewport, + ); + } + if let Some(message) = &self.on_drag { + shell.publish(message.clone()); + } + return; + } + self.content.as_widget_mut().update( + &mut tree.children[0], + event, + content, + cursor, + renderer, + clipboard, + shell, + viewport, + ); + // The button up, whoever took it, ends the press. + if let Event::Mouse( + mouse::Event::ButtonReleased(mouse::Button::Left) | mouse::Event::CursorLeft, + ) = event + { + tree.state.downcast_mut::<Drag>().pressed = None; + } + if shell.is_event_captured() { + // An item took it. A press on one may still move the window, but not on text, where + // a drag selects, nor on what's dragged itself, such as the light and dark pill. + if let Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) = event { + let on_text = matches!( + self.content.as_widget().mouse_interaction( + &tree.children[0], + content, + cursor, + viewport, + renderer, + ), + mouse::Interaction::Text + | mouse::Interaction::Grab + | mouse::Interaction::Grabbing + ); + let drag = tree.state.downcast_mut::<Drag>(); + drag.pressed = cursor + .position_over(layout.bounds()) + .filter(|_| !on_text && self.on_drag.is_some()); + drag.on_item = true; + drag.last = None; + } + return; + } + let drag = tree.state.downcast_mut::<Drag>(); + match event { + Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => { + let Some(at) = cursor.position_over(layout.bounds()) else { + return; + }; + let click = mouse::Click::new(at, mouse::Button::Left, drag.last); + drag.last = Some(click); + if click.kind() == mouse::click::Kind::Double { + drag.pressed = None; + if let Some(message) = &self.on_maximize { + shell.publish(message.clone()); + } + } else { + drag.pressed = Some(at); + drag.on_item = false; + } + shell.capture_event(); + } + Event::Mouse( + mouse::Event::ButtonReleased(mouse::Button::Left) | mouse::Event::CursorLeft, + ) => drag.pressed = None, + _ => {} + } + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + style: &renderer::Style, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + ) { + let bounds = layout.bounds(); + let look = theme.header_bar(); + // Rounded, its top corners keep inside the window's, a line in from its edge. + let radius = if self.rounded { + let r = window::CORNER_RADIUS - window::BORDER; + iced::border::Radius { + top_left: r, + top_right: r, + bottom_right: 0.0, + bottom_left: 0.0, + } + } else { + iced::border::Radius::default() + }; + fill_rounded( + renderer, + bounds, + Background::Color(color(look.fill)), + radius, + ); + fill_rounded( + renderer, + bounds, + Background::Gradient(edge_tints(look.start, look.end, look.reach)), + radius, + ); + let line = Rectangle { + y: bounds.y + bounds.height - size::BORDER, + height: size::BORDER, + ..bounds + }; + fill(renderer, line, Background::Color(color(look.line))); + let content = inside(layout); + self.content.as_widget().draw( + &tree.children[0], + renderer, + theme, + style, + content, + cursor, + viewport, + ); + } + + fn mouse_interaction( + &self, + tree: &Tree, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + renderer: &Renderer, + ) -> mouse::Interaction { + let content = inside(layout); + self.content.as_widget().mouse_interaction( + &tree.children[0], + content, + cursor, + viewport, + renderer, + ) + } + + fn overlay<'b>( + &'b mut self, + tree: &'b mut Tree, + layout: Layout<'b>, + renderer: &Renderer, + viewport: &Rectangle, + translation: Vector, + ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { + let content = inside(layout); + self.content.as_widget_mut().overlay( + &mut tree.children[0], + content, + renderer, + viewport, + translation, + ) + } +} + +/// The edge tints as a gradient, left to right: the start's tint fading to nothing across +/// `reach` of the width, nothing, then the end's tint fading in across the last `reach`, as the +/// mockup's CSS. iced eases between a gradient's stops where CSS goes straight, so each fade +/// gets two more stops, on the straight line, which keeps it within a fraction of a level of it. +fn edge_tints( + start: crate::ui::tokens::Color, + end: crate::ui::tokens::Color, + reach: f32, +) -> Gradient { + let start = color(start); + let end = color(end); + let fade = |tint: iced::Color, amount: f32| iced::Color { + a: tint.a * amount, + ..tint + }; + let third = reach / 3.0; + Gradient::Linear( + Linear::new(Degrees(90.0)) + .add_stop(0.0, start) + .add_stop(third, fade(start, 2.0 / 3.0)) + .add_stop(2.0 * third, fade(start, 1.0 / 3.0)) + .add_stop(reach, fade(start, 0.0)) + .add_stop(1.0 - reach, fade(end, 0.0)) + .add_stop(1.0 - 2.0 * third, fade(end, 1.0 / 3.0)) + .add_stop(1.0 - third, fade(end, 2.0 / 3.0)) + .add_stop(1.0, end), + ) +} + +/// A rectangle filled edge to edge. +fn fill(renderer: &mut Renderer, bounds: Rectangle, background: Background) { + fill_rounded( + renderer, + bounds, + background, + iced::border::Radius::default(), + ); +} + +/// A rectangle filled, its corners rounded each by its own radius. +fn fill_rounded( + renderer: &mut Renderer, + bounds: Rectangle, + background: Background, + radius: iced::border::Radius, +) { + renderer.fill_quad( + renderer::Quad { + bounds, + border: Border { + radius, + ..Border::default() + }, + shadow: Shadow::default(), + snap: true, + }, + background, + ); +} + +/// The close button, a window button whose hover is red: Enter or Space closes the window when it +/// has focus, as a click does. +pub fn close_button<Message>(on_press: Message) -> WindowButton<Message> { + crate::ui::icon::window_button(Icon::CLOSE, on_press).danger() +} + +/// The back button, at a folded window's header bar's start: back from the page to the sidebar. +pub fn back_button<Message>(on_press: Message) -> WindowButton<Message> { + crate::ui::icon::window_button(Icon::BACK, on_press) +} + +pub use crate::ui::icon::WindowButton; + +/// How a floating window's corners are made. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum Corners { + /// Square: maximized, or the frame drawn by no one (`LEONIDA_WINDOW_FRAME=0`). + #[default] + Square, + /// Rounded by the app, on a transparent window: everything drawn is cut to the rounded + /// rectangle and the line drawn round it, as the design language has it. + Drawn, + /// Rounded by the system, on an opaque window (Windows 11's own corners): the app draws only + /// its line, at the system's radius. + System, +} + +/// A window's frame round its content, filling the window: bg behind everything. Square and +/// without resize zones until set up. +pub fn window_frame<'a, Message>( + content: impl Into<Element<'a, Message>>, +) -> WindowFrame<'a, Message> { + WindowFrame { + content: content.into(), + corners: Corners::Square, + on_resize: None, + } +} + +/// What a header bar or a window frame holds: its layout's one child, which its layout always +/// has. +fn inside(layout: Layout<'_>) -> Layout<'_> { + layout.children().next().unwrap_or(layout) +} + +/// A window's frame round its content ([`window_frame`]): made into an [`Element`] once it's set +/// up. +pub struct WindowFrame<'a, Message> { + content: Element<'a, Message>, + corners: Corners, + on_resize: Option<Box<dyn Fn(Edge) -> Message + 'a>>, +} + +impl<'a, Message> WindowFrame<'a, Message> { + /// Its corners while it floats, and a line round the edge unless they're square. Drawn + /// corners need a transparent window. + pub fn corners(self, corners: Corners) -> Self { + Self { corners, ..self } + } + + /// Zones inside its edges that resize the window ([`resize_edge`]): pressing one sends the + /// direction to resize in, and the pointer over one shows it. + pub fn on_resize(self, on_resize: impl Fn(Edge) -> Message + 'a) -> Self { + Self { + on_resize: Some(Box::new(on_resize)), + ..self + } + } + + fn rounded(&self) -> bool { + self.corners != Corners::Square + } + + fn inset(&self) -> f32 { + if self.rounded() { window::BORDER } else { 0.0 } + } + + /// The resize zone under the pointer, if it has any. + fn edge(&self, layout: Layout<'_>, cursor: mouse::Cursor) -> Option<Edge> { + let bounds = layout.bounds(); + self.on_resize.as_ref()?; + let at = cursor.position_over(bounds)?; + resize_edge(bounds.size(), Point::new(at.x - bounds.x, at.y - bounds.y)) + } + + /// The pointer as the content sees it: over a resize zone, it's the zone's. + fn content_cursor(&self, layout: Layout<'_>, cursor: mouse::Cursor) -> mouse::Cursor { + if self.edge(layout, cursor).is_some() { + cursor.levitate() + } else { + cursor + } + } +} + +impl<Message> Widget<Message, Theme, Renderer> for WindowFrame<'_, Message> { + fn children(&self) -> Vec<Tree> { + vec![Tree::new(&self.content)] + } + + fn diff(&self, tree: &mut Tree) { + tree.diff_children(std::slice::from_ref(&self.content)); + } + + fn size(&self) -> Size<Length> { + Size::new(Length::Fill, Length::Fill) + } + + fn layout( + &mut self, + tree: &mut Tree, + renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + let size = limits.resolve(Length::Fill, Length::Fill, Size::ZERO); + let inset = self.inset(); + let inside = layout::Limits::new( + Size::ZERO, + Size::new( + (size.width - 2.0 * inset).max(0.0), + (size.height - 2.0 * inset).max(0.0), + ), + ); + let content = self + .content + .as_widget_mut() + .layout(&mut tree.children[0], renderer, &inside) + .move_to(Point::new(inset, inset)); + layout::Node::with_children(size, vec![content]) + } + + fn operate( + &mut self, + tree: &mut Tree, + layout: Layout<'_>, + renderer: &Renderer, + operation: &mut dyn Operation, + ) { + let content = inside(layout); + self.content + .as_widget_mut() + .operate(&mut tree.children[0], content, renderer, operation); + } + + fn update( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + renderer: &Renderer, + clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + viewport: &Rectangle, + ) { + if let Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) = event + && let Some(direction) = self.edge(layout, cursor) + && let Some(on_resize) = &self.on_resize + { + shell.publish(on_resize(direction)); + shell.capture_event(); + return; + } + let content = inside(layout); + let cursor = self.content_cursor(layout, cursor); + self.content.as_widget_mut().update( + &mut tree.children[0], + event, + content, + cursor, + renderer, + clipboard, + shell, + viewport, + ); + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + style: &renderer::Style, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + ) { + let bounds = layout.bounds(); + let look = theme.window(); + // Drawn corners: the fill keeps inside them itself too, for a renderer that can't round + // what's drawn (`shape::round`). + let radius = if self.corners == Corners::Drawn { + look.radius + } else { + 0.0 + }; + fill_rounded( + renderer, + bounds, + Background::Color(color(look.fill)), + radius.into(), + ); + let content = inside(layout); + self.content.as_widget().draw( + &tree.children[0], + renderer, + theme, + style, + content, + self.content_cursor(layout, cursor), + viewport, + ); + draw_corners(renderer, theme, bounds, self.corners); + } + + fn mouse_interaction( + &self, + tree: &Tree, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + renderer: &Renderer, + ) -> mouse::Interaction { + if let Some(direction) = self.edge(layout, cursor) { + return direction.cursor(); + } + let content = inside(layout); + self.content.as_widget().mouse_interaction( + &tree.children[0], + content, + cursor, + viewport, + renderer, + ) + } + + fn overlay<'b>( + &'b mut self, + tree: &'b mut Tree, + layout: Layout<'b>, + renderer: &Renderer, + viewport: &Rectangle, + translation: Vector, + ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { + let content = inside(layout); + let (rounded, corners) = (self.rounded(), self.corners); + let overlay = self.content.as_widget_mut().overlay( + &mut tree.children[0], + content, + renderer, + viewport, + translation, + )?; + // An overlay, such as an open menu, draws after everything, the rounding too: rounded + // again over it, it keeps the window's corners, as a dialog in the window does. + Some(if rounded { + overlay::Element::new(Box::new(Rounded { + overlay, + bounds: layout.bounds() + translation, + corners, + })) + } else { + overlay + }) + } +} + +/// A rounded window's overlay, rounded at the window's corners and lined at its edge again once +/// it's drawn ([`shape::round`]). +struct Rounded<'b, Message> { + overlay: overlay::Element<'b, Message, Theme, Renderer>, + /// The window's. + bounds: Rectangle, + corners: Corners, +} + +/// The frame's corners and line, last, in a layer of their own: drawn corners round everything +/// drawn before them ([`shape::round`]); the system's get only the line, at Windows 11's radius. +fn draw_corners(renderer: &mut Renderer, theme: &Theme, bounds: Rectangle, corners: Corners) { + let look = theme.window(); + let (radius, clear) = match corners { + Corners::Square => return, + Corners::Drawn => (look.radius, true), + Corners::System => (SYSTEM_CORNER_RADIUS, false), + }; + renderer.with_layer(bounds, |renderer| { + shape::round( + renderer, + bounds, + radius, + window::BORDER, + color(look.line), + clear, + ); + }); +} + +/// Windows 11's corners on a window that asks for them rounded (`DWMWCP_ROUND`): 8 pixels. +pub const SYSTEM_CORNER_RADIUS: f32 = 8.0; + +impl<Message> overlay::Overlay<Message, Theme, Renderer> for Rounded<'_, Message> { + fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node { + self.overlay.as_overlay_mut().layout(renderer, bounds) + } + + fn draw( + &self, + renderer: &mut Renderer, + theme: &Theme, + style: &renderer::Style, + layout: Layout<'_>, + cursor: mouse::Cursor, + ) { + self.overlay + .as_overlay() + .draw(renderer, theme, style, layout, cursor); + draw_corners(renderer, theme, self.bounds, self.corners); + } + + fn operate(&mut self, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn Operation) { + self.overlay + .as_overlay_mut() + .operate(layout, renderer, operation); + } + + fn update( + &mut self, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + renderer: &Renderer, + clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + ) { + self.overlay + .as_overlay_mut() + .update(event, layout, cursor, renderer, clipboard, shell); + } + + fn mouse_interaction( + &self, + layout: Layout<'_>, + cursor: mouse::Cursor, + renderer: &Renderer, + ) -> mouse::Interaction { + self.overlay + .as_overlay() + .mouse_interaction(layout, cursor, renderer) + } + + fn overlay<'a>( + &'a mut self, + layout: Layout<'a>, + renderer: &Renderer, + ) -> Option<overlay::Element<'a, Message, Theme, Renderer>> { + let (bounds, corners) = (self.bounds, self.corners); + self.overlay + .as_overlay_mut() + .overlay(layout, renderer) + .map(|overlay| { + overlay::Element::new(Box::new(Rounded { + overlay, + bounds, + corners, + })) + }) + } + + fn index(&self) -> f32 { + self.overlay.as_overlay().index() + } +} + +impl<'a, Message: 'a> From<WindowFrame<'a, Message>> for Element<'a, Message> { + fn from(frame: WindowFrame<'a, Message>) -> Self { + Element::new(frame) + } +} + +/// Which edge or corner of a window `size` big a point in it resizes, if any: a band +/// `RESIZE_BAND` wide inside each edge, and at each corner the band's parts reaching +/// `RESIZE_CORNER` along both edges (`crate::ui::tokens::window`). A window too small for both of +/// opposite bands resizes from the top and the left. +pub fn resize_edge(size: Size, at: Point) -> Option<Edge> { + let (band, corner) = (window::RESIZE_BAND, window::RESIZE_CORNER); + if !(0.0..size.width).contains(&at.x) || !(0.0..size.height).contains(&at.y) { + return None; + } + let (left, right) = (at.x < band, at.x >= size.width - band); + let (top, bottom) = (at.y < band, at.y >= size.height - band); + let sides = left || right; + let ends = top || bottom; + let north = top || (sides && at.y < corner); + let south = !north && (bottom || (sides && at.y >= size.height - corner)); + let west = left || (ends && at.x < corner); + let east = !west && (right || (ends && at.x >= size.width - corner)); + Some(match (north, south, west, east) { + (true, _, true, _) => Edge::NorthWest, + (true, _, _, true) => Edge::NorthEast, + (_, true, true, _) => Edge::SouthWest, + (_, true, _, true) => Edge::SouthEast, + (true, ..) => Edge::North, + (_, true, ..) => Edge::South, + (_, _, true, _) => Edge::West, + (_, _, _, true) => Edge::East, + _ => return None, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + const WINDOW: Size = Size::new(800.0, 600.0); + + fn at(x: f32, y: f32) -> Option<Edge> { + resize_edge(WINDOW, Point::new(x, y)) + } + + #[test] + fn the_middle_resizes_nothing() { + assert_eq!(at(400.0, 300.0), None); + assert_eq!(at(6.0, 300.0), None); + assert_eq!(at(400.0, 6.0), None); + assert_eq!(at(793.0, 300.0), None); + assert_eq!(at(400.0, 593.0), None); + // Outside the window: not its. + assert_eq!(at(-1.0, 300.0), None); + assert_eq!(at(800.0, 300.0), None); + assert_eq!(at(400.0, 600.0), None); + } + + #[test] + fn edges_resize_in_their_direction() { + assert_eq!(at(0.0, 300.0), Some(Edge::West)); + assert_eq!(at(5.9, 300.0), Some(Edge::West)); + assert_eq!(at(799.0, 300.0), Some(Edge::East)); + assert_eq!(at(794.0, 300.0), Some(Edge::East)); + assert_eq!(at(400.0, 0.0), Some(Edge::North)); + assert_eq!(at(400.0, 599.5), Some(Edge::South)); + // Just past a corner's reach, an edge again. + assert_eq!(at(14.0, 0.0), Some(Edge::North)); + assert_eq!(at(0.0, 14.0), Some(Edge::West)); + assert_eq!(at(785.9, 599.0), Some(Edge::South)); + } + + #[test] + fn corners_reach_along_both_edges() { + for (x, y) in [(0.0, 0.0), (13.9, 2.0), (2.0, 13.9), (5.0, 5.0)] { + assert_eq!(at(x, y), Some(Edge::NorthWest), "{x}, {y}"); + } + assert_eq!(at(799.0, 0.0), Some(Edge::NorthEast)); + assert_eq!(at(787.0, 3.0), Some(Edge::NorthEast)); + assert_eq!(at(797.0, 13.0), Some(Edge::NorthEast)); + assert_eq!(at(0.0, 599.0), Some(Edge::SouthWest)); + assert_eq!(at(10.0, 597.0), Some(Edge::SouthWest)); + assert_eq!(at(799.0, 599.0), Some(Edge::SouthEast)); + assert_eq!(at(796.0, 587.0), Some(Edge::SouthEast)); + // Inside the corner's square but off the band: nothing. + assert_eq!(at(10.0, 10.0), None); + } + + #[test] + fn a_tiny_window_resizes_from_the_top_left() { + let tiny = Size::new(10.0, 10.0); + assert_eq!( + resize_edge(tiny, Point::new(5.0, 5.0)), + Some(Edge::NorthWest) + ); + assert_eq!(resize_edge(Size::ZERO, Point::ORIGIN), None); + } + + #[test] + fn the_pointer_shows_the_direction() { + use mouse::Interaction::*; + let shapes = [ + (Edge::North, ResizingVertically), + (Edge::South, ResizingVertically), + (Edge::East, ResizingHorizontally), + (Edge::West, ResizingHorizontally), + (Edge::NorthWest, ResizingDiagonallyDown), + (Edge::SouthEast, ResizingDiagonallyDown), + (Edge::NorthEast, ResizingDiagonallyUp), + (Edge::SouthWest, ResizingDiagonallyUp), + ]; + for (direction, shape) in shapes { + assert_eq!(direction.cursor(), shape); + } + } + + #[test] + fn edge_tints_fade_straight_to_nothing() { + let theme = <Theme as Default>::default(); + let look = theme.header_bar(); + let Gradient::Linear(linear) = edge_tints(look.start, look.end, look.reach); + let stops: Vec<_> = linear.stops.iter().flatten().collect(); + assert_eq!(stops.len(), 8); + assert_eq!(stops[0].color, color(look.start)); + assert_eq!(stops[7].color, color(look.end)); + assert_eq!(stops[3].offset, 0.28); + assert_eq!(stops[3].color.a, 0.0); + assert_eq!(stops[4].color.a, 0.0); + // On the straight line from the tint to nothing. + assert!((stops[1].color.a - color(look.start).a * 2.0 / 3.0).abs() < 1e-6); + assert!((stops[6].color.a - color(look.end).a * 2.0 / 3.0).abs() < 1e-6); + } + + #[test] + fn headers_map_their_slots() { + let empty = header::<u8>(); + assert!(empty.is_empty()); + let full = header::<u8>() + .start(crate::ui::text::interface("Gallery")) + .center(crate::ui::text::interface("Search")) + .end(crate::ui::text::interface("Synced")); + assert!(!full.is_empty()); + let mapped = full.map(u32::from); + assert!(mapped.start.is_some() && mapped.center.is_some() && mapped.end.is_some()); + let only_end = header::<u8>().end(crate::ui::text::interface("Synced")); + assert!(!only_end.is_empty()); + } +} diff --git a/launcher/src/ui/chrome/fold.rs b/launcher/src/ui/chrome/fold.rs new file mode 100644 index 0000000000..bcad2e38bf --- /dev/null +++ b/launcher/src/ui/chrome/fold.rs @@ -0,0 +1,315 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! A folded window's two panes, its sidebar and its page, one at a time, as on a phone: choosing a +//! place slides the page in from the right over the sidebar, which drifts a little to the left +//! beneath it; going back slides the page out to the right, the sidebar coming back from the left. + +use iced::advanced::layout::{self, Layout}; +use iced::advanced::renderer; +use iced::advanced::widget::{Operation, Tree, Widget, tree}; +use iced::advanced::{Clipboard, Shell, mouse, overlay}; +use iced::{Event, Length, Rectangle, Size, Vector, window}; + +use crate::ui::tokens::motion; + +use crate::ui::transition::Transition; +use crate::ui::{Element, Renderer, Theme}; + +/// How far the sidebar drifts as the page covers it, a share of the width. +const DRIFT: f32 = 0.3; + +/// The sidebar and the page, `page` saying which shows. The page should have a fill of its own: +/// it passes over the sidebar. +pub fn folded<'a, Message>( + sidebar: impl Into<Element<'a, Message>>, + page: impl Into<Element<'a, Message>>, + page_shown: bool, +) -> Folded<'a, Message> { + Folded { + panes: [sidebar.into(), page.into()], + page_shown, + } +} + +/// A folded window's panes ([`folded`]). +pub struct Folded<'a, Message> { + panes: [Element<'a, Message>; 2], + page_shown: bool, +} + +/// Where the sidebar and the page are across a `width`, `at` the eased share of the way to the +/// page: the sidebar from 0 to drifted left, the page from off the right edge to 0. +fn offsets(at: f32, width: f32) -> (f32, f32) { + let at = at.clamp(0.0, 1.0); + (-width * DRIFT * at, width * (1.0 - at)) +} + +#[derive(Default)] +struct State { + /// Whether the page showed when last seen, and the slide under way: how far the page has + /// come in, from 0 to 1. + seen: Option<bool>, + slide: Option<Transition>, +} + +impl<Message> Folded<'_, Message> { + /// The pane that shows, or that's coming: the one that takes events, focus and menus. + fn shown(&self) -> usize { + usize::from(self.page_shown) + } +} + +impl<Message> Widget<Message, Theme, Renderer> for Folded<'_, Message> { + fn tag(&self) -> tree::Tag { + tree::Tag::of::<State>() + } + + fn state(&self) -> tree::State { + tree::State::new(State::default()) + } + + fn children(&self) -> Vec<Tree> { + self.panes.iter().map(Tree::new).collect() + } + + fn diff(&self, tree: &mut Tree) { + tree.diff_children(&self.panes); + } + + fn size(&self) -> Size<Length> { + Size::new(Length::Fill, Length::Fill) + } + + fn layout( + &mut self, + tree: &mut Tree, + renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + let size = limits.resolve(Length::Fill, Length::Fill, Size::ZERO); + let limits = layout::Limits::new(Size::ZERO, size); + // The pane that shows is laid out; the other only while it's drawn, sliding, or about to + // be, the other pane asked for. + let state = tree.state.downcast_ref::<State>(); + let both = state.slide.is_some() || state.seen != Some(self.page_shown); + let shown = self.shown(); + let nodes = self + .panes + .iter_mut() + .zip(&mut tree.children) + .enumerate() + .map(|(at, (pane, tree))| { + if both || at == shown { + pane.as_widget_mut().layout(tree, renderer, &limits) + } else { + layout::Node::new(Size::ZERO) + } + }) + .collect(); + layout::Node::with_children(size, nodes) + } + + fn operate( + &mut self, + tree: &mut Tree, + layout: Layout<'_>, + renderer: &Renderer, + operation: &mut dyn Operation, + ) { + let shown = self.shown(); + if let Some(pane_layout) = layout.children().nth(shown) { + self.panes[shown].as_widget_mut().operate( + &mut tree.children[shown], + pane_layout, + renderer, + operation, + ); + } + } + + fn update( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + renderer: &Renderer, + clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + viewport: &Rectangle, + ) { + let state = tree.state.downcast_mut::<State>(); + // The other pane asked for: it slides in; turned back part of the way, it goes back from + // where it got to. + if let Some(seen) = state.seen + && seen != self.page_shown + { + let (was, to) = ( + f32::from(u8::from(seen)), + f32::from(u8::from(self.page_shown)), + ); + Transition::turn(&mut state.slide, was, to, motion::SLOW, shell); + } + state.seen = Some(self.page_shown); + if let Event::Window(window::Event::RedrawRequested(now)) = event { + Transition::advance(&mut state.slide, *now, shell); + } + let shown = self.shown(); + // Sliding, the other pane's still drawn: it has the window's events too, with no pointer, + // so its own animations, such as the sidebar's mark, go on rather than freeze. + let sliding = tree.state.downcast_ref::<State>().slide.is_some(); + if sliding && matches!(event, Event::Window(_)) { + let other = 1 - shown; + if let Some(other_layout) = layout.children().nth(other) { + self.panes[other].as_widget_mut().update( + &mut tree.children[other], + event, + other_layout, + mouse::Cursor::Unavailable, + renderer, + clipboard, + shell, + viewport, + ); + } + } + // Sliding, nothing is where it's laid out, so the pointer is nowhere on it: a click lands + // once the pane has come. + let cursor = if sliding { + mouse::Cursor::Unavailable + } else { + cursor + }; + if let Some(pane_layout) = layout.children().nth(shown) { + self.panes[shown].as_widget_mut().update( + &mut tree.children[shown], + event, + pane_layout, + cursor, + renderer, + clipboard, + shell, + viewport, + ); + } + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + style: &renderer::Style, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + ) { + let state = tree.state.downcast_ref::<State>(); + let Some(slide) = state.slide else { + let shown = self.shown(); + if let Some(pane_layout) = layout.children().nth(shown) { + self.panes[shown].as_widget().draw( + &tree.children[shown], + renderer, + theme, + style, + pane_layout, + cursor, + viewport, + ); + } + return; + }; + // Sliding: the sidebar beneath, the page over it, neither under the pointer. Each in a + // layer of its own, the page's last: iced draws layers in the order they're made, so the + // page's fill, in a layer of its own, covers the layers the sidebar made, its list's. + let (sidebar, page) = offsets(slide.at(), layout.bounds().width); + for ((at, x), pane_layout) in [(0, sidebar), (1, page)].into_iter().zip(layout.children()) { + iced::advanced::Renderer::with_layer(renderer, layout.bounds(), |renderer| { + iced::advanced::Renderer::with_translation( + renderer, + Vector::new(x, 0.0), + |renderer| { + self.panes[at].as_widget().draw( + &tree.children[at], + renderer, + theme, + style, + pane_layout, + mouse::Cursor::Unavailable, + viewport, + ); + }, + ); + }); + } + } + + fn mouse_interaction( + &self, + tree: &Tree, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + renderer: &Renderer, + ) -> mouse::Interaction { + if tree.state.downcast_ref::<State>().slide.is_some() { + return mouse::Interaction::default(); + } + let shown = self.shown(); + layout + .children() + .nth(shown) + .map(|pane_layout| { + self.panes[shown].as_widget().mouse_interaction( + &tree.children[shown], + pane_layout, + cursor, + viewport, + renderer, + ) + }) + .unwrap_or_default() + } + + fn overlay<'b>( + &'b mut self, + tree: &'b mut Tree, + layout: Layout<'b>, + renderer: &Renderer, + viewport: &Rectangle, + translation: Vector, + ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { + let shown = self.shown(); + let pane_layout = layout.children().nth(shown)?; + let [sidebar, page] = &mut self.panes; + let pane = if shown == 1 { page } else { sidebar }; + pane.as_widget_mut().overlay( + &mut tree.children[shown], + pane_layout, + renderer, + viewport, + translation, + ) + } +} + +impl<'a, Message: 'a> From<Folded<'a, Message>> for Element<'a, Message> { + fn from(folded: Folded<'a, Message>) -> Self { + Element::new(folded) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_page_comes_in_from_the_right_as_the_sidebar_drifts_left() { + let near = + |(a, b): (f32, f32), (c, d): (f32, f32)| (a - c).abs() < 1e-3 && (b - d).abs() < 1e-3; + assert!(near(offsets(0.0, 400.0), (0.0, 400.0))); + assert!(near(offsets(1.0, 400.0), (-120.0, 0.0))); + assert!(near(offsets(0.5, 400.0), (-60.0, 200.0))); + } +} diff --git a/launcher/src/ui/edit.rs b/launcher/src/ui/edit.rs new file mode 100644 index 0000000000..a7524befb5 --- /dev/null +++ b/launcher/src/ui/edit.rs @@ -0,0 +1,547 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Single-line text editing: what a key does to a text and its selection. It knows nothing of +//! iced, so it's property-tested here and fuzzed on its own (fuzz/, which builds this file and +//! `secret.rs` by path). Offsets are bytes, always on grapheme boundaries, so an accent never parts +//! from its letter. + +use std::ops::Range; + +use unicode_segmentation::UnicodeSegmentation; + +/// Where a text is edited: a `String`, or a secret's fixed buffer. +pub trait Buffer { + fn text(&self) -> &str; + + /// Replaces a range, on char boundaries, with text. False, changing nothing, if the result + /// wouldn't fit. + fn replace(&mut self, range: Range<usize>, with: &str) -> bool; + + /// How many more bytes it takes. + fn room(&self) -> usize; +} + +impl Buffer for String { + fn text(&self) -> &str { + self + } + + fn replace(&mut self, range: Range<usize>, with: &str) -> bool { + self.replace_range(range, with); + true + } + + fn room(&self) -> usize { + usize::MAX + } +} + +/// A selection: from the anchor, where it started, to the head, where the caret is. Empty when +/// they meet. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)] +pub struct Selection { + pub anchor: usize, + pub head: usize, +} + +impl Selection { + /// Just a caret. + pub fn caret(at: usize) -> Self { + Self { + anchor: at, + head: at, + } + } + + pub fn range(&self) -> Range<usize> { + self.anchor.min(self.head)..self.anchor.max(self.head) + } + + pub fn is_empty(&self) -> bool { + self.anchor == self.head + } + + /// The selection within `text`, on its grapheme boundaries: for a text changed elsewhere. + pub fn clamp(self, text: &str) -> Self { + Self { + anchor: boundary_at_or_after(text, self.anchor), + head: boundary_at_or_after(text, self.head), + } + } +} + +/// Where the caret goes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Motion { + Left, + Right, + WordLeft, + WordRight, + Home, + End, +} + +/// An edit, as keys ask for them. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Edit<'a> { + /// Typed or pasted text, replacing the selection, as much as fits. The fields are + /// single-line: a line break or a tab between words is a space, and other control characters + /// are dropped. + Insert(&'a str), + /// Backspace: the selection, or the letter (or word) before the caret. + DeleteBack { + word: bool, + }, + /// Delete: the selection, or the letter (or word) after the caret. + DeleteForward { + word: bool, + }, + /// Moves the caret, extending the selection with `select`. + Move { + motion: Motion, + select: bool, + }, + SelectAll, +} + +/// What of a typed or pasted text goes into a line with `room` bytes left, as slices of it, so no +/// copy of it is made: what's typed into a secret lands only in its buffer. Control characters +/// are left out; a line break or a tab between words is a space, and at its ends nothing, so a +/// copied line's break doesn't come along. What doesn't fit is cut at a letter's end. +fn fitting(typed: &str, mut room: usize) -> Vec<&str> { + let typed = typed.trim_matches(char::is_control); + // Each piece, and whether it's a space put for a break. + let mut pieces = Vec::new(); + let (mut start, mut gap, mut spaced) = (0, false, false); + for (at, c) in typed.char_indices() { + if c.is_control() { + if !gap { + pieces.push((&typed[start..at], false)); + (gap, spaced) = (true, false); + } + spaced |= matches!(c, '\n' | '\r' | '\t' | '\u{b}' | '\u{c}'); + } else if gap { + if spaced { + pieces.push((" ", true)); + } + (gap, start) = (false, at); + } + } + if !gap { + pieces.push((&typed[start..], false)); + } + let mut kept: Vec<(&str, bool)> = Vec::with_capacity(pieces.len()); + for (piece, space) in pieces.into_iter().filter(|(piece, _)| !piece.is_empty()) { + if piece.len() <= room { + room -= piece.len(); + kept.push((piece, space)); + continue; + } + let end = piece + .grapheme_indices(true) + .map(|(at, letter)| at + letter.len()) + .take_while(|&end| end <= room) + .last() + .unwrap_or(0); + if end > 0 { + kept.push((&piece[..end], false)); + } + // Cut short after a break: not its space alone at the end. + if kept.last().is_some_and(|(_, space)| *space) { + kept.pop(); + } + break; + } + kept.into_iter().map(|(piece, _)| piece).collect() +} + +/// Applies an edit, and says whether the text changed. With `words` off, as for a hidden secret, +/// word motions and deletions reach the ends, so they show nothing of where its words are. +pub fn apply<B: Buffer + ?Sized>( + buffer: &mut B, + selection: &mut Selection, + edit: Edit<'_>, + words: bool, +) -> bool { + *selection = selection.clamp(buffer.text()); + let text = buffer.text(); + let at = selection.head; + let changed = match edit { + Edit::Insert(typed) => { + let range = selection.range(); + let pieces = fitting(typed, buffer.room().saturating_add(range.len())); + if pieces.is_empty() { + return false; + } + let mut at = range.start; + let mut done = buffer.replace(range, ""); + for piece in pieces { + done &= buffer.replace(at..at, piece); + at += piece.len(); + } + *selection = Selection::caret(at); + done + } + Edit::DeleteBack { word } => { + let range = if selection.is_empty() { + let from = match (word, words) { + (false, _) => previous(text, at), + (true, true) => word_start(text, at), + (true, false) => 0, + }; + from..at + } else { + selection.range() + }; + delete(buffer, selection, range) + } + Edit::DeleteForward { word } => { + let range = if selection.is_empty() { + let to = match (word, words) { + (false, _) => next(text, at), + (true, true) => word_end(text, at), + (true, false) => text.len(), + }; + at..to + } else { + selection.range() + }; + delete(buffer, selection, range) + } + Edit::Move { motion, select } => { + let range = selection.range(); + let head = match (motion, words) { + (Motion::Left, _) if !select && !selection.is_empty() => range.start, + (Motion::Right, _) if !select && !selection.is_empty() => range.end, + (Motion::Left, _) => previous(text, at), + (Motion::Right, _) => next(text, at), + (Motion::WordLeft, true) => word_start(text, at), + (Motion::WordRight, true) => word_end(text, at), + (Motion::Home, _) | (Motion::WordLeft, false) => 0, + (Motion::End, _) | (Motion::WordRight, false) => text.len(), + }; + *selection = if select { + Selection { + anchor: selection.anchor, + head, + } + } else { + Selection::caret(head) + }; + false + } + Edit::SelectAll => { + *selection = Selection { + anchor: 0, + head: text.len(), + }; + false + } + }; + *selection = selection.clamp(buffer.text()); + changed +} + +fn delete<B: Buffer + ?Sized>( + buffer: &mut B, + selection: &mut Selection, + range: Range<usize>, +) -> bool { + if range.is_empty() { + *selection = Selection::caret(range.start); + return false; + } + let start = range.start; + // Removing never grows the text, so it always fits. + let changed = buffer.replace(range, ""); + *selection = Selection::caret(start); + changed +} + +/// The grapheme boundary at or after a byte offset, or the end. +fn boundary_at_or_after(text: &str, at: usize) -> usize { + if at >= text.len() { + return text.len(); + } + text.grapheme_indices(true) + .map(|(start, _)| start) + .find(|start| *start >= at) + .unwrap_or(text.len()) +} + +/// The boundary before `at`, or the start. +fn previous(text: &str, at: usize) -> usize { + text.grapheme_indices(true) + .map(|(start, _)| start) + .take_while(|start| *start < at) + .last() + .unwrap_or(0) +} + +/// The boundary after `at`, or the end. +fn next(text: &str, at: usize) -> usize { + text.grapheme_indices(true) + .map(|(start, grapheme)| start + grapheme.len()) + .find(|end| *end > at) + .unwrap_or(text.len()) +} + +fn is_word(segment: &str) -> bool { + segment.chars().any(char::is_alphanumeric) +} + +/// The start of the word before `at`, skipping the spaces and punctuation in between. +fn word_start(text: &str, at: usize) -> usize { + text.split_word_bound_indices() + .rev() + .find(|(start, segment)| *start < at && is_word(segment)) + .map_or(0, |(start, _)| start) +} + +/// The end of the word after `at`. +fn word_end(text: &str, at: usize) -> usize { + text.split_word_bound_indices() + .map(|(start, segment)| (start + segment.len(), segment)) + .find(|(end, segment)| *end > at && is_word(segment)) + .map_or(text.len(), |(end, _)| end) +} + +/// How many graphemes come before a byte offset: a caret's place among the letters. +#[cfg(test)] +fn graphemes_before(text: &str, at: usize) -> usize { + text.grapheme_indices(true) + .take_while(|(start, _)| *start < at) + .count() +} + +/// The byte offset of the grapheme boundary nearest after a char offset, as a click finds it. +#[cfg(test)] +fn boundary_of_char(text: &str, chars: usize) -> usize { + let byte = text + .char_indices() + .nth(chars) + .map_or(text.len(), |(at, _)| at); + boundary_at_or_after(text, byte) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn run(text: &str, at: usize, edits: &[Edit<'_>]) -> (String, Selection) { + let mut text = text.to_owned(); + let mut selection = Selection::caret(at); + for edit in edits { + apply(&mut text, &mut selection, *edit, true); + } + (text, selection) + } + + #[test] + fn typing_replaces_the_selection() { + let (text, selection) = run("harbour", 0, &[Edit::SelectAll, Edit::Insert("Neon")]); + assert_eq!((text.as_str(), selection), ("Neon", Selection::caret(4))); + let (text, _) = run("ab", 1, &[Edit::Insert("x\r\ny\t\u{7}")]); + assert_eq!( + text, "ax yb", + "single line: a break a space, at the end nothing" + ); + let (text, _) = run("", 0, &[Edit::Insert("a\u{7}b\n")]); + assert_eq!(text, "ab", "other control characters dropped"); + let mut text = String::from("ab"); + let mut selection = Selection::caret(1); + assert!(!apply(&mut text, &mut selection, Edit::Insert("\n"), true)); + } + + #[test] + fn a_paste_that_doesnt_fit_is_cut_at_a_letters_end() { + assert_eq!(fitting("harbour", 4), ["harb"]); + // é as e and its accent: not parted. + assert_eq!(fitting("cafe\u{301}s", 5), ["caf"]); + assert_eq!( + fitting("one\ntwo", 4), + ["one"], + "not a break's space alone at the end" + ); + assert_eq!(fitting(" ", 4), [" "], "a typed space is a space"); + assert_eq!(fitting("one\ntwo", 6), ["one", " ", "tw"]); + assert!(fitting("x", 0).is_empty()); + } + + #[test] + fn deleting_takes_whole_graphemes() { + // e and a combining acute accent are one letter. + let (text, selection) = run("cafe\u{301}!", 6, &[Edit::DeleteBack { word: false }]); + assert_eq!((text.as_str(), selection), ("caf!", Selection::caret(3))); + let (text, _) = run("cafe\u{301}!", 3, &[Edit::DeleteForward { word: false }]); + assert_eq!(text, "caf!"); + let (text, selection) = run("", 0, &[Edit::DeleteBack { word: false }]); + assert_eq!((text.as_str(), selection), ("", Selection::caret(0))); + } + + #[test] + fn words_skip_spaces_and_punctuation() { + let text = "nvme0n1 — 512 GB"; + let mut selection = Selection::caret(text.len()); + let mut buffer = text.to_owned(); + let mut starts = Vec::new(); + for _ in 0..4 { + let left = Edit::Move { + motion: Motion::WordLeft, + select: false, + }; + apply(&mut buffer, &mut selection, left, true); + starts.push(selection.head); + } + assert_eq!(starts, [text.len() - 2, 12, 0, 0]); + let (rest, _) = run("one two three", 14, &[Edit::DeleteBack { word: true }]); + assert_eq!(rest, "one two "); + let (rest, _) = run("one two three", 3, &[Edit::DeleteForward { word: true }]); + assert_eq!(rest, "one three"); + } + + #[test] + fn hidden_words_reach_the_ends() { + let mut text = String::from("two words"); + let mut selection = Selection::caret(6); + let right = Edit::Move { + motion: Motion::WordRight, + select: false, + }; + apply(&mut text, &mut selection, right, false); + assert_eq!(selection, Selection::caret(9)); + apply( + &mut text, + &mut selection, + Edit::DeleteBack { word: true }, + false, + ); + assert_eq!(text, ""); + } + + #[test] + fn moving_collapses_or_extends_the_selection() { + let select = |motion| Edit::Move { + motion, + select: true, + }; + let go = |motion| Edit::Move { + motion, + select: false, + }; + let (_, selection) = run("harbour", 2, &[select(Motion::Right), select(Motion::End)]); + assert_eq!(selection, Selection { anchor: 2, head: 7 }); + let (_, selection) = run("harbour", 2, &[select(Motion::End), go(Motion::Left)]); + assert_eq!(selection, Selection::caret(2)); + let (_, selection) = run("harbour", 2, &[select(Motion::Home), go(Motion::Right)]); + assert_eq!(selection, Selection::caret(2)); + let (text, selection) = run( + "harbour", + 2, + &[select(Motion::End), Edit::DeleteBack { word: false }], + ); + assert_eq!((text.as_str(), selection), ("ha", Selection::caret(2))); + assert_eq!(Selection { anchor: 5, head: 1 }.range(), 1..5); + } + + #[test] + fn offsets_land_on_boundaries() { + let text = "e\u{301}x"; + assert_eq!(Selection::caret(1).clamp(text), Selection::caret(3)); + assert_eq!(Selection::caret(99).clamp(text), Selection::caret(4)); + assert_eq!(graphemes_before(text, 3), 1); + assert_eq!(graphemes_before(text, 4), 2); + assert_eq!(boundary_of_char(text, 1), 3); + assert_eq!(boundary_of_char(text, 9), 4); + } + + mod properties { + use super::*; + use proptest::prelude::*; + + fn edit() -> impl Strategy<Value = (u8, String)> { + (0u8..12, "[a-z é\u{301}🙂\n—-]{0,4}") + } + + fn to_edit((kind, text): &(u8, String)) -> Edit<'_> { + let motion = [ + Motion::Left, + Motion::Right, + Motion::WordLeft, + Motion::WordRight, + Motion::Home, + Motion::End, + ][usize::from(*kind) % 6]; + match kind { + 0..=2 => Edit::Insert(text), + 3 => Edit::DeleteBack { word: false }, + 4 => Edit::DeleteBack { word: true }, + 5 => Edit::DeleteForward { word: false }, + 6 => Edit::DeleteForward { word: true }, + 7 => Edit::SelectAll, + 8 | 9 => Edit::Move { + motion, + select: true, + }, + _ => Edit::Move { + motion, + select: false, + }, + } + } + + fn is_boundary(text: &str, at: usize) -> bool { + at == text.len() || text.grapheme_indices(true).any(|(start, _)| start == at) + } + + proptest! { + #[test] + fn the_selection_stays_on_boundaries( + start in "[a-z é\u{301}🙂]{0,8}", + edits in proptest::collection::vec(edit(), 0..24), + words: bool, + ) { + let mut text = start; + let mut selection = Selection::caret(text.len()); + for edit in &edits { + apply(&mut text, &mut selection, to_edit(edit), words); + prop_assert!(is_boundary(&text, selection.anchor)); + prop_assert!(is_boundary(&text, selection.head)); + prop_assert!(!text.chars().any(char::is_control)); + } + } + + #[test] + fn typing_then_backspacing_restores_the_text( + start in "[a-z é🙂]{0,8}", + typed in "[a-z🙂]{1,6}", + at in 0usize..10, + ) { + let mut text = start.clone(); + let mut selection = Selection::caret(at).clamp(&text); + for letter in typed.chars() { + let letter = letter.to_string(); + apply(&mut text, &mut selection, Edit::Insert(&letter), true); + } + for _ in typed.chars() { + apply(&mut text, &mut selection, Edit::DeleteBack { word: false }, true); + } + prop_assert_eq!(text, start); + } + + #[test] + fn moves_never_change_the_text( + start in "[a-z é\u{301}🙂—]{0,8}", + moves in proptest::collection::vec(8u8..12, 0..16), + ) { + let mut text = start.clone(); + let mut selection = Selection::caret(0); + for kind in moves { + let edit = (kind, String::new()); + prop_assert!(!apply(&mut text, &mut selection, to_edit(&edit), true)); + } + prop_assert_eq!(text, start); + } + } + } +} diff --git a/launcher/src/ui/field.rs b/launcher/src/ui/field.rs new file mode 100644 index 0000000000..8da4712c51 --- /dev/null +++ b/launcher/src/ui/field.rs @@ -0,0 +1,483 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Text fields: [`TextField`], single-line, with a caret that blinks only for a few seconds after +//! the last input, and selection by Shift and the arrow keys or by dragging. A text field's value +//! is the app's, as iced's are. +//! +//! Input methods: none are asked for yet. A text field takes their committed text when the +//! desktop turns them on. + +mod text; + +pub use text::{TextField, text_field}; + +use std::time::Duration; + +use iced::advanced::Renderer as _; +use iced::advanced::Shell; +use iced::keyboard::{Key, Modifiers, key::Named}; +use iced::time::Instant; +use iced::{Point, Rectangle, Size, mouse}; + +use crate::ui::tokens::{motion, size, space, typography}; + +use crate::ui::edit::{Edit, Motion, Selection}; +use crate::ui::focus::Focus; +use crate::ui::paint::{self, Plain}; +use crate::ui::theme::{Interaction, Look, color}; +use crate::ui::{Renderer, Theme}; + +/// The padding inside a field. +const PAD: f32 = space::L; + +/// The caret's blink: for a few seconds after the last input, shown, fading out, hidden and +/// fading in again, then shown and still. +#[derive(Debug, Clone, Copy, Default)] +struct Blink { + since: Option<Instant>, + /// How much it shows, from 0 to 1. + opacity: f32, +} + +/// How long the caret takes to fade out, or in: most of each half of its blink, slowly. +const CARET_FADE: Duration = motion::SLOW; +/// A frame, while the caret fades: the next one's asked for this soon, 30 a second. Each frame +/// draws the whole window again, and a fade this slow looks as smooth at 30 as at 60. +const FRAME: Duration = Duration::from_millis(33); + +impl Blink { + fn restart(&mut self) { + self.start(Instant::now()); + } + + /// Shows the caret, blinking from `now`. + fn start(&mut self, now: Instant) { + self.since = Some(now); + self.opacity = 1.0; + } + + /// At a redraw: how much the caret shows now, and when to draw next while it blinks: every + /// frame while it fades, and otherwise when it next starts to. + fn at(&mut self, now: Instant) -> Option<Instant> { + let since = self.since?; + let elapsed = now.saturating_duration_since(since); + if elapsed >= motion::CARET_BLINKS_FOR { + self.opacity = 1.0; + return None; + } + let blink = motion::CARET_BLINK; + let fade = crate::ui::system::duration(CARET_FADE).min(blink); + let period = blink * 2; + let periods = u32::try_from(elapsed.as_nanos() / period.as_nanos()).unwrap_or(u32::MAX); + let start = since + period * periods; + let into = now.saturating_duration_since(start); + let faded = |from: Duration| { + motion::EASE.at(into.saturating_sub(from).as_secs_f32() / fade.as_secs_f32()) + }; + // Shown, fading out by half way; hidden, fading in by the end. + let (opacity, next) = if into < blink - fade { + (1.0, start + blink - fade) + } else if into < blink { + (1.0 - faded(blink - fade), now + FRAME) + } else if into < period - fade { + (0.0, start + period - fade) + } else { + (faded(period - fade), now + FRAME) + }; + self.opacity = opacity; + Some(next.min(since + motion::CARET_BLINKS_FOR)) + } +} + +/// What both fields keep of their line: focus, the selection, the scroll, the caret, and where +/// each letter boundary is, worked out once a layout. +#[derive(Default)] +struct Line { + focus: Focus, + selection: Selection, + scroll: f32, + blink: Blink, + /// Whether it had focus at the last redraw: gaining it starts the caret. + was_focused: bool, + dragging: bool, + modifiers: Modifiers, + /// Every letter boundary's byte offset and x, from the text's start. + xs: Vec<(usize, f32)>, + placeholder: Plain, + /// How wide the text area was at the last layout. + width: f32, +} + +impl Line { + /// How far the text reaches: its rightmost boundary, the end of left-to-right text, the + /// start of right-to-left. + fn end(&self) -> f32 { + self.xs.iter().map(|(_, x)| *x).fold(0.0, f32::max) + } + + fn x_of(&self, at: usize) -> f32 { + self.xs + .iter() + .find(|(offset, _)| *offset >= at) + .or(self.xs.last()) + .map_or(0.0, |(_, x)| *x) + } + + /// The boundary nearest an x from the text's start. + fn hit(&self, x: f32) -> usize { + self.xs + .iter() + .min_by(|(_, a), (_, b)| (a - x).abs().total_cmp(&(b - x).abs())) + .map_or(0, |(at, _)| *at) + } + + /// At a layout: the text area is this wide, and the caret stays in sight in it. + fn laid_out(&mut self, width: f32) { + self.width = width; + self.follow_caret(width); + } + + /// The caret or the selection moved, and the text didn't change: the caret stays in sight, + /// with no new layout. + fn caret_moved<Message>(&mut self, shell: &mut Shell<'_, Message>) { + self.follow_caret(self.width); + shell.request_redraw(); + } + + /// Scrolls so the caret stays in sight in an area this wide. + fn follow_caret(&mut self, width: f32) { + let caret = self.x_of(self.selection.head); + if caret - self.scroll > width - size::CARET { + self.scroll = caret - width + size::CARET; + } else if caret < self.scroll { + self.scroll = caret; + } + let end = self.end(); + self.scroll = self + .scroll + .min((end - width + size::CARET).max(0.0)) + .max(0.0); + } + + /// A press in the text: the caret goes there, or the selection reaches there with Shift. A + /// focus scope lets go of focus as the press reaches it, so it counts as focused if it was at + /// the last redraw. + fn press(&mut self, x: f32) { + let at = self.hit(x + self.scroll); + let focused = self.focus.is_focused() || self.was_focused; + self.selection = if self.modifiers.shift() && focused { + Selection { + anchor: self.selection.anchor, + head: at, + } + } else { + Selection::caret(at) + }; + self.focus.click(); + self.dragging = true; + self.blink.restart(); + } + + /// The pointer moved while dragging: whether the selection changed. + fn drag(&mut self, x: f32) -> bool { + let at = self.hit(x + self.scroll); + if at == self.selection.head { + return false; + } + self.selection.head = at; + self.blink.restart(); + true + } + + /// A redraw: the caret's blink asks for the next. Focus just come, by Tab or a click, the + /// caret shows at once, blinking. + fn redraw<Message>(&mut self, now: Instant, shell: &mut Shell<'_, Message>) { + let focused = self.focus.is_focused(); + if focused && !self.was_focused { + self.blink.start(now); + } + self.was_focused = focused; + if focused && let Some(next) = self.blink.at(now) { + shell.request_redraw_at(next); + } + } +} + +/// The text area inside a field's bounds, left of a toggle this wide, if any. +fn text_area(bounds: Rectangle, toggle: Option<f32>) -> Rectangle { + let inner = bounds.shrink([0.0, PAD]); + match toggle { + None => inner, + Some(width) => Rectangle { + width: (bounds.width - PAD - space::XS - width - space::S).max(0.0), + ..inner + }, + } +} + +fn interaction(enabled: bool, over: bool) -> Interaction { + if !enabled { + Interaction::Disabled + } else if over { + Interaction::Hovered + } else { + Interaction::Idle + } +} + +/// The edit a key asks for, if any. `latin` is the key's letter on a Latin layout, by where it +/// is: Ctrl+A selects all whatever layout's letter is on the A key. +fn key_edit<'k>( + key: &Key, + latin: Option<char>, + text: Option<&'k str>, + modifiers: Modifiers, +) -> Option<Edit<'k>> { + let word = modifiers.command(); + let select = modifiers.shift(); + let go = |motion| Some(Edit::Move { motion, select }); + match key { + Key::Named(Named::Backspace) => Some(Edit::DeleteBack { word }), + Key::Named(Named::Delete) => Some(Edit::DeleteForward { word }), + Key::Named(Named::ArrowLeft) if word => go(Motion::WordLeft), + Key::Named(Named::ArrowRight) if word => go(Motion::WordRight), + Key::Named(Named::ArrowLeft) => go(Motion::Left), + Key::Named(Named::ArrowRight) => go(Motion::Right), + Key::Named(Named::Home) => go(Motion::Home), + Key::Named(Named::End) => go(Motion::End), + Key::Character(_) if modifiers.command() && latin == Some('a') => Some(Edit::SelectAll), + _ if modifiers.command() || modifiers.alt() => None, + _ => text + .filter(|text| !text.chars().any(char::is_control) && !text.is_empty()) + .map(Edit::Insert), + } +} + +/// Draws a field's box, and inside its text area the selection, the content and the caret; then +/// the focus ring at `ring` of its strength, as it fades in and out. +#[allow(clippy::too_many_arguments)] +fn draw_line( + renderer: &mut Renderer, + theme: &Theme, + line: &Line, + bounds: Rectangle, + area: Rectangle, + look: &Look, + focused: bool, + ring: f32, + preview: bool, + empty: bool, + content: impl FnOnce(&mut Renderer, f32, f32, Rectangle), +) { + paint::boxed(renderer, bounds, look); + let height = typography::INTERFACE.size * typography::INTERFACE.line_height; + let top = bounds.center_y() - height / 2.0; + let origin = area.x - line.scroll; + let clip = Rectangle { + x: area.x - size::CARET, + width: area.width + 2.0 * size::CARET, + ..bounds + }; + // How much the caret shows: a preview's still at the end. + let shown = |focused: bool, opacity: f32| if focused { opacity } else { 0.0 }; + let (caret_shown, selection) = if preview { + let end = line.xs.last().map_or(0, |(at, _)| *at); + (shown(focused, 1.0), Selection::caret(end)) + } else { + (shown(focused, line.blink.opacity), line.selection) + }; + // Kept to the text area, in a layer clipped to it, only when there's more than fits: each + // layer costs a frame a text preparation of its own. What fits is inside without one, and + // text is clipped where it's drawn. + let overflows = !empty && (line.scroll > 0.0 || line.end() > area.width); + let inside = |renderer: &mut Renderer| { + if !selection.is_empty() && focused { + // From the lesser x to the greater: right to left, the selection's start is right + // of its end. + let (a, b) = ( + line.x_of(selection.range().start), + line.x_of(selection.range().end), + ); + let (from, to) = (a.min(b), a.max(b)); + let marked = Look::solid(theme.selection(), 0.0); + let bounds = + Rectangle::new(Point::new(origin + from, top), Size::new(to - from, height)); + paint::boxed(renderer, bounds, &marked); + } + if empty { + let ink = color(theme.placeholder()); + paint::fill( + renderer, + &line.placeholder, + Point::new(area.x, top), + ink, + clip, + ); + } else { + content(renderer, origin, top, clip); + } + if caret_shown > 0.0 && selection.is_empty() { + let x = origin + line.x_of(selection.head); + let ink = theme.caret(); + // Round at both ends: its corners half its width. + let caret = Look::solid(ink.opacity(ink.alpha() * caret_shown), size::CARET / 2.0); + let bounds = Rectangle::new(Point::new(x, top), Size::new(size::CARET, height)); + paint::boxed(renderer, bounds, &caret); + } + }; + if overflows { + renderer.with_layer(clip, inside); + } else { + inside(renderer); + } + paint::outline_lit(renderer, theme, bounds, look.radius, ring); +} + +/// Whether a press is outside a field: it lets go of focus, as a click elsewhere does, without +/// waiting for a focus scope. +pub(crate) fn pressed_outside( + event: &iced::Event, + cursor: mouse::Cursor, + bounds: Rectangle, +) -> bool { + matches!( + event, + iced::Event::Mouse(mouse::Event::ButtonPressed(_)) + | iced::Event::Touch(iced::touch::Event::FingerPressed { .. }) + ) && !cursor.is_over(bounds) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_caret_fades_out_and_in_then_stays() { + let mut blink = Blink::default(); + assert_eq!(blink.at(Instant::now()), None, "no input, no blinking"); + blink.restart(); + let since = blink.since.unwrap(); + let (half, fade) = (motion::CARET_BLINK, CARET_FADE); + // Shown, and nothing to draw till it starts to fade. + assert_eq!(blink.at(since), Some(since + half - fade)); + assert_eq!(blink.opacity, 1.0); + // Fading out: partly shown, and the next frame wanted. + let fading = since + half - fade / 2; + assert_eq!(blink.at(fading), Some(fading + FRAME)); + assert!(blink.opacity > 0.0 && blink.opacity < 1.0); + // Hidden, till it starts to fade back in. + assert_eq!(blink.at(since + half), Some(since + 2 * half - fade)); + assert_eq!(blink.opacity, 0.0); + // The last redraw it asks for is when it stops, shown. + let late = since + motion::CARET_BLINKS_FOR - Duration::from_millis(1); + assert_eq!(blink.at(late), Some(since + motion::CARET_BLINKS_FOR)); + assert_eq!(blink.at(since + motion::CARET_BLINKS_FOR), None); + assert_eq!(blink.opacity, 1.0); + } + + #[test] + fn focus_coming_shows_the_caret_blinking() { + let mut line = Line::default(); + let mut messages: Vec<()> = Vec::new(); + let mut shell = Shell::new(&mut messages); + let now = Instant::now(); + line.focus.click(); + line.redraw(now, &mut shell); + assert_eq!(line.blink.opacity, 1.0, "focused, the caret shows at once"); + assert_eq!(line.blink.since, Some(now)); + } + + #[test] + fn ctrl_a_selects_all_on_any_layout() { + // A Russian layout's key where A is types Ñ„: by where it is, it's still Ctrl+A. + let key = Key::Character("Ñ„".into()); + assert_eq!( + key_edit(&key, Some('a'), None, Modifiers::CTRL), + Some(Edit::SelectAll) + ); + assert_eq!(key_edit(&key, None, None, Modifiers::CTRL), None); + } + + #[test] + fn keys_ask_for_edits() { + let none = Modifiers::empty(); + let edit = |key: Key, text: Option<&'static str>, modifiers| { + let latin = match &key { + Key::Character(c) => c.chars().next(), + Key::Named(_) | Key::Unidentified => None, + }; + key_edit(&key, latin, text, modifiers) + }; + assert_eq!( + edit(Key::Named(Named::Backspace), None, Modifiers::CTRL), + Some(Edit::DeleteBack { word: true }) + ); + assert_eq!( + edit(Key::Named(Named::ArrowLeft), None, Modifiers::SHIFT), + Some(Edit::Move { + motion: Motion::Left, + select: true + }) + ); + assert_eq!( + edit(Key::Named(Named::ArrowRight), None, Modifiers::CTRL), + Some(Edit::Move { + motion: Motion::WordRight, + select: false + }) + ); + assert_eq!( + edit(Key::Character("a".into()), Some("a"), Modifiers::CTRL), + Some(Edit::SelectAll) + ); + assert_eq!( + edit(Key::Character("é".into()), Some("é"), none), + Some(Edit::Insert("é")) + ); + assert_eq!( + edit(Key::Character("q".into()), Some("q"), Modifiers::ALT), + None + ); + assert_eq!( + edit(Key::Character("c".into()), Some("c"), Modifiers::CTRL), + None + ); + assert_eq!(edit(Key::Named(Named::Escape), Some("\u{1b}"), none), None); + assert_eq!(edit(Key::Named(Named::F1), None, none), None); + } + + #[test] + fn a_line_finds_and_follows_its_caret() { + let mut line = Line { + xs: vec![(0, 0.0), (1, 10.0), (2, 20.0), (3, 30.0)], + ..Line::default() + }; + assert_eq!(line.x_of(2), 20.0); + assert_eq!(line.x_of(9), 30.0); + assert_eq!(line.hit(14.0), 1); + assert_eq!(line.hit(16.0), 2); + line.selection = Selection::caret(3); + line.follow_caret(12.0); + assert_eq!(line.scroll, 20.0); + line.selection = Selection::caret(0); + line.follow_caret(12.0); + assert_eq!(line.scroll, 0.0); + line.press(25.0); + assert_eq!(line.selection, Selection::caret(2)); + assert!(line.focus.is_focused() && line.dragging); + assert!(line.drag(5.0)); + assert!(!line.drag(4.0)); + assert_eq!(line.selection, Selection { anchor: 2, head: 0 }); + } + + #[test] + fn areas_leave_room_for_the_toggle() { + let bounds = Rectangle::new(Point::ORIGIN, Size::new(200.0, 36.0)); + assert_eq!(text_area(bounds, None).width, 200.0 - 2.0 * PAD); + let area = text_area(bounds, Some(50.0)); + assert_eq!(area.width, 200.0 - PAD - 50.0 - space::XS - space::S); + assert_eq!(interaction(false, true), Interaction::Disabled); + assert_eq!(interaction(true, true), Interaction::Hovered); + assert_eq!(interaction(true, false), Interaction::Idle); + } +} diff --git a/launcher/src/ui/field/text.rs b/launcher/src/ui/field/text.rs new file mode 100644 index 0000000000..121297285e --- /dev/null +++ b/launcher/src/ui/field/text.rs @@ -0,0 +1,601 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! The text field: a name, a host name, a list's filter. Its value is the app's. + +use std::borrow::Cow; + +use iced::advanced::layout::{self, Layout}; +use iced::advanced::text::Renderer as _; +use iced::advanced::widget::{Operation, Tree, Widget, tree}; +use iced::advanced::{Clipboard, Shell, clipboard, input_method, mouse, renderer}; +use iced::keyboard::{self, Key, key::Named}; +use iced::{Event, Length, Point, Rectangle, Size, touch, window}; +use unicode_segmentation::UnicodeSegmentation; + +use crate::ui::tokens::{size, typography}; + +use super::{Line, draw_line, interaction, key_edit, pressed_outside, text_area}; +use crate::ui::edit::{self, Buffer, Edit}; +use crate::ui::input; +use crate::ui::paint::{self, Plain}; +use crate::ui::theme::{Interaction, color}; +use crate::ui::{Element, Renderer, Theme}; + +/// The longest value a text field takes by default, in bytes: a name, a host name. +pub const MAX_LEN: usize = 256; + +/// A single-line text field showing `value`. Without a message for input it is disabled. +pub fn text_field<'a, Message>( + placeholder: impl Into<String>, + value: &'a str, +) -> TextField<'a, Message> { + TextField { + placeholder: placeholder.into(), + value: Cow::Borrowed(value), + on_input: None, + on_submit: None, + max_len: MAX_LEN, + invalid: false, + width: Length::Fill, + preview: None, + } +} + +/// A text field. Ctrl+C, X and V copy, cut and paste. +pub struct TextField<'a, Message> { + placeholder: String, + /// The app's value, and after an edit the new one, so a second key in the same batch of + /// events edits that, as the app will. + value: Cow<'a, str>, + on_input: Option<Box<dyn Fn(String) -> Message + 'a>>, + on_submit: Option<Message>, + max_len: usize, + invalid: bool, + width: Length, + preview: Option<(Interaction, bool)>, +} + +impl<'a, Message> TextField<'a, Message> { + /// The message for each change, with the new value. + pub fn on_input(self, on_input: impl Fn(String) -> Message + 'a) -> Self { + Self { + on_input: Some(Box::new(on_input)), + ..self + } + } + + /// The message Enter sends. + pub fn on_submit(self, message: Message) -> Self { + Self { + on_submit: Some(message), + ..self + } + } + + /// The longest value it takes, in bytes: [`MAX_LEN`] unless set. A paste that would make it + /// longer is cut to what fits, at a letter's end; a value already longer, from the app, can + /// still be shortened. + pub fn max_len(self, max_len: usize) -> Self { + Self { max_len, ..self } + } + + /// Shows the value as not acceptable, with a red line. Say why next to it. + pub fn invalid(self, invalid: bool) -> Self { + Self { invalid, ..self } + } + + pub fn width(self, width: impl Into<Length>) -> Self { + Self { + width: width.into(), + ..self + } + } + + /// Draws it as if in this state, for the gallery; focused, with a still caret at the end. + pub fn preview(self, interaction: Interaction, focused: bool) -> Self { + Self { + preview: Some((interaction, focused)), + ..self + } + } + + fn enabled(&self) -> bool { + self.on_input.is_some() + } + + /// Applies an edit, telling the app the new value. + fn edit(&mut self, line: &mut Line, edit: Edit<'_>, shell: &mut Shell<'_, Message>) { + let mut value = Limited::new(self.value.clone().into_owned(), self.max_len); + if edit::apply(&mut value, &mut line.selection, edit, true) { + if let Some(on_input) = &self.on_input { + shell.publish(on_input(value.text.clone())); + } + self.value = Cow::Owned(value.text); + // Laid out again, the new text's shaped before another key in the same batch. + shell.invalidate_layout(); + shell.request_redraw(); + } else { + line.caret_moved(shell); + } + line.blink.restart(); + } + + /// Ctrl+C, X, V and A: by where the key is, on any layout. + fn clipboard( + &mut self, + line: &mut Line, + key: &str, + clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + ) -> bool { + let selected = self + .value + .get(line.selection.range()) + .unwrap_or_default() + .to_owned(); + match key { + "c" if !selected.is_empty() => { + clipboard.write(clipboard::Kind::Standard, selected); + true + } + "x" if !selected.is_empty() => { + clipboard.write(clipboard::Kind::Standard, selected); + self.edit(line, Edit::DeleteBack { word: false }, shell); + true + } + "v" => { + if let Some(pasted) = clipboard.read(clipboard::Kind::Standard) { + self.edit(line, Edit::Insert(&pasted), shell); + } + true + } + "a" => { + self.edit(line, Edit::SelectAll, shell); + true + } + _ => false, + } + } +} + +/// A value under edit, which grows no longer than its limit. One already longer, from the app, +/// can shrink but not grow: within an edit it may go back up to the length it had. +struct Limited { + text: String, + max: usize, +} + +impl Limited { + fn new(text: String, limit: usize) -> Self { + let max = limit.max(text.len()); + Self { text, max } + } +} + +impl Buffer for Limited { + fn text(&self) -> &str { + &self.text + } + + fn replace(&mut self, range: std::ops::Range<usize>, with: &str) -> bool { + if self.text.len() - range.len() + with.len() > self.max { + return false; + } + self.text.replace_range(range, with); + true + } + + fn room(&self) -> usize { + self.max.saturating_sub(self.text.len()) + } +} + +/// Every letter boundary's offset and x in a shaped line. A boundary is where its letter's glyph +/// begins: the glyph's left edge, or, right to left, as Hebrew and Arabic run, its right edge; +/// inside a glyph that covers several letters, part of the way along it; at the text's end, or a +/// letter with no glyph of its own, where the glyph before it ends. Glyphs come in the order +/// they're drawn, which right to left reverses, so each byte is first matched to its glyph. +pub(super) fn boundaries(paragraph: &Plain, text: &str) -> Vec<(usize, f32)> { + let glyphs: Vec<(usize, usize, f32, f32, bool)> = paragraph + .raw() + .buffer() + .layout_runs() + .next() + .map(|run| { + run.glyphs + .iter() + .map(|g| (g.start, g.end, g.x, g.w, g.level.is_rtl())) + .collect() + }) + .unwrap_or_default(); + // Which glyph each byte is in. + let mut owner: Vec<Option<usize>> = vec![None; text.len() + 1]; + for (at, &(start, end, ..)) in glyphs.iter().enumerate() { + for byte in owner.iter_mut().take(end.min(text.len())).skip(start) { + *byte = Some(at); + } + } + let edge = |at: usize| match owner.get(at).copied().flatten() { + Some(glyph) => { + let (start, end, x, w, rtl) = glyphs[glyph]; + let along = w * (at - start) as f32 / (end - start).max(1) as f32; + if rtl { x + w - along } else { x + along } + } + None => owner[..at.min(owner.len())] + .iter() + .rev() + .flatten() + .next() + .map_or(0.0, |&glyph| { + let (_, _, x, w, rtl) = glyphs[glyph]; + if rtl { x } else { x + w } + }), + }; + text.grapheme_indices(true) + .map(|(at, _)| at) + .chain(std::iter::once(text.len())) + .map(|at| (at, edge(at))) + .collect() +} + +#[derive(Default)] +struct TextState { + line: Line, + value: Plain, + /// What it showed when last drawn: how it looks, focus, how much the caret shows, the + /// selection. + drawn: Option<(Interaction, bool, u8, crate::ui::edit::Selection)>, + /// Its glow under the pointer, fading in and out on the glows' own timing. + lit: crate::ui::transition::Lit, + /// Its focus ring, fading in and out with focus on the same timing. + focus_lit: crate::ui::transition::Lit, +} + +impl<Message: Clone> Widget<Message, Theme, Renderer> for TextField<'_, Message> { + fn tag(&self) -> tree::Tag { + tree::Tag::of::<TextState>() + } + + fn state(&self) -> tree::State { + tree::State::new(TextState::default()) + } + + fn size(&self) -> Size<Length> { + Size::new(self.width, Length::Shrink) + } + + fn layout( + &mut self, + tree: &mut Tree, + _renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + let state = tree.state.downcast_mut::<TextState>(); + let role = &typography::INTERFACE; + paint::shape(&mut state.line.placeholder, role, &self.placeholder); + // The letter boundaries are found again only when the text is shaped again. + if paint::shape(&mut state.value, role, &self.value) || state.line.xs.is_empty() { + state.line.xs = boundaries(&state.value, &self.value); + } + state.line.selection = state.line.selection.clamp(&self.value); + let size = limits.resolve(self.width, Length::Shrink, Size::new(0.0, size::CONTROL)); + let size = Size::new(size.width, size::CONTROL); + let area = text_area(Rectangle::with_size(size), None); + state.line.laid_out(area.width); + layout::Node::new(size) + } + + fn operate( + &mut self, + tree: &mut Tree, + layout: Layout<'_>, + _renderer: &Renderer, + operation: &mut dyn Operation, + ) { + if self.enabled() && self.preview.is_none() { + let state = tree.state.downcast_mut::<TextState>(); + let area = text_area(layout.bounds(), None); + operation.focusable(None, area, &mut state.line.focus); + } + } + + fn update( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + _renderer: &Renderer, + clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + _viewport: &Rectangle, + ) { + // A preview is a picture of a state: it takes no input. + if self.preview.is_some() { + return; + } + let state = tree.state.downcast_mut::<TextState>(); + // Disabled, it lets go of focus: no outline, keys no longer its, and no second focus + // once it's enabled again. + if !self.enabled() && state.line.focus.is_focused() { + state.line.focus.unfocus(); + shell.request_redraw(); + } + let line = &mut state.line; + let bounds = layout.bounds(); + let area = text_area(bounds, None); + if let Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) = event { + line.modifiers = *modifiers; + } + if let Event::Window(window::Event::RedrawRequested(now)) = event { + line.redraw(*now, shell); + } + if pressed_outside(event, cursor, bounds) && line.focus.is_focused() { + line.focus.unfocus(); + shell.request_redraw(); + } + if self.enabled() { + match event { + Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerPressed { .. }) + if cursor.is_over(bounds) => + { + line.press(cursor.position().map_or(0.0, |p| p.x) - area.x); + line.caret_moved(shell); + shell.capture_event(); + } + Event::Mouse(mouse::Event::CursorMoved { position }) + | Event::Touch(touch::Event::FingerMoved { position, .. }) + if line.dragging => + { + if line.drag(position.x - area.x) { + line.caret_moved(shell); + } + } + Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) + | Event::Touch( + touch::Event::FingerLifted { .. } | touch::Event::FingerLost { .. }, + ) => line.dragging = false, + Event::Keyboard(keyboard::Event::KeyPressed { + key, + text, + modifiers, + physical_key, + repeat, + .. + }) if line.focus.is_focused() => { + let handled = match key { + // Enter is the field's only with something to send, and sends it once a + // press; without, it's the form's or the app's. + Key::Named(Named::Enter) => match &self.on_submit { + Some(message) => { + if !repeat { + shell.publish(message.clone()); + } + true + } + None => false, + }, + // By where the key is, not what it types: Ctrl+C copies on any layout. + Key::Character(_) if modifiers.command() => { + let latin = key.to_latin(*physical_key).map(String::from); + self.clipboard(line, latin.as_deref().unwrap_or(""), clipboard, shell) + } + _ => match key_edit( + key, + key.to_latin(*physical_key), + text.as_deref(), + *modifiers, + ) { + Some(edit) => { + self.edit(line, edit, shell); + true + } + None => false, + }, + }; + if handled { + line.focus.key(); + shell.capture_event(); + } + } + Event::InputMethod(input_method::Event::Commit(text)) + if line.focus.is_focused() => + { + self.edit(line, Edit::Insert(text), shell); + shell.capture_event(); + } + _ => {} + } + } + let shown = interaction(self.enabled(), cursor.is_over(bounds)); + state.lit.frame(event, shell); + state.lit.aim( + matches!(shown, Interaction::Hovered | Interaction::Pressed), + shell, + ); + let focused = line.focus.is_focused(); + state.focus_lit.frame(event, shell); + state.focus_lit.aim(focused, shell); + let now = ( + shown, + line.focus.is_focused(), + (line.blink.opacity * 255.0).round() as u8, + line.selection, + ); + input::redraw_on_change(&mut state.drawn, now, event, shell); + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + _style: &renderer::Style, + layout: Layout<'_>, + cursor: mouse::Cursor, + _viewport: &Rectangle, + ) { + let state = tree.state.downcast_ref::<TextState>(); + let bounds = layout.bounds(); + let (interaction, focused) = self.preview.unwrap_or(( + interaction(self.enabled(), cursor.is_over(bounds)), + state.line.focus.is_focused(), + )); + let look = theme.field(interaction, focused, self.invalid); + // The hover glow on its own fade; a preview shows it whole. + let lit = if self.preview.is_some() { + f32::from(u8::from(look.glow.is_some())) + } else { + state.lit.share() + }; + let glow = theme + .field(Interaction::Hovered, focused, self.invalid) + .glow; + let look = look.lit(glow, lit); + let area = text_area(bounds, None); + let value = &state.value; + draw_line( + renderer, + theme, + &state.line, + bounds, + area, + &look, + focused, + // The focus ring on its fade; a preview shows it as its state is. + if self.preview.is_some() { + f32::from(u8::from(focused)) + } else { + state.focus_lit.share() + }, + self.preview.is_some(), + self.value.is_empty(), + |renderer, origin, top, clip| { + renderer.fill_paragraph( + value.raw(), + Point::new(origin, top), + color(look.ink), + clip, + ); + }, + ); + } + + fn mouse_interaction( + &self, + _tree: &Tree, + layout: Layout<'_>, + cursor: mouse::Cursor, + _viewport: &Rectangle, + _renderer: &Renderer, + ) -> mouse::Interaction { + if self.enabled() && cursor.is_over(layout.bounds()) { + mouse::Interaction::Text + } else { + mouse::Interaction::default() + } + } +} + +impl<'a, Message: Clone + 'a> From<TextField<'a, Message>> for Element<'a, Message> { + fn from(field: TextField<'a, Message>) -> Self { + Element::new(field) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ui::edit::Selection; + + #[test] + fn boundaries_come_in_one_pass_and_grow() { + let text = "Ae\u{301} ffi 🙂"; + let mut plain = Plain::default(); + paint::shape(&mut plain, &typography::INTERFACE, text); + let xs = boundaries(&plain, text); + let offsets: Vec<usize> = xs.iter().map(|(at, _)| *at).collect(); + let mut expected: Vec<usize> = text.grapheme_indices(true).map(|(at, _)| at).collect(); + expected.push(text.len()); + assert_eq!(offsets, expected); + assert_eq!(xs[0].1, 0.0); + assert!(xs.windows(2).all(|pair| pair[0].1 <= pair[1].1), "{xs:?}"); + assert!((xs.last().unwrap().1 - plain.min_width()).abs() < 1.0); + assert_eq!(boundaries(&Plain::default(), ""), [(0, 0.0)]); + } + + #[test] + #[ignore = "with stock iced the system's Hebrew font shapes it, and an unbounded right-to-left \ + line lays out at infinity; the original runs it with only its own fonts (an \ + iced_graphics fork)"] + fn right_to_left_the_first_letter_is_at_the_right() { + // Hebrew runs right to left: its first letter's boundary is the line's right edge, and + // its end the left. + crate::ui::font::load(); + let text = "\u{5d0}\u{5d1}\u{5d2}"; + let mut plain = Plain::default(); + paint::shape(&mut plain, &typography::INTERFACE, text); + let xs = boundaries(&plain, text); + assert_eq!( + xs.iter().map(|(at, _)| *at).collect::<Vec<_>>(), + [0, 2, 4, 6] + ); + assert!( + xs.windows(2).all(|pair| pair[0].1 > pair[1].1), + "right to left: {xs:?}" + ); + assert!( + xs[3].1.abs() < 1e-3 && (xs[0].1 - plain.min_width()).abs() < 1.0, + "{xs:?}" + ); + } + + #[test] + fn a_value_over_the_limit_can_shrink_but_not_grow() { + // Each edit starts from the app's value, as the field's do. + let edit = |text: &str, mut selection: Selection, edit: Edit<'_>| { + let mut value = Limited::new(text.to_owned(), 5); + let changed = edit::apply(&mut value, &mut selection, edit, true); + (changed, value.text) + }; + let long = "a".repeat(10); + let back = Edit::DeleteBack { word: false }; + assert_eq!( + edit(&long, Selection::caret(10), back), + (true, "a".repeat(9)) + ); + let grown = edit(&long, Selection::caret(10), Edit::Insert("b")); + assert_eq!(grown, (false, long.clone())); + // Two letters for one shortens it, so it's taken. + let pair = Selection { anchor: 0, head: 2 }; + let shorter = edit(&long, pair, Edit::Insert("b")); + assert_eq!(shorter, (true, format!("b{}", "a".repeat(8)))); + } + + #[test] + fn a_limited_value_takes_what_fits() { + let mut value = Limited::new("abc".into(), 5); + let mut selection = Selection::caret(3); + assert!(edit::apply( + &mut value, + &mut selection, + Edit::Insert("def"), + true + )); + assert_eq!(value.text, "abcde", "cut to what fits"); + assert_eq!(value.room(), 0); + assert!( + !edit::apply(&mut value, &mut selection, Edit::Insert("x"), true), + "full, nothing more" + ); + selection = Selection { anchor: 0, head: 5 }; + assert!(edit::apply( + &mut value, + &mut selection, + Edit::Insert("xyz"), + true + )); + assert_eq!(value.text, "xyz"); + } +} diff --git a/launcher/src/ui/flow.rs b/launcher/src/ui/flow.rs new file mode 100644 index 0000000000..089da0bf27 --- /dev/null +++ b/launcher/src/ui/flow.rs @@ -0,0 +1,301 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! A flow: children side by side while they fit, one under another when they don't, as a setting's +//! words and its control are on a phone. A child that fills its room is never narrower than the +//! flow's least width beside the others. + +use iced::advanced::layout::{self, Layout}; +use iced::advanced::renderer; +use iced::advanced::widget::{Operation, Tree, Widget}; +use iced::advanced::{Clipboard, Shell, mouse, overlay}; +use iced::{Alignment, Event, Length, Point, Rectangle, Size, Vector}; + +use crate::ui::tokens::{size, space}; + +use crate::ui::{Element, Renderer, Theme}; + +/// Children side by side while they fit, stacked when they don't. +pub fn flow<'a, Message>( + children: impl IntoIterator<Item = Element<'a, Message>>, +) -> Flow<'a, Message> { + Flow { + children: children.into_iter().collect(), + spacing: space::L, + least: size::FLOW_LEAST, + align: Alignment::Center, + } +} + +/// A flow ([`flow`]). +pub struct Flow<'a, Message> { + children: Vec<Element<'a, Message>>, + spacing: f32, + least: f32, + align: Alignment, +} + +impl<'a, Message> Flow<'a, Message> { + /// The room between children, across and down. + pub fn spacing(self, spacing: f32) -> Self { + Self { spacing, ..self } + } + + /// The least a child that fills its room may be beside the others: narrower, they stack. + pub fn least(self, least: f32) -> Self { + Self { least, ..self } + } + + /// How children line up side by side: centered by default. + pub fn align_y(self, align: Alignment) -> Self { + Self { align, ..self } + } +} + +/// Whether children of these widths fit side by side in `room`: the fixed ones as wide as they +/// are, the filling ones (None) at least `least`. +fn side_by_side(widths: &[Option<f32>], room: f32, spacing: f32, least: f32) -> bool { + let gaps = spacing * widths.len().saturating_sub(1) as f32; + let need: f32 = widths.iter().map(|width| width.unwrap_or(least)).sum(); + need + gaps <= room +} + +fn fills(length: Length) -> bool { + matches!(length, Length::Fill | Length::FillPortion(_)) +} + +impl<Message> Widget<Message, Theme, Renderer> for Flow<'_, Message> { + fn children(&self) -> Vec<Tree> { + self.children.iter().map(Tree::new).collect() + } + + fn diff(&self, tree: &mut Tree) { + tree.diff_children(&self.children); + } + + fn size(&self) -> Size<Length> { + Size::new(Length::Fill, Length::Shrink) + } + + fn layout( + &mut self, + tree: &mut Tree, + renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + let room = limits.max().width; + let tall = limits.max().height; + let loose = layout::Limits::new(Size::ZERO, Size::new(room, tall)); + // Each child is laid out once, at the width it ends up with, as laying out text at a + // second width wraps it again: the fixed ones first, whose widths decide. + let mut nodes: Vec<Option<layout::Node>> = self + .children + .iter_mut() + .zip(&mut tree.children) + .map(|(child, tree)| { + (!fills(child.as_widget().size().width)) + .then(|| child.as_widget_mut().layout(tree, renderer, &loose)) + }) + .collect(); + let widths: Vec<Option<f32>> = nodes + .iter() + .map(|node| node.as_ref().map(|node| node.size().width)) + .collect(); + // With no bound on the width, as across a sideways scroll, they're side by side, the + // filling ones as narrow as they may be. + let beside = !room.is_finite() || side_by_side(&widths, room, self.spacing, self.least); + let fixed: f32 = widths.iter().flatten().sum(); + let gaps = self.spacing * self.children.len().saturating_sub(1) as f32; + let count = widths.iter().filter(|width| width.is_none()).count().max(1); + let share = if room.is_finite() { + ((room - fixed - gaps) / count as f32).max(0.0) + } else { + self.least + }; + // Side by side, the filling children share what the others leave; stacked, each has + // the whole room. + let filled = if beside { + layout::Limits::new(Size::ZERO, Size::new(share, tall)) + } else { + loose + }; + let nodes: Vec<layout::Node> = nodes + .iter_mut() + .zip(self.children.iter_mut().zip(&mut tree.children)) + .map(|(node, (child, tree))| { + node.take() + .unwrap_or_else(|| child.as_widget_mut().layout(tree, renderer, &filled)) + }) + .collect(); + if beside { + let height = nodes + .iter() + .map(|node| node.size().height) + .fold(0.0, f32::max); + let mut x = 0.0; + let nodes: Vec<layout::Node> = nodes + .into_iter() + .map(|node| { + let size = node.size(); + let y = match self.align { + Alignment::Start => 0.0, + Alignment::Center => (height - size.height) / 2.0, + Alignment::End => height - size.height, + }; + let node = node.move_to(Point::new(x, y)); + x += size.width + self.spacing; + node + }) + .collect(); + let width = if room.is_finite() { + room + } else { + (x - self.spacing).max(0.0) + }; + layout::Node::with_children(Size::new(width, height), nodes) + } else { + // Stacked, each from the start, as wide as it is or, filling, the whole room. + let mut y = 0.0; + let nodes: Vec<layout::Node> = nodes + .into_iter() + .map(|node| { + let height = node.size().height; + let node = node.move_to(Point::new(0.0, y)); + y += height + self.spacing; + node + }) + .collect(); + let height = (y - self.spacing).max(0.0); + layout::Node::with_children(Size::new(room, height), nodes) + } + } + + fn operate( + &mut self, + tree: &mut Tree, + layout: Layout<'_>, + renderer: &Renderer, + operation: &mut dyn Operation, + ) { + for ((child, tree), layout) in self + .children + .iter_mut() + .zip(&mut tree.children) + .zip(layout.children()) + { + child + .as_widget_mut() + .operate(tree, layout, renderer, operation); + } + } + + fn update( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + renderer: &Renderer, + clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + viewport: &Rectangle, + ) { + for ((child, tree), layout) in self + .children + .iter_mut() + .zip(&mut tree.children) + .zip(layout.children()) + { + child.as_widget_mut().update( + tree, event, layout, cursor, renderer, clipboard, shell, viewport, + ); + } + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + style: &renderer::Style, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + ) { + for ((child, tree), layout) in self + .children + .iter() + .zip(&tree.children) + .zip(layout.children()) + { + child + .as_widget() + .draw(tree, renderer, theme, style, layout, cursor, viewport); + } + } + + fn mouse_interaction( + &self, + tree: &Tree, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + renderer: &Renderer, + ) -> mouse::Interaction { + self.children + .iter() + .zip(&tree.children) + .zip(layout.children()) + .map(|((child, tree), layout)| { + child + .as_widget() + .mouse_interaction(tree, layout, cursor, viewport, renderer) + }) + .max() + .unwrap_or_default() + } + + fn overlay<'b>( + &'b mut self, + tree: &'b mut Tree, + layout: Layout<'b>, + renderer: &Renderer, + viewport: &Rectangle, + translation: Vector, + ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { + overlay::from_children( + &mut self.children, + tree, + layout, + renderer, + viewport, + translation, + ) + } +} + +impl<'a, Message: 'a> From<Flow<'a, Message>> for Element<'a, Message> { + fn from(flow: Flow<'a, Message>) -> Self { + Element::new(flow) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn children_go_side_by_side_while_they_fit() { + // Words that fill, at least 160, and a 220 field, 16 between. + let widths = [None, Some(220.0)]; + assert!(side_by_side(&widths, 396.0, 16.0, 160.0)); + assert!(!side_by_side(&widths, 395.0, 16.0, 160.0)); + // Fixed alone: as wide as they are. + assert!(side_by_side( + &[Some(100.0), Some(100.0)], + 216.0, + 16.0, + 160.0 + )); + assert!(side_by_side(&[], 0.0, 16.0, 160.0)); + } +} diff --git a/launcher/src/ui/focus.rs b/launcher/src/ui/focus.rs new file mode 100644 index 0000000000..cce734d4f1 --- /dev/null +++ b/launcher/src/ui/focus.rs @@ -0,0 +1,788 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! The focus model. Every widget that takes input can hold keyboard focus, +//! and the focused one takes the keys and shows the focus outline. A [`scope`] around a window's +//! content moves focus: Tab to the next widget and Shift+Tab to the previous, in the order they're +//! laid out, round the end; a click focuses what it hits and nothing else. Focus moved by the +//! keyboard into a widget scrolled out of sight scrolls it into view. +//! +//! The scope also remembers which keys' presses a widget took, and takes their releases too, +//! wherever focus has gone by then: a key held while a secret field hands its secret over and the +//! page changes never reaches the app's keyboard subscriptions. Nor do its repeats, should focus +//! have moved somewhere that ignores them. A release can go astray (the window loses focus while +//! the key is down), so a fresh press nothing takes hands that key back to the app. +//! +//! And it keeps touches in order: one finger at a time, so a second finger's lift can't finish +//! the first's press; and once a finger lifts, the content sees no pointer until a mouse moves +//! it, so what was tapped isn't left hovered. + +use std::cell::{Cell, RefCell}; + +use iced::advanced::layout::{self, Layout}; +use iced::advanced::widget::operation::{Focusable, Operation, Scrollable}; +use iced::advanced::widget::{Id, Tree, Widget, tree}; +use iced::advanced::{Clipboard, Shell, mouse, overlay, renderer}; +use iced::keyboard::{self, Key, key::Named, key::Physical}; +use iced::widget::scrollable::AbsoluteOffset; +use iced::{Event, Length, Rectangle, Size, Vector, touch}; + +use crate::ui::{Element, Renderer, Theme}; + +/// Whether a widget holds keyboard focus: part of every focusable widget's state. Focus from the +/// keyboard shows the outline at once; focus from a click shows it once a key is used, as a +/// browser's `:focus-visible` does. Text fields show it whenever they're focused. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Focus { + focused: bool, + shown: bool, +} + +impl Focus { + pub fn is_focused(&self) -> bool { + self.focused + } + + /// Whether the outline shows. + pub fn is_shown(&self) -> bool { + self.focused && self.shown + } + + /// Focus from a click. + pub(crate) fn click(&mut self) { + self.focused = true; + self.shown = false; + } + + /// A key was used on the focused widget. + pub(crate) fn key(&mut self) { + self.shown = self.focused; + } + + /// Lets go of focus, as a click elsewhere does. + pub(crate) fn unfocus(&mut self) { + *self = Self::default(); + } + + /// Lets go of focus unless the widget takes it now: one disabled while it has focus lets go, + /// as nothing can move focus off a widget that no longer counts, and it would be a second + /// focus once it's enabled again. + pub(crate) fn keep_if(&mut self, takes: bool) { + if !takes { + self.unfocus(); + } + } +} + +impl Focusable for Focus { + fn is_focused(&self) -> bool { + self.focused + } + + fn focus(&mut self) { + self.focused = true; + self.shown = true; + } + + fn unfocus(&mut self) { + Focus::unfocus(self); + } +} + +/// Moves keyboard focus among the widgets in its content. Put one around a window's content. +pub fn scope<'a, Message: 'a>(content: impl Into<Element<'a, Message>>) -> Scope<'a, Message> { + Scope { + content: content.into(), + } +} + +pub struct Scope<'a, Message> { + content: Element<'a, Message>, +} + +/// What a scope keeps: the keys whose presses a widget took, and what it knows of touches. Both +/// are shared with what floats over the content, which sees every event first. +#[derive(Debug, Default)] +struct ScopeState { + held: RefCell<Held>, + touches: Cell<Touches>, +} + +/// What a scope knows of touches: the finger that's down, if any, and whether a finger has +/// lifted since a mouse last moved the pointer. A touch moves the pointer to the finger, and +/// nothing takes it away when the finger lifts (winit's), so what was tapped would stay hovered, +/// a sheet's tapped row lit: once a finger lifts, the content sees no pointer until a mouse moves +/// it. Every change is the same however often it's made, as an event can reach both what floats +/// over the content and the content. +#[derive(Debug, Clone, Copy, Default)] +struct Touches { + finger: Option<touch::Finger>, + lifted: bool, +} + +impl Touches { + /// Before an event is seen: a mouse moving, or a finger going down, brings the pointer back. + fn before(&mut self, event: &Event) { + if let Event::Mouse(mouse::Event::CursorMoved { .. }) + | Event::Touch(touch::Event::FingerPressed { .. }) = event + { + self.lifted = false; + } + } + + /// Whether an event goes on to the content: while a finger is down, another finger's don't, + /// so a second finger's lift doesn't finish the first's press. + fn admits(self, event: &Event) -> bool { + match (event, self.finger) { + ( + Event::Touch( + touch::Event::FingerPressed { id, .. } + | touch::Event::FingerMoved { id, .. } + | touch::Event::FingerLifted { id, .. } + | touch::Event::FingerLost { id, .. }, + ), + Some(finger), + ) => *id == finger, + _ => true, + } + } + + /// The pointer the content sees, with an event or to draw: none once a finger has lifted; + /// a touch's own events are where the finger is. + fn cursor(self, event: Option<&Event>, cursor: mouse::Cursor) -> mouse::Cursor { + if self.lifted && !matches!(event, Some(Event::Touch(_))) { + mouse::Cursor::Unavailable + } else { + cursor + } + } + + /// After an event is seen: the finger that went down is the one, until it lifts. + fn after(&mut self, event: &Event) { + match event { + Event::Touch(touch::Event::FingerPressed { id, .. }) => { + self.finger.get_or_insert(*id); + } + Event::Touch( + touch::Event::FingerLifted { id, .. } | touch::Event::FingerLost { id, .. }, + ) if self.finger.is_none_or(|finger| finger == *id) => { + self.finger = None; + self.lifted = true; + } + _ => {} + } + } +} + +/// The keys whose presses a widget took, still held, and who took each. +#[derive(Debug, Default)] +struct Held(Vec<(Physical, Taker)>); + +/// Who took a key's press: the widget focused then, by its focus's place in memory, which stays +/// as long as the widget does wherever focus order puts it (none if nothing was focused), or +/// what floats over the content, such as a menu. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Taker { + Focused(Option<usize>), + Overlay, +} + +impl Held { + /// A key pressed, not repeated: who took it now is who its repeats belong to, whatever an + /// earlier press whose release went astray left. + fn press(&mut self, key: &Physical, taker: Taker) { + self.0.retain(|(held, _)| held != key); + self.0.push((*key, taker)); + } + + fn taker(&self, key: &Physical) -> Option<Taker> { + self.0 + .iter() + .find_map(|(held, taker)| (held == key).then_some(*taker)) + } + + fn holds(&self, key: &Physical) -> bool { + self.taker(key).is_some() + } + + /// Whether the key's press was taken; it's let go of either way. + fn release(&mut self, key: &Physical) -> bool { + let before = self.0.len(); + self.0.retain(|(held, _)| held != key); + self.0.len() != before + } +} + +/// Counts the focusable widgets, and finds the focused one. +#[derive(Default)] +struct Census { + total: usize, + focused: Option<usize>, + bounds: Option<Rectangle>, + /// The focused widget's own focus, by where it is in memory: the widget for as long as it + /// lives, wherever focus order puts it. + whose: Option<usize>, +} + +impl Operation for Census { + fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) { + operate(self); + } + + fn focusable(&mut self, _id: Option<&Id>, bounds: Rectangle, state: &mut dyn Focusable) { + if state.is_focused() { + self.focused = Some(self.total); + self.bounds = Some(bounds); + self.whose = Some(std::ptr::from_mut(state).cast::<()>() as usize); + } + self.total += 1; + } +} + +/// Said of the focusable widget that comes next, through [`Operation::custom`]: what it does +/// can't be undone, such as a danger button's Erase. +pub(crate) struct Danger; + +/// Focuses the widget at an index, or none, and unfocuses the others. +struct FocusOnly { + target: Option<usize>, + at: usize, + /// Where the widget it focused is. + bounds: Option<Rectangle>, +} + +impl Operation for FocusOnly { + fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) { + operate(self); + } + + fn focusable(&mut self, _id: Option<&Id>, bounds: Rectangle, state: &mut dyn Focusable) { + if self.target == Some(self.at) { + state.focus(); + self.bounds = Some(bounds); + } else { + state.unfocus(); + } + self.at += 1; + } +} + +/// Scrolls the scroll areas that hold these bounds until they're in sight. +struct Reveal { + target: Rectangle, +} + +/// Room left around a widget scrolled into view, for its focus outline. +const MARGIN: f32 = crate::ui::tokens::space::M; + +impl Operation for Reveal { + fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) { + operate(self); + } + + fn scrollable( + &mut self, + _id: Option<&Id>, + bounds: Rectangle, + content_bounds: Rectangle, + translation: Vector, + state: &mut dyn Scrollable, + ) { + // Not another scroll area's, nor the area itself, focused as a whole: it isn't moved to + // show itself. + if !content_bounds.contains(self.target.center()) || bounds == self.target { + return; + } + // Just enough to bring it in sight with the margin round it; one too long to fit shows + // its start, where its outline begins, not its end. + let offset = |start: f32, length: f32, target: f32, target_length: f32, scrolled: f32| { + let shown = start + scrolled; + let fits = target_length + 2.0 * MARGIN <= length; + if target - MARGIN < shown || (!fits && target - MARGIN > shown) { + Some(scrolled + target - MARGIN - shown) + } else if fits && target + target_length + MARGIN > shown + length { + Some(scrolled + target + target_length + MARGIN - shown - length) + } else { + None + } + }; + let t = self.target; + let x = offset(bounds.x, bounds.width, t.x, t.width, translation.x); + let y = offset(bounds.y, bounds.height, t.y, t.height, translation.y); + if x.is_some() || y.is_some() { + state.scroll_to(AbsoluteOffset { + x: x.map(|x| x.max(0.0)), + y: y.map(|y| y.max(0.0)), + }); + } + } +} + +/// Where Tab moves focus from `focused` among `total`: forwards round the end, or backwards. +pub(crate) fn next(focused: Option<usize>, total: usize, forwards: bool) -> Option<usize> { + if total == 0 { + return None; + } + Some(match (focused, forwards) { + (None, true) => 0, + (None, false) => total - 1, + (Some(at), true) => (at + 1) % total, + (Some(at), false) => (at + total - 1) % total, + }) +} + +impl<Message> Scope<'_, Message> { + fn census(&mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer) -> Census { + let mut census = Census::default(); + self.content + .as_widget_mut() + .operate(tree, layout, renderer, &mut census); + census + } + + /// Focuses the widget at `target`, and only it: where it is, if there's one. + fn focus_only( + &mut self, + tree: &mut Tree, + layout: Layout<'_>, + renderer: &Renderer, + target: Option<usize>, + ) -> Option<Rectangle> { + let mut operation = FocusOnly { + target, + at: 0, + bounds: None, + }; + self.content + .as_widget_mut() + .operate(tree, layout, renderer, &mut operation); + operation.bounds + } +} + +impl<Message> Widget<Message, Theme, Renderer> for Scope<'_, Message> { + fn size(&self) -> Size<Length> { + self.content.as_widget().size() + } + + fn size_hint(&self) -> Size<Length> { + self.content.as_widget().size_hint() + } + + fn children(&self) -> Vec<Tree> { + vec![Tree::new(&self.content)] + } + + fn diff(&self, tree: &mut Tree) { + tree.diff_children(std::slice::from_ref(&self.content)); + } + + fn tag(&self) -> tree::Tag { + tree::Tag::of::<ScopeState>() + } + + fn state(&self) -> tree::State { + tree::State::new(ScopeState::default()) + } + + fn layout( + &mut self, + tree: &mut Tree, + renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + self.content + .as_widget_mut() + .layout(&mut tree.children[0], renderer, limits) + } + + fn operate( + &mut self, + tree: &mut Tree, + layout: Layout<'_>, + renderer: &Renderer, + operation: &mut dyn Operation, + ) { + self.content + .as_widget_mut() + .operate(&mut tree.children[0], layout, renderer, operation); + } + + fn update( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + renderer: &Renderer, + clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + viewport: &Rectangle, + ) { + let Tree { + state, children, .. + } = tree; + let ScopeState { held, touches } = state.downcast_mut::<ScopeState>(); + let held = held.get_mut(); + let content = &mut children[0]; + let mut touched = touches.get(); + touched.before(event); + if !touched.admits(event) { + touches.set(touched); + shell.capture_event(); + return; + } + let cursor = touched.cursor(Some(event), cursor); + touched.after(event); + if touched.lifted && !touches.get().lifted { + // What was under the finger is no longer hovered. + shell.request_redraw(); + } + touches.set(touched); + // A release whose press a widget took is taken before anything else sees it. + if let Event::Keyboard(keyboard::Event::KeyReleased { physical_key, .. }) = event + && held.release(physical_key) + { + shell.capture_event(); + } + match event { + Event::Keyboard(keyboard::Event::KeyPressed { + key: Key::Named(Named::Tab), + modifiers, + physical_key, + .. + }) if !(modifiers.control() || modifiers.alt() || modifiers.logo()) => { + held.press(physical_key, Taker::Focused(None)); + // Three walks of the tree: to count, to focus, and to scroll into view. + let census = self.census(content, layout, renderer); + let target = next(census.focused, census.total, !modifiers.shift()); + if let Some(bounds) = self.focus_only(content, layout, renderer, target) { + let mut reveal = Reveal { target: bounds }; + self.content + .as_widget_mut() + .operate(content, layout, renderer, &mut reveal); + } + shell.capture_event(); + shell.request_redraw(); + return; + } + // What the click hits focuses itself; everything else lets go. + Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerPressed { .. }) + if self.census(content, layout, renderer).focused.is_some() => + { + let _ = self.focus_only(content, layout, renderer, None); + shell.request_redraw(); + } + _ => {} + } + // A held key's repeats go where its press went, or nowhere: once focus has moved, as + // Tab or a page change moves it, a secret's last letter held down isn't typed into the + // next field; nor are the repeats of a press a menu took, after it closed. + if let Event::Keyboard(keyboard::Event::KeyPressed { + physical_key, + repeat: true, + .. + }) = event + && let Some(taker) = held.taker(physical_key) + { + // Taken with nothing focused, by something that isn't there now, such as a dialog + // gone: nobody's. + let moved = match taker { + Taker::Overlay | Taker::Focused(None) => true, + Taker::Focused(whose) => self.census(content, layout, renderer).whose != whose, + }; + if moved { + shell.capture_event(); + return; + } + } + self.content.as_widget_mut().update( + content, event, layout, cursor, renderer, clipboard, shell, viewport, + ); + if let Event::Keyboard(keyboard::Event::KeyPressed { + physical_key, + repeat, + .. + }) = event + { + if shell.is_event_captured() { + if !repeat { + let whose = self.census(content, layout, renderer).whose; + held.press(physical_key, Taker::Focused(whose)); + } + } else if !repeat { + // Its last release went astray, and the app has its press now, so its release. + held.release(physical_key); + } else if held.holds(physical_key) { + shell.capture_event(); + } + } + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + style: &renderer::Style, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + ) { + let touches = tree.state.downcast_ref::<ScopeState>().touches.get(); + self.content.as_widget().draw( + &tree.children[0], + renderer, + theme, + style, + layout, + touches.cursor(None, cursor), + viewport, + ); + } + + fn mouse_interaction( + &self, + tree: &Tree, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + renderer: &Renderer, + ) -> mouse::Interaction { + let touches = tree.state.downcast_ref::<ScopeState>().touches.get(); + self.content.as_widget().mouse_interaction( + &tree.children[0], + layout, + touches.cursor(None, cursor), + viewport, + renderer, + ) + } + + fn overlay<'b>( + &'b mut self, + tree: &'b mut Tree, + layout: Layout<'b>, + renderer: &Renderer, + viewport: &Rectangle, + translation: Vector, + ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { + let Tree { + state, children, .. + } = tree; + let ScopeState { held, touches } = state.downcast_ref::<ScopeState>(); + self.content + .as_widget_mut() + .overlay(&mut children[0], layout, renderer, viewport, translation) + .map(|overlay| { + overlay::Element::new(Box::new(Touched { + overlay, + held, + touches, + })) + }) + } +} + +/// What floats over a scope's content, such as an open menu, seeing touches as the content does: +/// one finger at a time, and no pointer once a finger lifts. It sees every event first, so it +/// keeps the scope's record of touches too. +struct Touched<'b, Message> { + overlay: overlay::Element<'b, Message, Theme, Renderer>, + held: &'b RefCell<Held>, + touches: &'b Cell<Touches>, +} + +impl<Message> overlay::Overlay<Message, Theme, Renderer> for Touched<'_, Message> { + fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node { + self.overlay.as_overlay_mut().layout(renderer, bounds) + } + + fn draw( + &self, + renderer: &mut Renderer, + theme: &Theme, + style: &renderer::Style, + layout: Layout<'_>, + cursor: mouse::Cursor, + ) { + let cursor = self.touches.get().cursor(None, cursor); + self.overlay + .as_overlay() + .draw(renderer, theme, style, layout, cursor); + } + + fn operate(&mut self, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn Operation) { + self.overlay + .as_overlay_mut() + .operate(layout, renderer, operation); + } + + fn update( + &mut self, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + renderer: &Renderer, + clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + ) { + let mut touched = self.touches.get(); + touched.before(event); + if !touched.admits(event) { + self.touches.set(touched); + shell.capture_event(); + return; + } + let cursor = touched.cursor(Some(event), cursor); + touched.after(event); + if touched.lifted && !self.touches.get().lifted { + shell.request_redraw(); + } + self.touches.set(touched); + self.overlay + .as_overlay_mut() + .update(event, layout, cursor, renderer, clipboard, shell); + // A press it took is held as one the content took, its release and repeats kept from + // the app: Enter held to choose in a menu doesn't go on to press Next. + if let Event::Keyboard(keyboard::Event::KeyPressed { + physical_key, + repeat: false, + .. + }) = event + && shell.is_event_captured() + { + self.held.borrow_mut().press(physical_key, Taker::Overlay); + } + } + + fn mouse_interaction( + &self, + layout: Layout<'_>, + cursor: mouse::Cursor, + renderer: &Renderer, + ) -> mouse::Interaction { + let cursor = self.touches.get().cursor(None, cursor); + self.overlay + .as_overlay() + .mouse_interaction(layout, cursor, renderer) + } + + fn overlay<'a>( + &'a mut self, + layout: Layout<'a>, + renderer: &Renderer, + ) -> Option<overlay::Element<'a, Message, Theme, Renderer>> { + let (held, touches) = (self.held, self.touches); + self.overlay + .as_overlay_mut() + .overlay(layout, renderer) + .map(|overlay| { + overlay::Element::new(Box::new(Touched { + overlay, + held, + touches, + })) + }) + } + + fn index(&self) -> f32 { + self.overlay.as_overlay().index() + } +} + +impl<'a, Message: 'a> From<Scope<'a, Message>> for Element<'a, Message> { + fn from(scope: Scope<'a, Message>) -> Self { + Element::new(scope) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn held_keys_are_let_go_once() { + let a = Physical::Code(keyboard::key::Code::KeyA); + let seven = Physical::Code(keyboard::key::Code::Digit7); + let mut held = Held::default(); + held.press(&a, Taker::Focused(Some(2))); + held.press(&a, Taker::Overlay); + held.press(&seven, Taker::Overlay); + // The last press counts. + assert_eq!(held.taker(&a), Some(Taker::Overlay)); + assert!(held.release(&a)); + assert!(!held.release(&a)); + assert!(held.release(&seven)); + assert!(held.0.is_empty()); + } + + #[test] + fn tab_goes_round() { + assert_eq!(next(None, 0, true), None); + assert_eq!(next(None, 3, true), Some(0)); + assert_eq!(next(None, 3, false), Some(2)); + assert_eq!(next(Some(0), 3, true), Some(1)); + assert_eq!(next(Some(2), 3, true), Some(0)); + assert_eq!(next(Some(0), 3, false), Some(2)); + assert_eq!(next(Some(1), 3, false), Some(0)); + } + + #[test] + fn keyboard_focus_shows_and_a_clicks_once_a_key_is_used() { + let mut focus = Focus::default(); + assert!(!focus.is_focused() && !focus.is_shown()); + Focusable::focus(&mut focus); + assert!(Focusable::is_focused(&focus) && focus.is_shown()); + focus.unfocus(); + assert!(!focus.is_focused() && !focus.is_shown()); + focus.click(); + assert!(focus.is_focused() && !focus.is_shown()); + focus.key(); + assert!(focus.is_shown()); + focus.unfocus(); + focus.key(); + assert!(!focus.is_shown()); + } + + #[test] + fn reveal_scrolls_just_enough() { + struct Spy(Option<AbsoluteOffset<Option<f32>>>); + impl Scrollable for Spy { + fn snap_to(&mut self, _: iced::widget::scrollable::RelativeOffset<Option<f32>>) {} + fn scroll_to(&mut self, offset: AbsoluteOffset<Option<f32>>) { + self.0 = Some(offset); + } + fn scroll_by(&mut self, _: AbsoluteOffset, _: Rectangle, _: Rectangle) {} + } + let viewport = Rectangle::new(iced::Point::ORIGIN, Size::new(100.0, 100.0)); + let content = Rectangle::new(iced::Point::ORIGIN, Size::new(100.0, 400.0)); + let scroll = |target: Rectangle, scrolled: f32| { + let mut spy = Spy(None); + Reveal { target }.scrollable( + None, + viewport, + content, + Vector::new(0.0, scrolled), + &mut spy, + ); + spy.0.and_then(|offset| offset.y) + }; + let at = |y: f32| Rectangle::new(iced::Point::new(10.0, y), Size::new(50.0, 20.0)); + // In sight: nothing moves. + assert_eq!(scroll(at(40.0), 0.0), None); + // Below: scrolled until its bottom and the margin show. + assert_eq!(scroll(at(150.0), 0.0), Some(78.0)); + // Above: scrolled back to its top, less the margin. + assert_eq!(scroll(at(20.0), 100.0), Some(12.0)); + // Near the top: not past the start. + assert_eq!(scroll(at(2.0), 50.0), Some(0.0)); + // Outside the content: another scroll area's. + assert_eq!(scroll(at(500.0), 0.0), None); + // Too tall to fit: its start shows, from below or above, and stays once it does. + let tall = |y: f32| Rectangle::new(iced::Point::new(10.0, y), Size::new(50.0, 150.0)); + assert_eq!(scroll(tall(40.0), 0.0), Some(32.0)); + assert_eq!(scroll(tall(40.0), 100.0), Some(32.0)); + assert_eq!(scroll(tall(40.0), 32.0), None); + } +} diff --git a/launcher/src/ui/font.rs b/launcher/src/ui/font.rs new file mode 100644 index 0000000000..95f553742f --- /dev/null +++ b/launcher/src/ui/font.rs @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! The launcher's fonts: the faces its text roles use, compiled in, so its text looks the same +//! on any system. [`load`] puts them in iced's font system before anything is drawn. + +use std::sync::{Arc, Once, PoisonError}; + +use crate::ui::tokens::typography::{Family, Slant}; +use crate::ui::tokens::{Face, Role}; +use iced::advanced::graphics::text::cosmic_text::fontdb; +use iced::font::{self, Font, Weight}; + +/// The default: interface text, IBM Plex Sans at 400. +pub const DEFAULT: Font = of(crate::ui::tokens::typography::INTERFACE.face); + +/// The iced font for a face. +pub const fn of(face: Face) -> Font { + Font { + family: font::Family::Name(face.family.name()), + weight: weight(face.weight), + stretch: font::Stretch::Normal, + style: match face.slant { + Slant::Upright => font::Style::Normal, + }, + } +} + +/// The iced font for a role. +pub const fn role(role: &Role) -> Font { + of(role.face) +} + +/// CSS weights to iced's, to the nearest hundred. +const fn weight(css: u16) -> Weight { + match css { + 0..150 => Weight::Thin, + 150..250 => Weight::ExtraLight, + 250..350 => Weight::Light, + 350..450 => Weight::Normal, + 450..550 => Weight::Medium, + 550..650 => Weight::Semibold, + 650..750 => Weight::Bold, + 750..850 => Weight::ExtraBold, + _ => Weight::Black, + } +} + +/// The font files, in the order of [`FACES`], under the SIL Open Font License 1.1 (their licence +/// texts are beside them in launcher/fonts, with SHA256SUMS). +pub const SHIPPED: [&[u8]; 4] = [ + include_bytes!("../../fonts/ChakraPetch-SemiBold.ttf"), + include_bytes!("../../fonts/ChakraPetch-Bold.ttf"), + include_bytes!("../../fonts/IBMPlexSans-Regular.ttf"), + include_bytes!("../../fonts/JetBrainsMono-Regular.ttf"), +]; + +/// Loads the fonts into iced's font system, before anything is drawn. The generic families point +/// at the launcher's: sans-serif at IBM Plex Sans, monospace at JetBrains Mono. Only the first +/// call loads. +pub fn load() { + static LOADED: Once = Once::new(); + LOADED.call_once(|| { + let mut system = iced::advanced::graphics::text::font_system() + .write() + .unwrap_or_else(PoisonError::into_inner); + load_into(system.raw().db_mut()); + }); +} + +fn load_into(db: &mut fontdb::Database) { + for bytes in SHIPPED { + db.load_font_source(fontdb::Source::Binary(Arc::new(bytes))); + } + db.set_sans_serif_family(Family::Body.name()); + db.set_monospace_family(Family::Mono.name()); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ui::tokens::typography::FACES; + + #[test] + fn every_shipped_face_is_its_file() { + let mut db = fontdb::Database::new(); + load_into(&mut db); + for face in FACES { + let query = fontdb::Query { + families: &[fontdb::Family::Name(face.family.name())], + weight: fontdb::Weight(face.weight), + stretch: fontdb::Stretch::Normal, + style: fontdb::Style::Normal, + }; + let id = db.query(&query).expect("the face is loaded"); + let found = db.face(id).unwrap(); + assert_eq!(found.weight, fontdb::Weight(face.weight), "{face:?}"); + } + assert_eq!(db.len(), FACES.len()); + } + + #[test] + fn weights_round_to_iceds() { + assert_eq!(weight(400), Weight::Normal); + assert_eq!(weight(600), Weight::Semibold); + assert_eq!(weight(700), Weight::Bold); + assert_eq!(DEFAULT.weight, Weight::Normal); + } +} diff --git a/launcher/src/ui/form.rs b/launcher/src/ui/form.rs new file mode 100644 index 0000000000..a063b84358 --- /dev/null +++ b/launcher/src/ui/form.rs @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! A form: fields one under another, each its name above its control, then a line that helps or, +//! in its place, what's wrong. Names go above, not beside: they +//! fit a phone's width and a translation's longer words. +//! +//! An error says what's wrong and what to do, in words, under the control, which the app also +//! marks (`invalid(true)`), so it's never color alone. What was typed stays. +//! +//! ```ignore +//! form([ +//! field("Host name", text_field("leonida", &state.host).on_input(Message::Host)) +//! .help("How other machines on the network see this one") +//! .error(state.host_error.clone()) +//! .into(), +//! ]) +//! ``` + +use iced::widget::Column; + +use crate::ui::tokens::{Accent, Ink, space}; + +use crate::ui::{Element, text}; + +/// Fields one under another. +pub fn form<'a, Message: 'a>( + fields: impl IntoIterator<Item = Element<'a, Message>>, +) -> Column<'a, Message, crate::ui::Theme, crate::ui::Renderer> { + Column::with_children(fields).spacing(space::XL) +} + +/// A field: its name, then its control. +pub fn field<'a, Message: 'a>( + name: impl Into<String>, + control: impl Into<Element<'a, Message>>, +) -> Field<'a, Message> { + Field { + name: name.into(), + control: control.into(), + help: None, + error: None, + } +} + +/// A form's field ([`field`]). +pub struct Field<'a, Message> { + name: String, + control: Element<'a, Message>, + help: Option<String>, + error: Option<String>, +} + +impl<'a, Message: 'a> Field<'a, Message> { + /// A line under the control that helps: what the field is for, or what it takes. + pub fn help(self, help: impl Into<String>) -> Self { + Self { + help: Some(help.into()), + ..self + } + } + + /// What's wrong, in the help's place, in red: what happened and what to do. `None` when + /// nothing is. + pub fn error(self, error: Option<String>) -> Self { + Self { error, ..self } + } +} + +impl<'a, Message: 'a> From<Field<'a, Message>> for Element<'a, Message> { + fn from(field: Field<'a, Message>) -> Self { + let mut parts = vec![ + text::interface(field.name).class(Ink::Text).into(), + field.control, + ]; + if let Some(error) = field.error { + parts.push( + text::interface(error) + .class(Ink::Accent(Accent::Red)) + .into(), + ); + } else if let Some(help) = field.help { + parts.push(text::interface(help).class(Ink::Muted).into()); + } + Column::with_children(parts).spacing(space::S).into() + } +} diff --git a/launcher/src/ui/icon.rs b/launcher/src/ui/icon.rs new file mode 100644 index 0000000000..73ce2dc063 --- /dev/null +++ b/launcher/src/ui/icon.rs @@ -0,0 +1,288 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! The window's own buttons, close and back, and the header bar's menu button: an icon in a +//! small square button. An icon is straight strokes in a 16 by 16 box, drawn at the icon stroke's +//! width with round caps. + +use iced::advanced::layout::{self, Layout}; +use iced::advanced::renderer; +use iced::advanced::widget::{Operation, Tree, Widget, tree}; +use iced::advanced::{Clipboard, Shell, mouse}; +use iced::keyboard::{self, Key, key::Named}; +use iced::{Event, Length, Rectangle, Size, touch}; + +use crate::ui::tokens::{size, window}; + +use crate::ui::focus::Focus; +use crate::ui::input; +use crate::ui::paint; +use crate::ui::shape; +use crate::ui::theme::{Interaction, color}; +use crate::ui::{Element, Renderer, Theme}; + +/// An icon: straight strokes, each from (x0, y0) to (x1, y1) in a 16 by 16 box. +#[derive(Debug, Clone, Copy, PartialEq)] +pub(crate) struct Icon { + strokes: &'static [[f32; 4]], +} + +impl Icon { + /// A cross: close. + pub const CLOSE: Icon = Icon { + strokes: &window::CLOSE_CROSS, + }; + /// A chevron pointing left: back. + pub const BACK: Icon = Icon { + strokes: &window::BACK_CHEVRON, + }; + + pub(crate) fn lines(&self) -> &[[f32; 4]] { + self.strokes + } +} + +/// A window button showing an icon, which sends `on_press` when it's clicked, or when it has +/// focus and Enter or Space is pressed. The keys and the pointer work as a button's. +pub(crate) fn window_button<Message>(icon: Icon, on_press: Message) -> WindowButton<Message> { + WindowButton { + icon, + on_press, + danger: false, + preview: None, + } +} + +/// A window button, close or back ([`close_button`](crate::ui::chrome::close_button), +/// [`back_button`](crate::ui::chrome::back_button)). +pub struct WindowButton<Message> { + icon: Icon, + on_press: Message, + danger: bool, + preview: Option<(Interaction, bool)>, +} + +impl<Message> WindowButton<Message> { + /// For what can't be undone, such as closing: red under the pointer. + pub(crate) fn danger(self) -> Self { + Self { + danger: true, + ..self + } + } + + /// Draws it as if in this state, whatever the pointer and focus do: for the gallery. + pub fn preview(self, interaction: Interaction, focused: bool) -> Self { + Self { + preview: Some((interaction, focused)), + ..self + } + } +} + +#[derive(Default)] +struct Pressing { + focus: Focus, + pressed: bool, + drawn: Option<(Interaction, bool)>, + /// Its glow under the pointer, fading in and out. + lit: crate::ui::transition::Lit, + /// Its focus ring's glow, fading in and out with keyboard focus. + focus_lit: crate::ui::transition::Lit, +} + +impl Pressing { + fn interaction(&self, over: bool) -> Interaction { + if self.pressed { + Interaction::Pressed + } else if over { + Interaction::Hovered + } else { + Interaction::Idle + } + } +} + +impl<Message: Clone> Widget<Message, Theme, Renderer> for WindowButton<Message> { + fn tag(&self) -> tree::Tag { + tree::Tag::of::<Pressing>() + } + + fn state(&self) -> tree::State { + tree::State::new(Pressing::default()) + } + + fn size(&self) -> Size<Length> { + Size::new( + Length::Fixed(window::BUTTON_SIZE), + Length::Fixed(window::BUTTON_SIZE), + ) + } + + fn layout( + &mut self, + _tree: &mut Tree, + _renderer: &Renderer, + _limits: &layout::Limits, + ) -> layout::Node { + layout::Node::new(Size::new(window::BUTTON_SIZE, window::BUTTON_SIZE)) + } + + fn operate( + &mut self, + tree: &mut Tree, + layout: Layout<'_>, + _renderer: &Renderer, + operation: &mut dyn Operation, + ) { + if self.preview.is_none() { + let state = tree.state.downcast_mut::<Pressing>(); + operation.focusable(None, layout.bounds(), &mut state.focus); + } + } + + fn update( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + _renderer: &Renderer, + _clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + _viewport: &Rectangle, + ) { + if self.preview.is_some() { + return; + } + let state = tree.state.downcast_mut::<Pressing>(); + let over = cursor.is_over(layout.bounds()); + match event { + Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerPressed { .. }) + if over => + { + state.pressed = true; + state.focus.click(); + shell.capture_event(); + } + Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerLifted { .. }) + if state.pressed => + { + state.pressed = false; + if over { + shell.publish(self.on_press.clone()); + } + shell.capture_event(); + } + Event::Touch(touch::Event::FingerLost { .. }) => state.pressed = false, + // Once a press: a key held down doesn't close a window and then the next. + Event::Keyboard(keyboard::Event::KeyPressed { + key: Key::Named(Named::Enter | Named::Space), + modifiers, + repeat: false, + .. + }) if state.focus.is_focused() && input::plain(*modifiers) => { + state.focus.key(); + shell.publish(self.on_press.clone()); + shell.capture_event(); + } + _ => {} + } + let interaction = state.interaction(over); + state.lit.frame(event, shell); + state.focus_lit.frame(event, shell); + state.focus_lit.aim(state.focus.is_shown(), shell); + state.lit.aim(interaction != Interaction::Idle, shell); + let now = (interaction, state.focus.is_shown()); + input::redraw_on_change(&mut state.drawn, now, event, shell); + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + _style: &renderer::Style, + layout: Layout<'_>, + cursor: mouse::Cursor, + _viewport: &Rectangle, + ) { + let state = tree.state.downcast_ref::<Pressing>(); + let bounds = layout.bounds(); + let (interaction, focused) = self.preview.unwrap_or(( + state.interaction(cursor.is_over(bounds)), + state.focus.is_shown(), + )); + let looks = |interaction| { + if self.danger { + theme.close_button(interaction) + } else { + theme.window_button(interaction) + } + }; + let mut look = looks(interaction); + if self.preview.is_none() { + // The glow fades in and out with the pointer. + let lit = if interaction == Interaction::Pressed { + Interaction::Pressed + } else { + Interaction::Hovered + }; + look = look.lit(looks(lit).glow, state.lit.share()); + } + paint::boxed(renderer, bounds, &look); + shape::icon( + renderer, + bounds, + self.icon.lines(), + size::ICON_STROKE, + color(look.ink), + ); + // The focus ring fades in and out with keyboard focus, drawn while it fades out too. + let ring = if self.preview.is_some() { + f32::from(u8::from(focused)) + } else { + state.focus_lit.share() + }; + paint::outline_faded( + renderer, + theme, + bounds, + look.radius, + theme.focus_glow().small(), + ring, + ); + } + + fn mouse_interaction( + &self, + _tree: &Tree, + layout: Layout<'_>, + cursor: mouse::Cursor, + _viewport: &Rectangle, + _renderer: &Renderer, + ) -> mouse::Interaction { + if self.preview.is_none() && cursor.is_over(layout.bounds()) { + mouse::Interaction::Pointer + } else { + mouse::Interaction::default() + } + } +} + +impl<'a, Message: Clone + 'a> From<WindowButton<Message>> for Element<'a, Message> { + fn from(button: WindowButton<Message>) -> Self { + Element::new(button) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_icons_are_the_window_buttons_glyphs() { + assert_eq!(Icon::CLOSE.lines(), window::CLOSE_CROSS); + } +} diff --git a/launcher/src/ui/input.rs b/launcher/src/ui/input.rs new file mode 100644 index 0000000000..9bb9f6fc25 --- /dev/null +++ b/launcher/src/ui/input.rs @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! What every widget's input handling shares: whether a key's press is a plain one, and asking +//! for a redraw only when what a widget would draw has changed. + +/// Asks for a redraw when what a widget would draw differs from what it last drew; a redraw +/// records what it draws. So nothing draws while nothing changes. +pub(crate) fn redraw_on_change<T: PartialEq + Copy, Message>( + drawn: &mut Option<T>, + now: T, + event: &iced::Event, + shell: &mut iced::advanced::Shell<'_, Message>, +) { + if let iced::Event::Window(iced::window::Event::RedrawRequested(_)) = event { + *drawn = Some(now); + } else if *drawn != Some(now) { + shell.request_redraw(); + } +} + +/// Whether a key press is plain: no Ctrl, Alt or Super with it. +pub(crate) fn plain(modifiers: iced::keyboard::Modifiers) -> bool { + !(modifiers.control() || modifiers.alt() || modifiers.logo()) +} diff --git a/launcher/src/ui/list.rs b/launcher/src/ui/list.rs new file mode 100644 index 0000000000..774e86c8f6 --- /dev/null +++ b/launcher/src/ui/list.rs @@ -0,0 +1,700 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! A selection list: one of many rows, such as the language, the keyboard layout or the Wi-Fi +//! network. It scrolls itself, keeping the chosen row in sight. + +use iced::advanced::layout::{self, Layout}; +use iced::advanced::widget::{Operation, Tree, Widget, tree}; +use iced::advanced::{Clipboard, Shell, mouse, renderer}; +use iced::keyboard::{self, Key, key::Named}; + +use iced::{Event, Length, Point, Rectangle, Size, touch, window}; + +use crate::ui::tokens::{motion, size, space, typography}; + +use crate::ui::focus::Focus; +use crate::ui::input; +use crate::ui::paint::{self, Plain}; +use crate::ui::theme::{Interaction, color}; +use crate::ui::transition::Transition; +use crate::ui::{Element, Renderer, Theme}; + +/// A list of rows, showing this many at once, with the chosen one's index. Without a message to +/// send it is disabled. +pub fn list<'a, Message>( + rows: impl IntoIterator<Item = impl Into<String>>, + chosen: Option<usize>, +) -> List<'a, Message> { + List { + rows: rows.into_iter().map(Into::into).collect(), + chosen, + shown: 6, + on_choose: None, + preview: None, + sidebar: false, + } +} + +/// A sidebar's places: every row shown, taller than a list's, with no +/// box round them; the chosen one marked. The keys and the pointer work as in a [`list`]. +pub fn navigation<'a, Message>( + rows: impl IntoIterator<Item = impl Into<String>>, + chosen: Option<usize>, +) -> List<'a, Message> { + let list = list(rows, chosen); + List { + shown: list.rows.len().max(1), + sidebar: true, + ..list + } +} + +/// A selection list. The arrow keys, Page Up and Page Down, Home and End move the choice; a +/// letter moves it to the next row that starts with it. The wheel scrolls it. +pub struct List<'a, Message> { + rows: Vec<String>, + chosen: Option<usize>, + shown: usize, + on_choose: Option<Box<dyn Fn(usize) -> Message + 'a>>, + preview: Option<(usize, Interaction, bool)>, + /// Drawn as a sidebar's places ([`navigation`]). + sidebar: bool, +} + +impl<'a, Message> List<'a, Message> { + /// How many rows show at once. + pub fn shown(self, rows: usize) -> Self { + Self { + shown: rows.max(1), + ..self + } + } + + pub fn on_choose(self, on_choose: impl Fn(usize) -> Message + 'a) -> Self { + Self { + on_choose: Some(Box::new(on_choose)), + ..self + } + } + + /// Draws one row as if in this state, and the focus outline, for the gallery. + pub fn preview(self, row: usize, interaction: Interaction, focused: bool) -> Self { + Self { + preview: Some((row, interaction, focused)), + ..self + } + } + + fn choose(&mut self, row: usize, shell: &mut Shell<'_, Message>) { + if let Some(on_choose) = &self.on_choose + && Some(row) != self.chosen + && row < self.rows.len() + { + shell.publish(on_choose(row)); + // Taken at once, so a second key in the same batch of events starts from it, as the + // app will. + self.chosen = Some(row); + } + } +} + +/// The row a key moves the choice to, among `rows` with `page` shown at once. +pub(crate) fn step( + rows: &[String], + chosen: Option<usize>, + page: usize, + key: &Key, +) -> Option<usize> { + let last = rows.len().checked_sub(1)?; + // A choice past the end, as the app's rows shrank under it (a rescan found fewer networks), + // is no choice. + let chosen = chosen.filter(|&at| at <= last); + let at = chosen.unwrap_or(0); + match key { + Key::Named(Named::ArrowDown) => Some(chosen.map_or(0, |at| (at + 1).min(last))), + Key::Named(Named::ArrowUp) => Some(chosen.map_or(last, |at| at.saturating_sub(1))), + Key::Named(Named::PageDown) => Some((at + page.saturating_sub(1).max(1)).min(last)), + Key::Named(Named::PageUp) => Some(at.saturating_sub(page.saturating_sub(1).max(1))), + Key::Named(Named::Home) => Some(0), + Key::Named(Named::End) => Some(last), + Key::Character(letter) => { + let letter = letter.to_lowercase(); + let starts = |row: &usize| rows[*row].to_lowercase().starts_with(&letter); + let from = chosen.map_or(0, |at| at + 1); + (from..rows.len()).chain(0..from).find(starts) + } + _ => None, + } +} + +/// The first row shown, so `row` is in sight with as little scrolling as can be. +pub(crate) fn scroll_to(first: usize, row: usize, shown: usize) -> usize { + if row < first { + row + } else if row >= first + shown { + row + 1 - shown + } else { + first + } +} + +/// What it last drew: the row under the pointer, the pressed one, the outline, the first row +/// shown, the chosen one. +#[derive(Debug, Clone, Copy, PartialEq)] +struct Drawn { + over: Option<usize>, + pressed: Option<usize>, + outline: bool, + first: usize, + chosen: Option<usize>, +} + +/// A sidebar's mark moving: the row it leaves, where it shrinks away, and the row it comes to, +/// where it grows, both at once, from their middles; each from the height it had, so a choice +/// changed again part of the way doesn't jump. +#[derive(Debug, Clone, Copy, PartialEq)] +struct Mark { + from: Option<usize>, + from_height: f32, + to: Option<usize>, + to_height: f32, + /// How far along it is, from 0 to 1. + moving: Transition, +} + +impl Mark { + /// The mark leaving `from` for `to`, from the heights they have now under `was`, the mark + /// moving before, if any; none with motion reduced. + fn new(was: Option<Mark>, from: Option<usize>, to: Option<usize>) -> Option<Self> { + let height = |row: Option<usize>| { + row.map_or(0.0, |row| { + was.map_or(f32::from(u8::from(Some(row) == from)), |was| { + was.height(row) + }) + }) + }; + Some(Self { + from, + from_height: height(from), + to, + to_height: height(to), + moving: Transition::start(0.0, 1.0, motion::SLOW)?, + }) + } + + /// How tall a row's mark is, a share of its whole height. + fn height(&self, row: usize) -> f32 { + let along = self.moving.at(); + if Some(row) == self.to { + self.to_height + (1.0 - self.to_height) * along + } else if Some(row) == self.from { + self.from_height * (1.0 - along) + } else { + 0.0 + } + } +} + +#[derive(Default)] +struct State { + /// The chosen row when last seen, and the mark moving from it. + marked: Option<Option<usize>>, + mark: Option<Mark>, + focus: Focus, + first: usize, + /// The chosen row when last laid out, to bring a new choice into sight. + laid_out: Option<usize>, + /// The rows' words, shaped: again only when they change. + labels: Vec<Plain>, + pressed: Option<usize>, + /// What a touchpad's wheel has scrolled short of a whole row, in rows. + wheeled: f32, + /// A finger's drag: where it went down and the first row then, and whether it's moved further + /// than a slip, so it scrolls the rows rather than choosing one. + drag: Option<Swipe>, + drawn: Option<Drawn>, + /// Its focus ring, fading in and out with keyboard focus on the glows' own timing. + focus_lit: crate::ui::transition::Lit, +} + +#[derive(Debug, Clone, Copy)] +struct Swipe { + from: f32, + first: usize, + moved: bool, +} + +/// The room between two rows. +const GAP: f32 = space::XS; + +impl<Message> List<'_, Message> { + /// From one row's top to the next's: a row and the gap after it. + fn pitch(&self) -> f32 { + self.row_height() + GAP + } + + fn row_height(&self) -> f32 { + if self.sidebar { + size::SIDEBAR_ROW + } else { + size::ROW + } + } + + /// Where the rows are: inside the box's padding, or, in a sidebar, edge to edge. + fn inner(&self, bounds: Rectangle) -> Rectangle { + if self.sidebar { + bounds + } else { + bounds.shrink(space::XS) + } + } + + fn row_at(&self, state: &State, layout: Layout<'_>, cursor: mouse::Cursor) -> Option<usize> { + let inner = self.inner(layout.bounds()); + let point = cursor.position_over(inner)?; + let down = point.y - inner.y; + // In the gap between two rows, neither. + if down % self.pitch() >= self.row_height() { + return None; + } + let row = state.first + (down / self.pitch()) as usize; + (row < self.rows.len()).then_some(row) + } + + /// What the focus outline goes round: the list, or a sidebar's chosen row, or its first, as + /// a sidebar's list has no box to round. + fn outlined(&self, bounds: Rectangle, first: usize) -> Rectangle { + if !self.sidebar { + return bounds; + } + let inner = self.inner(bounds); + let slot = self.chosen.unwrap_or(0).saturating_sub(first) as f32; + Rectangle::new( + Point::new(inner.x, inner.y + slot * self.pitch()), + Size::new(inner.width, self.row_height()), + ) + } + + fn max_first(&self) -> usize { + self.rows.len().saturating_sub(self.shown) + } +} + +impl<Message> Widget<Message, Theme, Renderer> for List<'_, Message> { + fn tag(&self) -> tree::Tag { + tree::Tag::of::<State>() + } + + fn state(&self) -> tree::State { + tree::State::new(State::default()) + } + + fn size(&self) -> Size<Length> { + Size::new(Length::Fill, Length::Shrink) + } + + fn layout( + &mut self, + tree: &mut Tree, + _renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + let state = tree.state.downcast_mut::<State>(); + state.labels.resize_with(self.rows.len(), Plain::default); + for (plain, row) in state.labels.iter_mut().zip(&self.rows) { + paint::shape(plain, &typography::INTERFACE, row); + } + if self.chosen != state.laid_out { + if let Some(row) = self.chosen { + state.first = scroll_to(state.first, row, self.shown); + } + state.laid_out = self.chosen; + } + state.first = state.first.min(self.max_first()); + let inset = if self.sidebar { 0.0 } else { 2.0 * space::XS }; + let rows = self.shown.max(1) as f32; + let height = rows * self.row_height() + (rows - 1.0) * GAP + inset; + let size = limits.resolve(Length::Fill, Length::Shrink, Size::new(0.0, height)); + layout::Node::new(Size::new(size.width, height)) + } + + fn operate( + &mut self, + tree: &mut Tree, + layout: Layout<'_>, + _renderer: &Renderer, + operation: &mut dyn Operation, + ) { + if self.on_choose.is_some() && self.preview.is_none() && !self.rows.is_empty() { + let state = tree.state.downcast_mut::<State>(); + // Where the outline goes, so focus scrolls that into view: a sidebar's long list + // in a scroll area would show its end, and not the row it outlines. + let outlined = self.outlined(layout.bounds(), state.first); + operation.focusable(None, outlined, &mut state.focus); + } + } + + fn update( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + _renderer: &Renderer, + _clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + _viewport: &Rectangle, + ) { + // A preview is a picture of a state: it takes no input. + if self.preview.is_some() { + return; + } + let state = tree.state.downcast_mut::<State>(); + state + .focus + .keep_if(self.on_choose.is_some() && !self.rows.is_empty()); + if self.sidebar { + // The chosen place changed: the mark leaves one row and comes to another. + if let Some(was) = state.marked + && was != self.chosen + { + state.mark = Mark::new(state.mark, was, self.chosen); + shell.request_redraw(); + } + state.marked = Some(self.chosen); + if let Event::Window(window::Event::RedrawRequested(now)) = event + && let Some(mark) = &mut state.mark + { + if mark.moving.frame(*now) { + shell.request_redraw(); + } else { + state.mark = None; + } + } + } + let over = self.row_at(state, layout, cursor); + let scrolls = self.rows.len() > self.shown; + if let Event::Mouse(mouse::Event::WheelScrolled { delta }) = event + && cursor.is_over(layout.bounds()) + && scrolls + { + // A wheel's line is a row; a touchpad's pixels add up, a row at a time. + state.wheeled -= match delta { + mouse::ScrollDelta::Lines { y, .. } => *y, + mouse::ScrollDelta::Pixels { y, .. } => y / self.pitch(), + }; + let rows = state.wheeled.trunc(); + state.wheeled -= rows; + let first = (state.first as f32 + rows).clamp(0.0, self.max_first() as f32) as usize; + // At an end, nothing's kept towards a row past it. + if (first == 0 && state.wheeled < 0.0) + || (first == self.max_first() && state.wheeled > 0.0) + { + state.wheeled = 0.0; + } + state.first = first; + shell.capture_event(); + } + // A finger dragged up or down further than a slip scrolls the rows, and lets go of the + // one it pressed; the drag is the list's, not a scroll area's round it. + match event { + Event::Touch(touch::Event::FingerPressed { position, .. }) + if scrolls && cursor.is_over(layout.bounds()) => + { + state.drag = Some(Swipe { + from: position.y, + first: state.first, + moved: false, + }); + } + Event::Touch(touch::Event::FingerMoved { position, .. }) => { + if let Some(drag) = &mut state.drag { + let by = drag.from - position.y; + drag.moved |= by.abs() > size::SLIP; + if drag.moved { + state.pressed = None; + let rows = (by / self.pitch()).round(); + let first = (drag.first as f32 + rows).clamp(0.0, self.max_first() as f32); + state.first = first as usize; + shell.capture_event(); + } + } + } + Event::Touch(touch::Event::FingerLifted { .. } | touch::Event::FingerLost { .. }) => { + let dragged = state.drag.take().is_some_and(|drag| drag.moved); + if dragged { + shell.capture_event(); + } + } + _ => {} + } + if self.on_choose.is_some() { + match event { + Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerPressed { .. }) + if over.is_some() => + { + state.pressed = over; + state.focus.click(); + shell.capture_event(); + } + Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerLifted { .. }) => { + if let Some(row) = state.pressed.take() { + if over == Some(row) { + self.choose(row, shell); + } + shell.capture_event(); + } + } + Event::Touch(touch::Event::FingerLost { .. }) => state.pressed = None, + Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) + if state.focus.is_focused() && input::plain(*modifiers) => + { + if let Some(row) = step(&self.rows, self.chosen, self.shown, key) { + state.focus.key(); + state.first = scroll_to(state.first, row, self.shown); + self.choose(row, shell); + shell.capture_event(); + } + } + _ => {} + } + } else { + state.pressed = None; + } + state.focus_lit.frame(event, shell); + state.focus_lit.aim(state.focus.is_shown(), shell); + let now = Drawn { + over, + pressed: state.pressed, + outline: state.focus.is_shown(), + first: state.first, + chosen: self.chosen, + }; + input::redraw_on_change(&mut state.drawn, now, event, shell); + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + _style: &renderer::Style, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + ) { + let state = tree.state.downcast_ref::<State>(); + let bounds = layout.bounds(); + let disabled = self.on_choose.is_none(); + let frame = theme.list(match self.preview { + _ if disabled => Interaction::Disabled, + Some((_, interaction, _)) => interaction, + None if cursor.is_over(bounds) => Interaction::Hovered, + None => Interaction::Idle, + }); + if !self.sidebar { + paint::boxed(renderer, bounds, &frame); + } + let inner = self.inner(bounds); + let height = self.row_height(); + let over = self.row_at(state, layout, cursor); + // No scrollbar: the wheel, the keys and the chosen row brought into sight scroll it. + let width = inner.width; + let shown = state + .labels + .iter() + .enumerate() + .skip(state.first) + .take(self.shown); + for (slot, (row, label)) in shown.enumerate() { + let bounds = Rectangle::new( + Point::new(inner.x, inner.y + slot as f32 * self.pitch()), + Size::new(width, height), + ); + // A row out of sight, as a sidebar's long list scrolled, isn't drawn. + if !bounds.intersects(viewport) { + continue; + } + let interaction = match self.preview { + Some((shown, interaction, _)) if shown == row => interaction, + _ if disabled => Interaction::Disabled, + _ if state.pressed == Some(row) => Interaction::Pressed, + _ if over == Some(row) => Interaction::Hovered, + _ => Interaction::Idle, + }; + let chosen = self.chosen == Some(row); + let look = if self.sidebar { + theme.sidebar_row(chosen, interaction) + } else { + theme.row(chosen, interaction) + }; + paint::boxed(renderer, bounds, &look); + // The mark's height: whole on the chosen row, or growing and shrinking as it moves. + let marked = match (state.mark, self.preview) { + (Some(mark), None) => mark.height(row), + _ => f32::from(u8::from(chosen)), + }; + if self.sidebar && marked > 0.0 && interaction != Interaction::Disabled { + // The mark: a pill at the row's start, set in as far from its start as from its + // top and bottom, from its middle as it grows. + let inset = size::SIDEBAR_MARK_INSET; + let tall = (height - 2.0 * inset) * marked; + let mark = Rectangle::new( + Point::new(bounds.x + inset, bounds.center_y() - tall / 2.0), + Size::new(size::SIDEBAR_MARK, tall), + ); + // A small light: it sparks, softly, and its glow grows and shrinks with it. + let ink = theme.sidebar_mark(); + let look = crate::ui::theme::Look::solid(ink, size::SIDEBAR_MARK / 2.0) + .glowing(theme.spark(ink).small()); + paint::boxed(renderer, mark, &look); + } + // A sidebar's words start past the mark's room, chosen or not, so they line up; long + // words end as far from the row's end, cut there. + let start = if self.sidebar { + 2.0 * size::SIDEBAR_MARK_INSET + size::SIDEBAR_MARK + } else { + space::M + }; + let words = typography::INTERFACE.size * typography::INTERFACE.line_height; + let at = Point::new(bounds.x + start, bounds.center_y() - words / 2.0); + let room = Rectangle::new( + Point::new(at.x, bounds.y), + Size::new((bounds.width - start - space::M).max(0.0), bounds.height), + ); + paint::fill(renderer, label, at, color(look.ink), room); + } + let focused = match self.preview { + Some((_, _, focused)) => focused, + None => state.focus.is_shown(), + }; + // The focus ring fades in and out with keyboard focus, drawn while it fades out too. + let ring = if self.preview.is_some() { + f32::from(u8::from(focused)) + } else { + state.focus_lit.share() + }; + if ring > 0.0 { + let outlined = self.outlined(bounds, state.first); + let radius = if self.sidebar { + crate::ui::tokens::radius::CHIP + } else { + frame.radius + }; + paint::outline_lit(renderer, theme, outlined, radius, ring); + } + } + + fn mouse_interaction( + &self, + tree: &Tree, + layout: Layout<'_>, + cursor: mouse::Cursor, + _viewport: &Rectangle, + _renderer: &Renderer, + ) -> mouse::Interaction { + let state = tree.state.downcast_ref::<State>(); + if self.on_choose.is_some() && self.row_at(state, layout, cursor).is_some() { + mouse::Interaction::Pointer + } else { + mouse::Interaction::default() + } + } +} + +impl<'a, Message: 'a> From<List<'a, Message>> for Element<'a, Message> { + fn from(list: List<'a, Message>) -> Self { + Element::new(list) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Instant; + + #[test] + fn the_mark_shrinks_from_one_row_as_it_grows_in_another() { + let start = Instant::now(); + let mut mark = Mark::new(None, Some(1), Some(4)).unwrap(); + mark.moving.frame(start); + assert_eq!( + (mark.height(1), mark.height(4), mark.height(2)), + (1.0, 0.0, 0.0) + ); + mark.moving.frame(start + motion::SLOW / 4); + let (leaving, coming) = (mark.height(1), mark.height(4)); + assert!(leaving < 0.5 && coming > 0.5 && (leaving + coming - 1.0).abs() < 1e-6); + // Chosen again part of the way, back to row 1: each goes on from the height it has. + let back = Mark::new(Some(mark), Some(4), Some(1)).unwrap(); + assert_eq!((back.height(4), back.height(1)), (coming, leaving)); + mark.moving.frame(start + motion::SLOW); + assert_eq!((mark.height(1), mark.height(4)), (0.0, 1.0)); + // From nothing chosen, it only grows. + let mut first = Mark::new(None, None, Some(0)).unwrap(); + first.moving.frame(start); + first.moving.frame(start + motion::SLOW); + assert_eq!(first.height(0), 1.0); + } + + fn rows() -> Vec<String> { + [ + "English", + "Español", + "Deutsch", + "Ελληνικά", + "Eesti", + "Suomi", + ] + .map(String::from) + .to_vec() + } + + #[test] + fn keys_move_the_choice() { + let rows = rows(); + let named = |at, key| step(&rows, at, 3, &Key::Named(key)); + assert_eq!(named(None, Named::ArrowDown), Some(0)); + assert_eq!(named(None, Named::ArrowUp), Some(5)); + assert_eq!(named(Some(5), Named::ArrowDown), Some(5)); + assert_eq!(named(Some(0), Named::ArrowUp), Some(0)); + assert_eq!(named(Some(0), Named::PageDown), Some(2)); + assert_eq!(named(Some(5), Named::PageUp), Some(3)); + assert_eq!(named(Some(3), Named::Home), Some(0)); + assert_eq!(named(Some(0), Named::End), Some(5)); + assert_eq!(named(Some(0), Named::Enter), None); + // A choice past the rows' end, as they shrank under it: no panic, taken as none. + let rows: Vec<String> = ["Home", "Office", "Cafe"].map(String::from).into(); + let letter = |key: &str| Key::Character(key.into()); + assert_eq!(step(&rows, Some(7), 3, &letter("z")), None); + assert_eq!(step(&rows, Some(7), 3, &letter("c")), Some(2)); + assert_eq!( + step(&rows, Some(7), 3, &Key::Named(Named::ArrowDown)), + Some(0) + ); + assert_eq!(step(&[], None, 3, &Key::Named(Named::ArrowDown)), None); + } + + #[test] + fn a_letter_finds_the_next_row_starting_with_it() { + let rows = rows(); + let letter = |at, letter: &str| step(&rows, at, 3, &Key::Character(letter.into())); + assert_eq!(letter(None, "e"), Some(0)); + assert_eq!(letter(Some(0), "E"), Some(1)); + assert_eq!(letter(Some(1), "e"), Some(4)); + assert_eq!(letter(Some(4), "e"), Some(0)); + assert_eq!(letter(Some(0), "ε"), Some(3)); + assert_eq!(letter(Some(0), "x"), None); + } + + #[test] + fn the_chosen_row_stays_in_sight() { + assert_eq!(scroll_to(0, 2, 3), 0); + assert_eq!(scroll_to(0, 3, 3), 1); + assert_eq!(scroll_to(4, 2, 3), 2); + assert_eq!(scroll_to(2, 4, 3), 2); + } +} diff --git a/launcher/src/ui/loader.rs b/launcher/src/ui/loader.rs new file mode 100644 index 0000000000..dad97b6a20 --- /dev/null +++ b/launcher/src/ui/loader.rs @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! A loader: a ring that pulses while something is under way and can't say how far, such as +//! signing in or looking for networks. A busy progress bar ([`crate::ui::progress::busy`]) says the +//! same along a line; a loader says it in a spot. + +use std::time::Duration; + +use iced::advanced::layout::{self, Layout}; +use iced::advanced::widget::{Tree, Widget, tree}; +use iced::advanced::{Clipboard, Shell, mouse, renderer}; +use iced::time::Instant; +use iced::{Event, Length, Rectangle, Size, window}; + +use crate::ui::tokens::{motion, size}; + +use crate::ui::theme::Look; +use crate::ui::transition::{phase, wants_frames}; +use crate::ui::{Element, Renderer, Theme, paint}; + +/// A loader, its ring [`size::LOADER`] across. With motion reduced, the ring is still. +pub fn loader() -> Loader { + Loader { + size: size::LOADER, + preview: None, + } +} + +/// A loader ([`loader`]). +pub struct Loader { + size: f32, + /// Drawn still this far into a pulse, for the gallery. + preview: Option<f32>, +} + +impl Loader { + /// How wide the ring is across: [`size::LOADER`] unless set. + pub fn size(self, size: f32) -> Self { + Self { size, ..self } + } + + /// Drawn still as it is `at` this far into a pulse, from 0 to 1, asking for no frames: for + /// the gallery. + pub fn preview(self, at: f32) -> Self { + Self { + preview: Some(at.clamp(0.0, 1.0)), + ..self + } + } +} + +/// How long a pulse takes: the ring brightens and dims once, and a ripple goes out from it. +const PULSE: Duration = Duration::from_millis(1400); +/// How far a ripple goes out past the ring, as a share of its size. +const RIPPLE: f32 = 0.5; + +/// A loader's pulse: when it started, and the frame it's at. +#[derive(Default)] +struct Pulse { + start: Option<Instant>, + now: Option<Instant>, +} + +impl Pulse { + /// How far into a pulse it is, from 0 to 1; with motion reduced, none. + fn at(&self) -> Option<f32> { + if crate::ui::system::reduced_motion() { + return None; + } + Some(phase(self.start?, self.now?, PULSE)) + } +} + +impl<Message> Widget<Message, Theme, Renderer> for Loader { + fn tag(&self) -> tree::Tag { + tree::Tag::of::<Pulse>() + } + + fn state(&self) -> tree::State { + tree::State::new(Pulse::default()) + } + + fn size(&self) -> Size<Length> { + Size::new(Length::Fixed(self.size), Length::Fixed(self.size)) + } + + fn layout( + &mut self, + _tree: &mut Tree, + _renderer: &Renderer, + _limits: &layout::Limits, + ) -> layout::Node { + layout::Node::new(Size::new(self.size, self.size)) + } + + fn update( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + _cursor: mouse::Cursor, + _renderer: &Renderer, + _clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + viewport: &Rectangle, + ) { + // It pulses: a frame after every frame while it's in sight, unless motion's reduced or + // it's a still. + if self.preview.is_none() + && let Event::Window(window::Event::RedrawRequested(now)) = event + { + let pulse = tree.state.downcast_mut::<Pulse>(); + pulse.start.get_or_insert(*now); + pulse.now = Some(*now); + if wants_frames(layout.bounds(), viewport) { + shell.request_redraw(); + } + } + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + _style: &renderer::Style, + layout: Layout<'_>, + _cursor: mouse::Cursor, + _viewport: &Rectangle, + ) { + let bounds = layout.bounds(); + let look = theme.loader(); + let ring = size::LOADER_RING; + let Some(at) = self + .preview + .or_else(|| tree.state.downcast_ref::<Pulse>().at()) + else { + paint::framed(renderer, bounds, &look, ring); + return; + }; + // The ring breathes, brightest half way through a pulse. + let breath = 0.5 - 0.5 * (std::f32::consts::TAU * at).cos(); + paint::framed(renderer, bounds, &look.faded(0.55 + 0.45 * breath), ring); + // A ripple goes out from it, thinning and fading as it goes. + let out = motion::EASE.at(at); + let ripple = bounds.expand(self.size * RIPPLE * out / 2.0); + let ripple_look = Look { glow: None, ..look }.faded(0.6 * (1.0 - out)); + paint::framed(renderer, ripple, &ripple_look, ring * (1.0 - 0.5 * out)); + } +} + +impl<'a, Message: 'a> From<Loader> for Element<'a, Message> { + fn from(loader: Loader) -> Self { + Element::new(loader) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_pulse_goes_round_and_round() { + let start = Instant::now(); + let at = |ms| { + Pulse { + start: Some(start), + now: Some(start + Duration::from_millis(ms)), + } + .at() + }; + if crate::ui::system::reduced_motion() { + return; + } + assert_eq!(at(0), Some(0.0)); + let half = at(700).unwrap(); + assert!((half - 0.5).abs() < 1e-3); + // A pulse later, it's where it began. + assert!(at(1400).unwrap() < 1e-3); + assert_eq!(Pulse::default().at(), None, "not drawn yet"); + } +} diff --git a/launcher/src/ui/mod.rs b/launcher/src/ui/mod.rs new file mode 100644 index 0000000000..03db9e4bf8 --- /dev/null +++ b/launcher/src/ui/mod.rs @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! The launcher's design system on stock iced 0.14: its UI kit. +//! +//! - [`tokens`]: colors (Sunset dark and light, from Leonida's logo), type, spacing, radii, +//! motion and glow. +//! - [`theme`], [`text`], [`font`]: the theme every widget draws from, text roles, the fonts. +//! - [`focus`]: the focus model; Tab and Shift+Tab move focus, Enter and Space press. +//! - The widgets: [`button`], [`field`] (a text field), [`loader`], [`progress`], [`scroll`], +//! [`status`], [`toggle`] (the light and dark pill), and [`chrome`], the window's own +//! decorations, which [`window`] runs. + +pub mod button; +pub mod checkbox; +pub mod choice; +pub mod chrome; +pub mod edit; +pub mod field; +pub mod flow; +pub mod focus; +pub mod font; +pub mod form; +mod icon; +mod input; +pub mod list; +pub mod loader; +mod paint; +pub mod progress; +pub mod scroll; +pub mod settings; +mod shape; +pub mod status; +pub mod switch; +pub mod system; +pub mod text; +pub mod theme; +pub mod toggle; +pub mod tokens; +pub(crate) mod transition; +pub mod window; + +pub use button::button; +pub use checkbox::checkbox; +pub use choice::choice; +pub use field::text_field; +pub use list::navigation; +pub use loader::loader; +pub use progress::progress; +pub use scroll::scroll_area; +pub use status::status; +pub use switch::switch; +pub use theme::{Emphasis, Frame, Interaction, Status, Theme}; +pub use toggle::toggle_group; +pub use tokens::{Accent, Ink, Surface}; + +pub use iced::{Alignment, Center, Fill, Length, Padding, Pixels, Point, Shrink, Size, keyboard}; + +/// The layout widgets, which draw nothing themselves. A `container` draws a [`Frame`]. +pub mod widget { + pub use crate::ui::flow::{Flow, flow}; + pub use iced::widget::{ + Column, Container, MouseArea, Row, Space, column, container, mouse_area, row, space, + }; +} + +/// iced's renderer: wgpu, or tiny-skia where wgpu has no adapter (and offscreen, in the tests). +pub type Renderer = iced::Renderer; + +/// A piece of interface, in the launcher's theme. +pub type Element<'a, Message> = iced::Element<'a, Message, Theme, Renderer>; diff --git a/launcher/src/ui/paint.rs b/launcher/src/ui/paint.rs new file mode 100644 index 0000000000..9d39373344 --- /dev/null +++ b/launcher/src/ui/paint.rs @@ -0,0 +1,174 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Drawing what the theme gives: boxes, dots and the focus outline. Shared by the widgets, which +//! draw only [`Look`]s. + +use iced::advanced::renderer::{self, Renderer as _}; +use iced::advanced::text::{self, Renderer as _}; +use iced::{Background, Border, Color, Pixels, Point, Rectangle, Shadow, Size}; + +use crate::ui::theme::{Halo, Look, color}; +use crate::ui::{Renderer, Theme}; + +/// A look's box, filling the bounds. +pub(crate) fn boxed(renderer: &mut Renderer, bounds: Rectangle, look: &Look) { + framed(renderer, bounds, look, crate::ui::tokens::size::BORDER); +} + +/// A look's box with its line this wide, such as a chosen picture's. Nothing's drawn of one that +/// can't be seen, such as a fade's far end. +pub(crate) fn framed(renderer: &mut Renderer, bounds: Rectangle, look: &Look, line: f32) { + let seen = |color: Option<crate::ui::tokens::Color>| color.is_some_and(|c| c.alpha() > 0.0); + if !seen(look.fill) && !seen(look.line) && !seen(look.glow.map(|glow| glow.color)) { + return; + } + let radius = look.radius.min(bounds.width / 2.0).min(bounds.height / 2.0); + renderer.fill_quad( + renderer::Quad { + bounds, + border: Border { + color: look.line.map(color).unwrap_or(Color::TRANSPARENT), + width: if look.line.is_some() { line } else { 0.0 }, + radius: radius.into(), + }, + shadow: look.glow.map(halo).unwrap_or_default(), + snap: true, + }, + look.fill + .map(|fill| Background::Color(color(fill))) + .unwrap_or(Background::Color(Color::TRANSPARENT)), + ); +} + +/// A glow as iced draws it: a quad's shadow, round the quad and never inside it. +fn halo(glow: Halo) -> Shadow { + Shadow { + color: color(glow.color), + offset: iced::Vector::new(0.0, glow.offset), + blur_radius: glow.blur, + } +} + +/// The focus outline around bounds whose corners have this radius, with focus's glow round it: +/// as a shadow never shows inside its quad, the control inside the outline stays clear. +pub(crate) fn outline(renderer: &mut Renderer, theme: &Theme, bounds: Rectangle, radius: f32) { + outline_glowing(renderer, theme, bounds, radius, theme.focus_glow()); +} + +/// The focus outline, with this glow round it: a window button's is small. +pub(crate) fn outline_glowing( + renderer: &mut Renderer, + theme: &Theme, + bounds: Rectangle, + radius: f32, + glow: Halo, +) { + outline_faded(renderer, theme, bounds, radius, glow, 1.0); +} + +/// The focus outline with focus's glow, at `share` of its strength: a focus ring fades in and +/// out on the glows' own timing, kept by the widget in a [`crate::ui::transition::Lit`]. +pub(crate) fn outline_lit( + renderer: &mut Renderer, + theme: &Theme, + bounds: Rectangle, + radius: f32, + share: f32, +) { + outline_faded(renderer, theme, bounds, radius, theme.focus_glow(), share); +} + +/// The focus outline with this glow, its line and glow both at `share` of their strength; +/// nothing at all at none. +pub(crate) fn outline_faded( + renderer: &mut Renderer, + theme: &Theme, + bounds: Rectangle, + radius: f32, + glow: Halo, + share: f32, +) { + let share = share.clamp(0.0, 1.0); + if share <= 0.0 { + return; + } + let outline = theme.outline(); + let grow = outline.offset + outline.width; + let radius = radius.min(bounds.width / 2.0).min(bounds.height / 2.0); + let bounds = bounds.expand(grow); + let glow = Halo { + color: glow.color.opacity(glow.color.alpha() * share), + ..glow + }; + renderer.fill_quad( + renderer::Quad { + bounds, + border: Border { + color: color(outline.color.opacity(outline.color.alpha() * share)), + width: outline.width, + radius: (radius + grow).into(), + }, + shadow: halo(glow), + snap: true, + }, + Background::Color(Color::TRANSPARENT), + ); +} + +/// A round dot, glowing if it's a light, such as a status chip's. +pub(crate) fn dot( + renderer: &mut Renderer, + center: Point, + diameter: f32, + ink: Color, + glow: Option<Halo>, +) { + let bounds = Rectangle::new( + Point::new(center.x - diameter / 2.0, center.y - diameter / 2.0), + Size::new(diameter, diameter), + ); + renderer.fill_quad( + renderer::Quad { + bounds, + border: Border { + radius: (diameter / 2.0).into(), + ..Border::default() + }, + shadow: glow.map(halo).unwrap_or_default(), + snap: false, + }, + Background::Color(ink), + ); +} + +/// A line of text kept shaped in a widget's state, reshaped only when it changes. +pub(crate) type Plain = + iced::advanced::text::paragraph::Plain<<Renderer as text::Renderer>::Paragraph>; + +/// A single line in a role, unbounded, to shape into a [`Plain`]. +pub(crate) fn unbounded<'a>( + role: &crate::ui::tokens::Role, + content: &'a str, +) -> text::Text<&'a str, iced::Font> { + text::Text { + content, + bounds: Size::INFINITE, + size: Pixels(role.size), + line_height: text::LineHeight::Relative(role.line_height), + font: crate::ui::font::role(role), + align_x: text::Alignment::Left, + align_y: iced::alignment::Vertical::Top, + shaping: text::Shaping::Auto, + wrapping: text::Wrapping::None, + } +} + +/// Shapes `content` into `plain` if it changed: whether it did. +pub(crate) fn shape(plain: &mut Plain, role: &crate::ui::tokens::Role, content: &str) -> bool { + plain.update(unbounded(role, content)) +} + +/// Draws a shaped line, its top left at a point. +pub(crate) fn fill(renderer: &mut Renderer, plain: &Plain, at: Point, ink: Color, clip: Rectangle) { + renderer.fill_paragraph(plain.raw(), at, ink, clip); +} diff --git a/launcher/src/ui/progress.rs b/launcher/src/ui/progress.rs new file mode 100644 index 0000000000..c08c53c1ca --- /dev/null +++ b/launcher/src/ui/progress.rs @@ -0,0 +1,281 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! A progress bar: how far a long step is, such as writing the system image; or, not knowing how +//! far, busy ([`busy`]). + +use std::time::Duration; + +use iced::advanced::layout::{self, Layout}; +use iced::advanced::widget::{Tree, Widget, tree}; +use iced::advanced::{Clipboard, Shell, mouse, renderer}; +use iced::time::Instant; +use iced::{Event, Length, Point, Rectangle, Size, window}; + +use crate::ui::tokens::{motion, size}; + +use crate::ui::theme::Progress as State; +use crate::ui::transition::{phase, wants_frames}; +use crate::ui::{Element, Renderer, Theme, paint}; + +/// A bar this far along, from 0 to 1, running. It never animates: it moves when the value does. +pub fn progress(done: f32) -> Progress { + Progress { + done: if done.is_nan() { + 0.0 + } else { + done.clamp(0.0, 1.0) + }, + state: State::Running, + busy: false, + preview: None, + } +} + +/// A bar for a step that's under way but can't say how far: a stretch of it grows out of its +/// start, runs across and shrinks into its end, over and over, never past the track; with motion +/// reduced, it rests in the middle. +pub fn busy() -> Progress { + Progress { + busy: true, + ..progress(0.0) + } +} + +/// A progress bar ([`progress`], [`busy`]). +pub struct Progress { + done: f32, + state: State, + busy: bool, + /// Busy, drawn still this far into its sweep, for the gallery. + preview: Option<f32>, +} + +/// How long a busy bar's stretch takes to cross it, and how far its tail starts behind its head, +/// as a share of that. +const SWEEP: Duration = Duration::from_millis(1600); +const TAIL: f32 = 0.3; + +/// A busy bar's sweep: when it started, and the frame it's at. +#[derive(Default)] +struct Sweep { + start: Option<Instant>, + now: Option<Instant>, +} + +impl Sweep { + /// Where the stretch's tail and head are, as shares of the bar's width: the head runs from + /// the start to the end, eased, the tail after it, so the stretch grows out of the start and + /// shrinks into the end; with motion reduced, a still stretch in the middle. + fn stretch(&self) -> (f32, f32) { + if crate::ui::system::reduced_motion() { + return (0.35, 0.65); + } + let (Some(start), Some(now)) = (self.start, self.now) else { + return (0.0, 0.0); + }; + // A third of the way in at first, so its first frame shows it. + stretch_at((phase(start, now, SWEEP) + 1.0 / 3.0).fract()) + } +} + +/// Where the stretch's tail and head are this far into a sweep, from 0 to 1. +fn stretch_at(into: f32) -> (f32, f32) { + let eased = |from: f32| motion::EASE.at(((into - from) / (1.0 - TAIL)).clamp(0.0, 1.0)); + (eased(TAIL), eased(0.0)) +} + +impl Progress { + /// Finished, in mint: the whole bar, however far it said it was. + pub fn done(self) -> Self { + Self { + done: 1.0, + state: State::Done, + busy: false, + preview: None, + } + } + + /// Busy, drawn still as it is `at` this far into its sweep, from 0 to 1, asking for no + /// frames: for the gallery. + pub fn preview(self, at: f32) -> Self { + Self { + preview: Some(at.clamp(0.0, 1.0)), + ..self + } + } + + /// Stopped by an error, in red: as far as it got, or, busy, the whole bar, still. + pub fn failed(self) -> Self { + Self { + state: State::Failed, + done: if self.busy { 1.0 } else { self.done }, + busy: false, + ..self + } + } +} + +impl<Message> Widget<Message, Theme, Renderer> for Progress { + fn tag(&self) -> tree::Tag { + tree::Tag::of::<Sweep>() + } + + fn state(&self) -> tree::State { + tree::State::new(Sweep::default()) + } + + fn update( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + _cursor: mouse::Cursor, + _renderer: &Renderer, + _clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + viewport: &Rectangle, + ) { + // Busy, it sweeps: a frame after every frame while it's in sight, unless motion's reduced + // or it's a still. + if self.busy + && self.preview.is_none() + && let Event::Window(window::Event::RedrawRequested(now)) = event + { + let sweep = tree.state.downcast_mut::<Sweep>(); + sweep.start.get_or_insert(*now); + sweep.now = Some(*now); + if wants_frames(layout.bounds(), viewport) { + shell.request_redraw(); + } + } + } + + fn size(&self) -> Size<Length> { + Size::new(Length::Fill, Length::Shrink) + } + + fn layout( + &mut self, + _tree: &mut Tree, + _renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + let size = limits.resolve(Length::Fill, Length::Shrink, Size::new(0.0, size::PROGRESS)); + layout::Node::new(Size::new(size.width, size::PROGRESS)) + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + _style: &renderer::Style, + layout: Layout<'_>, + _cursor: mouse::Cursor, + _viewport: &Rectangle, + ) { + let bounds = layout.bounds(); + let look = theme.progress(self.state); + paint::boxed(renderer, bounds, &look); + if self.busy { + // The stretch, always inside the track: shorter than the bar is tall, as it comes out + // of the start or goes into the end, it fades with its length, its glow too. + let (tail, head) = match self.preview { + Some(at) => stretch_at(at), + None => tree.state.downcast_ref::<Sweep>().stretch(), + }; + let length = (head - tail) * bounds.width; + if length > 0.0 { + let shown = Rectangle::new( + Point::new(bounds.x + tail * bounds.width, bounds.y), + Size::new(length.max(bounds.height.min(length * 2.0)), bounds.height), + ); + let shown = Rectangle { + x: shown.x.min(bounds.x + bounds.width - shown.width), + ..shown + }; + let look = theme + .progress_bar(self.state) + .faded((length / bounds.height).min(1.0)); + paint::boxed(renderer, shown, &look); + } + return; + } + if self.done > 0.0 { + let done = Rectangle::new( + Point::new(bounds.x, bounds.y), + Size::new((bounds.width * self.done).max(bounds.height), bounds.height), + ); + let look = theme.progress_bar(self.state); + if self.state == State::Running { + sunset(renderer, theme, done, &look); + } else { + paint::boxed(renderer, done, &look); + } + } + } +} + +/// A running bar's done part in the launcher's palette: the logo's gradient across it, blue at +/// its start to orange at its end, with the bar's glow. +fn sunset(renderer: &mut Renderer, theme: &Theme, done: Rectangle, look: &crate::ui::theme::Look) { + use iced::advanced::Renderer as _; + use iced::gradient::Linear; + let stops = theme.progress_gradient(); + let last = (stops.len() - 1).max(1) as f32; + let gradient = stops + .iter() + .enumerate() + .fold(Linear::new(iced::Degrees(90.0)), |gradient, (at, stop)| { + gradient.add_stop(at as f32 / last, crate::ui::theme::color(*stop)) + }); + let radius = look.radius.min(done.height / 2.0); + renderer.fill_quad( + renderer::Quad { + bounds: done, + border: iced::Border { + radius: radius.into(), + ..iced::Border::default() + }, + shadow: look + .glow + .map_or_else(iced::Shadow::default, |glow| iced::Shadow { + color: crate::ui::theme::color(glow.color), + offset: iced::Vector::new(0.0, glow.offset), + blur_radius: glow.blur, + }), + snap: true, + }, + iced::Background::Gradient(iced::Gradient::Linear(gradient)), + ); +} + +impl<'a, Message: 'a> From<Progress> for Element<'a, Message> { + fn from(progress: Progress) -> Self { + Element::new(progress) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn done_is_the_whole_bar_and_failed_keeps_how_far() { + assert_eq!(progress(0.4).done().done, 1.0); + assert_eq!(progress(0.7).failed().done, 0.7); + // Busy, failed stops it: the whole bar, still, asking for no frames. + let failed = busy().failed(); + assert!(!failed.busy && failed.done == 1.0 && failed.state == State::Failed); + } + + #[test] + fn progress_stays_between_none_and_all() { + assert_eq!(progress(-1.0).done, 0.0); + assert_eq!(progress(2.0).done, 1.0); + assert_eq!(progress(f32::NAN).done, 0.0); + assert_eq!(progress(0.5).state, State::Running); + assert_eq!(progress(1.0).done().state, State::Done); + assert_eq!(progress(0.3).failed().state, State::Failed); + } +} diff --git a/launcher/src/ui/scroll.rs b/launcher/src/ui/scroll.rs new file mode 100644 index 0000000000..628ea0a2a9 --- /dev/null +++ b/launcher/src/ui/scroll.rs @@ -0,0 +1,1422 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! A scroll area: content taller than its window, such as a long form at a large scale. The wheel +//! scrolls it, a mouse wheel's steps gliding rather than jumping, and focus moved by the keyboard +//! scrolls the focused widget into view ([`crate::ui::focus`]). Scrolled on past an end, the content +//! gives a little and springs back. +//! +//! An area with more to show than fits and nothing in it that takes focus, such as a long text, +//! takes focus itself, as a browser's does, so nothing is left that only a pointer can reach: +//! focused, the arrow keys scroll it by a wheel's step, Page Up, Page Down and Space by what +//! shows less a step, and Home and End to its ends, gliding as a wheel's steps do. + +use std::time::{Duration, Instant}; + +use iced::advanced::layout::{self, Layout}; +use iced::advanced::widget::operation::{Focusable, Operation, Scrollable as Scrolled}; +use iced::advanced::widget::{Id, Tree, Widget, tree}; +use iced::advanced::{Clipboard, Shell, mouse, overlay, renderer}; +use iced::keyboard::{self, Key, key::Named}; +use iced::widget::container; +use iced::widget::scrollable::{self, AbsoluteOffset, Direction, Scrollable, Scrollbar}; +use iced::{ + Background, Border, Event, Length, Point, Rectangle, Shadow, Size, Vector, touch, window, +}; + +use crate::ui::tokens::motion; +use crate::ui::tokens::{radius, size, space}; + +use crate::ui::focus::Focus; +use crate::ui::theme::{Interaction, color as ink}; +use crate::ui::{Element, Renderer, Theme, input, paint}; + +/// Scrolls its content up and down, a mouse wheel's steps gliding to where they lead. +pub fn scroll_area<'a, Message: 'a>( + content: impl Into<Element<'a, Message>>, +) -> Smooth<'a, Message> { + Smooth { + // As wide as the room it's given, so its bar is at that room's edge, not its content's. + inner: Scrollable::with_direction(content, Direction::Vertical(bar())) + .width(Length::Fill) + .class(Bar::Hidden) + .into(), + moves: !crate::ui::system::reduced_motion(), + } +} + +/// A scroll area whose mouse-wheel steps glide: iced jumps a step at once, and this puts it back +/// and moves there over [`motion::NORMAL`] on the design language's curve. A wheel a child takes, such as a +/// list's, a touchpad's smooth deltas and the scrollbar work as they always did. iced's own +/// scrollable takes no keys: an area with nothing in it that takes focus takes it itself, and +/// the keys scroll it (see the module). +/// +/// A finger scrolls it from anywhere, a button or a checkbox too: what it pressed takes the +/// touch until it has moved further up or down than a slip ([`size::SLIP`]), and then lets go +/// (a lost touch), and the area follows the finger. A drag a child keeps, such as a switch's +/// knob, or one that goes across, stays the child's. +/// +/// Scrolled on past an end, by a mouse wheel, a touchpad or a finger, the content gives (a +/// spring): a wheel's step bumps it, a touchpad or a finger pulls it, harder the further it is, +/// and it springs back. +pub struct Smooth<'a, Message> { + inner: Element<'a, Message>, + /// Whether it moves: glides and gives. Not with motion reduced. + moves: bool, +} + +/// A glide from one offset to another. +#[derive(Debug, Clone, Copy, PartialEq)] +struct Glide { + from: Vector, + to: Vector, + /// When it started: the first frame drawn after the step. + start: Option<Instant>, + /// Where it last put the area: moved from there by anything else, such as Tab's reveal, it + /// stops, and doesn't put it back. + put: Vector, +} + +impl Glide { + fn new(from: Vector, to: Vector) -> Self { + Self { + from, + to, + start: None, + put: from, + } + } + + /// Where it is at `now`, and whether it's over. + fn at(&mut self, now: Instant) -> (Vector, bool) { + let start = *self.start.get_or_insert(now); + let t = + (now - start).as_secs_f32() / crate::ui::system::duration(motion::NORMAL).as_secs_f32(); + if t >= 1.0 { + (self.to, true) + } else { + let k = motion::EASE.at(t); + (self.from + (self.to - self.from) * k, false) + } + } +} + +/// How far the content is past an end, a critically damped spring pulling it back: positive past +/// the bottom, the content moved up; negative past the top. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +struct Stretch { + /// Where it was and how fast it moved, in pixels a second, `since` then. + at: f32, + speed: f32, + since: Option<Instant>, +} + +/// The spring's rate, per second: back to rest in about [`motion::SLOW`]. +const SPRING: f32 = 6.0 / motion::SLOW.as_secs_f32(); +/// The furthest the content goes past an end, but never more than a third of the area. +const REACH: f32 = 80.0; +/// A wheel's step past an end bumps the content this share of the step at the most. +const BUMP: f32 = 1.0 / 3.0; +/// Below this far and this fast, the content is at rest. +const AT_REST: (f32, f32) = (0.25, 5.0); +/// iced's pixels for a wheel's line. +const LINE: f32 = 60.0; +/// How near an end counts as at it. +const EDGE: f32 = 0.5; + +impl Stretch { + /// Where it is and how fast it moves at `now`. + fn at(self, now: Instant) -> (f32, f32) { + let Some(since) = self.since else { + return (0.0, 0.0); + }; + let t = now.saturating_duration_since(since).as_secs_f32(); + let b = self.speed + SPRING * self.at; + let decay = (-SPRING * t).exp(); + ( + (self.at + b * t) * decay, + (self.speed - SPRING * b * t) * decay, + ) + } + + fn set(&mut self, now: Instant, at: f32, speed: f32) { + *self = if at.abs() < AT_REST.0 && speed.abs() < AT_REST.1 { + Self::default() + } else { + Self { + at, + speed, + since: Some(now), + } + }; + } + + /// A wheel's step `by` pixels past an end: a bump, smaller the further it already is, never + /// past `reach`. + fn kick(&mut self, now: Instant, by: f32, reach: f32) { + let (at, speed) = self.at(now); + let push = by * BUMP * SPRING * std::f32::consts::E; + self.set(now, at, speed + push * give(at, by, reach)); + } + + /// A touchpad's pull `by` pixels past an end: the content follows, less the further it + /// already is, never past `reach`, and comes to rest there before it springs back. + fn pull(&mut self, now: Instant, by: f32, reach: f32) { + let (at, _) = self.at(now); + self.set(now, at + by * give(at, by, reach), 0.0); + } + + /// A pull `by` pixels back toward the end: the content comes back first, as far as it went; + /// what's left of `by` scrolls. + fn give_back(&mut self, now: Instant, by: f32) -> f32 { + let (at, _) = self.at(now); + let to = at + by; + if to * at > 0.0 { + self.set(now, to, 0.0); + 0.0 + } else { + *self = Self::default(); + to + } + } + + /// Whether it's still moving at `now`. + fn moving(self, now: Instant) -> bool { + let (at, speed) = self.at(now); + at.abs() >= AT_REST.0 || speed.abs() >= AT_REST.1 + } +} + +/// How much of a push `by` past an end the content takes, already `at` of `reach`: all of it back +/// toward the end, and less and less of it further out. +fn give(at: f32, by: f32, reach: f32) -> f32 { + if at * by < 0.0 { + return 1.0; + } + let left = (1.0 - at.abs() / reach).max(0.0); + left * left +} + +/// A finger on the area: where it went down, where it was last, and whose drag it is. +#[derive(Debug, Clone, Copy, PartialEq)] +struct Touch { + finger: touch::Finger, + from: Point, + last: Point, + drag: Drag, +} + +/// Whose a finger's drag is. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Drag { + /// Not yet anyone's: it hasn't moved further than a slip. + Undecided, + /// The area's: it scrolls with the finger. + Area, + /// Someone else's: a child that drags, such as a switch's knob, a drag across, or iced's own + /// scrolling of a press on nothing. + Other, +} + +impl Drag { + /// Who a finger moved `by` since it went down drags, if it's been decided: up or down further + /// than a slip, the area; across further, someone else. + fn decide(by: Vector) -> Option<Self> { + if by.y.abs() > size::SLIP && by.y.abs() >= by.x.abs() { + Some(Self::Area) + } else if by.x.abs() > size::SLIP { + Some(Self::Other) + } else { + None + } + } +} + +/// Whether an event ends a scroll transaction begun `since` ago, as iced's scrollable reckons it: +/// in one, the wheel is the area's own, and a child never sees it. Its times are iced_widget +/// 0.14.2's, private there; Cargo.lock holds iced_widget there, so they're checked again when +/// it moves. +fn ends_transaction(event: &Event, since: Duration) -> bool { + match event { + Event::Mouse( + mouse::Event::ButtonPressed(_) + | mouse::Event::ButtonReleased(_) + | mouse::Event::CursorLeft, + ) => true, + Event::Mouse(mouse::Event::CursorMoved { .. }) => since > Duration::from_millis(100), + _ => since > Duration::from_millis(1500), + } +} + +#[derive(Default)] +struct State { + glide: Option<Glide>, + /// How far the content is past an end, and where it was drawn. + stretch: Stretch, + stretched: f32, + /// When the wheel last scrolled it, while iced's transaction lasts. + transaction: Option<Instant>, + /// Where it was scrolled to at the last frame, and its bounds and its content's. + shown: Option<(Vector, Rectangle, Rectangle)>, + /// When it last moved, and how opaque its bar is now. + moved: Option<Instant>, + bar: f32, + /// Whether the pointer is over where the bar is: it shows while it is. + over_bar: bool, + /// The finger on it, if one is. + touch: Option<Touch>, + /// The thumb dragged by the pointer: where the press was, and how far the area was + /// scrolled then. + dragging: Option<(f32, f32)>, + /// Its own focus, when it takes focus: more to show than fits, and nothing in it that does. + focus: Focus, + takes: bool, + /// Its focus ring, fading in and out with keyboard focus on the glows' own timing. + focus_lit: crate::ui::transition::Lit, +} + +/// How long the bar stays after the area stops moving, and how long it then takes to fade. +const BAR_STAYS: Duration = Duration::from_millis(700); +const BAR_FADES: Duration = motion::SLOW; + +/// How opaque the bar is `since` the area last moved: whole while it stays, then fading out on +/// the design language's curve, both half as long on battery saver; and when to look again, if it's still +/// showing. +fn bar_opacity(since: Duration) -> (f32, Option<Duration>) { + bar_opacity_over( + since, + crate::ui::system::duration(BAR_STAYS), + crate::ui::system::duration(BAR_FADES), + ) +} + +/// The same, the bar staying `stays`, then fading over `fades`. +fn bar_opacity_over(since: Duration, stays: Duration, fades: Duration) -> (f32, Option<Duration>) { + if since < stays { + (1.0, Some(stays - since)) + } else if since < stays + fades { + let t = (since - stays).as_secs_f32() / fades.as_secs_f32(); + (1.0 - motion::EASE.at(t), Some(Duration::ZERO)) + } else { + (0.0, None) + } +} + +/// Where the bar's thumb is: at the area's right edge, as iced's bar is, as far from the top and +/// the bottom as from the side, its length the share of the content shown. None when everything +/// shows. +fn thumb(translation: Vector, bounds: Rectangle, content: Rectangle) -> Option<Rectangle> { + let hidden = content.height - bounds.height; + if hidden <= 0.5 { + return None; + } + let (length, travel) = thumb_length(bounds, content); + let at = (translation.y / hidden).clamp(0.0, 1.0) * travel; + Some(Rectangle::new( + iced::Point::new( + bounds.x + bounds.width - space::XXS - space::S, + bounds.y + space::XXS + at, + ), + Size::new(space::S, length), + )) +} + +/// How long the bar's thumb is, its share of the track as the area's of the content but never +/// shorter than a finger's grip, and how far it travels from the top to the bottom. +fn thumb_length(bounds: Rectangle, content: Rectangle) -> (f32, f32) { + let track = bounds.height - 2.0 * space::XXS; + let length = (track * bounds.height / content.height).max(space::XXL); + (length, (track - length).max(0.0)) +} + +/// Where the pointer shows the bar: a strip at the area's right edge, as wide as the bar and its +/// margins. +fn bar_strip(bounds: Rectangle) -> Rectangle { + let width = space::S + 2.0 * space::XXS; + Rectangle::new( + iced::Point::new(bounds.x + bounds.width - width, bounds.y), + Size::new(width, bounds.height), + ) +} + +/// The scroll area's own offset: the first scrollable an operation meets, not a nested one's. +struct Offset { + read: Option<Vector>, + bounds: Option<(Rectangle, Rectangle)>, + write: Option<Vector>, + done: bool, +} + +impl Operation for Offset { + fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) { + // Once it's met its scrollable, nothing further in: the rest of the page isn't walked. + if !self.done { + operate(self); + } + } + + fn scrollable( + &mut self, + _id: Option<&Id>, + bounds: Rectangle, + content_bounds: Rectangle, + translation: Vector, + state: &mut dyn Scrolled, + ) { + if self.done { + return; + } + self.done = true; + self.read = Some(translation); + self.bounds = Some((bounds, content_bounds)); + if let Some(to) = self.write { + state.scroll_to(AbsoluteOffset { + x: Some(to.x), + y: Some(to.y), + }); + } + } +} + +/// Counts the focusable widgets an operation meets. +struct Count(usize); + +impl Operation for Count { + fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) { + operate(self); + } + + fn focusable(&mut self, _id: Option<&Id>, _bounds: Rectangle, _state: &mut dyn Focusable) { + self.0 += 1; + } +} + +/// Where a key on the focused area scrolls it to, down from the top, `at` now, `shown` high with +/// `hidden` more below: the arrows by a wheel's step, Page Up, Page Down and Space (Shift+Space +/// up) by what shows less a step, so a line carries over, and Home and End to the ends. None for +/// a key that doesn't scroll. +fn scroll_key(key: &Key, shift: bool, at: f32, shown: f32, hidden: f32) -> Option<f32> { + let page = (shown - LINE).max(LINE); + let to = match key { + Key::Named(Named::ArrowDown) => at + LINE, + Key::Named(Named::ArrowUp) => at - LINE, + Key::Named(Named::PageDown) => at + page, + Key::Named(Named::PageUp) => at - page, + Key::Named(Named::Space) if shift => at - page, + Key::Named(Named::Space) => at + page, + Key::Named(Named::Home) => 0.0, + Key::Named(Named::End) => hidden, + _ => return None, + }; + Some(to.clamp(0.0, hidden.max(0.0))) +} + +impl<Message> Smooth<'_, Message> { + /// Whether it takes focus itself: there's more to show than fits, and nothing in it takes + /// focus, which would scroll it into view. + fn takes_focus(&mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer) -> bool { + let Some((_, bounds, content)) = self.geometry(tree, layout, renderer, None) else { + return false; + }; + if content.height - bounds.height <= EDGE { + return false; + } + let mut count = Count(0); + self.inner + .as_widget_mut() + .operate(&mut tree.children[0], layout, renderer, &mut count); + count.0 == 0 + } + + /// A key on it while it has focus: scrolled, gliding as a wheel's step does, and the key + /// taken if it moved. Whether the key was one that scrolls. + fn key( + &mut self, + key: &Key, + modifiers: keyboard::Modifiers, + tree: &mut Tree, + layout: Layout<'_>, + renderer: &Renderer, + shell: &mut Shell<'_, Message>, + ) -> bool { + let Some((translation, bounds, content)) = self.geometry(tree, layout, renderer, None) + else { + return false; + }; + let state = tree.state.downcast_mut::<State>(); + // Pressed again while it glides, from where the glide was headed. + let at = state.glide.map_or(translation.y, |glide| glide.to.y); + let hidden = content.height - bounds.height; + let Some(to) = scroll_key(key, modifiers.shift(), at, bounds.height, hidden) else { + return false; + }; + state.focus.key(); + shell.request_redraw(); + if (to - translation.y).abs() <= EDGE && state.glide.is_none() { + return true; + } + let to = Vector::new(translation.x, to); + if self.moves { + state.glide = Some(Glide::new(translation, to)); + } else { + let _ = self.offset(tree, layout, renderer, Some(to)); + } + shell.capture_event(); + true + } +} + +impl<Message> Smooth<'_, Message> { + /// Its offset now, or, given one, set to it. + fn offset( + &mut self, + tree: &mut Tree, + layout: Layout<'_>, + renderer: &Renderer, + write: Option<Vector>, + ) -> Option<Vector> { + self.geometry(tree, layout, renderer, write) + .map(|(translation, _, _)| translation) + } + + /// Its offset, its bounds and its content's, or, given an offset, set to it first. + fn geometry( + &mut self, + tree: &mut Tree, + layout: Layout<'_>, + renderer: &Renderer, + write: Option<Vector>, + ) -> Option<(Vector, Rectangle, Rectangle)> { + let mut offset = Offset { + read: None, + bounds: None, + write, + done: false, + }; + self.inner + .as_widget_mut() + .operate(&mut tree.children[0], layout, renderer, &mut offset); + let (bounds, content) = offset.bounds?; + Some((write.unwrap_or(offset.read?), bounds, content)) + } + + /// A wheel over the area, a mouse's or a touchpad's: iced scrolls it, then a mouse's step + /// glides there; and scrolled on past an end, if the wheel is the area's own, the content + /// gives (a spring). + #[allow(clippy::too_many_arguments)] + fn wheel( + &mut self, + delta: mouse::ScrollDelta, + now: Instant, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + renderer: &Renderer, + clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + viewport: &Rectangle, + ) { + // How far down it's asked to scroll, as iced counts it. + let (by, step) = match delta { + mouse::ScrollDelta::Lines { y, .. } => (-y * LINE, true), + mouse::ScrollDelta::Pixels { y, .. } => (-y, false), + }; + let glides = self.moves && step; + if !glides { + // A touchpad takes over from the glide where it is. + tree.state.downcast_mut::<State>().glide = None; + } + let before = self.geometry(tree, layout, renderer, None); + self.inner.as_widget_mut().update( + &mut tree.children[0], + event, + layout, + cursor, + renderer, + clipboard, + shell, + viewport, + ); + let after = self.offset(tree, layout, renderer, None); + let (Some((before, bounds, content)), Some(after)) = (before, after) else { + return; + }; + if !self.moves { + return; + } + let state = tree.state.downcast_mut::<State>(); + if after != before { + state.transaction = Some(now); + } + // A touchpad pulling back from past an end brings the content back before it scrolls. + if !step && state.stretch.at(now).0 * by < 0.0 { + let left = state.stretch.give_back(now, by); + let _ = self.offset( + tree, + layout, + renderer, + Some(before + Vector::new(0.0, left)), + ); + shell.capture_event(); + shell.request_redraw(); + return; + } + if after != before { + if glides { + // The area itself moved, not a child: back to where it was, and glide on from + // where the glide was headed. + let to = state.glide.map_or(before, |glide| glide.to) + (after - before); + let _ = self.offset(tree, layout, renderer, Some(before)); + let state = tree.state.downcast_mut::<State>(); + state.glide = Some(Glide::new(before, to)); + shell.request_redraw(); + } + return; + } + // It didn't move. Past an end, the wheel is the area's own if no child took it, or if + // it's in a transaction, where no child sees the wheel. + let ours = !shell.is_event_captured() || state.transaction.is_some(); + let hidden = content.height - bounds.height; + let past = hidden > EDGE + && ((by < 0.0 && before.y <= EDGE) || (by > 0.0 && before.y >= hidden - EDGE)); + if ours && past { + let reach = REACH.min(bounds.height / 3.0); + if step { + state.stretch.kick(now, by, reach); + } else { + state.stretch.pull(now, by, reach); + } + shell.capture_event(); + shell.request_redraw(); + } + } +} + +impl<Message> Smooth<'_, Message> { + /// The thumb the area draws, dragged by the pointer: the area follows it, the thumb's travel + /// across the content. The area drags it itself, as iced's own draggable thumb is elsewhere + /// on a long page, being shorter. Whether the event was the drag's. + fn drag_thumb( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + renderer: &Renderer, + shell: &mut Shell<'_, Message>, + ) -> bool { + let state = tree.state.downcast_mut::<State>(); + let Some((translation, bounds, content)) = state.shown else { + return false; + }; + match event { + Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) + if state.bar > 0.0 + && thumb(translation, bounds, content) + .is_some_and(|thumb| cursor.is_over(thumb.expand(space::XXS))) => + { + let Some(at) = cursor.position() else { + return false; + }; + state.dragging = Some((at.y, translation.y)); + state.glide = None; + shell.capture_event(); + true + } + Event::Mouse(mouse::Event::CursorMoved { position }) => { + let Some((from, scrolled)) = state.dragging else { + return false; + }; + let (_, travel) = thumb_length(bounds, content); + let hidden = (content.height - bounds.height).max(0.0); + let by = if travel > 0.0 { + (position.y - from) * hidden / travel + } else { + 0.0 + }; + let to = (scrolled + by).clamp(0.0, hidden); + let _ = self.offset(tree, layout, renderer, Some(Vector::new(translation.x, to))); + shell.capture_event(); + shell.request_redraw(); + true + } + Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) + if state.dragging.is_some() => + { + state.dragging = None; + state.moved = Some(Instant::now()); + shell.capture_event(); + shell.request_redraw(); + true + } + _ => false, + } + } + + /// The area scrolled `by` pixels down with a finger, as a touchpad's delta scrolls it: past an + /// end the content gives, and pulled back it comes back first. + fn follow( + &mut self, + by: f32, + now: Instant, + tree: &mut Tree, + layout: Layout<'_>, + renderer: &Renderer, + ) { + let Some((before, bounds, content)) = self.geometry(tree, layout, renderer, None) else { + return; + }; + let hidden = (content.height - bounds.height).max(0.0); + let state = tree.state.downcast_mut::<State>(); + let by = if self.moves && state.stretch.at(now).0 * by < 0.0 { + state.stretch.give_back(now, by) + } else { + by + }; + let to = (before.y + by).clamp(0.0, hidden); + let past = before.y + by - to; + if self.moves && past != 0.0 && hidden > EDGE { + state + .stretch + .pull(now, past, REACH.min(bounds.height / 3.0)); + } + if to != before.y { + let _ = self.offset(tree, layout, renderer, Some(Vector::new(before.x, to))); + } + } + + /// A finger's event, if it's one the area takes for itself rather than passing on: a drag + /// that's become the area's moves it, and lifting it ends the drag. A drag the area takes + /// over first tells what the finger pressed that it's lost the touch. + #[allow(clippy::too_many_arguments)] + fn touch( + &mut self, + event: &touch::Event, + tree: &mut Tree, + layout: Layout<'_>, + cursor: mouse::Cursor, + renderer: &Renderer, + clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + viewport: &Rectangle, + ) -> bool { + let state = tree.state.downcast_mut::<State>(); + let ours = |id: &touch::Finger| state.touch.is_some_and(|touch| touch.finger == *id); + match *event { + touch::Event::FingerPressed { id, position } => { + if state.touch.is_none() && cursor.is_over(layout.bounds()) { + state.touch = Some(Touch { + finger: id, + from: position, + last: position, + drag: Drag::Undecided, + }); + } + false + } + touch::Event::FingerMoved { id, position } if ours(&id) => { + let Some(mut touch) = state.touch else { + return false; + }; + match touch.drag { + Drag::Area => { + let by = touch.last.y - position.y; + touch.last = position; + tree.state.downcast_mut::<State>().touch = Some(touch); + self.follow(by, Instant::now(), tree, layout, renderer); + shell.capture_event(); + shell.request_redraw(); + true + } + Drag::Other => false, + Drag::Undecided => { + // What the finger pressed sees it move first: if it keeps the drag, or + // iced scrolls a press on nothing, the drag is theirs. + let before = self.offset(tree, layout, renderer, None); + self.inner.as_widget_mut().update( + &mut tree.children[0], + &Event::Touch(*event), + layout, + cursor, + renderer, + clipboard, + shell, + viewport, + ); + let after = self.offset(tree, layout, renderer, None); + touch.drag = if shell.is_event_captured() || after != before { + Drag::Other + } else { + Drag::decide(position - touch.from).unwrap_or(Drag::Undecided) + }; + if touch.drag == Drag::Area { + // The area's now: what the finger pressed lets go, as if the touch + // were taken away, and the area follows from here, without a jump. + touch.last = position; + self.inner.as_widget_mut().update( + &mut tree.children[0], + &Event::Touch(touch::Event::FingerLost { id, position }), + layout, + cursor, + renderer, + clipboard, + shell, + viewport, + ); + shell.capture_event(); + shell.request_redraw(); + } + tree.state.downcast_mut::<State>().touch = Some(touch); + true + } + } + } + touch::Event::FingerLifted { id, position } + | touch::Event::FingerLost { id, position } + if ours(&id) => + { + let drag = state.touch.take().map(|touch| touch.drag); + if drag != Some(Drag::Area) { + return false; + } + // What it pressed let go when the area took the drag: iced's own drag ends. + self.inner.as_widget_mut().update( + &mut tree.children[0], + &Event::Touch(touch::Event::FingerLost { id, position }), + layout, + cursor, + renderer, + clipboard, + shell, + viewport, + ); + shell.capture_event(); + shell.request_redraw(); + true + } + _ => false, + } + } +} + +impl<Message> Widget<Message, Theme, Renderer> for Smooth<'_, Message> { + fn tag(&self) -> tree::Tag { + tree::Tag::of::<State>() + } + + fn state(&self) -> tree::State { + tree::State::new(State::default()) + } + + fn children(&self) -> Vec<Tree> { + vec![Tree::new(&self.inner)] + } + + fn diff(&self, tree: &mut Tree) { + tree.diff_children(std::slice::from_ref(&self.inner)); + } + + fn size(&self) -> Size<Length> { + self.inner.as_widget().size() + } + + fn layout( + &mut self, + tree: &mut Tree, + renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + self.inner + .as_widget_mut() + .layout(&mut tree.children[0], renderer, limits) + } + + fn operate( + &mut self, + tree: &mut Tree, + layout: Layout<'_>, + renderer: &Renderer, + operation: &mut dyn Operation, + ) { + let takes = self.takes_focus(tree, layout, renderer); + let state = tree.state.downcast_mut::<State>(); + state.takes = takes; + state.focus.keep_if(takes); + if takes { + operation.focusable(None, layout.bounds(), &mut state.focus); + } + self.inner + .as_widget_mut() + .operate(&mut tree.children[0], layout, renderer, operation); + } + + fn update( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + renderer: &Renderer, + clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + viewport: &Rectangle, + ) { + let now = Instant::now(); + let state = tree.state.downcast_mut::<State>(); + state.transaction = state + .transaction + .filter(|&since| !ends_transaction(event, now.saturating_duration_since(since))); + // Over where the bar is, the bar shows, while there's more to scroll to; let go of, it + // stays a while and fades, as after scrolling. + if let Event::Mouse(mouse::Event::CursorMoved { .. } | mouse::Event::CursorLeft) = event { + let over = state.shown.is_some_and(|(translation, bounds, content)| { + thumb(translation, bounds, content).is_some() && cursor.is_over(bar_strip(bounds)) + }); + if over != state.over_bar { + state.over_bar = over; + if !over { + state.moved = Some(now); + } + shell.request_redraw(); + } + } + // Taking focus itself, a click on it focuses it; the keys then scroll it. + if let Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerPressed { .. }) = event + && cursor.is_over(layout.bounds()) + { + let state = tree.state.downcast_mut::<State>(); + if state.takes { + state.focus.click(); + } + } + // The focus ring fades in and out with keyboard focus, before any key handling returns. + { + let state = tree.state.downcast_mut::<State>(); + let ringed = state.takes && state.focus.is_shown(); + state.focus_lit.frame(event, shell); + state.focus_lit.aim(ringed, shell); + } + if let Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) = event + && tree.state.downcast_ref::<State>().focus.is_focused() + && input::plain(*modifiers) + && self.key(key, *modifiers, tree, layout, renderer, shell) + { + return; + } + if self.drag_thumb(tree, event, layout, cursor, renderer, shell) { + return; + } + if let Event::Mouse(mouse::Event::WheelScrolled { delta }) = event + && cursor.is_over(layout.bounds()) + { + self.wheel( + *delta, now, tree, event, layout, cursor, renderer, clipboard, shell, viewport, + ); + return; + } + if let Event::Touch(touch) = event { + if cursor.is_over(layout.bounds()) { + // A finger takes over from the glide where it is. + tree.state.downcast_mut::<State>().glide = None; + } + if self.touch( + touch, tree, layout, cursor, renderer, clipboard, shell, viewport, + ) { + return; + } + } + if let Event::Window(window::Event::RedrawRequested(now)) = event { + let mut write = None; + if let Some(mut glide) = tree.state.downcast_mut::<State>().glide.take() { + let moved_since = self + .offset(tree, layout, renderer, None) + .is_some_and(|offset| (offset - glide.put).y.abs() > EDGE); + if !moved_since { + let (at, over) = glide.at(*now); + glide.put = at; + if !over { + tree.state.downcast_mut::<State>().glide = Some(glide); + shell.request_redraw(); + } + write = Some(at); + } + } + let state = tree.state.downcast_mut::<State>(); + // Past an end, the content springs back. + state.stretched = state.stretch.at(*now).0; + if state.stretch.moving(*now) { + shell.request_redraw(); + } else { + state.stretch = Stretch::default(); + state.stretched = 0.0; + } + // The bar shows while the area moves, by whatever means, then fades. + let shown = self.geometry(tree, layout, renderer, write); + let state = tree.state.downcast_mut::<State>(); + if let (Some((was, ..)), Some((now_at, ..))) = (state.shown, shown) + && was != now_at + { + state.moved = Some(*now); + } + state.shown = shown; + state.bar = 0.0; + if state.over_bar || state.dragging.is_some() { + state.bar = 1.0; + } else if let Some(moved) = state.moved { + let (opacity, again) = bar_opacity(now.saturating_duration_since(moved)); + state.bar = opacity; + match again { + Some(wait) if wait.is_zero() => shell.request_redraw(), + Some(wait) => shell.request_redraw_at(*now + wait), + None => state.moved = None, + } + } + } else if matches!(event, Event::Mouse(mouse::Event::ButtonPressed(_))) + && cursor.is_over(layout.bounds()) + { + // A press, as on the scrollbar, takes over from the glide where it is. + tree.state.downcast_mut::<State>().glide = None; + } + // Past an end, the content is drawn moved by the stretch: the pointer's over what's drawn + // under it. + let stretched = Vector::new(0.0, tree.state.downcast_ref::<State>().stretched); + self.inner.as_widget_mut().update( + &mut tree.children[0], + event, + layout, + cursor + stretched, + renderer, + clipboard, + shell, + viewport, + ); + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + style: &renderer::Style, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + ) { + let state = tree.state.downcast_ref::<State>(); + if state.stretched == 0.0 { + self.inner.as_widget().draw( + &tree.children[0], + renderer, + theme, + style, + layout, + cursor, + viewport, + ); + } else if let Some(shown) = layout.bounds().intersection(viewport) { + // Past an end: the content moved by the stretch, and the pointer over what's drawn + // under it. iced doesn't clip a layer to the one round it, so the area's own layer is + // kept inside it by the viewport it's given: where it shows, moved back. + let shift = Vector::new(0.0, -state.stretched); + iced::advanced::Renderer::with_translation(renderer, shift, |renderer| { + self.inner.as_widget().draw( + &tree.children[0], + renderer, + theme, + style, + layout, + cursor + Vector::new(0.0, state.stretched), + &(shown - shift), + ); + }); + } + if state.bar > 0.0 + && let Some((translation, bounds, content)) = state.shown + && let Some(thumb) = thumb(translation, bounds, content) + { + let mut color = ink(theme.scroller(Interaction::Hovered)); + color.a *= state.bar; + iced::advanced::Renderer::with_layer(renderer, bounds, |renderer| { + iced::advanced::Renderer::fill_quad( + renderer, + renderer::Quad { + bounds: thumb, + border: Border { + radius: radius::ROUND.into(), + ..Border::default() + }, + shadow: Shadow::default(), + snap: true, + }, + Background::Color(color), + ); + }); + } + // The focus ring on its fade, drawn while it fades out too. + paint::outline_lit( + renderer, + theme, + layout.bounds(), + radius::CONTROL, + state.focus_lit.share(), + ); + } + + fn mouse_interaction( + &self, + tree: &Tree, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + renderer: &Renderer, + ) -> mouse::Interaction { + let stretched = Vector::new(0.0, tree.state.downcast_ref::<State>().stretched); + self.inner.as_widget().mouse_interaction( + &tree.children[0], + layout, + cursor + stretched, + viewport, + renderer, + ) + } + + fn overlay<'b>( + &'b mut self, + tree: &'b mut Tree, + layout: Layout<'b>, + renderer: &Renderer, + viewport: &Rectangle, + translation: Vector, + ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { + self.inner.as_widget_mut().overlay( + &mut tree.children[0], + layout, + renderer, + viewport, + translation, + ) + } +} + +impl<'a, Message: 'a> From<Smooth<'a, Message>> for Element<'a, Message> { + fn from(smooth: Smooth<'a, Message>) -> Self { + Element::new(smooth) + } +} + +/// Scrolls its content sideways, such as a table wider than its window; the wheel still scrolls +/// what's round it up and down. +pub fn scroll_across<'a, Message: 'a>( + content: impl Into<Element<'a, Message>>, +) -> Scrollable<'a, Message, Theme, Renderer> { + // The bar takes room of its own below the content, rather than lying over its last row. + Scrollable::with_direction(content, Direction::Horizontal(bar().spacing(space::S))) +} + +/// Scrolls its content both ways, for a page wider than the window. +pub fn scroll_both<'a, Message: 'a>( + content: impl Into<Element<'a, Message>>, +) -> Scrollable<'a, Message, Theme, Renderer> { + Scrollable::with_direction( + content, + Direction::Both { + vertical: bar(), + horizontal: bar(), + }, + ) +} + +fn bar() -> Scrollbar { + Scrollbar::new() + .width(space::S) + .scroller_width(space::S) + .margin(space::XXS) +} + +/// Whether a scroll area's bar is drawn: always, or by the area itself, while it scrolls +/// ([`Smooth`]); hidden, iced's bar is still there to drag. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Bar { + #[default] + Shown, + Hidden, +} + +impl scrollable::Catalog for Theme { + type Class<'a> = Bar; + + fn default<'a>() -> Self::Class<'a> { + Bar::Shown + } + + fn style(&self, class: &Bar, status: scrollable::Status) -> scrollable::Style { + let (vertical, horizontal) = match status { + scrollable::Status::Active { .. } => (Interaction::Idle, Interaction::Idle), + scrollable::Status::Hovered { + is_vertical_scrollbar_hovered, + is_horizontal_scrollbar_hovered, + .. + } => ( + hovered(is_vertical_scrollbar_hovered), + hovered(is_horizontal_scrollbar_hovered), + ), + scrollable::Status::Dragged { + is_vertical_scrollbar_dragged, + is_horizontal_scrollbar_dragged, + .. + } => ( + pressed(is_vertical_scrollbar_dragged), + pressed(is_horizontal_scrollbar_dragged), + ), + }; + let rail = |interaction| scrollable::Rail { + background: None, + border: Border::default(), + scroller: scrollable::Scroller { + background: Background::Color(match class { + Bar::Shown => ink(self.scroller(interaction)), + Bar::Hidden => iced::Color::TRANSPARENT, + }), + border: Border { + radius: radius::ROUND.into(), + ..Border::default() + }, + }, + }; + let badge = self.badge(); + scrollable::Style { + container: container::Style::default(), + vertical_rail: rail(vertical), + horizontal_rail: rail(horizontal), + gap: None, + auto_scroll: scrollable::AutoScroll { + background: Background::Color(ink(badge.fill.unwrap_or(badge.ink))), + border: Border { + color: ink(badge.line.unwrap_or(badge.ink)), + width: crate::ui::tokens::size::BORDER, + radius: radius::ROUND.into(), + }, + shadow: Shadow::default(), + icon: ink(badge.ink), + }, + } + } +} + +fn hovered(yes: bool) -> Interaction { + if yes { + Interaction::Hovered + } else { + Interaction::Idle + } +} + +fn pressed(yes: bool) -> Interaction { + if yes { + Interaction::Pressed + } else { + Interaction::Idle + } +} + +#[cfg(test)] +mod tests { + use super::*; + use iced::widget::scrollable::Catalog as _; + + #[test] + fn the_scroller_shows_what_the_pointer_does() { + let theme = <Theme as Default>::default(); + let idle = theme.style( + &Bar::Shown, + scrollable::Status::Active { + is_horizontal_scrollbar_disabled: false, + is_vertical_scrollbar_disabled: false, + }, + ); + let line = Background::Color(ink(theme.palette().line)); + assert_eq!(idle.vertical_rail.scroller.background, line); + let dragged = theme.style( + &Bar::Shown, + scrollable::Status::Dragged { + is_horizontal_scrollbar_dragged: false, + is_vertical_scrollbar_dragged: true, + is_horizontal_scrollbar_disabled: false, + is_vertical_scrollbar_disabled: false, + }, + ); + let dim = Background::Color(ink(theme.palette().dim)); + assert_eq!(dragged.vertical_rail.scroller.background, dim); + assert_eq!(dragged.horizontal_rail.scroller.background, line); + let hovered = theme.style( + &Bar::Shown, + scrollable::Status::Hovered { + is_horizontal_scrollbar_hovered: true, + is_vertical_scrollbar_hovered: false, + is_horizontal_scrollbar_disabled: false, + is_vertical_scrollbar_disabled: false, + }, + ); + assert_eq!(hovered.horizontal_rail.scroller.background, dim); + <Theme as scrollable::Catalog>::default(); + let _: Element<'_, ()> = scroll_area(crate::ui::text::interface("x")).into(); + let _: Scrollable<'_, (), Theme, Renderer> = scroll_both(crate::ui::text::interface("x")); + } + + #[test] + fn the_keys_scroll_by_a_step_a_page_less_a_step_or_to_an_end() { + let named = |key| Key::Named(key); + let to = |key, shift, at, shown| scroll_key(&named(key), shift, at, shown, 1000.0); + assert_eq!(to(Named::ArrowDown, false, 0.0, 240.0), Some(60.0)); + assert_eq!(to(Named::ArrowUp, false, 30.0, 240.0), Some(0.0)); + assert_eq!(to(Named::PageDown, false, 100.0, 240.0), Some(280.0)); + assert_eq!(to(Named::PageUp, false, 100.0, 240.0), Some(0.0)); + assert_eq!(to(Named::Space, false, 100.0, 240.0), Some(280.0)); + assert_eq!(to(Named::Space, true, 300.0, 240.0), Some(120.0)); + assert_eq!(to(Named::PageDown, false, 900.0, 240.0), Some(1000.0)); + assert_eq!(to(Named::End, false, 0.0, 240.0), Some(1000.0)); + assert_eq!(to(Named::Home, false, 500.0, 240.0), Some(0.0)); + // An area shorter than a step still pages by one. + assert_eq!(to(Named::PageDown, false, 0.0, 50.0), Some(60.0)); + assert_eq!(to(Named::Tab, false, 0.0, 240.0), None); + assert_eq!( + scroll_key(&Key::Character("j".into()), false, 0.0, 240.0, 1000.0), + None + ); + } + + #[test] + fn a_glide_eases_to_its_end_and_stops() { + let mut glide = Glide::new(Vector::new(0.0, 0.0), Vector::new(0.0, 120.0)); + let start = Instant::now(); + assert_eq!(glide.at(start), (Vector::new(0.0, 0.0), false)); + let (quarter, over) = glide.at(start + motion::NORMAL / 4); + assert!( + !over && quarter.y > 60.0 && quarter.y < 120.0, + "{quarter:?}" + ); + let (end, over) = glide.at(start + motion::NORMAL + Duration::from_millis(1)); + assert!(over && end == Vector::new(0.0, 120.0)); + } + + #[test] + fn the_bar_stays_then_fades_then_goes() { + assert_eq!(bar_opacity(Duration::ZERO), (1.0, Some(BAR_STAYS))); + let (mid, again) = bar_opacity(BAR_STAYS + BAR_FADES / 2); + assert!( + mid > 0.0 && mid < 1.0 && again == Some(Duration::ZERO), + "{mid}" + ); + assert_eq!(bar_opacity(BAR_STAYS + BAR_FADES), (0.0, None)); + } + + #[test] + fn the_thumb_is_the_share_shown_where_it_is() { + let bounds = Rectangle::new(iced::Point::new(0.0, 0.0), Size::new(400.0, 300.0)); + let content = Rectangle::new(iced::Point::new(0.0, 0.0), Size::new(400.0, 900.0)); + let top = thumb(Vector::new(0.0, 0.0), bounds, content).unwrap(); + // As far in from the top and the bottom as from the side; a third of the track long. + let track = 300.0 - 2.0 * space::XXS; + assert_eq!((top.y, top.height), (space::XXS, track / 3.0)); + assert_eq!(top.x, 400.0 - space::XXS - space::S); + let bottom = thumb(Vector::new(0.0, 600.0), bounds, content).unwrap(); + assert_eq!(bottom.y + bottom.height, 300.0 - space::XXS); + // Everything shows: no bar. + assert!(thumb(Vector::new(0.0, 0.0), bounds, bounds).is_none()); + } + + /// Where the stretch is at each frame for `ms`, at 60 frames a second. + fn frames(stretch: Stretch, start: Instant, ms: u64) -> Vec<f32> { + (0..=ms / 16) + .map(|frame| stretch.at(start + Duration::from_millis(frame * 16)).0) + .collect() + } + + #[test] + fn a_wheel_step_past_the_end_bumps_and_springs_back() { + let start = Instant::now(); + let mut stretch = Stretch::default(); + stretch.kick(start, LINE, REACH); + let path = frames(stretch, start, 600); + let peak = path.iter().copied().fold(0.0, f32::max); + // About a third of the step at the most, and never past the end it went from. + assert!( + peak > LINE * BUMP * 0.9 && peak <= LINE * BUMP + 0.01, + "{peak}" + ); + assert!(path.iter().all(|at| *at >= 0.0), "{path:?}"); + // Back at rest in about motion::SLOW. + assert!( + !stretch.moving(start + motion::SLOW + motion::FAST), + "{path:?}" + ); + // Past the top, the same the other way. + let mut up = Stretch::default(); + up.kick(start, -LINE, REACH); + let low = frames(up, start, 600).into_iter().fold(0.0, f32::min); + assert!((low + peak).abs() < 0.01, "{low} {peak}"); + } + + #[test] + fn a_pull_gives_less_the_further_it_goes_and_never_past_its_reach() { + let start = Instant::now(); + let mut stretch = Stretch::default(); + let mut last = 0.0; + let mut steps = Vec::new(); + for _ in 0..200 { + stretch.pull(start, 10.0, REACH); + let (at, speed) = stretch.at(start); + assert_eq!(speed, 0.0); + steps.push(at - last); + last = at; + } + assert!(last < REACH, "{last}"); + assert!(steps.windows(2).all(|pair| pair[1] <= pair[0]), "{steps:?}"); + assert_eq!(steps[0], 10.0); + } + + #[test] + fn pulling_back_takes_the_stretch_in_first() { + let start = Instant::now(); + let mut stretch = Stretch::default(); + stretch.pull(start, 30.0, REACH); + let (at, _) = stretch.at(start); + // Back by less than it went: nothing left to scroll. + assert_eq!(stretch.give_back(start, -10.0), 0.0); + assert!((stretch.at(start).0 - (at - 10.0)).abs() < 1e-4); + // Back by more: at rest, and the rest scrolls. + let left = stretch.give_back(start, -50.0); + assert!((left - (at - 60.0)).abs() < 1e-4, "{left}"); + assert_eq!(stretch, Stretch::default()); + assert!(!stretch.moving(start)); + } + + #[test] + fn give_is_whole_back_toward_the_end_and_less_further_out() { + assert_eq!(give(0.0, 5.0, REACH), 1.0); + assert_eq!(give(40.0, -5.0, REACH), 1.0); + assert_eq!(give(-40.0, 5.0, REACH), 1.0); + assert_eq!(give(40.0, 5.0, 80.0), 0.25); + assert_eq!(give(-40.0, -5.0, 80.0), 0.25); + assert_eq!(give(80.0, 5.0, 80.0), 0.0); + assert_eq!(give(120.0, 5.0, 80.0), 0.0); + } + + #[test] + fn a_transaction_ends_as_iceds_does() { + let click = Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)); + let left = Event::Mouse(mouse::Event::CursorLeft); + let moved = Event::Mouse(mouse::Event::CursorMoved { + position: iced::Point::ORIGIN, + }); + let wheel = Event::Mouse(mouse::Event::WheelScrolled { + delta: mouse::ScrollDelta::Lines { x: 0.0, y: -1.0 }, + }); + let ms = Duration::from_millis; + assert!(ends_transaction(&click, ms(0))); + assert!(ends_transaction(&left, ms(0))); + assert!(!ends_transaction(&moved, ms(100)) && ends_transaction(&moved, ms(101))); + assert!(!ends_transaction(&wheel, ms(1500)) && ends_transaction(&wheel, ms(1501))); + } +} diff --git a/launcher/src/ui/settings.rs b/launcher/src/ui/settings.rs new file mode 100644 index 0000000000..20e3a4d9cc --- /dev/null +++ b/launcher/src/ui/settings.rs @@ -0,0 +1,336 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! A list of settings: a group's title, then a card of rows, +//! each a setting's name, what it does, and its control at the end, whatever the control is: a +//! switch, a dropdown, a field, a stepper. On or off is a switch, never a checkbox. +//! +//! ```ignore +//! group("Scrolling") +//! .row( +//! row("Scroll on output") +//! .description("Scroll when applications in the terminal print") +//! .control(switch(on).on_toggle(Message::ScrollOnOutput)) +//! .on_press(Message::ScrollOnOutput(!on)), +//! ) +//! ``` + +use iced::advanced::layout::{self, Layout}; +use iced::advanced::widget::{Operation, Tree, Widget, tree}; +use iced::advanced::{Clipboard, Shell, mouse, overlay, renderer}; +use iced::widget::{Column, Space, column, container}; +use iced::{Event, Length, Rectangle, Size, Vector, touch}; + +use crate::ui::tokens::{Ink, Surface, space}; + +use crate::ui::theme::Frame; +use crate::ui::{Element, Fill, Renderer, Theme, text}; + +/// The room inside a row, above and below its words and round its sides. +const ROW_PAD: [f32; 2] = [space::L, space::XL]; + +/// A setting: its name, and what follows. +pub fn row<'a, Message>(title: impl Into<String>) -> Row<'a, Message> { + Row { + title: title.into(), + description: None, + control: None, + on_press: None, + } +} + +/// A setting's row: its name, what it does below it, and its control at the end. +pub struct Row<'a, Message> { + title: String, + description: Option<String>, + control: Option<Element<'a, Message>>, + on_press: Option<Message>, +} + +impl<'a, Message: Clone + 'a> Row<'a, Message> { + /// What the setting does, in a line or two below its name. + pub fn description(self, description: impl Into<String>) -> Self { + Self { + description: Some(description.into()), + ..self + } + } + + /// Its control, at the row's end: any widget. + pub fn control(self, control: impl Into<Element<'a, Message>>) -> Self { + Self { + control: Some(control.into()), + ..self + } + } + + /// What a click anywhere on the row sends, as a switch's row turns it over: pressed and let + /// go on the row, as a button is, so a finger that lands on it to scroll the page sends + /// nothing. A click on the control goes to the control alone. + pub fn on_press(self, message: Message) -> Self { + Self { + on_press: Some(message), + ..self + } + } +} + +impl<'a, Message: Clone + 'a> From<Row<'a, Message>> for Element<'a, Message> { + fn from(row: Row<'a, Message>) -> Self { + let words = Column::with_children( + std::iter::once(text::interface(row.title).into()).chain( + row.description + .map(|description| text::interface(description).class(Ink::Muted).into()), + ), + ) + .spacing(space::XXS) + .width(Fill); + // The control beside the words while they have room, below them when they don't, as on + // a phone. + let content = container( + crate::ui::flow::flow(std::iter::once(words.into()).chain(row.control)) + .spacing(space::XL), + ) + .padding(ROW_PAD); + match row.on_press { + Some(on_press) => Element::new(Pressable { + content: content.into(), + on_press, + }), + None => content.into(), + } + } +} + +/// A row that sends its message on a click: pressed on it and let go on it. What's in it, its +/// control, takes its own presses first. +struct Pressable<'a, Message> { + content: Element<'a, Message>, + on_press: Message, +} + +/// Whether a press began on the row. +#[derive(Default)] +struct Pressed(bool); + +impl<Message: Clone> Widget<Message, Theme, Renderer> for Pressable<'_, Message> { + fn tag(&self) -> tree::Tag { + tree::Tag::of::<Pressed>() + } + + fn state(&self) -> tree::State { + tree::State::new(Pressed::default()) + } + + fn children(&self) -> Vec<Tree> { + vec![Tree::new(&self.content)] + } + + fn diff(&self, tree: &mut Tree) { + tree.diff_children(std::slice::from_ref(&self.content)); + } + + fn size(&self) -> Size<Length> { + self.content.as_widget().size() + } + + fn layout( + &mut self, + tree: &mut Tree, + renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + self.content + .as_widget_mut() + .layout(&mut tree.children[0], renderer, limits) + } + + fn operate( + &mut self, + tree: &mut Tree, + layout: Layout<'_>, + renderer: &Renderer, + operation: &mut dyn Operation, + ) { + self.content + .as_widget_mut() + .operate(&mut tree.children[0], layout, renderer, operation); + } + + fn update( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + renderer: &Renderer, + clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + viewport: &Rectangle, + ) { + self.content.as_widget_mut().update( + &mut tree.children[0], + event, + layout, + cursor, + renderer, + clipboard, + shell, + viewport, + ); + if shell.is_event_captured() { + return; + } + let pressed = &mut tree.state.downcast_mut::<Pressed>().0; + let over = cursor.is_over(layout.bounds()); + match event { + Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerPressed { .. }) + if over => + { + *pressed = true; + shell.capture_event(); + } + Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerLifted { .. }) + if *pressed => + { + *pressed = false; + if over { + shell.publish(self.on_press.clone()); + } + shell.capture_event(); + } + Event::Touch(touch::Event::FingerLost { .. }) => *pressed = false, + _ => {} + } + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + style: &renderer::Style, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + ) { + self.content.as_widget().draw( + &tree.children[0], + renderer, + theme, + style, + layout, + cursor, + viewport, + ); + } + + fn mouse_interaction( + &self, + tree: &Tree, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + renderer: &Renderer, + ) -> mouse::Interaction { + let inside = self.content.as_widget().mouse_interaction( + &tree.children[0], + layout, + cursor, + viewport, + renderer, + ); + if inside == mouse::Interaction::None && cursor.is_over(layout.bounds()) { + mouse::Interaction::Pointer + } else { + inside + } + } + + fn overlay<'b>( + &'b mut self, + tree: &'b mut Tree, + layout: Layout<'b>, + renderer: &Renderer, + viewport: &Rectangle, + translation: Vector, + ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> { + self.content.as_widget_mut().overlay( + &mut tree.children[0], + layout, + renderer, + viewport, + translation, + ) + } +} + +/// A group of settings under a title. +pub fn group<'a, Message>(title: impl Into<String>) -> Group<'a, Message> { + Group { + title: title.into(), + description: None, + rows: Vec::new(), + } +} + +/// A group of settings: its title, then its rows in a card, a line between each. +pub struct Group<'a, Message> { + title: String, + description: Option<String>, + rows: Vec<Element<'a, Message>>, +} + +impl<'a, Message: Clone + 'a> Group<'a, Message> { + /// A line or two below the title, about the group. + pub fn description(self, description: impl Into<String>) -> Self { + Self { + description: Some(description.into()), + ..self + } + } + + /// Adds a row. + pub fn row(mut self, row: Row<'a, Message>) -> Self { + self.rows.push(row.into()); + self + } + + /// Adds anything else to the card, with a row's room round it, such as a picture choice. + pub fn item(mut self, item: impl Into<Element<'a, Message>>) -> Self { + self.rows + .push(container(item).padding(space::XL).width(Fill).into()); + self + } +} + +impl<'a, Message: Clone + 'a> From<Group<'a, Message>> for Element<'a, Message> { + fn from(group: Group<'a, Message>) -> Self { + let mut rows = Vec::with_capacity(group.rows.len() * 2); + for (at, row) in group.rows.into_iter().enumerate() { + if at > 0 { + rows.push( + container(Space::new()) + .width(Fill) + .height(crate::ui::tokens::size::BORDER) + .class(Frame::Divider) + .into(), + ); + } + rows.push(row); + } + let card = container(Column::with_children(rows)) + .width(Fill) + .class(Frame::Card(Surface::Panel)); + let heading = Column::with_children( + std::iter::once(text::label(group.title).into()).chain( + group + .description + .map(|description| text::interface(description).class(Ink::Muted).into()), + ), + ) + .spacing(space::XS); + column![heading, card].spacing(space::M).into() + } +} diff --git a/launcher/src/ui/shape.rs b/launcher/src/ui/shape.rs new file mode 100644 index 0000000000..b9eb0801b2 --- /dev/null +++ b/launcher/src/ui/shape.rs @@ -0,0 +1,805 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Shapes iced's quads can't draw, as one custom primitive drawn by signed distance fields, +//! antialiased (`shape.wgsl`): +//! +//! - **Rounding:** a window's corners. iced clips only to rectangles, so content reaching a corner +//! would show square. Drawn in a layer after everything else, it multiplies what's drawn by +//! the coverage of the rounded rectangle inside the line (premultiplied, so every channel), and +//! then adds the line in the ring that leaves: content clipped to the inside of the line and the +//! line drawn over the edge, as CSS's `border` with `overflow: hidden` draws. +//! - **Strokes:** a line icon's round-capped strokes, such as the close button's cross. Meshes +//! would be jagged, as windows draw without multisampling. +//! +//! A primitive draws after its layer's quads and before its text. + +use std::sync::atomic::{AtomicU32, Ordering}; + +use iced::advanced::graphics::geometry::Renderer as _; +use iced::advanced::renderer::{self as quads, Renderer as _}; +use iced::widget::canvas; +use iced::{Background, Border, Color, Point, Rectangle, Shadow, Size, Vector}; +use iced_wgpu::graphics::{Viewport, color}; +use iced_wgpu::primitive::{self, Renderer as _}; +use iced_wgpu::wgpu; + +use crate::ui::tokens::size; + +use crate::ui::Renderer; + +/// The most strokes an icon has. +pub(crate) const MAX_STROKES: usize = 4; + +/// A shape to draw in its bounds, in logical pixels. +#[derive(Debug)] +pub(crate) struct Shape { + kind: Kind, + /// How wide its bounds were drawn: drawn under a transformation that scales, the bounds it's + /// prepared with are wider by as much, and so is it. + width: f32, + /// Where its parameters are in the pipeline's buffer this frame. + slot: AtomicU32, +} + +#[derive(Debug, Clone, PartialEq)] +enum Kind { + /// Rounded corners of the bounds less [`REACH`] all round, and a line inside their edge + /// `width` wide. + Rounding { + radius: f32, + width: f32, + line: Color, + }, + /// Round-capped strokes, `count` of them, from one point to another, from the bounds' top + /// left; or, if `centered`, from the top left of an icon's box in the middle of the bounds. + Strokes { + segments: [[f32; 4]; MAX_STROKES], + count: usize, + width: f32, + ink: Color, + centered: bool, + }, +} + +/// Whether the renderer draws custom primitives: wgpu does; its fallback, tiny-skia, doesn't. +fn primitives(renderer: &Renderer) -> bool { + matches!(renderer, Renderer::Primary(_)) +} + +/// How much further each way than the corners it rounds a rounding's drawn: where they end +/// mid-pixel, that pixel's center is on the drawing's edge and nothing's drawn there, so the +/// corner stayed square. The layer's own bounds keep it to the window. +const REACH: f32 = 1.0; + +/// Rounds the corners of everything drawn so far in `bounds` if `clear`, and draws a line along +/// their edge. Draw it in a layer of its own, after everything it rounds. On a renderer without +/// custom primitives, only the line is drawn: what's under the corners has to keep out of them +/// itself (the frame's fill and the header bar's are rounded quads). +pub(crate) fn round( + renderer: &mut Renderer, + bounds: Rectangle, + radius: f32, + width: f32, + line: Color, + clear: bool, +) { + if clear && primitives(renderer) { + let reach = bounds.expand(REACH); + renderer.draw_primitive( + reach, + Shape::new( + Kind::Rounding { + radius, + width, + line, + }, + reach, + ), + ); + return; + } + renderer.fill_quad( + quads::Quad { + bounds, + border: Border { + color: line, + width, + radius: radius.into(), + }, + shadow: Shadow::default(), + snap: true, + }, + Background::Color(Color::TRANSPARENT), + ); +} + +/// An icon's strokes as a shape keeps them: at most [`MAX_STROKES`]. +fn kept(segments: &[[f32; 4]]) -> ([[f32; 4]; MAX_STROKES], usize) { + debug_assert!( + segments.len() <= MAX_STROKES, + "an icon of {} strokes: shape.wgsl draws {MAX_STROKES}", + segments.len() + ); + let mut kept = [[0.0; 4]; MAX_STROKES]; + let count = segments.len().min(MAX_STROKES); + kept[..count].copy_from_slice(&segments[..count]); + (kept, count) +} + +/// Draws an icon's strokes, its box in the middle of `within`, such as a button: the middle of +/// the whole pixels iced draws a quad filling `within` on, as it snaps a quad's edges to them, so +/// the icon is exactly in the middle of the button at any scale. +pub(crate) fn icon( + renderer: &mut Renderer, + within: Rectangle, + segments: &[[f32; 4]], + width: f32, + ink: Color, +) { + if !primitives(renderer) { + canvas_strokes(renderer, within, segments, width, ink); + return; + } + let (segments, count) = kept(segments); + renderer.draw_primitive( + within, + Shape::new( + Kind::Strokes { + segments, + count, + width, + ink, + centered: true, + }, + within, + ), + ); +} + +/// The strokes as round-capped paths, for a renderer without custom primitives: the icon's box +/// in the middle of `within`. +fn canvas_strokes( + renderer: &mut Renderer, + within: Rectangle, + segments: &[[f32; 4]], + width: f32, + ink: Color, +) { + let origin = Point::new( + (within.center_x() - size::ICON / 2.0).round(), + (within.center_y() - size::ICON / 2.0).round(), + ); + let mut frame = canvas::Frame::new(renderer, Size::new(size::ICON, size::ICON)); + for &[x0, y0, x1, y1] in segments { + let path = canvas::Path::line(Point::new(x0, y0), Point::new(x1, y1)); + frame.stroke( + &path, + canvas::Stroke::default() + .with_color(ink) + .with_width(width) + .with_line_cap(canvas::LineCap::Round), + ); + } + let geometry = frame.into_geometry(); + renderer.with_translation(Vector::new(origin.x, origin.y), |renderer| { + renderer.draw_geometry(geometry); + }); +} +impl Shape { + fn new(kind: Kind, bounds: Rectangle) -> Self { + Self { + kind, + width: bounds.width, + slot: AtomicU32::new(0), + } + } + + /// Its parameters as the shader takes them, in physical pixels, its bounds as prepared, at + /// the window's `scale`. + fn uniforms(&self, bounds: &Rectangle, scale: f32) -> Uniforms { + // As much larger as a transformation made its bounds. + let grown = if self.width > 0.0 { + bounds.width / self.width + } else { + 1.0 + }; + let sized = scale * grown; + let mut uniforms = Uniforms { + origin: [bounds.x * scale, bounds.y * scale], + size: [bounds.width * scale, bounds.height * scale], + ..Uniforms::default() + }; + match &self.kind { + Kind::Rounding { + radius, + width, + line, + } => { + let area = bounds.shrink(REACH * grown); + uniforms.origin = [area.x * scale, area.y * scale]; + uniforms.size = [area.width * scale, area.height * scale]; + uniforms.color = premultiplied(*line); + uniforms.radius = radius * sized; + uniforms.width = width * sized; + } + Kind::Strokes { + segments, + count, + width, + ink, + centered, + } => { + if *centered { + // As iced's quads snap their edges to whole pixels. + let snap = |at: f32| (at * scale + 0.001).round(); + let middle_x = (snap(bounds.x) + snap(bounds.x + bounds.width)) / 2.0; + let middle_y = (snap(bounds.y) + snap(bounds.y + bounds.height)) / 2.0; + let half = size::ICON * sized / 2.0; + uniforms.origin = [middle_x - half, middle_y - half]; + } + uniforms.color = premultiplied(*ink); + uniforms.width = width * sized; + uniforms.count = *count as u32; + for (to, from) in uniforms.segments.iter_mut().zip(&segments[..*count]) { + *to = from.map(|c| c * sized); + } + } + } + uniforms + } +} + +/// Where a rounding draws, in a target `target` physical pixels big: the corners its radius +/// reaches into and strips along the edges its line covers, each pixel in one of them only, as +/// the mask multiplies what's drawn. Away from them it changes nothing, so the window's middle +/// isn't drawn over twice a frame. A window too small for them is one region, its whole. +fn regions(uniforms: &Uniforms, target: (u32, u32)) -> Regions { + let [x, y] = uniforms.origin; + let [width, height] = uniforms.size; + // A pixel more each way, for the reach and antialiasing. + let (x0, y0) = ((x - REACH).floor(), (y - REACH).floor()); + let (x1, y1) = ((x + width + REACH).ceil(), (y + height + REACH).ceil()); + let edge = uniforms.width.ceil() + 2.0; + let corner = uniforms.radius.ceil().max(uniforms.width.ceil()) + 2.0; + let whole = [[x0, y0, x1, y1]]; + let parts = [ + // The corners. + [x0, y0, x0 + corner, y0 + corner], + [x1 - corner, y0, x1, y0 + corner], + [x0, y1 - corner, x0 + corner, y1], + [x1 - corner, y1 - corner, x1, y1], + // The edges between them. + [x0 + corner, y0, x1 - corner, y0 + edge], + [x0 + corner, y1 - edge, x1 - corner, y1], + [x0, y0 + corner, x0 + edge, y1 - corner], + [x1 - edge, y0 + corner, x1, y1 - corner], + ]; + let rects: &[[f32; 4]] = if x1 - x0 <= 2.0 * corner || y1 - y0 <= 2.0 * corner { + &whole + } else { + &parts + }; + let (w, h) = (target.0 as f32, target.1 as f32); + let mut regions = Regions::default(); + for &[left, top, right, bottom] in rects { + let (left, right) = (left.clamp(0.0, w), right.clamp(0.0, w)); + let (top, bottom) = (top.clamp(0.0, h), bottom.clamp(0.0, h)); + if right > left && bottom > top { + regions.rects[regions.count] = [ + left as u32, + top as u32, + (right - left) as u32, + (bottom - top) as u32, + ]; + regions.count += 1; + } + } + regions +} + +/// Scissor rectangles a shape draws in, `[x, y, width, height]` in physical pixels: none, a +/// shape that draws in its whole bounds. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +struct Regions { + rects: [[u32; 4]; 8], + count: usize, +} + +/// A color as iced's shaders take it, premultiplied. +fn premultiplied(color: Color) -> [f32; 4] { + let [r, g, b, a] = color::pack(color).components(); + [r * a, g * a, b * a, a] +} + +/// `Shape` in `shape.wgsl`. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +struct Uniforms { + origin: [f32; 2], + size: [f32; 2], + color: [f32; 4], + radius: f32, + width: f32, + count: u32, + segments: [[f32; 4]; MAX_STROKES], +} + +/// Its size in the shader's layout: 48 bytes, then the segments. +const UNIFORMS: u64 = 48 + 16 * MAX_STROKES as u64; + +impl Uniforms { + /// Its bytes, in the shader's layout. Written out by hand: `unsafe` is forbidden, so no + /// casting. + fn bytes(&self) -> Bytes { + let mut bytes = [0; UNIFORMS as usize]; + let line = [self.radius, self.width]; + let words = self + .origin + .iter() + .chain(&self.size) + .chain(&self.color) + .chain(&line) + .map(|value| value.to_ne_bytes()) + .chain([self.count.to_ne_bytes(), 0.0_f32.to_ne_bytes()]) + .chain( + self.segments + .iter() + .flatten() + .map(|value| value.to_ne_bytes()), + ); + for (to, word) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(words) { + to.copy_from_slice(&word); + } + bytes + } +} + +/// A shape's parameters, as the buffer holds them. +type Bytes = [u8; UNIFORMS as usize]; + +impl primitive::Primitive for Shape { + type Pipeline = Pipeline; + + fn prepare( + &self, + pipeline: &mut Pipeline, + device: &wgpu::Device, + queue: &wgpu::Queue, + bounds: &Rectangle, + viewport: &Viewport, + ) { + let uniforms = self.uniforms(bounds, viewport.scale_factor()); + let regions = match self.kind { + Kind::Rounding { .. } => { + let target = viewport.physical_size(); + regions(&uniforms, (target.width, target.height)) + } + Kind::Strokes { .. } => Regions::default(), + }; + for &stage in Stage::of(&self.kind) { + pipeline.stages.make(device, stage); + } + let slot = pipeline.push(device, queue, uniforms.bytes(), regions); + self.slot.store(slot, Ordering::Relaxed); + } + + fn draw(&self, pipeline: &Pipeline, pass: &mut wgpu::RenderPass<'_>) -> bool { + let slot = self.slot.load(Ordering::Relaxed); + let offset = slot * pipeline.stride as u32; + let regions = pipeline + .regions + .get(slot as usize) + .copied() + .unwrap_or_default(); + for &stage in Stage::of(&self.kind) { + let Some(stage) = pipeline.stages.get(stage) else { + continue; + }; + pass.set_pipeline(stage); + pass.set_bind_group(0, &pipeline.bind_group, &[offset]); + if regions.count == 0 { + pass.draw(0..3, 0..1); + } + // In its regions alone: the renderer sets the next primitive's scissor, and the whole + // target's after the last. + for &[x, y, width, height] in ®ions.rects[..regions.count] { + pass.set_scissor_rect(x, y, width, height); + pass.draw(0..3, 0..1); + } + } + true + } +} + +/// The shapes' render pipelines, and a buffer of every shape's parameters this frame, one slot +/// each, bound at its offset. +pub(crate) struct Pipeline { + stages: Stages, + layout: wgpu::BindGroupLayout, + buffer: wgpu::Buffer, + bind_group: wgpu::BindGroup, + /// A slot's size: the uniforms, aligned as the device wants dynamic offsets. + stride: u64, + capacity: u64, + /// This frame's slots, kept to copy into a larger buffer; and last frame's, which the buffer + /// still holds, so a slot that's the same isn't written again. + slots: Vec<Bytes>, + last: Vec<Bytes>, + /// Where each slot's shape draws, if not its whole bounds. + regions: Vec<Regions>, +} + +/// One of the shader's fragment stages, each its own render pipeline. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Stage { + /// Multiplies what's drawn by the coverage inside a window's line (blended Zero, SrcAlpha). + Mask, + /// The line, added (One, One). + Line, + /// Round-capped strokes over what's drawn, premultiplied. + Strokes, +} + +impl Stage { + fn entry(self) -> &'static str { + match self { + Self::Mask => "mask", + Self::Line => "line", + Self::Strokes => "strokes", + } + } + + fn blend(self) -> wgpu::BlendState { + // What's drawn, times the coverage: premultiplied, so color and alpha alike. + let multiply = wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::Zero, + dst_factor: wgpu::BlendFactor::SrcAlpha, + operation: wgpu::BlendOperation::Add, + }; + let add = wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::One, + dst_factor: wgpu::BlendFactor::One, + operation: wgpu::BlendOperation::Add, + }; + match self { + Self::Mask => wgpu::BlendState { + color: multiply, + alpha: multiply, + }, + Self::Line => wgpu::BlendState { + color: add, + alpha: add, + }, + Self::Strokes => wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING, + } + } + + /// The stages a shape of this kind is drawn with. + fn of(kind: &Kind) -> &'static [Self] { + match kind { + Kind::Rounding { width, .. } if *width > 0.0 => &[Self::Mask, Self::Line], + Kind::Rounding { .. } => &[Self::Mask], + Kind::Strokes { .. } => &[Self::Strokes], + } + } +} + +/// The render pipelines, each made the first time a shape needs it: a +/// pipeline is compiled when it's made, tens of milliseconds each on lavapipe, and most windows +/// draw one or two kinds of shape, or none. +struct Stages { + shader: wgpu::ShaderModule, + layout: wgpu::PipelineLayout, + format: wgpu::TextureFormat, + made: [Option<wgpu::RenderPipeline>; 4], +} + +impl Stages { + fn make(&mut self, device: &wgpu::Device, stage: Stage) { + let made = &mut self.made[stage as usize]; + if made.is_some() { + return; + } + *made = Some( + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("launcher shapes"), + layout: Some(&self.layout), + vertex: wgpu::VertexState { + module: &self.shader, + entry_point: Some("vs_main"), + buffers: &[], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }, + fragment: Some(wgpu::FragmentState { + module: &self.shader, + entry_point: Some(stage.entry()), + targets: &[Some(wgpu::ColorTargetState { + format: self.format, + blend: Some(stage.blend()), + write_mask: wgpu::ColorWrites::ALL, + })], + compilation_options: wgpu::PipelineCompilationOptions::default(), + }), + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + multiview: None, + cache: None, + }), + ); + } + + fn get(&self, stage: Stage) -> Option<&wgpu::RenderPipeline> { + self.made[stage as usize].as_ref() + } +} + +impl Pipeline { + /// Takes a slot for a shape's parameters, and writes them, unless the slot holds them from + /// the last frame, as a still window's shapes do. + fn push( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + bytes: Bytes, + regions: Regions, + ) -> u32 { + let slot = self.slots.len(); + self.slots.push(bytes); + self.regions.push(regions); + if slot as u64 >= self.capacity { + self.capacity = (self.capacity * 2).max(slot as u64 + 1); + (self.buffer, self.bind_group) = + buffer(device, &self.layout, self.stride, self.capacity); + // A new buffer holds nothing: what it held last frame is gone too. + self.last.clear(); + for (at, slot) in self.slots.iter().enumerate() { + queue.write_buffer(&self.buffer, at as u64 * self.stride, slot); + } + } else if self.last.get(slot) != Some(&bytes) { + queue.write_buffer(&self.buffer, slot as u64 * self.stride, &bytes); + } + slot as u32 + } +} + +fn buffer( + device: &wgpu::Device, + layout: &wgpu::BindGroupLayout, + stride: u64, + capacity: u64, +) -> (wgpu::Buffer, wgpu::BindGroup) { + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("launcher shapes"), + size: stride * capacity, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("launcher shapes"), + layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &buffer, + offset: 0, + size: wgpu::BufferSize::new(UNIFORMS), + }), + }], + }); + (buffer, bind_group) +} + +impl primitive::Pipeline for Pipeline { + fn new(device: &wgpu::Device, _queue: &wgpu::Queue, format: wgpu::TextureFormat) -> Self { + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("launcher shapes"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: true, + min_binding_size: wgpu::BufferSize::new(UNIFORMS), + }, + count: None, + }], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("launcher shapes"), + bind_group_layouts: &[&layout], + push_constant_ranges: &[], + }); + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("launcher shapes"), + source: wgpu::ShaderSource::Wgsl(include_str!("shape.wgsl").into()), + }); + let alignment = u64::from(device.limits().min_uniform_buffer_offset_alignment); + let stride = UNIFORMS.div_ceil(alignment) * alignment; + let capacity = 4; + let (buffer, bind_group) = buffer(device, &layout, stride, capacity); + Self { + stages: Stages { + shader, + layout: pipeline_layout, + format, + made: [None, None, None, None], + }, + layout, + buffer, + bind_group, + stride, + capacity, + slots: Vec::new(), + last: Vec::new(), + regions: Vec::new(), + } + } + + /// A frame is drawn: its slots are free again, and what they held is what the buffer holds. + fn trim(&mut self) { + std::mem::swap(&mut self.slots, &mut self.last); + self.slots.clear(); + self.regions.clear(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_kind_is_drawn_with_only_the_stages_it_needs() { + let rounding = |width| Kind::Rounding { + radius: 14.0, + width, + line: Color::WHITE, + }; + assert_eq!(Stage::of(&rounding(1.0)), [Stage::Mask, Stage::Line]); + assert_eq!(Stage::of(&rounding(0.0)), [Stage::Mask]); + let (segments, count) = kept(&[[0.0, 0.0, 1.0, 1.0]]); + let strokes = Kind::Strokes { + segments, + count, + width: 1.4, + ink: Color::WHITE, + centered: false, + }; + assert_eq!(Stage::of(&strokes), [Stage::Strokes]); + } + + #[test] + fn uniforms_are_in_physical_pixels_and_premultiplied() { + let area = Rectangle::new(iced::Point::new(10.0, 20.0), iced::Size::new(100.0, 50.0)); + let line = Color::from_rgba(1.0, 0.5, 0.0, 0.5); + let bounds = area.expand(REACH); + let rounding = Shape::new( + Kind::Rounding { + radius: 14.0, + width: 1.0, + line, + }, + bounds, + ); + let uniforms = rounding.uniforms(&bounds, 1.5); + assert_eq!(uniforms.origin, [15.0, 30.0]); + assert_eq!(uniforms.size, [150.0, 75.0]); + assert_eq!((uniforms.radius, uniforms.width), (21.0, 1.5)); + assert_eq!(uniforms.color, [0.5, 0.25, 0.0, 0.5]); + assert_eq!(uniforms.count, 0); + + let (segments, count) = kept(&[[4.5, 4.5, 11.5, 11.5], [11.5, 4.5, 4.5, 11.5]]); + let cross = Shape::new( + Kind::Strokes { + segments, + count, + width: 1.4, + ink: Color::WHITE, + centered: false, + }, + area, + ); + let uniforms = cross.uniforms(&area, 2.0); + assert_eq!(uniforms.count, 2); + assert_eq!(uniforms.segments[1], [23.0, 9.0, 9.0, 23.0]); + assert_eq!(uniforms.segments[2], [0.0; 4]); + assert_eq!(uniforms.width, 2.8); + assert_eq!(uniforms.color, [1.0; 4]); + // Under a transformation that makes it twice as large, as a dialog coming up does, its + // strokes are twice as large too. + let grown = Rectangle::new(area.position(), area.size() * 2.0); + let uniforms = cross.uniforms(&grown, 1.0); + assert_eq!(uniforms.segments[1], [23.0, 9.0, 9.0, 23.0]); + assert_eq!(uniforms.width, 2.8); + } + + #[test] + fn an_icon_is_in_the_middle_of_the_whole_pixels_its_button_fills() { + // A 32 button at 7.5 across, as a header bar's margin puts one at 1.5×: iced snaps the + // button's quad to whole pixels, and the icon's box is in the middle of those. + let button = Rectangle::new(iced::Point::new(7.5, 7.0), iced::Size::new(32.0, 32.0)); + let (segments, count) = kept(&crate::ui::tokens::window::CLOSE_CROSS); + let cross = Shape::new( + Kind::Strokes { + segments, + count, + width: size::ICON_STROKE, + ink: Color::WHITE, + centered: true, + }, + button, + ); + for (scale, origin) in [ + (1.0, [16.0, 15.0]), + (1.5, [23.0, 23.0]), + (2.0, [31.0, 30.0]), + ] { + let uniforms = cross.uniforms(&button, scale); + assert_eq!(uniforms.origin, origin, "at {scale}×"); + // The box is the icon's size at that scale, its middle the snapped button's. + let half = size::ICON * scale / 2.0; + let snap = |at: f32| (at * scale + 0.001).round(); + let middle = (snap(button.x) + snap(button.x + button.width)) / 2.0; + assert_eq!(uniforms.origin[0] + half, middle); + } + } + + #[test] + fn a_rounding_draws_only_where_its_corners_and_line_are() { + let uniforms = Uniforms { + origin: [0.0, 0.0], + size: [800.0, 600.0], + radius: 14.0, + width: 1.0, + ..Uniforms::default() + }; + let regions = regions(&uniforms, (800, 600)); + assert_eq!(regions.count, 8); + let rects = ®ions.rects[..regions.count]; + // The corners, 16 square from a pixel outside, the radius and antialiasing, and the + // edges between them, 3 deep; kept to the target. + assert_eq!(rects[0], [0, 0, 15, 15]); + assert_eq!(rects[3], [785, 585, 15, 15]); + assert_eq!(rects[4], [15, 0, 770, 2]); + assert_eq!(rects[7], [798, 15, 2, 570]); + // Every pixel on the edge in one of them, none in two: the mask multiplies. + let inside = |x: u32, y: u32| { + rects + .iter() + .filter(|[rx, ry, w, h]| x >= *rx && x < rx + w && y >= *ry && y < ry + h) + .count() + }; + for x in 0..800 { + assert_eq!(inside(x, 0), 1, "top, at {x}"); + assert_eq!(inside(x, 599), 1, "bottom, at {x}"); + } + for y in 0..600 { + assert_eq!(inside(0, y), 1, "left, at {y}"); + assert_eq!(inside(799, y), 1, "right, at {y}"); + } + assert_eq!(inside(400, 300), 0, "the middle isn't drawn over"); + // Too small for them: the whole, kept to the target. + let small = Uniforms { + size: [20.0, 20.0], + ..uniforms + }; + let regions = super::regions(&small, (800, 600)); + assert_eq!(®ions.rects[..regions.count], [[0, 0, 21, 21]]); + } + + #[test] + fn uniforms_take_the_shaders_layout() { + let uniforms = Uniforms { + origin: [1.0, 2.0], + count: 3, + segments: [[0.0, 0.0, 0.0, 9.0]; MAX_STROKES], + ..Uniforms::default() + }; + let bytes = uniforms.bytes(); + assert_eq!(bytes.len() as u64, UNIFORMS); + let word = |at: usize| <[u8; 4]>::try_from(&bytes[at * 4..at * 4 + 4]).unwrap(); + assert_eq!(f32::from_ne_bytes(word(1)), 2.0); + // origin, size, color, radius, width, then the count at byte 40. + assert_eq!(u32::from_ne_bytes(word(10)), 3); + assert_eq!(f32::from_ne_bytes(word(15)), 9.0); + } +} diff --git a/launcher/src/ui/shape.wgsl b/launcher/src/ui/shape.wgsl new file mode 100644 index 0000000000..b37ce19cab --- /dev/null +++ b/launcher/src/ui/shape.wgsl @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +// Shapes iced's quads can't draw, by their signed distance fields, antialiased (shape.rs): a +// window's rounded corners and line, line icons, and the void's radial tints. +// +// The render pass's viewport is the primitive's bounds, so the vertex shader covers it with one +// triangle; the fragment shaders measure from the shape's origin in physical pixels. Colors are +// premultiplied, as iced draws. + +struct Shape { + // The shape's top left and size, in physical pixels. + origin: vec2<f32>, + size: vec2<f32>, + // The line's or the strokes' color, premultiplied. + color: vec4<f32>, + // The corners' radius, and the line's or a stroke's width. + radius: f32, + width: f32, + // How many of the segments are strokes. + count: u32, + _padding: f32, + // Strokes, from xy to zw, from the origin. The tinted void's: two tints, each its ellipse + // (its middle, xy, and radii, zw) and its color, premultiplied; their fades are in radius and + // width. + segments: array<vec4<f32>, 4>, +} + +@group(0) @binding(0) var<uniform> shape: Shape; + +@vertex +fn vs_main(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> { + let corner = vec2<f32>(f32((index << 1u) & 2u), f32(index & 2u)); + return vec4<f32>(corner * 2.0 - 1.0, 0.0, 1.0); +} + +// The distance from a point to a rounded rectangle centered on the origin: negative inside. +fn rounded(p: vec2<f32>, half: vec2<f32>, radius: f32) -> f32 { + let r = min(radius, min(half.x, half.y)); + let q = abs(p) - half + vec2<f32>(r); + return min(max(q.x, q.y), 0.0) + length(max(q, vec2<f32>(0.0))) - r; +} + +// How much of a pixel a distance covers, as iced's quads measure it. +fn coverage(distance: f32) -> f32 { + return clamp(0.5 - distance, 0.0, 1.0); +} + +// Inside the line: what the content keeps. +fn inner(at: vec2<f32>) -> f32 { + let half = shape.size * 0.5; + let p = at - shape.origin - half; + let inset = max(half - vec2<f32>(shape.width), vec2<f32>(0.0)); + return coverage(rounded(p, inset, max(shape.radius - shape.width, 0.0))); +} + +// The window's whole shape, its line included. +fn outer(at: vec2<f32>) -> f32 { + let half = shape.size * 0.5; + return coverage(rounded(at - shape.origin - half, half, shape.radius)); +} + +// Multiplies what's drawn by the coverage inside the line (blended Zero, SrcAlpha): the corners +// and the line's ring go transparent. +@fragment +fn mask(@builtin(position) at: vec4<f32>) -> @location(0) vec4<f32> { + return vec4<f32>(0.0, 0.0, 0.0, inner(at.xy)); +} + +// The line in the ring the mask cleared, added (blended One, One). +@fragment +fn line(@builtin(position) at: vec4<f32>) -> @location(0) vec4<f32> { + return shape.color * max(outer(at.xy) - inner(at.xy), 0.0); +} + +// Round-capped strokes, their union, over what's drawn (premultiplied). +@fragment +fn strokes(@builtin(position) at: vec4<f32>) -> @location(0) vec4<f32> { + let p = at.xy - shape.origin; + var distance = 1.0e6; + for (var i = 0u; i < shape.count; i++) { + let segment = shape.segments[i]; + let pa = p - segment.xy; + let ba = segment.zw - segment.xy; + let h = clamp(dot(pa, ba) / max(dot(ba, ba), 1.0e-6), 0.0, 1.0); + distance = min(distance, length(pa - ba * h)); + } + return shape.color * coverage(distance - shape.width * 0.5); +} diff --git a/launcher/src/ui/status.rs b/launcher/src/ui/status.rs new file mode 100644 index 0000000000..1cdd0ff77a --- /dev/null +++ b/launcher/src/ui/status.rs @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Status chips: a check's or a step's state, a dot and a word, never color alone. + +use iced::advanced::layout::{self, Layout}; +use iced::advanced::widget::{Tree, Widget, tree}; +use iced::advanced::{mouse, renderer}; +use iced::{Length, Point, Rectangle, Size}; + +use crate::ui::tokens::{size, space, typography}; + +use crate::ui::paint::{self, Plain}; +use crate::ui::theme::{Status, color}; +use crate::ui::{Element, Renderer, Theme}; + +/// A chip saying a state in a word: "Passed", "Needs setup mode". +pub fn status(status: Status, word: impl Into<String>) -> Chip { + Chip { + status, + word: word.into(), + } +} + +/// A status chip ([`status`]): a dot and a few words in a pill, in its status's accent. +pub struct Chip { + status: Status, + word: String, +} + +const PAD_X: f32 = space::M; +const PAD_Y: f32 = space::XXS; + +impl<Message> Widget<Message, Theme, Renderer> for Chip { + fn tag(&self) -> tree::Tag { + tree::Tag::of::<Plain>() + } + + fn state(&self) -> tree::State { + tree::State::new(Plain::default()) + } + + fn size(&self) -> Size<Length> { + Size::new(Length::Shrink, Length::Shrink) + } + + fn layout( + &mut self, + tree: &mut Tree, + _renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + let word = tree.state.downcast_mut::<Plain>(); + paint::shape(word, &typography::META, &self.word); + let text = word.min_bounds(); + let size = Size::new( + (2.0 * PAD_X + size::DOT + space::S + text.width).ceil(), + (2.0 * PAD_Y + text.height).ceil(), + ); + layout::Node::new(limits.resolve(Length::Shrink, Length::Shrink, size)) + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + _style: &renderer::Style, + layout: Layout<'_>, + _cursor: mouse::Cursor, + viewport: &Rectangle, + ) { + let word = tree.state.downcast_ref::<Plain>(); + let bounds = layout.bounds(); + let look = theme.status(self.status); + paint::boxed(renderer, bounds, &look); + let ink = color(look.ink); + let dot = Point::new(bounds.x + PAD_X + size::DOT / 2.0, bounds.center_y()); + paint::dot(renderer, dot, size::DOT, ink, Some(theme.spark(look.ink))); + let text = word.min_bounds(); + let at = Point::new( + bounds.x + PAD_X + size::DOT + space::S, + bounds.center_y() - text.height / 2.0, + ); + paint::fill(renderer, word, at, ink, *viewport); + } +} + +impl<'a, Message: 'a> From<Chip> for Element<'a, Message> { + fn from(chip: Chip) -> Self { + Element::new(chip) + } +} diff --git a/launcher/src/ui/switch.rs b/launcher/src/ui/switch.rs new file mode 100644 index 0000000000..88ce2be121 --- /dev/null +++ b/launcher/src/ui/switch.rs @@ -0,0 +1,437 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Switches: on or off, as a setting's row ends with one, such as "Scroll on output". The knob +//! slides from one end to the other, and can be dragged there. + +use iced::advanced::layout::{self, Layout}; +use iced::advanced::widget::{Operation, Tree, Widget, tree}; +use iced::advanced::{Clipboard, Shell, mouse, renderer}; +use iced::keyboard::{self, Key, key::Named}; +use iced::{Event, Length, Point, Rectangle, Size, touch, window}; + +use crate::ui::tokens::{motion, size}; + +use crate::ui::focus::Focus; +use crate::ui::input; +use crate::ui::paint; +use crate::ui::theme::{Interaction, Look}; +use crate::ui::transition::Transition; +use crate::ui::{Element, Renderer, Theme}; + +/// Room round the knob inside the track. +const INSET: f32 = 3.0; + +/// A switch, on or off. Without a message to send it is disabled. +pub fn switch<'a, Message>(on: bool) -> Switch<'a, Message> { + Switch { + on, + on_toggle: None, + preview: None, + } +} + +/// A switch: a click on it, or Space when it has focus, turns it over, its knob sliding +/// across; or the knob is dragged across, by the pointer or a finger, and let go nearer one end. +pub struct Switch<'a, Message> { + on: bool, + on_toggle: Option<Box<dyn Fn(bool) -> Message + 'a>>, + preview: Option<(Interaction, bool)>, +} + +impl<'a, Message> Switch<'a, Message> { + /// The message it sends with the new value. + pub fn on_toggle(self, on_toggle: impl Fn(bool) -> Message + 'a) -> Self { + Self { + on_toggle: Some(Box::new(on_toggle)), + ..self + } + } + + /// Draws it as if in this state, for the gallery. + pub fn preview(self, interaction: Interaction, focused: bool) -> Self { + Self { + preview: Some((interaction, focused)), + ..self + } + } + + fn interaction(&self, state: &State, over: bool) -> Interaction { + match (&self.on_toggle, state.drag.is_some(), over) { + (None, _, _) => Interaction::Disabled, + (Some(_), true, _) => Interaction::Pressed, + (Some(_), false, true) => Interaction::Hovered, + (Some(_), false, false) => Interaction::Idle, + } + } + + /// Turns it to `on`, if that's a change, and sends it. + fn set(&mut self, on: bool, shell: &mut Shell<'_, Message>) { + if let Some(on_toggle) = &self.on_toggle + && on != self.on + { + shell.publish(on_toggle(on)); + self.on = on; + } + } +} + +/// Where the knob is in a track, `at` the share of the way from its start, off, to its end, on. +pub(crate) fn knob(track: Rectangle, at: f32) -> Rectangle { + let diameter = track.height - 2.0 * INSET; + let travel = track.width - 2.0 * INSET - diameter; + Rectangle::new( + Point::new( + track.x + INSET + travel * at.clamp(0.0, 1.0), + track.y + INSET, + ), + Size::new(diameter, diameter), + ) +} + +/// How far the knob travels across a track. +fn travel(track: Rectangle) -> f32 { + track.width - 2.0 * INSET - (track.height - 2.0 * INSET) +} + +/// A press on the knob's track: where it began, where the knob was, and whether it has moved far +/// enough to be a drag. +#[derive(Debug, Clone, Copy, PartialEq)] +struct Drag { + from_x: f32, + from_at: f32, + dragged: bool, +} + +#[derive(Default)] +struct State { + focus: Focus, + /// Where the knob is drawn, from 0, off, to 1, on; and the value it was last drawn for. + at: f32, + seen: Option<bool>, + slide: Option<Transition>, + drag: Option<Drag>, + drawn: Option<(Interaction, bool, bool)>, + /// Its glow while on, fading in and out on the glows' own timing, apart from the knob. + lit: crate::ui::transition::Lit, + /// Its focus ring, fading in and out with keyboard focus on the same timing. + focus_lit: crate::ui::transition::Lit, +} + +impl State { + /// The knob slides to `on`'s end from where it is, or with motion reduced, jumps there. + fn slide_to(&mut self, on: bool) { + let to = f32::from(u8::from(on)); + self.slide = Transition::start(self.at, to, motion::FAST); + if self.slide.is_none() { + self.at = to; + } + } +} + +/// Where an event puts the pointer or the finger across, if it says. +fn across(event: &Event, cursor: mouse::Cursor) -> Option<f32> { + match event { + Event::Touch( + touch::Event::FingerPressed { position, .. } + | touch::Event::FingerMoved { position, .. }, + ) => Some(position.x), + Event::Mouse(mouse::Event::CursorMoved { position }) => Some(position.x), + _ => cursor.position().map(|position| position.x), + } +} + +impl<Message> Widget<Message, Theme, Renderer> for Switch<'_, Message> { + fn tag(&self) -> tree::Tag { + tree::Tag::of::<State>() + } + + fn state(&self) -> tree::State { + tree::State::new(State::default()) + } + + fn size(&self) -> Size<Length> { + Size::new( + Length::Fixed(size::SWITCH_WIDTH), + Length::Fixed(size::SWITCH_HEIGHT), + ) + } + + fn layout( + &mut self, + _tree: &mut Tree, + _renderer: &Renderer, + _limits: &layout::Limits, + ) -> layout::Node { + layout::Node::new(Size::new(size::SWITCH_WIDTH, size::SWITCH_HEIGHT)) + } + + fn operate( + &mut self, + tree: &mut Tree, + layout: Layout<'_>, + _renderer: &Renderer, + operation: &mut dyn Operation, + ) { + if self.on_toggle.is_some() && self.preview.is_none() { + let state = tree.state.downcast_mut::<State>(); + operation.focusable(None, layout.bounds(), &mut state.focus); + } + } + + fn update( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + _renderer: &Renderer, + _clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + _viewport: &Rectangle, + ) { + if self.preview.is_some() { + return; + } + let track = layout.bounds(); + let state = tree.state.downcast_mut::<State>(); + state.focus.keep_if(self.on_toggle.is_some()); + // The value changed from outside, as a row's click turns it: the knob slides there. + match state.seen { + None => state.at = f32::from(u8::from(self.on)), + Some(seen) if seen != self.on && state.drag.is_none() => state.slide_to(self.on), + Some(_) => {} + } + state.seen = Some(self.on); + let over = cursor.is_over(track); + if self.on_toggle.is_some() { + match event { + Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerPressed { .. }) + if over => + { + if let Some(x) = across(event, cursor) { + state.drag = Some(Drag { + from_x: x, + from_at: state.at, + dragged: false, + }); + } + state.focus.click(); + shell.capture_event(); + } + Event::Mouse(mouse::Event::CursorMoved { .. }) + | Event::Touch(touch::Event::FingerMoved { .. }) => { + if let Some(drag) = &mut state.drag + && let Some(x) = across(event, cursor) + { + // Further than a slip, it drags the knob rather than clicks; the drag is + // the switch's, not a scroll area's round it. + let moved = x - drag.from_x; + drag.dragged |= moved.abs() > size::SLIP; + if drag.dragged { + state.slide = None; + state.at = (drag.from_at + moved / travel(track)).clamp(0.0, 1.0); + shell.request_redraw(); + shell.capture_event(); + } + } + } + Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerLifted { .. }) => { + if let Some(drag) = state.drag.take() { + // Dragged, it goes to the nearer end; clicked, it turns over. + let on = if drag.dragged { + state.at >= 0.5 + } else if over { + !self.on + } else { + self.on + }; + state.slide_to(on); + self.set(on, shell); + let state = tree.state.downcast_mut::<State>(); + state.seen = Some(self.on); + shell.request_redraw(); + shell.capture_event(); + } + } + Event::Touch(touch::Event::FingerLost { .. }) => { + if state.drag.take().is_some() { + state.slide_to(self.on); + shell.request_redraw(); + } + } + // Space, not Enter, as a checkbox: Enter is the form's, such as to go on. Once a + // press: held down, it doesn't flicker. + Event::Keyboard(keyboard::Event::KeyPressed { + key: Key::Named(Named::Space), + modifiers, + repeat: false, + .. + }) if state.focus.is_focused() && input::plain(*modifiers) => { + state.focus.key(); + state.slide_to(!self.on); + self.set(!self.on, shell); + let state = tree.state.downcast_mut::<State>(); + state.seen = Some(self.on); + shell.request_redraw(); + shell.capture_event(); + } + _ => {} + } + } else { + state.drag = None; + } + let state = tree.state.downcast_mut::<State>(); + if let Event::Window(window::Event::RedrawRequested(now)) = event + && let Some(slide) = &mut state.slide + { + let moving = slide.frame(*now); + state.at = slide.at(); + if moving { + shell.request_redraw(); + } else { + state.slide = None; + } + } + state.lit.frame(event, shell); + state.lit.aim(self.on && self.on_toggle.is_some(), shell); + state.focus_lit.frame(event, shell); + state.focus_lit.aim(state.focus.is_shown(), shell); + let now = ( + self.interaction(state, over), + state.focus.is_shown(), + self.on, + ); + input::redraw_on_change(&mut state.drawn, now, event, shell); + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + _style: &renderer::Style, + layout: Layout<'_>, + cursor: mouse::Cursor, + _viewport: &Rectangle, + ) { + let state = tree.state.downcast_ref::<State>(); + let track = layout.bounds(); + let (interaction, focused) = self.preview.unwrap_or(( + self.interaction(state, cursor.is_over(track)), + state.focus.is_shown(), + )); + // Where the knob is: where it slides or is dragged to, or, before it's seen a change, + // where its value puts it. + let at = match (self.preview, state.seen) { + (None, Some(_)) => state.at, + _ => f32::from(u8::from(self.on)), + }; + // The off and on looks crossfade as the knob crosses: at either end, one alone. + let (off, on) = ( + theme.switch(false, interaction), + theme.switch(true, interaction), + ); + paint::boxed(renderer, track, &off.track.faded(1.0 - at)); + let glow = on.track.glow; + paint::boxed( + renderer, + track, + &Look { + glow: None, + ..on.track + } + .faded(at), + ); + // The on glow, on its own fade. + let lit = if self.preview.is_some() { + at + } else { + state.lit.share() + }; + paint::boxed( + renderer, + track, + &Look { + fill: None, + line: None, + ..on.track + } + .lit(glow, lit), + ); + let knob = knob(track, at); + let radius = knob.height / 2.0; + paint::boxed(renderer, knob, &Look::solid(off.knob, radius)); + paint::boxed( + renderer, + knob, + &Look::solid(on.knob.opacity(on.knob.alpha() * at), radius), + ); + // The focus ring fades in and out with keyboard focus, drawn while it fades out too. + let ring = if self.preview.is_some() { + f32::from(u8::from(focused)) + } else { + state.focus_lit.share() + }; + paint::outline_lit(renderer, theme, track, off.track.radius, ring); + } + + fn mouse_interaction( + &self, + tree: &Tree, + layout: Layout<'_>, + cursor: mouse::Cursor, + _viewport: &Rectangle, + _renderer: &Renderer, + ) -> mouse::Interaction { + let state = tree.state.downcast_ref::<State>(); + if self.on_toggle.is_none() || self.preview.is_some() { + mouse::Interaction::default() + } else if state.drag.is_some_and(|drag| drag.dragged) { + mouse::Interaction::Grabbing + } else if cursor.is_over(layout.bounds()) { + mouse::Interaction::Pointer + } else { + mouse::Interaction::default() + } + } +} + +impl<'a, Message: 'a> From<Switch<'a, Message>> for Element<'a, Message> { + fn from(switch: Switch<'a, Message>) -> Self { + Element::new(switch) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_knob_sits_at_the_start_off_and_the_end_on() { + let track = Rectangle::new(Point::new(0.0, 0.0), Size::new(40.0, 22.0)); + let off = knob(track, 0.0); + let on = knob(track, 1.0); + assert_eq!( + off, + Rectangle::new(Point::new(3.0, 3.0), Size::new(16.0, 16.0)) + ); + assert_eq!(on.x, 21.0); + assert_eq!((on.y, on.width), (3.0, 16.0)); + // Halfway, halfway across; never past either end. + assert_eq!(knob(track, 0.5).x, 12.0); + assert_eq!(knob(track, 2.0), on); + assert_eq!(travel(track), 18.0); + } + + #[test] + fn a_faded_look_keeps_its_shape_and_loses_its_color() { + let cyan = crate::ui::tokens::Palette::SUNSET_DARK.accent(crate::ui::tokens::Accent::Cyan); + let look = Look::solid(cyan, 4.0); + let half = look.faded(0.5); + assert_eq!(half.radius, 4.0); + assert_eq!(half.fill.map(crate::ui::tokens::Color::alpha), Some(0.5)); + assert_eq!(look.faded(1.0), look); + } +} diff --git a/launcher/src/ui/system.rs b/launcher/src/ui/system.rs new file mode 100644 index 0000000000..b0ada5a4c3 --- /dev/null +++ b/launcher/src/ui/system.rs @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! What the system asks of the interface: motion reduced, for those it bothers, and battery saver, +//! for the battery. Each is read once, from an environment variable, until Settings has the +//! switch (the design language's Motion). +//! +//! - **Reduced motion** turns off every animation that isn't needed: a wheel's steps jump, the +//! ends don't give, a dialog or a page is there at once, a loader holds still. +//! - **Battery saver** shortens animations to half ([`duration`]), and the theme it's set on +//! ([`Theme::saving_battery`](crate::ui::Theme::saving_battery)) shrinks glow to half its blur and +//! leaves out the void's radial tints, the one gradient a shader draws over a whole surface. + +use std::sync::OnceLock; +use std::time::Duration; + +/// The environment variable that turns non-essential motion off: `LEONIDA_REDUCE_MOTION=1`. +pub const REDUCE_MOTION_VARIABLE: &str = "LEONIDA_REDUCE_MOTION"; + +/// The environment variable that saves battery: `LEONIDA_BATTERY_SAVER=1`. +pub const BATTERY_SAVER_VARIABLE: &str = "LEONIDA_BATTERY_SAVER"; + +/// Whether a variable is set to 1. +fn on(variable: &str) -> bool { + std::env::var_os(variable).is_some_and(|value| value == "1") +} + +/// Whether motion is reduced ([`REDUCE_MOTION_VARIABLE`]), read once. +pub fn reduced_motion() -> bool { + static REDUCED: OnceLock<bool> = OnceLock::new(); + *REDUCED.get_or_init(|| on(REDUCE_MOTION_VARIABLE)) +} + +/// Whether battery saver is on ([`BATTERY_SAVER_VARIABLE`]), read once. +pub fn battery_saver() -> bool { + static SAVING: OnceLock<bool> = OnceLock::new(); + *SAVING.get_or_init(|| on(BATTERY_SAVER_VARIABLE)) +} + +/// How long an animation the design gives `whole` lasts: half as long on battery saver, so half as +/// many frames are drawn. +pub fn duration(whole: Duration) -> Duration { + shortened(whole, battery_saver()) +} + +fn shortened(whole: Duration, saving: bool) -> Duration { + if saving { whole / 2 } else { whole } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn battery_saver_halves_animations() { + let slow = crate::ui::tokens::motion::SLOW; + assert_eq!(shortened(slow, false), slow); + assert_eq!(shortened(slow, true), slow / 2); + } +} diff --git a/launcher/src/ui/text.rs b/launcher/src/ui/text.rs new file mode 100644 index 0000000000..8b003c48e2 --- /dev/null +++ b/launcher/src/ui/text.rs @@ -0,0 +1,265 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Text in the launcher's type roles. The role sets the face, size, line height and case; the ink, set +//! with `.class(…)`, the color, `text` by default: +//! +//! ``` +//! use leonida_launcher::ui::{Ink, text}; +//! +//! let hint = text::interface("Choose a disk").class(Ink::Muted); +//! ``` +//! +//! Labels are spaced out letter by letter, which iced's text can't do. + +use std::borrow::Cow; + +use crate::ui::tokens::Ink; +use crate::ui::tokens::typography::{self, Role}; +use iced::advanced::layout::{self, Layout}; +use iced::advanced::text::{self, Renderer as _}; +use iced::advanced::widget::{Tree, Widget, tree}; +use iced::advanced::{mouse, renderer}; +use iced::widget::Text; +use iced::widget::text::{IntoFragment, LineHeight}; +use iced::{Length, Pixels, Point, Rectangle, Size}; +use unicode_segmentation::UnicodeSegmentation; + +use crate::ui::paint::Plain; +use crate::ui::{Element, Renderer, Theme, font}; + +/// Where a text may break onto a new line, as `.wrapping(…)` takes it: at words by default, or +/// never, for a line that should be cut rather than broken. +pub use iced::widget::text::Wrapping; + +/// Text set in a role. Labels are better made with [`label`], which spaces their letters. +pub fn role<'a>(role: &Role, content: impl IntoFragment<'a>) -> Text<'a, Theme, Renderer> { + let content = content.into_fragment(); + let content = if role.uppercase { + Cow::Owned(content.to_uppercase()) + } else { + content + }; + iced::widget::text(content) + .font(font::role(role)) + .size(role.size) + .line_height(LineHeight::Relative(role.line_height)) +} + +/// A page or window title. +pub fn title<'a>(content: impl IntoFragment<'a>) -> Text<'a, Theme, Renderer> { + role(&typography::TITLE, content) +} + +/// A section heading. +pub fn heading<'a>(content: impl IntoFragment<'a>) -> Text<'a, Theme, Renderer> { + role(&typography::HEADING, content) +} + +/// Interface text: controls, lists, messages. +pub fn interface<'a>(content: impl IntoFragment<'a>) -> Text<'a, Theme, Renderer> { + role(&typography::INTERFACE, content) +} + +/// Metadata, counts, paths and status, in the `muted` ink. +pub fn meta<'a>(content: impl IntoFragment<'a>) -> Text<'a, Theme, Renderer> { + role(&typography::META, content).class(Ink::Muted) +} + +/// A small uppercase label, spaced out, in the `muted` ink. +pub fn label(content: impl AsRef<str>) -> Label { + Label { + content: content.as_ref().to_uppercase(), + ink: Ink::Muted, + role: &typography::LABEL, + } +} + +/// An app's name, as its header bar shows it: a label a step larger and bolder. +pub fn brand(content: impl AsRef<str>) -> Label { + Label { + role: &typography::BRAND, + ..label(content) + } +} + +/// A label: its letters set one by one, the role's letter spacing after each, one widget, each +/// letter shaped once. +#[derive(Debug, Clone, PartialEq)] +pub struct Label { + content: String, + ink: Ink, + role: &'static crate::ui::tokens::Role, +} + +impl Label { + pub fn ink(self, ink: impl Into<Ink>) -> Self { + Self { + ink: ink.into(), + ..self + } + } + + /// The letters, as they're set: grapheme clusters, so an accent stays on its letter. + #[cfg(test)] + fn letters(&self) -> impl Iterator<Item = &str> { + self.content.graphemes(true) + } +} + +impl<'a, Message: 'a> From<Label> for Element<'a, Message> { + fn from(label: Label) -> Self { + Element::new(label) + } +} + +/// A label's letters, each shaped once and again only when it changes, and where each goes. +#[derive(Default)] +struct Letters { + shaped: Vec<Plain>, + at: Vec<Point>, +} + +impl Label { + /// Its words, each its letters and, but for the last, a no-break space after it: a space + /// alone would measure nothing. + fn words(&self) -> impl Iterator<Item = impl Iterator<Item = &str>> { + let last = self.content.split(' ').count().saturating_sub(1); + self.content + .split(' ') + .enumerate() + .map(move |(at, word)| word.graphemes(true).chain((at < last).then_some("\u{a0}"))) + } +} + +impl<Message> Widget<Message, Theme, Renderer> for Label { + fn tag(&self) -> tree::Tag { + tree::Tag::of::<Letters>() + } + + fn state(&self) -> tree::State { + tree::State::new(Letters::default()) + } + + fn size(&self) -> Size<Length> { + Size::new(Length::Shrink, Length::Shrink) + } + + /// Letter by letter, the role's letter spacing after each, and word by word, so a label too + /// long for its room wraps between words, as words do: as a row of words, each a row of its + /// letters, would lay them out. + fn layout( + &mut self, + tree: &mut Tree, + _renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + let Letters { shaped, at } = tree.state.downcast_mut::<Letters>(); + let role = self.role; + let spacing = role.letter_spacing_px(); + let room = limits.max(); + let mut count = 0; + at.clear(); + let (mut x, mut y, mut line, mut widest) = (0.0_f32, 0.0_f32, 0.0_f32, 0.0_f32); + for word in self.words() { + // The word's letters, from its start, and how wide and tall it is. + let first = at.len(); + let (mut along, mut tall) = (0.0_f32, 0.0_f32); + for letter in word { + if count == shaped.len() { + shaped.push(Plain::default()); + } + let plain = &mut shaped[count]; + let _ = plain.update(text::Text { + content: letter, + bounds: room, + size: Pixels(role.size), + line_height: LineHeight::Relative(role.line_height), + font: font::role(role), + align_x: text::Alignment::default(), + align_y: iced::alignment::Vertical::Top, + shaping: text::Shaping::default(), + wrapping: text::Wrapping::default(), + }); + let size = limits.resolve(Length::Shrink, Length::Shrink, plain.min_bounds()); + at.push(Point::new(along, 0.0)); + along += size.width + spacing; + tall = tall.max(size.height); + count += 1; + } + let wide = (along - spacing).max(0.0); + // Too wide for what's left of the line: on the next. + if x != 0.0 && x + wide > room.width { + widest = widest.max(x - spacing); + (x, y, line) = (0.0, y + line, 0.0); + } + line = line.max(tall); + for point in &mut at[first..] { + *point = Point::new(point.x + x, y); + } + x += wide + spacing; + } + shaped.truncate(count); + if x != 0.0 { + widest = widest.max(x - spacing); + } + let size = limits.resolve(Length::Shrink, Length::Shrink, Size::new(widest, y + line)); + layout::Node::new(size) + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + _style: &renderer::Style, + layout: Layout<'_>, + _cursor: mouse::Cursor, + viewport: &Rectangle, + ) { + let letters = tree.state.downcast_ref::<Letters>(); + let ink = crate::ui::theme::color(theme.ink(self.ink)); + let origin = layout.position(); + for (plain, at) in letters.shaped.iter().zip(&letters.at) { + let at = Point::new(origin.x + at.x, origin.y + at.y); + renderer.fill_paragraph(plain.raw(), at, ink, *viewport); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn labels_are_capitals_in_muted() { + let label = label("Disks · éa"); + assert_eq!(label.content, "DISKS · ÉA"); + assert_eq!(label.ink, Ink::Muted); + assert_eq!( + label.clone().ink(crate::ui::tokens::Accent::Cyan).ink, + Ink::Accent(crate::ui::tokens::Accent::Cyan) + ); + } + + #[test] + fn a_letter_keeps_its_accent() { + // E and a combining acute accent stay one letter. + let label = label("Cafe\u{301} x"); + let letters: Vec<_> = label.letters().collect(); + assert_eq!(letters, ["C", "A", "F", "E\u{301}", " ", "X"]); + let _: Element<'_, ()> = label.into(); + } + + #[test] + fn roles_build_text() { + // Building them is what can be checked without a renderer; the gallery's screenshots + // show how they look. + let _: [Text<'_, Theme, Renderer>; 4] = [ + title("Title"), + heading("Heading"), + interface("Interface"), + meta("meta"), + ]; + let _ = role(&typography::LABEL, "upper"); + } +} diff --git a/launcher/src/ui/theme.rs b/launcher/src/ui/theme.rs new file mode 100644 index 0000000000..54a66c8f6e --- /dev/null +++ b/launcher/src/ui/theme.rs @@ -0,0 +1,1126 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! The theme: the tokens mapped to iced's styles and to each widget's [`Look`]. +//! +//! A theme carries a [`Palette`], one named look in one mode, and every color any widget draws +//! comes from it: the surfaces, lines and inks, the accents' tints, the focus outline. Sunset in +//! dark is the default, and Sunset in light the other mode. +//! +//! It is its own type, not iced's `Theme`, so the tokens stay the only source of colors: a text's +//! class is an [`Ink`] and a container's a [`Frame`], and neither takes a color of the app's +//! choosing. + +use crate::ui::tokens::{Accent, Ink, Palette, Surface, ThemeName, radius, size, window}; +use iced::theme::{self, Base, Mode}; +use iced::widget::{container, text}; +use iced::{Background, Border, Shadow}; + +/// The theme: a palette, Sunset dark by default, and whether it saves battery. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct Theme { + palette: Palette, + /// On battery saver, glow is half as soft ([`crate::ui::system`]). + saving: bool, +} + +/// A token's color in iced. +pub fn color(token: crate::ui::tokens::Color) -> iced::Color { + let [r, g, b] = token.rgb8(); + iced::Color::from_rgba8(r, g, b, token.alpha()) +} + +impl Theme { + /// A theme in a palette. + pub const fn new(palette: Palette) -> Self { + Self { + palette, + saving: false, + } + } + + /// The same theme, saving battery or not: on battery saver, glow blurs half as far. + pub const fn saving_battery(self, saving: bool) -> Self { + Self { saving, ..self } + } + + /// Whether it saves battery. + pub const fn saves_battery(&self) -> bool { + self.saving + } + + /// A named theme in a mode. + pub const fn of(theme: ThemeName, mode: crate::ui::tokens::Mode) -> Self { + Self::new(Palette::of(theme, mode)) + } + + /// What it's called, as screenshots are filed: "sunset-dark". + pub const fn name(&self) -> &'static str { + self.palette.name + } + + pub const fn palette(&self) -> &Palette { + &self.palette + } + + /// An ink's color. + pub const fn ink(&self, ink: Ink) -> crate::ui::tokens::Color { + self.palette.ink(ink) + } + + /// A surface's color. + pub const fn surface(&self, surface: Surface) -> crate::ui::tokens::Color { + self.palette.surface(surface) + } + + /// On the way from this theme to `to`, `share` of the way, as one fades into the other + /// ([`Palette::mixed`]). + pub fn mixed(&self, to: &Theme, share: f32) -> Self { + Self::new(self.palette.mixed(&to.palette, share)).saving_battery(self.saving || to.saving) + } +} + +impl Base for Theme { + fn default(_preference: Mode) -> Self { + <Self as Default>::default() + } + + fn mode(&self) -> Mode { + match self.palette.mode { + crate::ui::tokens::Mode::Dark => Mode::Dark, + crate::ui::tokens::Mode::Light => Mode::Light, + } + } + + fn base(&self) -> theme::Style { + theme::Style { + background_color: color(self.surface(Surface::Bg)), + text_color: color(self.ink(Ink::Text)), + } + } + + fn palette(&self) -> Option<theme::Palette> { + let p = &self.palette; + Some(theme::Palette { + background: color(p.surface(Surface::Bg)), + text: color(p.ink(Ink::Text)), + primary: color(p.accent(Accent::Cyan)), + success: color(p.accent(Accent::Mint)), + warning: color(p.accent(Accent::Amber)), + danger: color(p.accent(Accent::Red)), + }) + } + + fn name(&self) -> &str { + self.palette.name + } +} + +impl text::Catalog for Theme { + type Class<'a> = Ink; + + fn default<'a>() -> Self::Class<'a> { + Ink::Text + } + + fn style(&self, ink: &Ink) -> text::Style { + text::Style { + color: Some(color(self.ink(*ink))), + } + } +} + +/// What a container draws behind its content. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub enum Frame { + /// Nothing. + #[default] + None, + /// A surface's fill, edge to edge: a page. + Fill(Surface), + /// A surface's fill with a border, at a control's radius. + Card(Surface), + /// The selected item: magenta's soft fill and line. + Selected, + /// An accent's soft fill and line, at a chip's radius. + Chip(Accent), + /// A line between two parts: the line's color, edge to edge. + Divider, +} + +impl container::Catalog for Theme { + type Class<'a> = Frame; + + fn default<'a>() -> Self::Class<'a> { + Frame::None + } + + fn style(&self, frame: &Frame) -> container::Style { + let p = &self.palette; + let border = |line: crate::ui::tokens::Color, radius: f32| Border { + color: color(line), + width: size::BORDER, + radius: radius.into(), + }; + let (background, border) = match *frame { + Frame::None => (None, Border::default()), + Frame::Fill(surface) => (Some(p.surface(surface)), Border::default()), + Frame::Divider => (Some(p.line), Border::default()), + Frame::Card(surface) => (Some(p.surface(surface)), border(p.line, radius::CONTROL)), + Frame::Selected => ( + Some(p.soft(Accent::Magenta)), + border(p.accent_line(Accent::Magenta), radius::CONTROL), + ), + Frame::Chip(accent) => ( + Some(p.soft(accent)), + border(p.accent_line(accent), radius::CHIP), + ), + }; + container::Style { + text_color: None, + background: background.map(|token| Background::Color(color(token))), + border, + shadow: Shadow::default(), + snap: true, + } + } +} + +/// How a widget looks in one state: its fill, its line and corner radius, and its ink (text, icon, +/// dot or bar). Only the theme makes them, from its palette; a widget draws what it's given. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Look { + pub fill: Option<crate::ui::tokens::Color>, + pub line: Option<crate::ui::tokens::Color>, + pub radius: f32, + pub ink: crate::ui::tokens::Color, + /// The glow round it: on hover, the selected item, a primary button on hover. Never at rest. + pub glow: Option<Halo>, +} + +/// How much of `text` tints a window button at rest: always faintly there. +const WINDOW_BUTTON_TINT: f32 = 0.05; + +/// A glow, drawn round a box and never inside it: the accent's color, how far down it sits (0 +/// for a halo all round), and how far it blurs, from a palette's glows. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Halo { + pub color: crate::ui::tokens::Color, + pub offset: f32, + pub blur: f32, +} + +impl Halo { + fn of(glow: crate::ui::tokens::effect::Glow, palette: &Palette) -> Self { + Self { + color: glow.halo_color(palette), + offset: glow.offset, + blur: glow.blur, + } + } + + /// A small glow, for a window button: half as far and half as bright. + pub fn small(self) -> Self { + Self { + color: self.color.opacity(self.color.alpha() / 2.0), + offset: self.offset / 2.0, + blur: self.blur / 2.0, + } + } +} + +impl Look { + fn boxed( + fill: crate::ui::tokens::Color, + line: crate::ui::tokens::Color, + radius: f32, + ink: crate::ui::tokens::Color, + ) -> Self { + Self { + fill: Some(fill), + line: Some(line), + radius, + ink, + glow: None, + } + } + + /// Just a fill, in its ink's color: a bar, a caret, a scroller. + pub fn solid(ink: crate::ui::tokens::Color, radius: f32) -> Self { + Self { + fill: Some(ink), + line: None, + radius, + ink, + glow: None, + } + } + + fn bare(radius: f32, ink: crate::ui::tokens::Color) -> Self { + Self { + fill: None, + line: None, + radius, + ink, + glow: None, + } + } + + /// The same, glowing. + pub fn glowing(self, glow: Halo) -> Self { + Self { + glow: Some(glow), + ..self + } + } + + /// The same with `glow` at a share of its strength, in place of its own: a glow fading in or + /// out as the pointer comes and goes ([`crate::ui::transition::Lit`]). + pub fn lit(self, glow: Option<Halo>, share: f32) -> Self { + let share = share.clamp(0.0, 1.0); + Self { + glow: glow.filter(|_| share > 0.0).map(|glow| Halo { + color: glow.color.opacity(glow.color.alpha() * share), + ..glow + }), + ..self + } + } + + /// The same at a share of its opacity, fill, line and glow: two looks crossfade as one goes + /// and the other comes. + pub fn faded(self, share: f32) -> Self { + let share = share.clamp(0.0, 1.0); + let fade = |color: crate::ui::tokens::Color| color.opacity(color.alpha() * share); + Self { + fill: self.fill.map(fade), + line: self.line.map(fade), + glow: self.glow.map(|glow| Halo { + color: fade(glow.color), + ..glow + }), + ..self + } + } +} + +/// What the pointer is doing to a widget, or that it's off. Keyboard focus is apart: it adds the +/// focus outline, whatever the interaction. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)] +pub enum Interaction { + #[default] + Idle, + Hovered, + Pressed, + Disabled, +} + +/// A button's weight. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)] +pub enum Emphasis { + /// The step forward: Check, Build, Play. One a screen. + Primary, + /// Everything else. + #[default] + Secondary, + /// What can't be undone, or stops what's under way: Cancel. + Danger, +} + +/// A long step's state. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)] +pub enum Progress { + #[default] + Running, + Done, + Failed, +} + +/// A check's or a step's state, as a status chip shows it: a dot and a word, never color alone. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)] +pub enum Status { + Passed, + Warning, + Failed, + /// Under way. + Running, + /// For information, or planned. + Info, + /// Not started. + #[default] + Waiting, +} + +/// The keyboard focus outline: 2px of cyan (Sunset's blue), 2px out from what it outlines. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Outline { + pub color: crate::ui::tokens::Color, + pub width: f32, + pub offset: f32, +} + +impl Theme { + /// Focus's glow, cyan: keyboard focus, round the outline, and a control under the pointer. + pub fn focus_glow(&self) -> Halo { + self.saved(Halo::of(self.palette.glows.focus, &self.palette)) + } + + /// The selected item's glow, magenta, and a primary button's under the pointer. + pub fn selected_glow(&self) -> Halo { + self.saved(Halo::of(self.palette.glows.selected, &self.palette)) + } + + /// A glow in an accent, focus's shape: a status chip's, a progress bar's. + pub fn accent_glow(&self, accent: Accent) -> Halo { + let glow = crate::ui::tokens::effect::Glow { + accent, + ..self.palette.glows.focus + }; + self.saved(Halo::of(glow, &self.palette)) + } + + /// A small light's glow, such as a status dot's: its own color, blurred (the palette's + /// spark). + pub fn spark(&self, ink: crate::ui::tokens::Color) -> Halo { + let spark = self.palette.glows.spark; + self.saved(Halo { + color: ink.opacity(ink.alpha() * spark.opacity), + offset: 0.0, + blur: spark.blur, + }) + } + + /// What can't be undone glows red under the pointer: the selected glow's shape, in red. + pub fn danger_glow(&self) -> Halo { + let glow = crate::ui::tokens::effect::Glow { + accent: Accent::Red, + ..self.palette.glows.selected + }; + self.saved(Halo::of(glow, &self.palette)) + } + + /// A glow as this theme draws it: on battery saver, half as soft. + fn saved(&self, glow: Halo) -> Halo { + if self.saving { + Halo { + blur: glow.blur / 2.0, + ..glow + } + } else { + glow + } + } + + /// The focus outline, shown whenever a widget has keyboard focus. + pub fn outline(&self) -> Outline { + Outline { + color: self.palette.accent(Accent::Cyan), + width: size::FOCUS_OUTLINE, + offset: size::FOCUS_OFFSET, + } + } + + /// Anything that's off: panel, a soft line, muted text. + fn disabled(&self, radius: f32) -> Look { + let p = &self.palette; + Look::boxed( + p.surface(Surface::Panel), + p.line_soft, + radius, + p.ink(Ink::Muted), + ) + } + + /// A control's label: text, or muted when it's off. + pub fn label(&self, interaction: Interaction) -> crate::ui::tokens::Color { + match interaction { + Interaction::Disabled => self.ink(Ink::Muted), + _ => self.ink(Ink::Text), + } + } + + pub fn button(&self, emphasis: Emphasis, interaction: Interaction) -> Look { + let p = &self.palette; + let text = p.ink(Ink::Text); + let tinted = |accent: Accent| { + let (fill, line) = match interaction { + Interaction::Idle => (p.soft(accent), p.accent_line(accent)), + Interaction::Hovered => (p.soft(accent), p.accent(accent)), + _ => (p.accent_line(accent), p.accent(accent)), + }; + let look = Look::boxed(fill, line, radius::BUTTON, text); + // Under the pointer a primary button glows as the selected item does; a danger + // button, red. + match (accent, interaction) { + (_, Interaction::Idle) => look, + (Accent::Red, _) => look.glowing(self.danger_glow()), + _ => look.glowing(self.selected_glow()), + } + }; + if interaction == Interaction::Disabled { + return self.disabled(radius::BUTTON); + } + match emphasis { + // The main action: the main color itself as its fill, its own ink on it; under the + // pointer it glows in the secondary color, and pressed, the secondary lines it, or + // the main color where the fill is the secondary's own (dark's orange button). + Emphasis::Primary => { + let look = Look::boxed(p.main_fill, p.main_fill, radius::BUTTON, p.on_main); + let pressed_line = if p.accent(Accent::Cyan) == p.main_fill { + p.accent(Accent::Magenta) + } else { + p.accent(Accent::Cyan) + }; + match interaction { + Interaction::Idle => look, + Interaction::Hovered => look.glowing(self.selected_glow()), + _ => Look { + line: Some(pressed_line), + ..look + } + .glowing(self.selected_glow()), + } + } + Emphasis::Danger => tinted(Accent::Red), + Emphasis::Secondary => { + // As a field: sunk, its line round it, cyan's tint under the pointer, with its + // glow; pressed, raised. + match interaction { + Interaction::Idle => { + Look::boxed(p.surface(Surface::Sunk), p.line, radius::BUTTON, text) + } + Interaction::Hovered => Look::boxed( + p.surface(Surface::Sunk), + p.accent_line(Accent::Cyan), + radius::BUTTON, + text, + ) + .glowing(self.focus_glow()), + _ => Look::boxed( + p.surface(Surface::Raise), + p.accent(Accent::Cyan), + radius::BUTTON, + text, + ) + .glowing(self.focus_glow()), + } + } + } + } + + /// A text field. An invalid one's line is red. + pub fn field(&self, interaction: Interaction, focused: bool, invalid: bool) -> Look { + let p = &self.palette; + let line = match (interaction, focused, invalid) { + (Interaction::Disabled, _, _) => return self.disabled(radius::BUTTON), + (_, true, true) => p.accent(Accent::Red), + (_, false, true) => p.accent_line(Accent::Red), + (_, true, false) => p.accent(Accent::Cyan), + (Interaction::Hovered | Interaction::Pressed, false, false) => { + p.accent_line(Accent::Cyan) + } + (Interaction::Idle, false, false) => p.line, + }; + let look = Look::boxed( + p.surface(Surface::Sunk), + line, + radius::BUTTON, + p.ink(Ink::Text), + ); + if matches!(interaction, Interaction::Hovered | Interaction::Pressed) { + look.glowing(self.focus_glow()) + } else { + look + } + } + + /// A field's placeholder: `dim`, the one text-like use it has. + pub fn placeholder(&self) -> crate::ui::tokens::Color { + self.palette.dim + } + + /// Selected text's highlight: magenta, which means selection. + pub fn selection(&self) -> crate::ui::tokens::Color { + self.palette.accent_line(Accent::Magenta) + } + + /// The text caret. + pub fn caret(&self) -> crate::ui::tokens::Color { + self.palette.accent(Accent::Cyan) + } + + /// A toggle group's pill ([`crate::ui::toggle`]): sunk, lined, its corners a button's. + pub fn toggle_group(&self) -> Look { + let p = &self.palette; + Look::boxed( + p.surface(Surface::Sunk), + p.line, + radius::BUTTON, + p.ink(Ink::Muted), + ) + } + + /// A segment of a toggle group: the chosen one raised, on cyan's line tint; the others muted, + /// and `text` under the pointer. + pub fn toggle_segment(&self, chosen: bool, interaction: Interaction) -> Look { + // Only the chosen segment glows, in its line's cyan; the others don't, even hovered. + let look = self.toggle_segment_look(chosen, interaction); + if chosen && interaction != Interaction::Disabled { + look.glowing(self.focus_glow()) + } else { + look + } + } + + fn toggle_segment_look(&self, chosen: bool, interaction: Interaction) -> Look { + let p = &self.palette; + let radius = radius::SEGMENT; + match (chosen, interaction) { + (true, Interaction::Disabled) => Look { + fill: Some(p.surface(Surface::Raise)), + ..Look::bare(radius, p.ink(Ink::Muted)) + }, + (false, Interaction::Disabled) => Look::bare(radius, p.dim), + (true, _) => Look::boxed( + p.surface(Surface::Raise), + p.accent_line(Accent::Cyan), + radius, + p.ink(Ink::Text), + ), + (false, Interaction::Hovered | Interaction::Pressed) => { + Look::bare(radius, p.ink(Ink::Text)) + } + (false, Interaction::Idle) => Look::bare(radius, p.ink(Ink::Muted)), + } + } + + /// A scroll indicator: a scroll area's. Decoration, so dim is allowed. + pub fn scroller(&self, interaction: Interaction) -> crate::ui::tokens::Color { + match interaction { + Interaction::Hovered | Interaction::Pressed => self.palette.dim, + _ => self.palette.line, + } + } + + /// A progress bar: its track, and the done part in the ink. + pub fn progress(&self, progress: Progress) -> Look { + let p = &self.palette; + Look::boxed( + p.line_soft, + p.line_soft, + radius::ROUND, + p.accent(progress_accent(progress)), + ) + } + + /// A progress bar's done part: its accent, glowing. + pub fn progress_bar(&self, progress: Progress) -> Look { + let accent = progress_accent(progress); + Look::solid(self.palette.accent(accent), radius::ROUND).glowing(self.accent_glow(accent)) + } + + /// A running bar's done part in Sunset: the logo's gradient, in this palette's accents, from + /// the bar's start to its end ([`crate::ui::tokens::Palette::sunset`]). + pub fn progress_gradient(&self) -> [crate::ui::tokens::Color; 2] { + self.palette.sunset() + } + + /// A loader's ring ([`crate::ui::loader`]): a cyan line, glowing, nothing inside it. + pub fn loader(&self) -> Look { + let cyan = self.palette.accent(Accent::Cyan); + Look { + line: Some(cyan), + ..Look::bare(radius::ROUND, cyan) + } + .glowing(self.accent_glow(Accent::Cyan)) + } + + /// A status chip; the dot and the word take its ink. + pub fn status(&self, status: Status) -> Look { + let p = &self.palette; + // Each lit, glowing in its accent; waiting isn't. + let tinted = |accent: Accent| { + Look::boxed( + p.soft(accent), + p.accent_line(accent), + radius::ROUND, + p.accent(accent), + ) + .glowing(self.accent_glow(accent)) + }; + match status { + Status::Passed => tinted(Accent::Mint), + Status::Warning => tinted(Accent::Amber), + Status::Failed => tinted(Accent::Red), + Status::Running => tinted(Accent::Cyan), + Status::Info => tinted(Accent::Violet), + // Waiting isn't lit. In dark, though, its line and its small light are the secondary + // color, the logo's orange: muted purple on the dark purple page hardly shows. + Status::Waiting => match p.mode { + crate::ui::tokens::Mode::Dark => Look { + line: Some(p.accent_line(Accent::Cyan)), + ..Look::bare(radius::ROUND, p.accent(Accent::Cyan)) + }, + crate::ui::tokens::Mode::Light => Look { + line: Some(p.line), + ..Look::bare(radius::ROUND, p.ink(Ink::Muted)) + }, + }, + } + } + + /// A scroll area's auto-scroll badge: panel, line and muted. + pub fn badge(&self) -> Look { + let p = &self.palette; + Look::boxed( + p.surface(Surface::Panel), + p.line, + radius::ROUND, + p.ink(Ink::Muted), + ) + } + + /// A checkbox's box, glowing under the pointer; its ink is the check mark's. + pub fn check(&self, checked: bool, interaction: Interaction) -> Look { + let look = self.check_box(checked, interaction); + self.glow_hovered(look, interaction) + } + + /// A look with focus's glow under the pointer, as every control has. + fn glow_hovered(&self, look: Look, interaction: Interaction) -> Look { + if matches!(interaction, Interaction::Hovered | Interaction::Pressed) { + look.glowing(self.focus_glow()) + } else { + look + } + } + + fn check_box(&self, checked: bool, interaction: Interaction) -> Look { + let p = &self.palette; + let cyan = p.accent(Accent::Cyan); + // Sunk as every control; its line `dim`, though, not `line`: a box this small is known by + // its edge alone, which needs 3:1. + let bg = p.surface(Surface::Sunk); + match (checked, interaction) { + (_, Interaction::Disabled) => Look::boxed( + p.surface(Surface::Panel), + p.line, + radius::CHECK, + p.ink(Ink::Muted), + ), + (true, _) => Look::boxed(p.soft(Accent::Cyan), cyan, radius::CHECK, cyan), + (false, Interaction::Hovered | Interaction::Pressed) => { + Look::boxed(bg, p.accent_line(Accent::Cyan), radius::CHECK, cyan) + } + (false, Interaction::Idle) => Look::boxed(bg, p.dim, radius::CHECK, cyan), + } + } + + /// One option of a single choice: a card, magenta when it's the chosen one. + pub fn option(&self, chosen: bool, interaction: Interaction) -> Look { + let p = &self.palette; + let text = p.ink(Ink::Text); + match (chosen, interaction) { + (_, Interaction::Disabled) => self.disabled(radius::CONTROL), + (true, _) => Look::boxed( + p.soft(Accent::Magenta), + p.accent_line(Accent::Magenta), + radius::CONTROL, + text, + ) + .glowing(self.selected_glow()), + (false, Interaction::Hovered | Interaction::Pressed) => Look::boxed( + p.surface(Surface::Sunk), + p.accent_line(Accent::Cyan), + radius::CONTROL, + text, + ) + .glowing(self.focus_glow()), + (false, Interaction::Idle) => { + Look::boxed(p.surface(Surface::Sunk), p.line, radius::CONTROL, text) + } + } + } + + /// An option's radio circle, glowing under the pointer; its ink is the chosen one's dot. + pub fn radio(&self, chosen: bool, interaction: Interaction) -> Look { + let look = self.radio_circle(chosen, interaction); + self.glow_hovered(look, interaction) + } + + fn radio_circle(&self, chosen: bool, interaction: Interaction) -> Look { + let p = &self.palette; + let cyan = p.accent(Accent::Cyan); + let (line, ink) = match (chosen, interaction) { + (_, Interaction::Disabled) => (p.line, p.ink(Ink::Muted)), + (true, _) => (cyan, cyan), + (false, Interaction::Hovered | Interaction::Pressed) => { + (p.accent_line(Accent::Cyan), cyan) + } + (false, Interaction::Idle) => (p.dim, cyan), + }; + Look::boxed(p.surface(Surface::Sunk), line, radius::ROUND, ink) + } + + /// A selection list's frame: it glows under the pointer, as every control does; its rows + /// don't. + pub fn list(&self, interaction: Interaction) -> Look { + let p = &self.palette; + if interaction == Interaction::Disabled { + self.disabled(radius::CONTROL) + } else { + let look = Look::boxed( + p.surface(Surface::Sunk), + p.line, + radius::CONTROL, + p.ink(Ink::Text), + ); + self.glow_hovered(look, interaction) + } + } + + /// A list's row: the chosen one magenta, a hovered one raised. + pub fn row(&self, chosen: bool, interaction: Interaction) -> Look { + let p = &self.palette; + let text = p.ink(Ink::Text); + match (chosen, interaction) { + (_, Interaction::Disabled) => Look::bare(radius::CHIP, p.ink(Ink::Muted)), + (true, _) => Look::boxed( + p.soft(Accent::Magenta), + p.accent_line(Accent::Magenta), + radius::CHIP, + text, + ), + (false, Interaction::Hovered | Interaction::Pressed) => Look { + fill: Some(p.surface(Surface::Raise)), + ..Look::bare(radius::CHIP, text) + }, + (false, Interaction::Idle) => Look::bare(radius::CHIP, text), + } + } + + /// A switch ([`mod@crate::ui::switch`]): off, sunk and lined with a muted knob; on, + /// cyan's soft fill and line with a cyan knob, light from interaction. Under the pointer its + /// line brightens. + pub fn switch(&self, on: bool, interaction: Interaction) -> SwitchLook { + // On, it's lit: it glows. Off, it doesn't, even under the pointer. + let look = self.switch_parts(on, interaction); + let track = if on && interaction != Interaction::Disabled { + look.track.glowing(self.focus_glow()) + } else { + look.track + }; + SwitchLook { track, ..look } + } + + fn switch_parts(&self, on: bool, interaction: Interaction) -> SwitchLook { + let p = &self.palette; + let radius = crate::ui::tokens::size::SWITCH_HEIGHT / 2.0; + let hovered = matches!(interaction, Interaction::Hovered | Interaction::Pressed); + match (on, interaction) { + (_, Interaction::Disabled) => SwitchLook { + track: Look::boxed(p.surface(Surface::Sunk), p.line, radius, p.dim), + knob: if on { p.ink(Ink::Muted) } else { p.dim }, + }, + (true, _) => SwitchLook { + track: Look::boxed( + p.soft(Accent::Cyan), + if hovered { + p.accent(Accent::Cyan) + } else { + p.accent_line(Accent::Cyan) + }, + radius, + p.ink(Ink::Text), + ), + knob: p.accent(Accent::Cyan), + }, + (false, _) => SwitchLook { + track: Look::boxed( + p.surface(Surface::Sunk), + if hovered { p.dim } else { p.line }, + radius, + p.ink(Ink::Text), + ), + knob: if hovered { + p.ink(Ink::Text) + } else { + p.ink(Ink::Muted) + }, + }, + } + } + + /// A row of a sidebar ([`crate::ui::list::navigation`]): muted at rest, raised under + /// the pointer; the chosen one in magenta's soft fill, which [`Theme::sidebar_mark`] edges. + pub fn sidebar_row(&self, chosen: bool, interaction: Interaction) -> Look { + let p = &self.palette; + match (chosen, interaction) { + (_, Interaction::Disabled) => Look::bare(radius::CHIP, p.ink(Ink::Muted)), + (true, _) => Look { + fill: Some(p.soft(Accent::Magenta)), + ..Look::bare(radius::CHIP, p.ink(Ink::Text)) + }, + (false, Interaction::Hovered | Interaction::Pressed) => Look { + fill: Some(p.surface(Surface::Raise)), + ..Look::bare(radius::CHIP, p.ink(Ink::Text)) + }, + (false, Interaction::Idle) => Look::bare(radius::CHIP, p.ink(Ink::Muted)), + } + } + + /// The mark at the chosen sidebar row's start: a short bar of magenta, the selection's accent. + pub fn sidebar_mark(&self) -> crate::ui::tokens::Color { + // The logo's orange in both modes, against the row's purple-tinted fill: the main color + // in light, the secondary in dark. + match self.palette.mode { + crate::ui::tokens::Mode::Light => self.palette.accent(Accent::Magenta), + crate::ui::tokens::Mode::Dark => self.palette.accent(Accent::Cyan), + } + } +} + +/// A switch's look: its track, and its knob's color. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct SwitchLook { + pub track: Look, + pub knob: crate::ui::tokens::Color, +} + +/// A header bar's look: its fill, the tints fading in from its edges, and its bottom line. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct BarLook { + pub fill: crate::ui::tokens::Color, + /// The tint at the left edge, and at the right, each fading to nothing across `reach` of the + /// bar's width. + pub start: crate::ui::tokens::Color, + pub end: crate::ui::tokens::Color, + pub reach: f32, + pub line: crate::ui::tokens::Color, +} + +/// A window frame's look: the fill behind everything, and while the window floats, its line and +/// corner radius. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct WindowLook { + pub fill: crate::ui::tokens::Color, + pub line: crate::ui::tokens::Color, + pub radius: f32, +} + +/// A window's own decorations (`crate::ui::chrome`). Their sizes are +/// `crate::ui::tokens::window`'s. +impl Theme { + /// The header bar: panel, the palette's edge tints and a line below. + pub fn header_bar(&self) -> BarLook { + let p = &self.palette; + BarLook { + fill: p.surface(Surface::Panel), + start: p.title_bar.start.color(p), + end: p.title_bar.end.color(p), + reach: p.title_bar.reach, + line: p.line, + } + } + + /// The close button: its cross `muted`, and red on red's soft tint under the pointer. + pub fn close_button(&self, interaction: Interaction) -> Look { + let p = &self.palette; + match interaction { + Interaction::Hovered | Interaction::Pressed => Look { + fill: Some(p.soft(Accent::Red)), + ..Look::bare(window::BUTTON_RADIUS, p.accent(Accent::Red)) + } + .glowing(self.danger_glow().small()), + Interaction::Idle | Interaction::Disabled => self.window_button_at_rest(), + } + } + + /// A window button at rest: its glyph `muted` on a faint tint of `text`, always there. + fn window_button_at_rest(&self) -> Look { + let p = &self.palette; + Look { + fill: Some(p.ink(Ink::Text).opacity(WINDOW_BUTTON_TINT)), + ..Look::bare(window::BUTTON_RADIUS, p.ink(Ink::Muted)) + } + } + + /// Any other window button: its glyph `muted`, as the close button's, and `text` under the + /// pointer on a tint of `text`. + pub fn window_button(&self, interaction: Interaction) -> Look { + let p = &self.palette; + let tint = |opacity| { + Look { + fill: Some(p.ink(Ink::Text).opacity(opacity)), + ..Look::bare(window::BUTTON_RADIUS, p.ink(Ink::Text)) + } + .glowing(self.focus_glow().small()) + }; + match interaction { + Interaction::Hovered => tint(0.14), + Interaction::Pressed => tint(0.2), + Interaction::Idle | Interaction::Disabled => self.window_button_at_rest(), + } + } + + /// A window's frame: bg behind everything, and while it floats, a line round its rounded + /// edge: the logo's deep purple outline in dark. + pub fn window(&self) -> WindowLook { + let p = &self.palette; + WindowLook { + fill: p.surface(Surface::Bg), + line: p.line, + radius: window::CORNER_RADIUS, + } + } +} + +/// A progress bar's accent: cyan running, mint done, red failed. +fn progress_accent(progress: Progress) -> Accent { + match progress { + Progress::Running => Accent::Cyan, + Progress::Done => Accent::Mint, + Progress::Failed => Accent::Red, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use iced::widget::container::Catalog as _; + + const DARK: Theme = Theme::new(Palette::SUNSET_DARK); + + fn frame(frame: Frame) -> container::Style { + DARK.style(&frame) + } + + #[test] + fn tokens_map_to_iced_colors() { + let p = Palette::SUNSET_DARK; + assert_eq!( + color(p.accent(Accent::Cyan)), + iced::Color::from_rgb8(0xfd, 0x77, 0x44) + ); + let soft = color(p.soft(Accent::Cyan)); + assert_eq!(soft.a, 0.14); + assert_eq!( + iced::Color { a: 1.0, ..soft }, + color(p.accent(Accent::Cyan)) + ); + } + + #[test] + fn the_base_is_text_on_bg() { + let theme = <Theme as Base>::default(Mode::Light); + assert_eq!(theme, DARK); + assert_eq!(theme.palette(), &Palette::SUNSET_DARK); + assert_eq!(theme.mode(), Mode::Dark); + assert_eq!(Base::name(&theme), "sunset-dark"); + let light = Theme::of(ThemeName::Sunset, crate::ui::tokens::Mode::Light); + assert_eq!((light.mode(), light.name()), (Mode::Light, "sunset-light")); + let base = theme.base(); + assert_eq!(base.background_color, color(theme.surface(Surface::Bg))); + assert_eq!(base.text_color, color(theme.ink(Ink::Text))); + } + + #[test] + fn text_takes_its_ink() { + let default = <Theme as text::Catalog>::default(); + assert_eq!(default, Ink::Text); + for ink in Ink::ALL { + let style = text::Catalog::style(&DARK, &ink); + assert_eq!(style.color, Some(color(DARK.ink(ink)))); + } + } + + #[test] + fn frames_draw_the_palette() { + let p = Palette::SUNSET_DARK; + let none = frame(<Theme as container::Catalog>::default()); + assert_eq!(none.background, None); + let card = frame(Frame::Card(Surface::Raise)); + assert_eq!(card.border.color, color(p.line)); + assert_eq!(card.border.width, 1.0); + let chip = frame(Frame::Chip(Accent::Mint)); + assert_eq!(chip.border.radius, radius::CHIP.into()); + } + + #[test] + fn no_look_draws_text_in_dim_in_any_palette() { + for palette in Palette::ALL { + let theme = Theme::new(palette); + for interaction in [ + Interaction::Idle, + Interaction::Hovered, + Interaction::Pressed, + Interaction::Disabled, + ] { + let mut looks = Vec::new(); + for emphasis in [Emphasis::Primary, Emphasis::Secondary, Emphasis::Danger] { + looks.push(theme.button(emphasis, interaction)); + } + for (focused, invalid) in + [(false, false), (true, false), (false, true), (true, true)] + { + looks.push(theme.field(interaction, focused, invalid)); + } + looks.push(theme.toggle_segment(true, interaction)); + for look in looks { + assert_ne!(look.ink, palette.dim, "{}: {look:?}", palette.name); + } + assert_ne!(theme.label(interaction), palette.dim); + } + } + } + + #[test] + fn every_look_comes_from_the_palette() { + let p = Palette::SUNSET_DARK; + // The main action is filled with the main color; focus and the glows take the secondary. + let primary = DARK.button(Emphasis::Primary, Interaction::Idle); + assert_eq!((primary.fill, primary.ink), (Some(p.main_fill), p.on_main)); + assert_eq!(DARK.outline().color, p.accent(Accent::Cyan)); + assert_eq!(DARK.progress(Progress::Running).ink, p.accent(Accent::Cyan)); + assert_eq!(DARK.progress_gradient()[1], p.accent(Accent::Cyan)); + let disabled = DARK.button(Emphasis::Primary, Interaction::Disabled); + assert_eq!(disabled.ink, p.ink(Ink::Muted)); + assert_eq!( + DARK.field(Interaction::Idle, true, true).line, + Some(p.accent(Accent::Red)) + ); + assert!(DARK.progress_bar(Progress::Running).glow.is_some()); + assert!(DARK.status(Status::Passed).glow.is_some()); + assert!(DARK.status(Status::Waiting).glow.is_none()); + assert!(DARK.toggle_segment(true, Interaction::Idle).glow.is_some()); + assert!( + DARK.toggle_segment(false, Interaction::Hovered) + .glow + .is_none() + ); + assert_eq!(DARK.scroller(Interaction::Hovered), p.dim); + assert_eq!(DARK.progress(Progress::Failed).ink, p.accent(Accent::Red)); + assert_eq!(DARK.status(Status::Info).fill, Some(p.soft(Accent::Violet))); + assert_eq!(DARK.placeholder(), p.dim); + assert_eq!(DARK.caret(), p.accent(Accent::Cyan)); + } + + #[test] + fn window_decorations_come_from_the_palette() { + for palette in Palette::ALL { + let theme = Theme::new(palette); + let bar = theme.header_bar(); + assert_eq!(bar.fill, palette.surface(Surface::Panel)); + assert_eq!(bar.line, palette.line); + let idle = theme.close_button(Interaction::Idle); + assert_eq!(idle.ink, palette.ink(Ink::Muted)); + for interaction in [Interaction::Hovered, Interaction::Pressed] { + let hovered = theme.close_button(interaction); + assert_eq!(hovered.fill, Some(palette.soft(Accent::Red))); + assert_eq!(hovered.ink, palette.accent(Accent::Red)); + } + let window = theme.window(); + assert_eq!(window.fill, palette.surface(Surface::Bg)); + assert_eq!((window.line, window.radius), (palette.line, 14.0)); + } + } +} diff --git a/launcher/src/ui/toggle.rs b/launcher/src/ui/toggle.rs new file mode 100644 index 0000000000..c0df95f2a6 --- /dev/null +++ b/launcher/src/ui/toggle.rs @@ -0,0 +1,516 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! A toggle group: a few choices side by side in a rounded box, the chosen one raised, such as +//! dark or light, or a view. + +use iced::advanced::layout::{self, Layout}; +use iced::advanced::widget::{Operation, Tree, Widget, tree}; +use iced::advanced::{Clipboard, Shell, mouse, renderer}; +use iced::keyboard::{self, Key, key::Named}; +use iced::{Event, Length, Point, Rectangle, Size, touch, window}; + +use crate::ui::tokens::{motion, size, space, typography}; +use crate::ui::transition::Transition; + +use crate::ui::focus::Focus; +use crate::ui::input; +use crate::ui::paint::{self, Plain}; +use crate::ui::theme::{Interaction, Look, color}; +use crate::ui::{Element, Renderer, Theme}; + +/// Room round the segments inside the group. +const INSET: f32 = crate::ui::tokens::size::SEGMENT_INSET; +/// Room either side of a segment's words. +const PAD: f32 = space::L; + +/// The choices, with the chosen one's index. Without a message to send it is disabled. +pub fn toggle_group<'a, Message>( + choices: impl IntoIterator<Item = impl Into<String>>, + chosen: usize, +) -> ToggleGroup<'a, Message> { + ToggleGroup { + choices: choices.into_iter().map(Into::into).collect(), + chosen, + homogeneous: false, + pill: false, + height: size::TOGGLE, + on_choose: None, + preview: None, + } +} + +/// A toggle group: one Tab stop; Left and Right, Home and End move the choice, as a click does. +pub struct ToggleGroup<'a, Message> { + choices: Vec<String>, + chosen: usize, + homogeneous: bool, + pill: bool, + height: f32, + on_choose: Option<Box<dyn Fn(usize) -> Message + 'a>>, + preview: Option<(usize, Interaction, bool)>, +} + +impl<'a, Message> ToggleGroup<'a, Message> { + /// The message for a choice, with its index: without one, it's disabled. + pub fn on_choose(self, on_choose: impl Fn(usize) -> Message + 'a) -> Self { + Self { + on_choose: Some(Box::new(on_choose)), + ..self + } + } + + /// Every segment as wide as the widest. + pub fn homogeneous(self, homogeneous: bool) -> Self { + Self { + homogeneous, + ..self + } + } + + /// Fully rounded, a pill, its segments too; otherwise its corners are a button's. + pub fn pill(self, pill: bool) -> Self { + Self { pill, ..self } + } + + /// Its corners and its segments': a pill's, half its height and half theirs, or a button's + /// and, inside them, running alongside. + fn radii(&self) -> (f32, f32) { + if self.pill { + (self.height / 2.0, (self.height - 2.0 * INSET) / 2.0) + } else { + ( + crate::ui::tokens::radius::BUTTON, + crate::ui::tokens::radius::SEGMENT, + ) + } + } + + /// Draws one segment as if in this state, and the focus outline, for the gallery. + pub fn preview(self, segment: usize, interaction: Interaction, focused: bool) -> Self { + Self { + preview: Some((segment, interaction, focused)), + ..self + } + } +} + +/// Where each segment is, left to right, from the words' widths, in a group `height` tall: `widths` +/// of the words, all as wide as the widest if `homogeneous`. +pub(crate) fn segments( + widths: &[f32], + homogeneous: bool, + at: Point, + height: f32, +) -> Vec<Rectangle> { + let widest = widths.iter().copied().fold(0.0, f32::max); + let mut x = at.x + INSET; + widths + .iter() + .map(|width| { + // Whole pixels, so the group's edges and the segments' fall on them. + let width = if homogeneous { widest } else { *width }.ceil() + 2.0 * PAD; + let segment = Rectangle::new( + Point::new(x, at.y + INSET), + Size::new(width, height - 2.0 * INSET), + ); + x += width; + segment + }) + .collect() +} + +/// The choice a key moves to among `count`, from `chosen`. +pub(crate) fn step(chosen: usize, count: usize, key: &Key) -> Option<usize> { + let last = count.checked_sub(1)?; + let to = match key { + Key::Named(Named::ArrowLeft) => chosen.saturating_sub(1), + Key::Named(Named::ArrowRight) => (chosen + 1).min(last), + Key::Named(Named::Home) => 0, + Key::Named(Named::End) => last, + _ => return None, + }; + Some(to) +} + +#[derive(Default)] +struct State { + focus: Focus, + words: Vec<Plain>, + pressed: Option<usize>, + drawn: Option<(Option<usize>, Option<usize>, bool, usize)>, + /// Where the chosen segment's highlight is drawn, by segment, between them as it slides or + /// is dragged; and the choice it was last drawn for. + at: f32, + seen: Option<usize>, + slide: Option<Transition>, + /// A press: where it began across, where the highlight was, and whether it has moved far + /// enough to be a drag. As a switch's knob: dragged, the highlight follows the pointer, and + /// the choice changes when it's let go. + drag: Option<(f32, f32, bool)>, + /// Its focus ring, fading in and out with keyboard focus on the glows' own timing. + focus_lit: crate::ui::transition::Lit, +} + +impl State { + /// The highlight slides to `segment` from where it is, or with motion reduced, jumps there. + fn slide_to(&mut self, segment: usize) { + let to = segment as f32; + self.slide = Transition::start(self.at, to, motion::FAST); + if self.slide.is_none() { + self.at = to; + } + } +} + +/// The highlight's rectangle `at` the given place among `segments`: between two, as far between +/// them as `at` is. +fn highlight(segments: &[Rectangle], at: f32) -> Option<Rectangle> { + let last = segments.len().checked_sub(1)?; + let at = at.clamp(0.0, last as f32); + let (from, to) = (at.floor() as usize, (at.ceil() as usize).min(last)); + let share = at - from as f32; + let (a, b) = (segments[from], segments[to]); + let mix = |x: f32, y: f32| x + (y - x) * share; + Some(Rectangle::new( + Point::new(mix(a.x, b.x), mix(a.y, b.y)), + Size::new(mix(a.width, b.width), mix(a.height, b.height)), + )) +} + +impl<Message> ToggleGroup<'_, Message> { + /// The segment under the pointer: its layout's children are the segments, laid out once. + fn segment_at(layout: Layout<'_>, cursor: mouse::Cursor) -> Option<usize> { + let point = cursor.position_over(layout.bounds())?; + layout + .children() + .position(|segment| segment.bounds().contains(point)) + } + + fn choose(&mut self, segment: usize, shell: &mut Shell<'_, Message>) { + if let Some(on_choose) = &self.on_choose + && segment != self.chosen + && segment < self.choices.len() + { + shell.publish(on_choose(segment)); + self.chosen = segment; + } + } +} + +impl<Message> Widget<Message, Theme, Renderer> for ToggleGroup<'_, Message> { + fn tag(&self) -> tree::Tag { + tree::Tag::of::<State>() + } + + fn state(&self) -> tree::State { + tree::State::new(State::default()) + } + + fn size(&self) -> Size<Length> { + Size::new(Length::Shrink, Length::Fixed(self.height)) + } + + fn layout( + &mut self, + tree: &mut Tree, + _renderer: &Renderer, + _limits: &layout::Limits, + ) -> layout::Node { + let state = tree.state.downcast_mut::<State>(); + state.words.resize_with(self.choices.len(), Plain::default); + for (plain, choice) in state.words.iter_mut().zip(&self.choices) { + paint::shape(plain, &typography::INTERFACE, choice); + } + // As wide as its segments, whatever room it's given: a toggle group doesn't shrink. + let widths: Vec<f32> = state + .words + .iter() + .map(|plain| plain.min_bounds().width) + .collect(); + let segments = segments(&widths, self.homogeneous, Point::ORIGIN, self.height); + let width = segments + .last() + .map_or(0.0, |last| last.x + last.width + INSET); + let nodes = segments + .iter() + .map(|segment| layout::Node::new(segment.size()).move_to(segment.position())) + .collect(); + layout::Node::with_children(Size::new(width, self.height), nodes) + } + + fn operate( + &mut self, + tree: &mut Tree, + layout: Layout<'_>, + _renderer: &Renderer, + operation: &mut dyn Operation, + ) { + if self.on_choose.is_some() && self.preview.is_none() && !self.choices.is_empty() { + let state = tree.state.downcast_mut::<State>(); + operation.focusable(None, layout.bounds(), &mut state.focus); + } + } + + fn update( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + _renderer: &Renderer, + _clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + _viewport: &Rectangle, + ) { + if self.preview.is_some() { + return; + } + let state = tree.state.downcast_mut::<State>(); + state + .focus + .keep_if(self.on_choose.is_some() && !self.choices.is_empty()); + // The highlight slides, a frame at a time. + if let Event::Window(window::Event::RedrawRequested(now)) = event + && let Some(slide) = &mut state.slide + { + let going = slide.frame(*now); + state.at = slide.at(); + if going { + shell.request_redraw(); + } else { + state.slide = None; + } + } + // The choice changed from outside, as Ctrl+L or a key does: the highlight slides there. + match state.seen { + None => state.at = self.chosen as f32, + Some(seen) if seen != self.chosen && state.drag.is_none() => { + state.slide_to(self.chosen); + shell.request_redraw(); + } + Some(_) => {} + } + state.seen = Some(self.chosen); + let over = Self::segment_at(layout, cursor); + let last = self.choices.len().saturating_sub(1) as f32; + if self.on_choose.is_some() { + match event { + Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerPressed { .. }) + if over.is_some() => + { + state.pressed = over; + if let Some(at) = cursor.position() { + state.drag = Some((at.x, state.at, false)); + } + state.focus.click(); + shell.capture_event(); + } + Event::Mouse(mouse::Event::CursorMoved { position }) + | Event::Touch(touch::Event::FingerMoved { position, .. }) => { + if let Some((from_x, from_at, dragged)) = &mut state.drag { + // Further than a slip, it drags the highlight rather than clicks. + let moved = position.x - *from_x; + *dragged |= moved.abs() > size::SLIP; + if *dragged { + let step = + (layout.bounds().width / self.choices.len().max(1) as f32).max(1.0); + state.slide = None; + state.at = (*from_at + moved / step).clamp(0.0, last); + shell.request_redraw(); + shell.capture_event(); + } + } + } + Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerLifted { .. }) => { + if state.pressed.take().is_some() { + // Dragged, the nearer segment; clicked, the one let go over. The choice + // changes now, as it's let go. + let dragged = state.drag.take().is_some_and(|(_, _, dragged)| dragged); + let segment = if dragged { + state.at.round() as usize + } else { + over.unwrap_or(self.chosen) + }; + state.slide_to(segment); + state.seen = Some(segment); + self.choose(segment, shell); + shell.request_redraw(); + shell.capture_event(); + } + } + Event::Touch(touch::Event::FingerLost { .. }) => { + state.pressed = None; + if state.drag.take().is_some() { + state.slide_to(self.chosen); + shell.request_redraw(); + } + } + Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) + if state.focus.is_focused() && input::plain(*modifiers) => + { + if let Some(segment) = step(self.chosen, self.choices.len(), key) { + state.focus.key(); + if segment != self.chosen { + state.slide_to(segment); + state.seen = Some(segment); + shell.request_redraw(); + } + self.choose(segment, shell); + shell.capture_event(); + } + } + _ => {} + } + } else { + state.pressed = None; + state.drag = None; + } + state.focus_lit.frame(event, shell); + state.focus_lit.aim(state.focus.is_shown(), shell); + let now = (over, state.pressed, state.focus.is_shown(), self.chosen); + input::redraw_on_change(&mut state.drawn, now, event, shell); + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + _style: &renderer::Style, + layout: Layout<'_>, + cursor: mouse::Cursor, + _viewport: &Rectangle, + ) { + let state = tree.state.downcast_ref::<State>(); + let bounds = layout.bounds(); + let disabled = self.on_choose.is_none(); + let (radius, segment_radius) = self.radii(); + paint::boxed( + renderer, + bounds, + &Look { + radius, + ..theme.toggle_group() + }, + ); + let over = Self::segment_at(layout, cursor); + let height = typography::INTERFACE.size * typography::INTERFACE.line_height; + let segments: Vec<Rectangle> = layout.children().map(|segment| segment.bounds()).collect(); + let interaction = |index: usize| match self.preview { + Some((shown, interaction, _)) if shown == index => interaction, + _ if disabled => Interaction::Disabled, + _ if state.pressed == Some(index) => Interaction::Pressed, + _ if over == Some(index) => Interaction::Hovered, + _ => Interaction::Idle, + }; + // Where the highlight is: the chosen segment's, sliding or dragged between them. + let at = match (self.preview, state.seen) { + (Some(_), _) | (None, None) => self.chosen as f32, + (None, Some(_)) => state.at, + }; + let nearest = (at.round().max(0.0) as usize).min(segments.len().saturating_sub(1)); + // The others first, as they look unchosen; then the highlight over them. + for (index, segment) in segments.iter().enumerate() { + let look = Look { + radius: segment_radius, + ..theme.toggle_segment(false, interaction(index)) + }; + paint::boxed(renderer, *segment, &look); + } + let shown = highlight(&segments, at); + if let Some(shown) = shown { + let look = Look { + radius: segment_radius, + ..theme.toggle_segment(true, interaction(nearest)) + }; + paint::boxed(renderer, shown, &look); + } + for (index, (segment, words)) in segments.iter().zip(&state.words).enumerate() { + let look = theme.toggle_segment(index == nearest, interaction(index)); + let width = words.min_bounds().width; + let place = Point::new( + segment.center_x() - width / 2.0, + segment.center_y() - height / 2.0, + ); + paint::fill(renderer, words, place, color(look.ink), bounds); + } + let focused = match self.preview { + Some((_, _, focused)) => focused, + None => state.focus.is_shown(), + }; + // The focus ring fades in and out with keyboard focus, round the highlight wherever it is. + let ring = if self.preview.is_some() { + f32::from(u8::from(focused)) + } else { + state.focus_lit.share() + }; + if let Some(shown) = shown { + paint::outline_lit(renderer, theme, shown, segment_radius, ring); + } + } + + /// A hand that grabs: it's dragged across, as well as clicked. A header bar leaves the + /// pointer's drag to it instead of moving the window. + fn mouse_interaction( + &self, + tree: &Tree, + layout: Layout<'_>, + cursor: mouse::Cursor, + _viewport: &Rectangle, + _renderer: &Renderer, + ) -> mouse::Interaction { + let pressed = tree.state.downcast_ref::<State>().pressed.is_some(); + if self.on_choose.is_some() && self.preview.is_none() && pressed { + mouse::Interaction::Grabbing + } else if self.on_choose.is_some() + && self.preview.is_none() + && Self::segment_at(layout, cursor).is_some() + { + mouse::Interaction::Grab + } else { + mouse::Interaction::default() + } + } +} + +impl<'a, Message: 'a> From<ToggleGroup<'a, Message>> for Element<'a, Message> { + fn from(group: ToggleGroup<'a, Message>) -> Self { + Element::new(group) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn segments_sit_side_by_side_inside_the_group() { + let at = Point::new(10.0, 20.0); + let s = segments(&[30.0, 50.0], false, at, size::TOGGLE); + assert_eq!( + s[0], + Rectangle::new(Point::new(13.0, 23.0), Size::new(54.0, 26.0)) + ); + assert_eq!(s[1].x, 13.0 + 54.0); + assert_eq!(s[1].width, 74.0); + // Homogeneous: as wide as the widest. + let s = segments(&[30.0, 50.0], true, at, size::TOGGLE); + assert_eq!((s[0].width, s[1].width), (74.0, 74.0)); + assert!(segments(&[], false, at, size::TOGGLE).is_empty()); + } + + #[test] + fn keys_move_the_choice_and_stop_at_the_ends() { + let left = Key::Named(Named::ArrowLeft); + let right = Key::Named(Named::ArrowRight); + assert_eq!(step(0, 3, &left), Some(0)); + assert_eq!(step(0, 3, &right), Some(1)); + assert_eq!(step(2, 3, &right), Some(2)); + assert_eq!(step(1, 3, &Key::Named(Named::Home)), Some(0)); + assert_eq!(step(0, 3, &Key::Named(Named::End)), Some(2)); + assert_eq!(step(0, 3, &Key::Character("a".into())), None); + assert_eq!(step(0, 0, &right), None); + } +} diff --git a/launcher/src/ui/tokens/color.rs b/launcher/src/ui/tokens/color.rs new file mode 100644 index 0000000000..c8688bcba5 --- /dev/null +++ b/launcher/src/ui/tokens/color.rs @@ -0,0 +1,898 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Colors: the roles colors play, apart from their values. The roles are the surfaces, the lines, +//! the inks text takes, `dim`, and the accents with their meanings and tints. A [`Palette`] gives +//! every role a value. +//! +//! A theme is a named look ([`ThemeName`]), and the mode, light or dark ([`Mode`]), is a switch +//! apart that applies to every theme, so each theme has a palette for each mode. Sunset is the one +//! theme here: [`Palette::SUNSET_DARK`], the default, and [`Palette::SUNSET_LIGHT`]. Its values come +//! from the logo's pixels: the gradient's stops (blue, violet, magenta, pink, coral, orange) give +//! the accents, its deep purple outline the lines, and its near-black purple shadow the dark +//! surfaces and the light palette's text. An accent keeps its stop's hue, lightened (dark) or +//! deepened (light) only as far as it must to read as text on every surface. +//! +//! Also WCAG 2.1 contrast, which the tests check for every palette. + +use std::fmt; + +/// An sRGB color with straight alpha. Only this module makes them, so every color in the launcher +/// is a token, a tint of one, or tokens painted over each other. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Color { + r: u8, + g: u8, + b: u8, + a: f32, +} + +impl Color { + pub(crate) const fn hex(rgb: u32) -> Self { + Self { + r: (rgb >> 16) as u8, + g: (rgb >> 8) as u8, + b: rgb as u8, + a: 1.0, + } + } + + /// The same color at this opacity. + pub const fn opacity(self, a: f32) -> Self { + Self { a, ..self } + } + + /// Red, green and blue. + pub const fn rgb8(self) -> [u8; 3] { + [self.r, self.g, self.b] + } + + /// The opacity, from 0 to 1. + pub const fn alpha(self) -> f32 { + self.a + } + + /// This color painted over an opaque one, blended in sRGB (as iced blends with `web-colors`). + pub fn over(self, below: Color) -> Color { + let mix = |top: u8, bottom: u8| { + (f32::from(top) * self.a + f32::from(bottom) * (1.0 - self.a)).round() as u8 + }; + Color { + r: mix(self.r, below.r), + g: mix(self.g, below.g), + b: mix(self.b, below.b), + a: 1.0, + } + } + + /// On the way from this color to `to`, `share` of the way, its opacity too: blended in sRGB, + /// as [`Color::over`] blends. + pub fn mix(self, to: Color, share: f32) -> Color { + let share = share.clamp(0.0, 1.0); + let mix = |from: u8, to: u8| { + (f32::from(from) + (f32::from(to) - f32::from(from)) * share).round() as u8 + }; + Color { + r: mix(self.r, to.r), + g: mix(self.g, to.g), + b: mix(self.b, to.b), + a: self.a + (to.a - self.a) * share, + } + } + + /// The relative luminance of WCAG 2.1, from 0 for black to 1 for white, ignoring opacity. + pub fn luminance(self) -> f64 { + let linear = |channel: u8| { + let c = f64::from(channel) / 255.0; + if c <= 0.04045 { + c / 12.92 + } else { + ((c + 0.055) / 1.055).powf(2.4) + } + }; + 0.2126 * linear(self.r) + 0.7152 * linear(self.g) + 0.0722 * linear(self.b) + } +} + +/// `#rrggbb`, and the opacity in percent after a tint's: `#3a8ede 14%`. +impl fmt::Display for Color { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "#{:02x}{:02x}{:02x}", self.r, self.g, self.b)?; + if self.a < 1.0 { + write!(f, " {}%", (self.a * 100.0).round())?; + } + Ok(()) + } +} + +/// The contrast ratio of WCAG 2.1 between two opaque colors, from 1 to 21. Paint a tint over its +/// surface first ([`Color::over`]). +pub fn contrast(a: Color, b: Color) -> f64 { + let (la, lb) = (a.luminance(), b.luminance()); + (la.max(lb) + 0.05) / (la.min(lb) + 0.05) +} + +/// The logo's own colors, as sampled from `assets/logo.png` (5×5 averages, fully opaque pixels). +pub mod logo { + use super::Color; + + /// The gradient's top: blue. + pub const BLUE: Color = Color::hex(0x036ed5); + /// Below it: violet. + pub const VIOLET: Color = Color::hex(0x984ecb); + /// The middle: magenta. + pub const MAGENTA: Color = Color::hex(0xe733ae); + /// Pink, where magenta turns to coral. + pub const PINK: Color = Color::hex(0xfa4093); + /// Coral. + pub const CORAL: Color = Color::hex(0xff5d72); + /// The bottom: orange. + pub const ORANGE: Color = Color::hex(0xfd7744); + /// The outline round the letters: deep purple. + pub const OUTLINE: Color = Color::hex(0x5c2694); + /// The shadow and the outline's inner edge: near-black purple. + pub const SHADOW: Color = Color::hex(0x1a012b); + + /// The gradient, top to bottom. + pub const GRADIENT: [Color; 6] = [BLUE, VIOLET, MAGENTA, PINK, CORAL, ORANGE]; +} + +/// The surfaces text and controls sit on. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Surface { + /// Behind windows. + Void, + /// The app background. + Bg, + /// Bars and title bars. + Panel, + /// Hovered rows and raised parts. + Raise, + /// Fields and embedded content, such as a log. + Sunk, +} + +impl Surface { + pub const ALL: [Self; 5] = [Self::Void, Self::Bg, Self::Panel, Self::Raise, Self::Sunk]; + + /// The token's name in the design language. + pub const fn name(self) -> &'static str { + match self { + Self::Void => "void", + Self::Bg => "bg", + Self::Panel => "panel", + Self::Raise => "raise", + Self::Sunk => "sunk", + } + } +} + +/// The accents. Each has one meaning, and color is never the only signal. The names are the +/// design language's roles; in Sunset, cyan is the logo's blue. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Accent { + Cyan, + Magenta, + Violet, + Mint, + Amber, + Red, + CodePink, +} + +impl Accent { + pub const ALL: [Self; 7] = [ + Self::Cyan, + Self::Magenta, + Self::Violet, + Self::Mint, + Self::Amber, + Self::Red, + Self::CodePink, + ]; + + /// The token's name in the design language. + pub const fn name(self) -> &'static str { + match self { + Self::Cyan => "cyan", + Self::Magenta => "magenta", + Self::Violet => "violet", + Self::Mint => "mint", + Self::Amber => "amber", + Self::Red => "red", + Self::CodePink => "code-pink", + } + } + + /// What the accent means, whatever its value in a palette. + pub const fn meaning(self) -> &'static str { + match self { + Self::Cyan => "Focus, links, interactive elements, the text caret", + Self::Magenta => "Selection, current item, brand", + Self::Violet => "Information, callouts, planned states", + Self::Mint => "Success, synced, done", + Self::Amber => "Warnings, conflicts", + Self::Red => "Errors, destructive actions", + Self::CodePink => "Inline code", + } + } + + const fn index(self) -> usize { + self as usize + } +} + +/// The colors text takes. In every palette each reaches WCAG's 4.5:1 for normal-size text on +/// every surface; `dim` doesn't, so it isn't one. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Ink { + /// Primary text and titles. + Text, + /// Long-form reading text. + Body, + /// Secondary text, small metadata such as counts and the status line included. + Muted, + Accent(Accent), +} + +impl Ink { + pub const ALL: [Self; 10] = [ + Self::Text, + Self::Body, + Self::Muted, + Self::Accent(Accent::Cyan), + Self::Accent(Accent::Magenta), + Self::Accent(Accent::Violet), + Self::Accent(Accent::Mint), + Self::Accent(Accent::Amber), + Self::Accent(Accent::Red), + Self::Accent(Accent::CodePink), + ]; + + /// The token's name in the design language. + pub const fn name(self) -> &'static str { + match self { + Self::Text => "text", + Self::Body => "body", + Self::Muted => "muted", + Self::Accent(accent) => accent.name(), + } + } +} + +impl From<Accent> for Ink { + fn from(accent: Accent) -> Self { + Self::Accent(accent) + } +} + +/// An accent's value: its color, and the opacities of its two tints, a soft fill for backgrounds +/// (7–15%) and a line for borders (38–45%). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Tinted { + pub color: Color, + pub soft: f32, + pub line: f32, +} + +/// A named look. Sunset, from Leonida's logo, is the one there is. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)] +pub enum ThemeName { + #[default] + Sunset, +} + +/// Light or dark, for every theme. Dark is the default. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)] +pub enum Mode { + #[default] + Dark, + Light, +} + +impl Mode { + /// The other one. + pub const fn toggled(self) -> Self { + match self { + Self::Dark => Self::Light, + Self::Light => Self::Dark, + } + } +} + +/// A value for every color role: one theme in one mode. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Palette { + pub theme: ThemeName, + pub mode: Mode, + /// What it's called: "sunset-dark". + pub name: &'static str, + void: Color, + bg: Color, + panel: Color, + raise: Color, + sunk: Color, + /// Borders. + pub line: Color, + /// Inner dividers, and a progress bar's track. + pub line_soft: Color, + text: Color, + body: Color, + muted: Color, + /// Placeholders, icons and decoration, never other text. + pub dim: Color, + /// The main action's fill: the main color as the logo has it, too bright or too dark to be + /// text on the page itself; and the ink on it. + pub main_fill: Color, + pub on_main: Color, + accents: [Tinted; 7], + /// A function's name in code. + pub code_function: Color, + pub glows: super::effect::Glows, + /// A title bar's edge tints. + pub title_bar: super::effect::EdgeTints, +} + +/// How far the veil's color goes from the background toward the logo's purple (dark) and its +/// orange (light): a tint, not a color of its own ([`Palette::veil`]). +pub const VEIL_TINT_DARK: f32 = 0.18; +pub const VEIL_TINT_LIGHT: f32 = 0.12; + +impl Palette { + /// Sunset in dark: the logo's near-black purple shadow as the app's background, surfaces a + /// step either side of it, its deep purple outline as the line. The logo's dark purple is the + /// main color (selection, the brand; the main action alone is filled orange, to stand out on + /// the purple page) and its light orange the secondary + /// (focus, what can be acted on, every glow). + pub const SUNSET_DARK: Palette = Palette { + theme: ThemeName::Sunset, + mode: Mode::Dark, + name: "sunset-dark", + void: Color::hex(0x0e0118), + bg: logo::SHADOW, + panel: Color::hex(0x210436), + raise: Color::hex(0x2c0a47), + sunk: Color::hex(0x130120), + line: logo::OUTLINE, + line_soft: Color::hex(0x3b1561), + text: Color::hex(0xf7efff), + body: Color::hex(0xe4d5f3), + muted: Color::hex(0xb9a2d2), + dim: Color::hex(0x7c5e9c), + // The main action's fill is the logo's orange itself, with the logo's shadow as its ink, so + // the one button that starts things stands out on the purple page, glowing orange too. + main_fill: logo::ORANGE, + on_main: logo::SHADOW, + // Each accent's soft and line opacities: Neon dark's, but amber's soft (8%). + accents: [ + // Cyan, the secondary: the logo's light orange, as it is. + Tinted { + color: logo::ORANGE, + soft: 0.14, + line: 0.38, + }, + // Magenta, the main: the logo's dark purple, 41% of the way to white to read as + // text and lines on the dark surfaces. + Tinted { + color: Color::hex(0x9f7fc0), + soft: 0.15, + line: 0.45, + }, + // Violet, information: the logo's blue, 22% of the way to white. + Tinted { + color: Color::hex(0x3a8ede), + soft: 0.10, + line: 0.45, + }, + // The logo has no green: success keeps a mint. + Tinted { + color: Color::hex(0x3ee0a6), + soft: 0.12, + line: 0.38, + }, + // Amber, warnings: a gold, apart from the orange. + Tinted { + color: Color::hex(0xffc643), + soft: 0.08, + line: 0.45, + }, + // Red, errors: the logo's coral, as it is. + Tinted { + color: logo::CORAL, + soft: 0.15, + line: 0.45, + }, + // Its pink, as it is. + Tinted { + color: logo::PINK, + soft: 0.10, + line: 0.40, + }, + ], + code_function: Color::hex(0xffc08a), + glows: super::effect::SUNSET_DARK, + title_bar: super::effect::SUNSET_DARK_TITLE_BAR, + }; + + /// Sunset in light: pale lavender surfaces and the logo's shadow as text. The logo's light + /// orange is the main color and its dark purple the secondary, every glow included. + pub const SUNSET_LIGHT: Palette = Palette { + theme: ThemeName::Sunset, + mode: Mode::Light, + name: "sunset-light", + void: Color::hex(0xefe5f8), + bg: Color::hex(0xfdf9ff), + panel: Color::hex(0xf6eefc), + raise: Color::hex(0xecdff7), + sunk: Color::hex(0xfaf4fe), + line: Color::hex(0xc9afe2), + line_soft: Color::hex(0xe3d3f1), + text: logo::SHADOW, + body: Color::hex(0x33104f), + muted: Color::hex(0x5e4379), + dim: Color::hex(0x9077aa), + // The main action's fill is the logo's light orange itself, with dark text on it. + main_fill: logo::ORANGE, + on_main: logo::SHADOW, + // Soft tints at 9% (violet and amber 8%, red 10%), lines at 40% (mint 35%): Neon light's. + accents: [ + // Cyan, the secondary: the logo's dark purple, as it is. + Tinted { + color: logo::OUTLINE, + soft: 0.09, + line: 0.40, + }, + // Magenta, the main: the logo's light orange, 37% of the way to black to read as + // text and lines on the light surfaces. + Tinted { + color: Color::hex(0x9f4b2b), + soft: 0.09, + line: 0.40, + }, + // Violet, information: the logo's blue, 11% of the way to black. + Tinted { + color: Color::hex(0x0362be), + soft: 0.08, + line: 0.40, + }, + Tinted { + color: Color::hex(0x1f7053), + soft: 0.09, + line: 0.35, + }, + // Amber, warnings: a deep gold, apart from the orange. + Tinted { + color: Color::hex(0x784c00), + soft: 0.08, + line: 0.40, + }, + // Red, errors: the logo's coral, 34% of the way to black. + Tinted { + color: Color::hex(0xa83d4b), + soft: 0.10, + line: 0.40, + }, + // Its pink, 28% of the way to black. + Tinted { + color: Color::hex(0xb42e6a), + soft: 0.09, + line: 0.40, + }, + ], + code_function: Color::hex(0x7f4a00), + glows: super::effect::SUNSET_LIGHT, + title_bar: super::effect::SUNSET_LIGHT_TITLE_BAR, + }; + + /// Every palette there is: the tests check each. + pub const ALL: [Palette; 2] = [Self::SUNSET_DARK, Self::SUNSET_LIGHT]; + + /// A theme's palette in a mode. + pub const fn of(theme: ThemeName, mode: Mode) -> Palette { + match (theme, mode) { + (ThemeName::Sunset, Mode::Dark) => Self::SUNSET_DARK, + (ThemeName::Sunset, Mode::Light) => Self::SUNSET_LIGHT, + } + } + + /// On the way from this palette to `to`, `share` of the way, as one mode fades into the + /// other: every color, tint and glow between the two. Which theme and mode it is, and its + /// name, are the nearer one's, and so are the accents its glows and tints take. + pub fn mixed(&self, to: &Palette, share: f32) -> Palette { + use super::effect::{EdgeTint, EdgeTints, Glow, Glows, Spark}; + let share = share.clamp(0.0, 1.0); + let nearer = if share < 0.5 { self } else { to }; + let color = |from: Color, to: Color| from.mix(to, share); + let number = |from: f32, to: f32| from + (to - from) * share; + let mut accents = self.accents; + for (tinted, to) in accents.iter_mut().zip(&to.accents) { + *tinted = Tinted { + color: color(tinted.color, to.color), + soft: number(tinted.soft, to.soft), + line: number(tinted.line, to.line), + }; + } + let glow = |from: Glow, to: Glow| Glow { + accent: if share < 0.5 { from.accent } else { to.accent }, + ring: number(from.ring, to.ring), + offset: number(from.offset, to.offset), + blur: number(from.blur, to.blur), + opacity: number(from.opacity, to.opacity), + }; + let tint = |from: EdgeTint, to: EdgeTint| EdgeTint { + accent: if share < 0.5 { from.accent } else { to.accent }, + opacity: number(from.opacity, to.opacity), + }; + Palette { + theme: nearer.theme, + mode: nearer.mode, + name: nearer.name, + void: color(self.void, to.void), + bg: color(self.bg, to.bg), + panel: color(self.panel, to.panel), + raise: color(self.raise, to.raise), + sunk: color(self.sunk, to.sunk), + line: color(self.line, to.line), + line_soft: color(self.line_soft, to.line_soft), + text: color(self.text, to.text), + body: color(self.body, to.body), + muted: color(self.muted, to.muted), + dim: color(self.dim, to.dim), + main_fill: color(self.main_fill, to.main_fill), + on_main: color(self.on_main, to.on_main), + accents, + code_function: color(self.code_function, to.code_function), + glows: Glows { + focus: glow(self.glows.focus, to.glows.focus), + selected: glow(self.glows.selected, to.glows.selected), + spark: Spark { + blur: number(self.glows.spark.blur, to.glows.spark.blur), + opacity: number(self.glows.spark.opacity, to.glows.spark.opacity), + }, + }, + title_bar: EdgeTints { + start: tint(self.title_bar.start, to.title_bar.start), + end: tint(self.title_bar.end, to.title_bar.end), + reach: number(self.title_bar.reach, to.title_bar.reach), + }, + } + } + + pub const fn surface(&self, surface: Surface) -> Color { + match surface { + Surface::Void => self.void, + Surface::Bg => self.bg, + Surface::Panel => self.panel, + Surface::Raise => self.raise, + Surface::Sunk => self.sunk, + } + } + + /// The veil over the Play page's scene: the background, tinted a little toward the logo's + /// purple in dark and its orange in light, so the scene fades into the theme's own color + /// rather than into plain background. Every text ink keeps 4.5:1 on it. + pub fn veil(&self) -> Color { + match self.mode { + Mode::Dark => self.bg.mix(logo::OUTLINE, VEIL_TINT_DARK), + Mode::Light => self.bg.mix(logo::ORANGE, VEIL_TINT_LIGHT), + } + } + + pub const fn ink(&self, ink: Ink) -> Color { + match ink { + Ink::Text => self.text, + Ink::Body => self.body, + Ink::Muted => self.muted, + Ink::Accent(accent) => self.accent(accent), + } + } + + pub const fn accent(&self, accent: Accent) -> Color { + self.accents[accent.index()].color + } + + /// An accent's opacities. + pub const fn tinted(&self, accent: Accent) -> Tinted { + self.accents[accent.index()] + } + + /// An accent's soft tint, a fill for backgrounds. + pub const fn soft(&self, accent: Accent) -> Color { + let tinted = self.tinted(accent); + tinted.color.opacity(tinted.soft) + } + + /// An accent's line tint, for borders. + pub const fn accent_line(&self, accent: Accent) -> Color { + let tinted = self.tinted(accent); + tinted.color.opacity(tinted.line) + } + + /// The theme's own gradient, as drawn pictures take it (the Play page's scene): for Sunset, + /// the logo's stops, top to bottom. + pub const fn gradient(&self) -> [Color; 6] { + match self.theme { + ThemeName::Sunset => logo::GRADIENT, + } + } + + /// The theme's outline color, as drawn pictures take it: for Sunset, the logo's deep purple. + pub const fn outline(&self) -> Color { + match self.theme { + ThemeName::Sunset => logo::OUTLINE, + } + } + + /// The theme's deepest color, as drawn pictures take it: for Sunset, the logo's shadow. + pub const fn shadow(&self) -> Color { + match self.theme { + ThemeName::Sunset => logo::SHADOW, + } + } + + /// The logo's gradient in this palette's accents, for what shows how far something is: cyan + /// (the blue), violet, magenta, then amber (the orange), each one that reads on the surfaces. + pub const fn sunset(&self) -> [Color; 2] { + match self.mode { + Mode::Dark => [self.accent(Accent::Magenta), self.accent(Accent::Cyan)], + Mode::Light => [self.accent(Accent::Cyan), self.accent(Accent::Magenta)], + } + } +} + +impl Default for Palette { + /// The default theme in the default mode: Sunset, dark. + fn default() -> Self { + Self::of(ThemeName::default(), Mode::default()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const MAIN: [Surface; 3] = [Surface::Bg, Surface::Panel, Surface::Raise]; + + fn on(palette: &Palette, color: Color, surface: Surface) -> f64 { + contrast(color, palette.surface(surface)) + } + + #[test] + fn contrast_runs_from_1_to_21() { + let black = Color::hex(0x000000); + let white = Color::hex(0xffffff); + assert_eq!(black.luminance(), 0.0); + assert!((white.luminance() - 1.0).abs() < 1e-12); + assert!((contrast(black, white) - 21.0).abs() < 1e-9); + assert_eq!(contrast(white, black), contrast(black, white)); + assert_eq!(contrast(logo::BLUE, logo::BLUE), 1.0); + } + + #[test] + fn every_ink_reads_on_every_surface() { + for palette in Palette::ALL { + for ink in Ink::ALL { + for surface in Surface::ALL { + let ratio = on(&palette, palette.ink(ink), surface); + assert!( + ratio >= 4.5, + "{}: {} on {}: {ratio:.2}", + palette.name, + ink.name(), + surface.name() + ); + } + } + } + } + + #[test] + fn every_ink_reads_on_the_veil() { + for palette in Palette::ALL { + let veil = palette.veil(); + // A tint of the background, the logo's purple in dark and its orange in light. + assert_ne!(veil, palette.surface(Surface::Bg), "{}", palette.name); + for ink in Ink::ALL { + let ratio = contrast(palette.ink(ink), veil); + assert!( + ratio >= 4.5, + "{}: {} on the veil: {ratio:.2}", + palette.name, + ink.name() + ); + } + } + } + + #[test] + fn dim_is_no_ink() { + for palette in Palette::ALL { + assert!(Ink::ALL.iter().all(|ink| palette.ink(*ink) != palette.dim)); + for surface in MAIN { + let ratio = on(&palette, palette.dim, surface); + assert!( + ratio < 4.5, + "{}: dim would pass as text on {surface:?}", + palette.name + ); + } + } + } + + #[test] + fn dim_meets_3_to_1_for_icons() { + // WCAG's 3:1 for icons and other non-text, which dim is for. + for palette in Palette::ALL { + for surface in Surface::ALL { + let ratio = on(&palette, palette.dim, surface); + assert!( + ratio >= 3.0, + "{}: dim on {}: {ratio:.2}", + palette.name, + surface.name() + ); + } + } + } + + #[test] + fn text_reads_on_every_soft_tint() { + // A selected or tinted part: text, body and muted on any accent's soft fill. + for palette in Palette::ALL { + for accent in Accent::ALL { + for surface in MAIN { + let fill = palette.soft(accent).over(palette.surface(surface)); + for ink in [Ink::Text, Ink::Body, Ink::Muted] { + let ratio = contrast(palette.ink(ink), fill); + assert!( + ratio >= 4.5, + "{}: {} on {}-soft over {}: {ratio:.2}", + palette.name, + ink.name(), + accent.name(), + surface.name() + ); + } + } + } + } + } + + #[test] + fn accents_read_on_their_own_tint_over_bg_and_panel() { + // A status chip: the accent on its own soft fill. + for palette in Palette::ALL { + for accent in Accent::ALL { + for surface in [Surface::Bg, Surface::Panel] { + let fill = palette.soft(accent).over(palette.surface(surface)); + let ratio = contrast(palette.accent(accent), fill); + assert!( + ratio >= 4.5, + "{}: {} on its tint over {}: {ratio:.2}", + palette.name, + accent.name(), + surface.name() + ); + } + } + } + } + + #[test] + fn tints_are_in_their_ranges() { + // The design language's: dark soft 7–15%, line 38–45%; light 8–10% and 35–40%. + let ranges = |mode| match mode { + Mode::Dark => (0.07..=0.15, 0.38..=0.45), + Mode::Light => (0.08..=0.10, 0.35..=0.40), + }; + for palette in Palette::ALL { + let (soft, line) = ranges(palette.mode); + for accent in Accent::ALL { + assert_eq!(palette.soft(accent).rgb8(), palette.accent(accent).rgb8()); + let (s, l) = ( + palette.soft(accent).alpha(), + palette.accent_line(accent).alpha(), + ); + assert!(soft.contains(&s), "{}: {accent:?} soft {s}", palette.name); + assert!(line.contains(&l), "{}: {accent:?} line {l}", palette.name); + } + } + let dark = Palette::SUNSET_DARK; + assert_eq!(dark.soft(Accent::Cyan).to_string(), "#fd7744 14%"); + } + + #[test] + fn code_reads_on_every_surface() { + for palette in Palette::ALL { + for surface in Surface::ALL { + let ratio = on(&palette, palette.code_function, surface); + assert!( + ratio >= 4.5, + "{}: on {}: {ratio:.2}", + palette.name, + surface.name() + ); + } + } + } + + #[test] + fn the_palettes_come_from_the_logo() { + let (dark, light) = (Palette::SUNSET_DARK, Palette::SUNSET_LIGHT); + // The shadow is dark's background and light's text; the outline is dark's line. + assert_eq!(dark.surface(Surface::Bg), logo::SHADOW); + assert_eq!(light.ink(Ink::Text), logo::SHADOW); + assert_eq!(dark.line, logo::OUTLINE); + // The two colors: in dark, purple the main and orange the secondary; in light, the other + // way round. The main action's fill is the logo's orange in both, its ink the shadow. + assert_eq!( + (dark.main_fill, light.main_fill), + (logo::ORANGE, logo::ORANGE) + ); + assert_eq!((dark.on_main, light.on_main), (logo::SHADOW, logo::SHADOW)); + assert_eq!(dark.accent(Accent::Cyan), logo::ORANGE); + assert_eq!(light.accent(Accent::Cyan), logo::OUTLINE); + // As text, the main keeps its hue: purple's blue over red, orange's red over the rest. + let [r, g, b] = dark.accent(Accent::Magenta).rgb8(); + assert!(b > r && r > g, "dark main {r} {g} {b}"); + let [r, g, b] = light.accent(Accent::Magenta).rgb8(); + assert!(r > g && g > b, "light main {r} {g} {b}"); + // The main's fill carries its ink at 4.5:1 and more. + for palette in Palette::ALL { + let ratio = contrast(palette.on_main, palette.main_fill); + assert!(ratio >= 4.5, "{}: {ratio:.2}", palette.name); + } + assert_eq!(dark.accent(Accent::Red), logo::CORAL); + assert_eq!(dark.accent(Accent::CodePink), logo::PINK); + assert_eq!(logo::GRADIENT[0], logo::BLUE); + // A running bar goes from purple to orange in both. + assert_eq!(dark.sunset(), [dark.accent(Accent::Magenta), logo::ORANGE]); + assert_eq!( + light.sunset(), + [logo::OUTLINE, light.accent(Accent::Magenta)] + ); + } + + #[test] + fn modes_choose_palettes() { + assert_eq!(Mode::Dark.toggled(), Mode::Light); + assert_eq!(Mode::Light.toggled(), Mode::Dark); + assert_eq!( + Palette::of(ThemeName::Sunset, Mode::Light), + Palette::SUNSET_LIGHT + ); + let light = Palette::SUNSET_LIGHT; + assert_eq!((light.mode, light.name), (Mode::Light, "sunset-light")); + assert_eq!(Palette::default(), Palette::SUNSET_DARK); + } + + #[test] + fn painting_blends_in_srgb() { + let bg = Palette::SUNSET_DARK.surface(Surface::Bg); + assert_eq!(logo::BLUE.over(bg), logo::BLUE); + assert_eq!(logo::BLUE.opacity(0.0).over(bg), bg); + } + + #[test] + fn roles_have_the_design_languages_names() { + let names: Vec<_> = Ink::ALL.iter().map(|ink| ink.name()).collect(); + assert_eq!( + names, + [ + "text", + "body", + "muted", + "cyan", + "magenta", + "violet", + "mint", + "amber", + "red", + "code-pink" + ] + ); + let surfaces: Vec<_> = Surface::ALL.iter().map(|s| s.name()).collect(); + assert_eq!(surfaces, ["void", "bg", "panel", "raise", "sunk"]); + assert!(Accent::ALL.iter().all(|a| !a.meaning().is_empty())); + assert_eq!(Ink::from(Accent::Mint), Ink::Accent(Accent::Mint)); + } +} diff --git a/launcher/src/ui/tokens/effect.rs b/launcher/src/ui/tokens/effect.rs new file mode 100644 index 0000000000..45a56c804c --- /dev/null +++ b/launcher/src/ui/tokens/effect.rs @@ -0,0 +1,196 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Effects: glow, and the faint tints on title bars. Light comes from interaction: glow shows +//! focus, the selected item and a primary button on hover, never resting UI. +//! +//! A glow's shape is a palette's: in dark it is a halo all round, in light a soft colored shadow +//! below ([`super::Palette::glows`]). + +use super::color::{Accent, Color, Palette}; + +/// A glow: a ring of the accent's line tint, and a blurred shadow of the accent around it. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Glow { + pub accent: Accent, + /// The ring's width, in logical pixels. + pub ring: f32, + /// How far down the shadow sits: 0 for a halo all round. + pub offset: f32, + /// The shadow's blur radius, in logical pixels. + pub blur: f32, + /// The shadow's opacity. + pub opacity: f32, +} + +impl Glow { + /// The ring's color in a palette. + pub const fn ring_color(self, palette: &Palette) -> Color { + palette.accent_line(self.accent) + } + + /// The halo's color in a palette. + pub const fn halo_color(self, palette: &Palette) -> Color { + palette.accent(self.accent).opacity(self.opacity) + } +} + +/// A palette's glows. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Glows { + /// Keyboard focus and hover, in cyan, the secondary color. Never the only sign of focus: a 2px + /// outline always shows it. + pub focus: Glow, + /// The selected item, and the main button on hover: in the secondary color too, as every glow. + pub selected: Glow, + /// The small lights, such as status dots: their accent, blurred this much. + pub spark: Spark, +} + +/// A small light's glow: its own accent, blurred. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Spark { + pub blur: f32, + pub opacity: f32, +} + +/// Sunset dark's: halos all round, Neon dark's shapes. +pub(crate) const SUNSET_DARK: Glows = Glows { + focus: Glow { + accent: Accent::Cyan, + ring: 1.0, + offset: 0.0, + blur: 22.0, + opacity: 0.16, + }, + selected: Glow { + accent: Accent::Cyan, + ring: 1.0, + offset: 0.0, + blur: 26.0, + opacity: 0.20, + }, + spark: Spark { + blur: 8.0, + opacity: 1.0, + }, +}; + +/// Sunset light's: soft colored shadows, 4px down. +pub(crate) const SUNSET_LIGHT: Glows = Glows { + focus: Glow { + accent: Accent::Cyan, + ring: 1.0, + offset: 4.0, + blur: 14.0, + opacity: 0.16, + }, + selected: Glow { + accent: Accent::Cyan, + ring: 1.0, + offset: 4.0, + blur: 14.0, + opacity: 0.16, + }, + spark: Spark { + blur: 4.0, + opacity: 0.45, + }, +}; + +/// An accent at an opacity, fading in from one edge of a bar. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct EdgeTint { + pub accent: Accent, + /// The opacity at the edge. + pub opacity: f32, +} + +impl EdgeTint { + /// The color at the edge, in a palette. + pub const fn color(self, palette: &Palette) -> Color { + palette.accent(self.accent).opacity(self.opacity) + } +} + +/// A title bar's edge tints, over its `panel`: the first accent fading from the left edge to +/// nothing, and the second from the right edge, each across `reach` of the bar's width. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct EdgeTints { + pub start: EdgeTint, + pub end: EdgeTint, + /// How far in from its edge each tint fades to nothing, as a fraction of the width. + pub reach: f32, +} + +/// Sunset dark's title bar: the main color at 12% from the left, the secondary at 8% from the +/// right. +pub(crate) const SUNSET_DARK_TITLE_BAR: EdgeTints = EdgeTints { + start: EdgeTint { + accent: Accent::Magenta, + opacity: 0.12, + }, + end: EdgeTint { + accent: Accent::Cyan, + opacity: 0.08, + }, + reach: 0.28, +}; + +/// Sunset light's: the same, fainter (6% and 5%), in light's deeper accents. +pub(crate) const SUNSET_LIGHT_TITLE_BAR: EdgeTints = EdgeTints { + start: EdgeTint { + accent: Accent::Magenta, + opacity: 0.06, + }, + end: EdgeTint { + accent: Accent::Cyan, + opacity: 0.05, + }, + reach: 0.28, +}; + +/// The brand gradient, for the brand word: the logo's blue to its magenta. +pub const BRAND: (Accent, Accent) = (Accent::Cyan, Accent::Magenta); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn glows_follow_the_design_language() { + // Dark: a 1px ring and a halo of 22–26px at 16–20%, all round. + let dark = Palette::SUNSET_DARK; + for glow in [dark.glows.focus, dark.glows.selected] { + assert_eq!((glow.ring, glow.offset), (1.0, 0.0)); + assert!((22.0..=26.0).contains(&glow.blur)); + assert!((0.16..=0.20).contains(&glow.opacity)); + assert_eq!(glow.ring_color(&dark), dark.accent_line(glow.accent)); + let halo = glow.halo_color(&dark); + assert_eq!(halo.rgb8(), dark.accent(glow.accent).rgb8()); + assert_eq!(halo.alpha(), glow.opacity); + } + // Light: the same ring, and a shadow 4px down, 14px soft, at 16%. + let light = Palette::SUNSET_LIGHT; + for glow in [light.glows.focus, light.glows.selected] { + let shape = (glow.ring, glow.offset, glow.blur, glow.opacity); + assert_eq!(shape, (1.0, 4.0, 14.0, 0.16)); + } + for palette in Palette::ALL { + assert_eq!(palette.glows.focus.accent, Accent::Cyan); + assert_eq!(palette.glows.selected.accent, Accent::Cyan); + } + } + + #[test] + fn title_bar_tints_are_faint() { + for palette in Palette::ALL { + let bar = palette.title_bar; + assert!(bar.start.opacity <= 0.12 && bar.end.opacity <= 0.10); + assert!(bar.start.opacity > 0.0 && bar.end.opacity > 0.0); + assert_eq!(bar.reach, 0.28); + let start = bar.start.color(&palette); + assert_eq!(start.rgb8(), palette.accent(bar.start.accent).rgb8()); + assert_eq!(start.alpha(), bar.start.opacity); + } + } +} diff --git a/launcher/src/ui/tokens/mod.rs b/launcher/src/ui/tokens/mod.rs new file mode 100644 index 0000000000..efbba0ea20 --- /dev/null +++ b/launcher/src/ui/tokens/mod.rs @@ -0,0 +1,186 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! The design tokens: colors, type, spacing, shape, motion and effects, as plain data with no +//! dependencies. They're the only source of colors, sizes and durations for the launcher's +//! widgets. +//! +//! Colors are roles, and a [`Palette`] gives each a value: [`Palette::SUNSET_DARK`] and +//! [`Palette::SUNSET_LIGHT`], from Leonida's logo. +//! +//! Text takes an [`Ink`], and `dim` isn't one: it's for placeholders, icons and decoration only, +//! as it falls below WCAG's 4.5:1 for normal-size text. The tests check the contrast of every ink +//! on every surface. + +pub mod color; +pub mod effect; +pub mod motion; +pub mod typography; + +pub use color::{Accent, Color, Ink, Mode, Palette, Surface, ThemeName}; +pub use typography::{Face, Family, Role, Slant}; + +/// The spacing scale for padding and gaps, in logical pixels. +pub mod space { + pub const XXS: f32 = 2.0; + pub const XS: f32 = 4.0; + pub const S: f32 = 6.0; + pub const M: f32 = 8.0; + pub const L: f32 = 12.0; + pub const XL: f32 = 16.0; + pub const XXL: f32 = 24.0; + pub const XXXL: f32 = 32.0; + + /// The whole scale, smallest first. + pub const SCALE: [f32; 8] = [XXS, XS, S, M, L, XL, XXL, XXXL]; +} + +/// Standard sizes, in logical pixels. +pub mod size { + /// A loader's ring, across: small, the default and large; and its line. + pub const LOADER_SMALL: f32 = 24.0; + pub const LOADER: f32 = 36.0; + pub const LOADER_LARGE: f32 = 48.0; + pub const LOADER_RING: f32 = 2.0; + /// A window's title bar. + pub const TITLE_BAR: f32 = 47.0; + /// Buttons and text fields. + pub const CONTROL: f32 = 36.0; + /// A toggle group's pill: a little lower than a control, so it fits a header bar. + pub const TOGGLE: f32 = 32.0; + /// A status chip's dot. + pub const DOT: f32 = 6.0; + /// A progress bar's thickness. + pub const PROGRESS: f32 = 6.0; + /// Every border: 1px everywhere. + pub const BORDER: f32 = 1.0; + /// The keyboard focus outline, always shown with focus (glow is never the only sign), and its + /// gap from what it outlines. + pub const FOCUS_OUTLINE: f32 = 2.0; + pub const FOCUS_OFFSET: f32 = 2.0; + /// A line icon. + pub const ICON: f32 = 16.0; + /// An icon's stroke, with round caps and joins. + pub const ICON_STROKE: f32 = 1.4; + /// Room round a toggle group's segments inside it. + pub const SEGMENT_INSET: f32 = 3.0; + /// The text caret's width. + pub const CARET: f32 = 2.0; + /// A list or table row. + pub const ROW: f32 = 28.0; + /// A sidebar's row: taller than a list's. + pub const SIDEBAR_ROW: f32 = 36.0; + /// The mark at the chosen sidebar row's start: a pill this wide, set in from the row's start + /// as far as from its top and bottom. + pub const SIDEBAR_MARK: f32 = 4.0; + pub const SIDEBAR_MARK_INSET: f32 = 8.0; + /// A switch's track: a pill, its knob inside it. + pub const SWITCH_WIDTH: f32 = 40.0; + pub const SWITCH_HEIGHT: f32 = 22.0; + /// A checkbox's box and a choice's radio circle. + pub const CHECK: f32 = 16.0; + /// The least a flow's filling child, such as a setting's words, is beside the others: + /// narrower, they go one under another. + pub const FLOW_LEAST: f32 = 160.0; + /// How far a press may move and still be a press: further, it's a drag, such as a finger + /// scrolling the page from a button. + pub const SLIP: f32 = super::space::S; +} + +/// Corner radii, in logical pixels. +pub mod radius { + /// A checkbox's box. + pub const CHECK: f32 = 4.0; + /// Chips and key caps (4–6px). + pub const CHIP: f32 = 6.0; + /// Controls and cards (8–10px). + pub const CONTROL: f32 = 10.0; + /// Buttons, toggle groups and window buttons. + pub const BUTTON: f32 = 8.0; + /// A toggle group's segment: a button's, its group's, less the room round it. + pub const SEGMENT: f32 = BUTTON - super::size::SEGMENT_INSET; + /// Windows (12–14px). + pub const WINDOW: f32 = 14.0; + /// Round ends: status chips, progress bars, dots. Larger than anything it rounds. + pub const ROUND: f32 = 999.0; +} + +/// A window's own decorations: the launcher draws them itself (client-side), the same on every +/// desktop. The header bar, its close button, the frame and the zones that resize the window. +pub mod window { + /// The header bar's height, its bottom line included. + pub const BAR_HEIGHT: f32 = super::size::TITLE_BAR; + /// Room round a sidebar's places, at its sides. + pub const SIDEBAR_PAD: f32 = super::space::S; + /// Room before the bar's first item: as far in as a sidebar's words start, so the app's name + /// lines up with them. + pub const BAR_PAD_START: f32 = + SIDEBAR_PAD + 2.0 * super::size::SIDEBAR_MARK_INSET + super::size::SIDEBAR_MARK; + /// A sidebar beside the page: always this wide. + pub const SIDEBAR_WIDTH: f32 = 240.0; + /// Narrower than this, in logical pixels, a window is as a phone's: its sidebar folds, + /// showing the sidebar or the page, and the page's header bar a way back. + pub const FOLD_BELOW: f32 = 640.0; + /// Between the bar's items. + pub const BAR_GAP: f32 = 14.0; + /// A window button: close, the only one. Square, and as tall as everything on the bar. + pub const BUTTON_SIZE: f32 = 32.0; + /// The close button's room on each side: above and below it in the bar, and from the + /// window's edge. + pub const BUTTON_MARGIN: f32 = (BAR_HEIGHT - super::size::BORDER - BUTTON_SIZE) / 2.0; + /// Room after the bar's last item: the close button's margin. + pub const BAR_PAD_END: f32 = BUTTON_MARGIN; + /// A window button's corners: a button's. + pub const BUTTON_RADIUS: f32 = super::radius::BUTTON; + /// The close button's cross, in its 16px icon box, in the icon stroke. Each stroke + /// `[x0, y0, x1, y1]`. + pub const CLOSE_CROSS: [[f32; 4]; 2] = [[3.7, 3.7, 12.3, 12.3], [12.3, 3.7, 3.7, 12.3]]; + /// The back button's chevron, pointing left, in the same box and stroke. + pub const BACK_CHEVRON: [[f32; 4]; 2] = [[10.0, 3.5, 5.5, 8.0], [5.5, 8.0, 10.0, 12.5]]; + /// The frame's corners while the window floats; maximized it's square. + pub const CORNER_RADIUS: f32 = super::radius::WINDOW; + /// The frame's line, while it floats. + pub const BORDER: f32 = super::size::BORDER; + /// The zones that resize a floating window: a band this wide inside each edge, and at each + /// corner a zone reaching this far along both edges. + pub const RESIZE_BAND: f32 = 6.0; + pub const RESIZE_CORNER: f32 = 14.0; + /// How far the pointer moves with the button held on the header bar before the window + /// moves with it, so a double-click doesn't start a move. + pub const DRAG_THRESHOLD: f32 = 4.0; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_spacing_scale_grows() { + assert!(space::SCALE.windows(2).all(|pair| pair[0] < pair[1])); + } + + #[test] + fn radii_are_in_the_design_languages_ranges() { + assert!((4.0..=6.0).contains(&radius::CHIP)); + assert!((8.0..=10.0).contains(&radius::CONTROL)); + assert!((12.0..=14.0).contains(&radius::WINDOW)); + } + + #[test] + fn the_window_decorations() { + assert_eq!(window::BAR_HEIGHT, 47.0); + assert_eq!((window::BUTTON_MARGIN, window::BAR_PAD_END), (7.0, 7.0)); + assert_eq!((window::BUTTON_SIZE, window::BUTTON_RADIUS), (32.0, 8.0)); + assert_eq!((window::CORNER_RADIUS, window::BORDER), (14.0, 1.0)); + const { assert!(window::RESIZE_CORNER > window::RESIZE_BAND) }; + const { assert!(window::RESIZE_CORNER >= window::CORNER_RADIUS) }; + for stroke in window::CLOSE_CROSS { + for c in stroke { + assert!((0.0..=size::ICON).contains(&c)); + } + } + // The close button sits inside the rounded corner's arc, so the corner needs no clipping. + let corner = window::CORNER_RADIUS; + let from_center = ((corner - window::BUTTON_MARGIN).powi(2) * 2.0).sqrt(); + assert!(from_center < corner); + } +} diff --git a/launcher/src/ui/tokens/motion.rs b/launcher/src/ui/tokens/motion.rs new file mode 100644 index 0000000000..ce2140d2f9 --- /dev/null +++ b/launcher/src/ui/tokens/motion.rs @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Motion: short and decisive, 150–400ms on one easing curve, and nothing looping at idle but +//! what shows that work is under way. + +use std::time::Duration; + +/// Small changes: a hover, a press, a fade. +pub const FAST: Duration = Duration::from_millis(150); +/// Most transitions: focus and selection. +pub const NORMAL: Duration = Duration::from_millis(200); +/// Large movements. +pub const SLOW: Duration = Duration::from_millis(400); + +/// A glow coming, as the pointer or focus arrives: slower than a hover's other changes, so light +/// gathers rather than switches on. The one place to tune every fading glow. +pub const GLOW_IN: Duration = Duration::from_millis(500); +/// A glow going, as the pointer or focus leaves: slower still, an afterglow. +pub const GLOW_OUT: Duration = Duration::from_millis(700); +/// The Play page's scene appearing once it's made, from nothing to whole. +pub const SCENE_IN: Duration = Duration::from_millis(500); + +/// The text caret's blink: shown this long, then hidden this long. +pub const CARET_BLINK: Duration = Duration::from_millis(500); +/// The caret blinks only this long after the last input, then stays shown, so nothing draws at +/// idle. +pub const CARET_BLINKS_FOR: Duration = Duration::from_secs(10); +/// An app draws nothing this long after the last input, unless work is under way. +pub const IDLE: Duration = Duration::from_secs(12); + +/// A CSS `cubic-bezier()` easing curve, from (0, 0) to (1, 1) through two control points. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct CubicBezier { + pub x1: f32, + pub y1: f32, + pub x2: f32, + pub y2: f32, +} + +impl CubicBezier { + /// How far along the motion is at `t`, the share of its time gone, both from 0 to 1: the + /// curve's y where its x is `t`, as CSS works it out. + pub fn at(self, t: f32) -> f32 { + let t = t.clamp(0.0, 1.0); + // One axis of the curve, its ends at 0 and 1: at s, and its slope. + let axis = |p1: f32, p2: f32, s: f32| { + let u = 1.0 - s; + 3.0 * u * u * s * p1 + 3.0 * u * s * s * p2 + s * s * s + }; + let slope = |p1: f32, p2: f32, s: f32| { + let u = 1.0 - s; + 3.0 * u * u * p1 + 6.0 * u * s * (p2 - p1) + 3.0 * s * s * (1.0 - p2) + }; + // The s whose x is t: Newton's method, and halving where it stalls. + let mut s = t; + for _ in 0..8 { + let error = axis(self.x1, self.x2, s) - t; + let d = slope(self.x1, self.x2, s); + if error.abs() < 1e-5 || d.abs() < 1e-6 { + break; + } + s = (s - error / d).clamp(0.0, 1.0); + } + if (axis(self.x1, self.x2, s) - t).abs() > 1e-4 { + let (mut low, mut high) = (0.0_f32, 1.0_f32); + for _ in 0..30 { + s = (low + high) / 2.0; + if axis(self.x1, self.x2, s) < t { + low = s; + } else { + high = s; + } + } + } + axis(self.y1, self.y2, s) + } +} + +/// `cubic-bezier(.2, .7, .2, 1)`: quick to start, gentle to settle. +pub const EASE: CubicBezier = CubicBezier { + x1: 0.2, + y1: 0.7, + x2: 0.2, + y2: 1.0, +}; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn durations_are_short_and_decisive() { + for duration in [FAST, NORMAL, SLOW] { + assert!((150..=400).contains(&duration.as_millis()), "{duration:?}"); + } + assert!(FAST < NORMAL && NORMAL < SLOW); + } + + #[test] + fn the_caret_stops_blinking_well_before_idle() { + assert!(CARET_BLINKS_FOR + CARET_BLINK < IDLE); + } + + #[test] + fn the_curve_runs_from_start_to_end_and_never_back() { + assert!(EASE.at(0.0).abs() < 1e-4); + assert!((EASE.at(1.0) - 1.0).abs() < 1e-4); + let mut last = 0.0; + for step in 1..=100 { + let y = EASE.at(step as f32 / 100.0); + assert!(y >= last - 1e-5, "{step}: {y} after {last}"); + last = y; + } + // Quick to start: well past halfway at a quarter of the time. + assert!(EASE.at(0.25) > 0.5, "{}", EASE.at(0.25)); + let linear = CubicBezier { + x1: 0.25, + y1: 0.25, + x2: 0.75, + y2: 0.75, + }; + assert!((linear.at(0.3) - 0.3).abs() < 1e-3); + } +} diff --git a/launcher/src/ui/tokens/typography.rs b/launcher/src/ui/tokens/typography.rs new file mode 100644 index 0000000000..4277e7d3d6 --- /dev/null +++ b/launcher/src/ui/tokens/typography.rs @@ -0,0 +1,163 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Type: three font families, the faces the launcher ships, and the roles text takes. +//! +//! Chakra Petch is the display face, for titles and spaced-out uppercase labels; IBM Plex Sans is +//! for interface text; JetBrains Mono for metadata, paths, status and the log. + +/// A font family. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Family { + Display, + Body, + Mono, +} + +impl Family { + /// The family's name, as the fonts give it. + pub const fn name(self) -> &'static str { + match self { + Self::Display => "Chakra Petch", + Self::Body => "IBM Plex Sans", + Self::Mono => "JetBrains Mono", + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Slant { + Upright, +} + +/// One font file: a family at a weight and slant. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct Face { + pub family: Family, + /// From 100 to 900, as in CSS: 400 is regular, 600 semibold. + pub weight: u16, + pub slant: Slant, +} + +impl Face { + /// The face's file in `launcher/fonts`; `None` for a face the launcher doesn't ship. + pub const fn file(self) -> Option<&'static str> { + Some(match (self.family, self.weight, self.slant) { + (Family::Display, 600, Slant::Upright) => "ChakraPetch-SemiBold.ttf", + (Family::Display, 700, Slant::Upright) => "ChakraPetch-Bold.ttf", + (Family::Body, 400, Slant::Upright) => "IBMPlexSans-Regular.ttf", + (Family::Mono, 400, Slant::Upright) => "JetBrainsMono-Regular.ttf", + _ => return None, + }) + } + + const fn upright(family: Family, weight: u16) -> Self { + Self { + family, + weight, + slant: Slant::Upright, + } + } +} + +/// The faces the launcher ships, and so the only ones text may use. +pub const FACES: [Face; 4] = [ + Face::upright(Family::Display, 600), + Face::upright(Family::Display, 700), + Face::upright(Family::Body, 400), + Face::upright(Family::Mono, 400), +]; + +/// A role text plays, with how it is set. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Role { + pub name: &'static str, + pub face: Face, + /// In logical pixels. + pub size: f32, + /// A multiple of the size. + pub line_height: f32, + /// Extra space after each letter, in ems. + pub letter_spacing: f32, + /// Set in capitals, whatever the text's case. + pub uppercase: bool, +} + +impl Role { + const fn new(name: &'static str, face: Face, size: f32, line_height: f32) -> Self { + Self { + name, + face, + size, + line_height, + letter_spacing: 0.0, + uppercase: false, + } + } + + /// The extra space after each letter, in logical pixels. + pub fn letter_spacing_px(&self) -> f32 { + self.letter_spacing * self.size + } +} + +/// Page and window titles. +pub const TITLE: Role = Role::new("title", Face::upright(Family::Display, 600), 34.0, 1.15); +/// Section headings. +pub const HEADING: Role = Role::new("heading", Face::upright(Family::Display, 600), 21.0, 1.3); +/// Small uppercase labels, spaced out: section names, eyebrows. +pub const LABEL: Role = Role { + letter_spacing: 0.14, + uppercase: true, + ..Role::new("label", Face::upright(Family::Display, 600), 11.0, 1.3) +}; +/// An app's name in its header bar: the display face, bold, a step larger than a label and more +/// spaced. +pub const BRAND: Role = Role { + letter_spacing: 0.24, + uppercase: true, + ..Role::new("brand", Face::upright(Family::Display, 700), 13.0, 1.3) +}; +/// Interface text: controls, lists, messages. The default. +pub const INTERFACE: Role = Role::new("interface", Face::upright(Family::Body, 400), 14.0, 1.3); +/// Metadata, counts, paths and the status line. +pub const META: Role = Role::new("meta", Face::upright(Family::Mono, 400), 11.0, 1.3); + +pub const ROLES: [Role; 6] = [TITLE, HEADING, LABEL, BRAND, INTERFACE, META]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_role_uses_a_shipped_face() { + for role in ROLES { + assert!(FACES.contains(&role.face), "{}", role.name); + } + } + + #[test] + fn every_shipped_face_has_a_file_of_its_own() { + let files: Vec<_> = FACES.iter().map(|face| face.file().unwrap()).collect(); + for (at, file) in files.iter().enumerate() { + assert!(!files[..at].contains(file), "{file}"); + } + assert_eq!(Face::upright(Family::Body, 700).file(), None); + } + + #[test] + fn labels_are_spaced_out_capitals() { + let capitals: Vec<_> = ROLES.iter().filter(|r| r.uppercase).collect(); + assert_eq!(capitals, [&LABEL, &BRAND]); + assert!((LABEL.letter_spacing_px() - 1.54).abs() < 1e-6); + const { assert!(BRAND.size > LABEL.size && BRAND.face.weight > LABEL.face.weight) }; + } + + #[test] + fn sizes_from_the_design_language() { + assert_eq!(TITLE.size, 34.0); + assert_eq!(HEADING.size, 21.0); + assert_eq!(LABEL.size, 11.0); + assert_eq!(INTERFACE.size, 14.0); + assert_eq!(META.face.family, Family::Mono); + } +} diff --git a/launcher/src/ui/transition.rs b/launcher/src/ui/transition.rs new file mode 100644 index 0000000000..7a94bfc9b8 --- /dev/null +++ b/launcher/src/ui/transition.rs @@ -0,0 +1,204 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Something on its way from where it is to where it's going, on the design language's curve: a checkbox's +//! mark fading in, a switch's knob sliding across, a dialog coming up, a page sliding in. +//! +//! Turned back part of the way, it goes back from where it is. Starting again from where it would +//! be had it begun at the far end jumps: the design language's curve is quick to start and slow to settle, so +//! a quarter of the time in is three quarters of the way, and the same time back is hardly any. + +use std::time::{Duration, Instant}; + +use crate::ui::tokens::motion; +use iced::Rectangle; +use iced::advanced::Shell; + +/// A value on its way from one place to another: a share, from 0 to 1, or anywhere between. +#[derive(Debug, Clone, Copy, PartialEq)] +pub(crate) struct Transition { + from: f32, + to: f32, + /// How long it takes: the whole way, from 0 to 1, the time it was given, less of the way as + /// much less. + takes: Duration, + /// When it started: the first frame drawn after it was asked for. + start: Option<Instant>, + /// Where it was at the last frame. + at: f32, +} + +impl Transition { + /// From `from` to `to`, the whole way from 0 to 1 taking `whole`; none with motion reduced, + /// or when it's already there, as it's then where it's going at once. + pub fn start(from: f32, to: f32, whole: Duration) -> Option<Self> { + (from != to && !crate::ui::system::reduced_motion()) + .then(|| Self::new(from, to, crate::ui::system::duration(whole))) + } + + fn new(from: f32, to: f32, whole: Duration) -> Self { + Self { + from, + to, + takes: whole.mul_f32((to - from).abs().min(1.0)), + start: None, + at: from, + } + } + + /// Where it is, as of the last frame. + pub fn at(&self) -> f32 { + self.at + } + + /// A frame at `now`: where it is then, and whether it's still on its way. + pub fn frame(&mut self, now: Instant) -> bool { + let start = *self.start.get_or_insert(now); + let t = if self.takes.is_zero() { + 1.0 + } else { + now.saturating_duration_since(start).as_secs_f32() / self.takes.as_secs_f32() + }; + if t >= 1.0 { + self.at = self.to; + false + } else { + self.at = self.from + (self.to - self.from) * motion::EASE.at(t); + true + } + } + + /// At a frame, the transition in `slot` moves on: the next frame's asked for while it's on + /// its way, and it's gone once it's there. + pub fn advance<Message>(slot: &mut Option<Self>, now: Instant, shell: &mut Shell<'_, Message>) { + if let Some(transition) = slot { + if transition.frame(now) { + shell.request_redraw(); + } else { + *slot = None; + } + } + } + + /// Turns what's in `slot` toward `to`, from where it's got to, or, if nothing's moving, from + /// `was`, and asks for a frame. Nothing moves with motion reduced: it's at `to` at once. + pub fn turn<Message>( + slot: &mut Option<Self>, + was: f32, + to: f32, + whole: Duration, + shell: &mut Shell<'_, Message>, + ) { + let from = slot.map_or(was, |transition| transition.at); + *slot = Self::start(from, to, whole); + shell.request_redraw(); + } +} + +/// A control's glow coming and going: under the pointer or with focus it fades in over +/// [`motion::GLOW_IN`], and out over [`motion::GLOW_OUT`], so light comes from interaction without +/// a jump. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub(crate) struct Lit { + /// How lit it is, from 0 to 1, as of the last frame. + share: f32, + /// Whether it's going to be lit, once it has been told. + aim: Option<bool>, + fade: Option<Transition>, +} + +impl Lit { + /// It should be lit, or not: it fades there from where it is. + pub fn aim<Message>(&mut self, lit: bool, shell: &mut Shell<'_, Message>) { + if self.aim == Some(lit) { + return; + } + let to = f32::from(u8::from(lit)); + if self.aim.is_none() { + // Its first look: as it is, no fade. + self.share = to; + } else { + let whole = if lit { + motion::GLOW_IN + } else { + motion::GLOW_OUT + }; + Transition::turn(&mut self.fade, self.share, to, whole, shell); + if self.fade.is_none() { + self.share = to; + } + } + self.aim = Some(lit); + } + + /// A frame: where the fade is, asking for the next while it's on its way. + pub fn frame<Message>(&mut self, event: &iced::Event, shell: &mut Shell<'_, Message>) { + if let iced::Event::Window(iced::window::Event::RedrawRequested(now)) = event { + Transition::advance(&mut self.fade, *now, shell); + self.share = match &self.fade { + Some(fade) => fade.at(), + None => f32::from(u8::from(self.aim.unwrap_or(false))), + }; + } + } + + /// How lit it is: 0 to 1. + pub fn share(&self) -> f32 { + self.share + } +} + +/// How far into a cycle `now` is, from 0 to 1, cycles having begun at `start`. In whole +/// microseconds, so it's as smooth after a week as after a second: a second's fraction in an +/// `f32` loses its smoothness after a few days. +pub(crate) fn phase(start: Instant, now: Instant, cycle: Duration) -> f32 { + let into = now.saturating_duration_since(start).as_micros() % cycle.as_micros().max(1); + into as f32 / cycle.as_micros().max(1) as f32 +} + +/// Whether something animating forever should ask for its next frame: not with motion reduced, +/// nor while it's out of sight, scrolled away; scrolled back, the redraws that scrolling it +/// brings bring it back to life. +pub(crate) fn wants_frames(bounds: Rectangle, viewport: &Rectangle) -> bool { + !crate::ui::system::reduced_motion() && bounds.intersects(viewport) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_eases_there_and_stops() { + let mut transition = Transition::new(0.0, 1.0, motion::FAST); + let start = Instant::now(); + assert!(transition.frame(start)); + assert_eq!(transition.at(), 0.0); + assert!(transition.frame(start + motion::FAST / 2)); + let mid = transition.at(); + assert!(mid > 0.5 && mid < 1.0, "quick to start: {mid}"); + assert!(!transition.frame(start + motion::FAST)); + assert_eq!(transition.at(), 1.0); + } + + #[test] + fn turned_back_it_goes_back_from_where_it_is() { + let mut slot = Some(Transition::new(0.0, 1.0, motion::SLOW)); + let start = Instant::now(); + let mut messages: Vec<()> = Vec::new(); + let mut shell = Shell::new(&mut messages); + Transition::advance(&mut slot, start, &mut shell); + Transition::advance(&mut slot, start + motion::SLOW / 4, &mut shell); + let there = slot.unwrap().at(); + assert!( + there > 0.6, + "a quarter of the time is most of the way: {there}" + ); + Transition::turn(&mut slot, 1.0, 0.0, motion::SLOW, &mut shell); + let mut back = slot.unwrap(); + let again = start + motion::SLOW / 4; + assert!(back.frame(again)); + assert_eq!(back.at(), there, "no jump"); + // Less of the way takes as much less time. + assert!(!back.frame(again + motion::SLOW.mul_f32(there))); + assert_eq!(back.at(), 0.0); + } +} diff --git a/launcher/src/ui/window.rs b/launcher/src/ui/window.rs new file mode 100644 index 0000000000..ae7a6b8fd5 --- /dev/null +++ b/launcher/src/ui/window.rs @@ -0,0 +1,573 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! The launcher's window: its own decorations ([`crate::ui::chrome`]), as the window runs +//! them: the window's state, what its header bar, sidebar, frame and events say, and what's done +//! about it. + +use std::ffi::OsStr; + +use iced::time::Instant; +use iced::{Color, Event, Size, Subscription, Task, window}; + +use crate::ui::chrome::{Corners, Edge, Header, header_bar, window_frame}; +use crate::ui::theme::Frame; +use crate::ui::tokens::{Surface, space, window as decorations}; +use crate::ui::widget::{Row, Space, container}; +use crate::ui::{Element, Fill, Theme, scroll_area}; +use iced::theme::{self, Base}; + +/// The environment variable that says who draws the window's frame. +pub const FRAME_VARIABLE: &str = "LEONIDA_WINDOW_FRAME"; + +/// Who draws the window's frame, as [`FRAME_VARIABLE`] says. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum FrameSetting { + /// The launcher draws it: rounded corners and a line while the window floats. + #[default] + Drawn, + /// Nobody: an opaque, square window, for a desktop that draws its own corners and border, or + /// a driver that misbehaves with a transparent window. + Off, +} + +impl FrameSetting { + /// The setting a value of [`FRAME_VARIABLE`] gives: unset or `1` draws the frame, `0` doesn't, + /// and anything else is as unset, with the line to say once on stderr. + pub fn parse(value: Option<&OsStr>) -> (Self, Option<String>) { + match value.map(|value| value.to_str()) { + None => (Self::Drawn, None), + Some(Some("1")) => (Self::Drawn, None), + Some(Some("0")) => (Self::Off, None), + Some(other) => ( + Self::Drawn, + Some(format!( + "{FRAME_VARIABLE}={} isn't 0 or 1: the launcher draws its frame", + other.unwrap_or("(not text)") + )), + ), + } + } + + /// The setting from the environment, saying on stderr what it doesn't understand. + pub fn from_env() -> Self { + let (setting, warning) = Self::parse(std::env::var_os(FRAME_VARIABLE).as_deref()); + if let Some(warning) = warning { + eprintln!("leonida-launcher: {warning}"); + } + setting + } +} + +/// The system the window opens on, as far as its frame goes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Platform { + /// Windows: no transparent window with stock iced, but Windows 11 rounds a window that asks. + Windows, + /// Linux (Wayland and X11) and the rest: a transparent window the launcher rounds itself. + Other, +} + +impl Platform { + /// The one it's built for. + pub const fn current() -> Self { + if cfg!(windows) { + Self::Windows + } else { + Self::Other + } + } +} + +/// Whether the window is transparent: when the launcher draws its frame's corners itself. +pub fn transparent(platform: Platform, frame: FrameSetting) -> bool { + frame == FrameSetting::Drawn && platform == Platform::Other +} + +/// The window's corners: drawn by the launcher on a transparent window, the system's on Windows, +/// and square while maximized, full-screen, or with the frame off. +pub fn corners(platform: Platform, frame: FrameSetting, floating: bool) -> Corners { + match (frame, floating, platform) { + (FrameSetting::Off, ..) | (_, false, _) => Corners::Square, + (FrameSetting::Drawn, true, Platform::Other) => Corners::Drawn, + (FrameSetting::Drawn, true, Platform::Windows) => Corners::System, + } +} + +/// The window's settings when it opens: without the system's decorations, as the launcher draws +/// its own; transparent where it rounds its corners itself; on Windows, asking for Windows 11's +/// rounded corners unless the frame is off. +pub fn settings(size: Size, min: Size, frame: FrameSetting) -> window::Settings { + let platform = Platform::current(); + window::Settings { + size, + min_size: Some(min), + decorations: false, + transparent: transparent(platform, frame), + platform_specific: platform_specific(frame), + ..window::Settings::default() + } +} + +#[cfg(windows)] +fn platform_specific(frame: FrameSetting) -> window::settings::PlatformSpecific { + use window::settings::platform::CornerPreference; + window::settings::PlatformSpecific { + corner_preference: match frame { + FrameSetting::Drawn => CornerPreference::Round, + FrameSetting::Off => CornerPreference::DoNotRound, + }, + undecorated_shadow: true, + ..window::settings::PlatformSpecific::default() + } +} + +#[cfg(not(windows))] +fn platform_specific(_frame: FrameSetting) -> window::settings::PlatformSpecific { + window::settings::PlatformSpecific::default() +} + +/// A window's state, as its decorations need it. +#[derive(Debug, Clone, PartialEq)] +pub struct Chrome { + frame: FrameSetting, + platform: Platform, + id: Option<window::Id>, + maximized: bool, + fullscreen: bool, + focused: bool, + /// Its size, in logical pixels. + size: Size, + /// What a folded window shows: its sidebar or its page. + pane: Pane, + /// The theme it's fading from, after the app's changed. + fade: Option<Fade>, +} + +/// A fade from one theme into the app's: from what showed when it changed, over +/// [`THEME_FADE`]. +#[derive(Debug, Clone, Copy, PartialEq)] +struct Fade { + from: Theme, + start: Instant, + /// The frame it's at. + at: Instant, +} + +/// How long one theme takes to fade into another. +pub const THEME_FADE: std::time::Duration = crate::ui::tokens::motion::SLOW; + +impl Fade { + /// How far into the new theme it is, eased. + fn share(&self) -> f32 { + let fade = crate::ui::system::duration(THEME_FADE); + let t = self.at.saturating_duration_since(self.start).as_secs_f32() / fade.as_secs_f32(); + crate::ui::tokens::motion::EASE.at(t.clamp(0.0, 1.0)) + } +} + +/// What a folded window shows ([`Chrome::folded`]). It starts on the sidebar. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Pane { + #[default] + Sidebar, + Page, +} + +/// What a window's decorations and its events say. +#[derive(Debug, Clone, PartialEq)] +pub enum ChromeMessage { + /// The header bar's empty area was dragged: the window moves with the pointer. + Drag, + /// The header bar's empty area was double-clicked: the window maximizes, or restores. + ToggleMaximize, + /// The close button was pressed. + Close, + /// A resize zone was pressed. + Resize(Edge), + /// The window opened, or was found. + Opened(window::Id), + /// The window gained focus, or lost it. + Focused(window::Id, bool), + /// The window opened at this size, or changed to it. + Resized(window::Id, Size), + /// A folded window's back button was pressed: from the page back to the sidebar. + Back, + /// Whether the window is maximized now. + Maximized(bool), + /// The window's mode now: full-screen or not. + Mode(window::Mode), + /// A frame, while a theme fades in. + Frame(Instant), +} + +impl Chrome { + /// A window's, before it opens: focused and floating. + pub fn new(size: Size, frame: FrameSetting) -> Self { + Self::on(Platform::current(), size, frame) + } + + /// The same, on a platform: for the tests. + pub fn on(platform: Platform, size: Size, frame: FrameSetting) -> Self { + Self { + frame, + platform, + id: None, + maximized: false, + fullscreen: false, + focused: true, + size, + pane: Pane::default(), + fade: None, + } + } + + /// While the theme fades: the one it fades from and how far into the new one it is. + pub fn theme_fade(&self) -> Option<(Theme, f32)> { + self.fade.map(|fade| (fade.from, fade.share())) + } + + /// The theme to draw in: the app's, `theme`, or while it fades in, on the way to it. + pub fn theme(&self, theme: Theme) -> Theme { + match &self.fade { + Some(fade) => fade.from.mixed(&theme, fade.share()), + None => theme, + } + } + + /// The app's theme changed from `before`, `now`: it fades in from what shows, unless motion + /// is reduced (`LEONIDA_REDUCE_MOTION`). + pub fn theme_changed(&mut self, before: Theme, now: Instant) { + self.fade = (!crate::ui::system::reduced_motion()).then(|| Fade { + from: self.theme(before), + start: now, + at: now, + }); + } + + /// Whether a theme is fading in: it wants every frame till it's done. + pub fn is_fading(&self) -> bool { + self.fade.is_some() + } + + /// Its size, in logical pixels. + pub fn size(&self) -> Size { + self.size + } + + /// Whether a window with a sidebar folds: narrower than [`decorations::FOLD_BELOW`]. + pub fn folded(&self) -> bool { + self.size.width < decorations::FOLD_BELOW + } + + /// What a folded window shows. + pub fn pane(&self) -> Pane { + self.pane + } + + /// Its size changed to this, as its events say; or, drawing it without a window, as in a + /// screenshot test, the size it's drawn at. + pub fn resize(&mut self, size: Size) { + self.size = size; + } + + /// A place was chosen: a folded window shows its page. + pub fn show_page(&mut self) { + self.pane = Pane::Page; + } + + /// Whether the window is transparent, for the launcher to draw its rounded corners. + pub fn transparent(&self) -> bool { + transparent(self.platform, self.frame) + } + + /// Whether it floats: not maximized or full-screen. + pub fn floating(&self) -> bool { + !(self.maximized || self.fullscreen) + } + + /// Its corners now. + pub fn corners(&self) -> Corners { + corners(self.platform, self.frame, self.floating()) + } + + /// Whether its edges resize it: while it floats. + pub fn resizable(&self) -> bool { + self.floating() + } + + pub fn is_maximized(&self) -> bool { + self.maximized + } + + pub fn is_focused(&self) -> bool { + self.focused + } + + /// What the window learns at start: its ID, once it has opened. + pub fn boot() -> Task<ChromeMessage> { + window::oldest().and_then(|id| Task::done(ChromeMessage::Opened(id))) + } + + /// The window events the decorations follow. + pub fn subscription() -> Subscription<ChromeMessage> { + iced::event::listen_with(|event, _status, id| match event { + Event::Window(window::Event::Opened { size, .. }) => { + Some(ChromeMessage::Resized(id, size)) + } + Event::Window(window::Event::Focused) => Some(ChromeMessage::Focused(id, true)), + Event::Window(window::Event::Unfocused) => Some(ChromeMessage::Focused(id, false)), + Event::Window(window::Event::Resized(size)) => Some(ChromeMessage::Resized(id, size)), + _ => None, + }) + } + + /// Acts on a message: moves, maximizes, resizes or closes the window, or notes its state. + pub fn update(&mut self, message: ChromeMessage) -> Task<ChromeMessage> { + match message { + ChromeMessage::Drag => self.act(window::drag), + ChromeMessage::ToggleMaximize => self.act(window::toggle_maximize), + ChromeMessage::Close => self.act(window::close), + ChromeMessage::Resize(edge) if self.resizable() => { + self.act(move |id| window::drag_resize(id, edge.direction())) + } + ChromeMessage::Resize(_) => Task::none(), + ChromeMessage::Back => { + self.pane = Pane::Sidebar; + Task::none() + } + ChromeMessage::Resized(id, size) => { + self.resize(size); + self.update(ChromeMessage::Opened(id)) + } + ChromeMessage::Opened(id) => { + self.id = Some(id); + // Whether it's maximized or full-screen now: winit says nothing of it otherwise. + Task::batch([ + window::is_maximized(id).map(ChromeMessage::Maximized), + window::mode(id).map(ChromeMessage::Mode), + ]) + } + ChromeMessage::Focused(id, focused) => { + self.id = Some(id); + self.focused = focused; + Task::none() + } + ChromeMessage::Maximized(maximized) => { + self.maximized = maximized; + Task::none() + } + ChromeMessage::Frame(at) => { + if let Some(fade) = &mut self.fade { + fade.at = at; + if fade.share() >= 1.0 { + self.fade = None; + } + } + Task::none() + } + ChromeMessage::Mode(mode) => { + self.fullscreen = mode == window::Mode::Fullscreen; + Task::none() + } + } + } + + /// A task on the window: on its ID, or the first window's until it's known. + fn act( + &self, + task: impl Fn(window::Id) -> Task<ChromeMessage> + Send + 'static, + ) -> Task<ChromeMessage> { + match self.id { + Some(id) => task(id), + None => window::oldest().and_then(task), + } + } + + /// The window: its frame round the header bar and the content, and with a sidebar, the + /// sidebar beside the content, or, folded, one of them, the header bar's back button + /// returning from the page. + pub fn view<'a, M: Clone + 'a>( + &self, + header: Header<'a, M>, + sidebar: Option<Element<'a, M>>, + content: Element<'a, M>, + wrap: fn(ChromeMessage) -> M, + ) -> Element<'a, M> { + let folded = sidebar.is_some() && self.folded(); + let back = folded && self.pane == Pane::Page; + let corners = self.corners(); + let mut bar = header_bar(header) + .rounded(corners == Corners::Drawn) + .on_drag(wrap(ChromeMessage::Drag)) + .on_maximize(wrap(ChromeMessage::ToggleMaximize)) + .on_close(wrap(ChromeMessage::Close)); + if back { + bar = bar.on_back(wrap(ChromeMessage::Back)); + } + let bar = Element::from(bar); + let pane = |sidebar: Element<'a, M>, width: f32| -> Element<'a, M> { + let width = if folded { Fill } else { width.into() }; + container(scroll_area( + container(sidebar) + .padding([space::M, decorations::SIDEBAR_PAD]) + .width(Fill), + )) + .width(width) + .height(Fill) + .class(Frame::Fill(Surface::Panel)) + .into() + }; + let body = match sidebar { + None => content, + // Folded, one pane at a time, sliding between them; the page passes over the sidebar, + // so it fills itself. + Some(sidebar) if folded => { + let page: Element<'a, M> = container(content) + .width(Fill) + .height(Fill) + .class(Frame::Fill(Surface::Bg)) + .into(); + crate::ui::chrome::folded(pane(sidebar, 0.0), page, back).into() + } + Some(sidebar) => Row::with_children([ + pane(sidebar, decorations::SIDEBAR_WIDTH), + container(Space::new()) + .width(decorations::BORDER) + .height(Fill) + .class(Frame::Divider) + .into(), + content, + ]) + .height(Fill) + .into(), + }; + let window: Element<'a, M> = iced::widget::Column::with_children([bar, body]) + .height(Fill) + .into(); + let frame = window_frame(window).corners(corners); + if self.resizable() { + frame + .on_resize(move |edge| wrap(ChromeMessage::Resize(edge))) + .into() + } else { + frame.into() + } + } + + /// The window's background: clear while the launcher draws its frame, for the rounded + /// corners, and the theme's otherwise. + pub fn style(&self, theme: &Theme) -> theme::Style { + let base = theme.base(); + if self.transparent() { + theme::Style { + background_color: Color::TRANSPARENT, + ..base + } + } else { + base + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const SIZE: Size = Size::new(960.0, 640.0); + + #[test] + fn the_switch_reads_as_documented() { + assert_eq!(FrameSetting::parse(None), (FrameSetting::Drawn, None)); + assert_eq!( + FrameSetting::parse(Some(OsStr::new("1"))), + (FrameSetting::Drawn, None) + ); + assert_eq!( + FrameSetting::parse(Some(OsStr::new("0"))), + (FrameSetting::Off, None) + ); + let (setting, warning) = FrameSetting::parse(Some(OsStr::new("yes"))); + assert_eq!(setting, FrameSetting::Drawn); + assert!(warning.unwrap().contains("LEONIDA_WINDOW_FRAME=yes")); + } + + #[test] + fn the_frame_follows_the_platform_the_switch_and_the_window() { + use FrameSetting::{Drawn, Off}; + use Platform::{Other, Windows}; + // Linux: transparent and rounded by the launcher while floating. + assert!(transparent(Other, Drawn)); + assert_eq!(corners(Other, Drawn, true), Corners::Drawn); + assert_eq!(corners(Other, Drawn, false), Corners::Square); + // Windows: opaque, Windows 11's own corners and the launcher's line while floating. + assert!(!transparent(Windows, Drawn)); + assert_eq!(corners(Windows, Drawn, true), Corners::System); + assert_eq!(corners(Windows, Drawn, false), Corners::Square); + // Off: opaque and square everywhere. + for platform in [Other, Windows] { + assert!(!transparent(platform, Off)); + for floating in [true, false] { + assert_eq!(corners(platform, Off, floating), Corners::Square); + } + } + } + + #[test] + fn maximized_its_square_and_doesnt_resize() { + let mut chrome = Chrome::on(Platform::Other, SIZE, FrameSetting::Drawn); + assert!(chrome.floating() && chrome.resizable() && chrome.transparent()); + assert_eq!(chrome.corners(), Corners::Drawn); + let _ = chrome.update(ChromeMessage::Maximized(true)); + assert!(chrome.is_maximized() && !chrome.resizable()); + assert_eq!(chrome.corners(), Corners::Square); + let _ = chrome.update(ChromeMessage::Maximized(false)); + let _ = chrome.update(ChromeMessage::Mode(window::Mode::Fullscreen)); + assert_eq!(chrome.corners(), Corners::Square); + } + + #[test] + fn a_narrow_window_folds_and_a_chosen_place_shows_its_page() { + let mut chrome = Chrome::on(Platform::Other, SIZE, FrameSetting::Drawn); + assert!(!chrome.folded()); + chrome.resize(Size::new(500.0, 640.0)); + assert!(chrome.folded()); + assert_eq!(chrome.pane(), Pane::Sidebar); + chrome.show_page(); + assert_eq!(chrome.pane(), Pane::Page); + let _ = chrome.update(ChromeMessage::Back); + assert_eq!(chrome.pane(), Pane::Sidebar); + } + + #[test] + fn a_new_theme_fades_in_from_what_showed_and_then_is_itself() { + use crate::ui::tokens::Palette; + if crate::ui::system::reduced_motion() { + return; + } + let (dark, light) = ( + Theme::new(Palette::SUNSET_DARK), + Theme::new(Palette::SUNSET_LIGHT), + ); + let mut chrome = Chrome::on(Platform::Other, SIZE, FrameSetting::Drawn); + assert_eq!(chrome.theme(light), light); + let start = Instant::now(); + chrome.theme_changed(dark, start); + assert!(chrome.is_fading()); + assert_eq!(chrome.theme(light), dark, "it starts from what showed"); + let _ = chrome.update(ChromeMessage::Frame(start + THEME_FADE / 4)); + let between = chrome.theme(light); + assert!(between != dark && between != light); + let _ = chrome.update(ChromeMessage::Frame(start + THEME_FADE)); + assert!(!chrome.is_fading()); + assert_eq!(chrome.theme(light), light); + } + + #[test] + fn the_background_is_clear_only_when_the_corners_are_drawn() { + let theme = <Theme as Default>::default(); + let drawn = Chrome::on(Platform::Other, SIZE, FrameSetting::Drawn); + assert_eq!(drawn.style(&theme).background_color, Color::TRANSPARENT); + let windows = Chrome::on(Platform::Windows, SIZE, FrameSetting::Drawn); + assert_ne!(windows.style(&theme).background_color, Color::TRANSPARENT); + } +} diff --git a/launcher/tests/backdrop.rs b/launcher/tests/backdrop.rs new file mode 100644 index 0000000000..e496071ccd --- /dev/null +++ b/launcher/tests/backdrop.rs @@ -0,0 +1,140 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! The Play page's scene is generated once per final key and cached: redraws, the pointer, focus, +//! page switches and a burst of resizes generate nothing more, and switching the mode back and +//! forth costs one picture per mode. Counted with a stand-in generator. + +mod common; + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Instant; + +use iced::keyboard::{Key, Modifiers, key::Named}; +use iced::{Event, Point, Size, mouse, window}; + +use leonida_launcher::app::{Message, Page, SIZE}; +use leonida_launcher::backdrop::DEBOUNCE; +use leonida_launcher::scene::{Input, Picture}; +use leonida_launcher::ui::window::ChromeMessage; + +use common::{Session, launcher}; + +static GENERATED: AtomicUsize = AtomicUsize::new(0); + +/// A stand-in generator: counts, and makes a blank picture of the size asked. +fn counting(input: &Input) -> Option<Picture> { + GENERATED.fetch_add(1, Ordering::SeqCst); + Some(Picture { + width: input.width, + height: input.height, + rgba: vec![0; input.width as usize * input.height as usize * 4], + }) +} + +fn settle(session: &mut Session) { + let later = Instant::now() + DEBOUNCE * 2; + let _ = session.launcher.update(Message::SceneTick(later)); +} + +#[test] +fn one_generation_per_distinct_final_key() { + let mut app = launcher(); + app.synchronous = true; + app.backdrop.generator = counting; + let mut session = Session::new(app, SIZE); + let generated = || GENERATED.load(Ordering::SeqCst); + + // At start: both modes' pictures, at once, with no wait. + let _ = session.launcher.update(Message::SceneTick(Instant::now())); + assert_eq!(generated(), 2, "both modes, at once"); + + // Many frames, the pointer moving, focus moving: nothing. + for at in 0..30 { + session.send(&[Event::Mouse(mouse::Event::CursorMoved { + position: Point::new(300.0 + at as f32 * 10.0, 200.0), + })]); + let _ = session.render(1.0); + session.press(Key::Named(Named::Tab), Modifiers::empty()); + settle(&mut session); + } + assert_eq!(generated(), 2); + + // Pages switched and back: nothing. + for page in [ + Page::GameFiles, + Page::Performance, + Page::Play, + Page::GameFiles, + Page::Play, + ] { + let _ = session.launcher.update(Message::Show(page)); + let _ = session.render(1.0); + settle(&mut session); + } + assert_eq!(generated(), 2); + + // A resize drag: many sizes, none held long enough, then the last one holds: both modes' + // pictures for it. + let id = window::Id::unique(); + for step in 0..25 { + let size = Size::new( + SIZE.width + step as f32 * 8.0, + SIZE.height + step as f32 * 3.0, + ); + let _ = session + .launcher + .update(Message::Chrome(ChromeMessage::Resized(id, size))); + let _ = session.launcher.update(Message::SceneTick(Instant::now())); + let _ = session.render(1.0); + } + assert_eq!(generated(), 2, "nothing while the size keeps changing"); + settle(&mut session); + assert_eq!(generated(), 4, "both modes for the final size"); + + // Light, dark, light: both are made already, nothing more. + for _ in 0..3 { + let _ = session.launcher.update(Message::ToggleShade); + settle(&mut session); + let _ = session.render(1.0); + assert_eq!(generated(), 4); + } + assert_eq!(session.launcher.backdrop.generations, 4); +} + +/// The RGBA pixel at `x`, `y` of a frame `width` wide. +fn pixel(rgba: &[u8], width: u32, x: u32, y: u32) -> [u8; 3] { + let at = ((y * width + x) * 4) as usize; + [rgba[at], rgba[at + 1], rgba[at + 2]] +} + +#[test] +fn while_resizing_the_last_scene_stays_until_the_new_one_is_made() { + let mut session = Session::new(launcher(), SIZE); + session.settle_scene(1.0); + let bg = session + .launcher + .theme() + .palette() + .surface(leonida_launcher::ui::Surface::Bg) + .rgb8(); + let seen = |session: &mut Session, size: Size| { + let rgba = session.render(1.0); + // Low on the right, where the shore and the water are: never the page's background. + let (x, y) = (size.width as u32 - 60, size.height as u32 - 40); + pixel(&rgba, size.width as u32, x, y) + }; + assert_ne!(seen(&mut session, SIZE), bg, "the scene shows"); + // A drag: sizes come one after another, none held long enough to make a new picture. + for step in 1..6 { + let size = Size::new( + SIZE.width + step as f32 * 30.0, + SIZE.height + step as f32 * 10.0, + ); + session.resize_to(size); + assert_ne!( + seen(&mut session, size), + bg, + "the last scene, while resizing to {size:?}" + ); + } +} diff --git a/launcher/tests/cancel.rs b/launcher/tests/cancel.rs new file mode 100644 index 0000000000..71bc05b2ee --- /dev/null +++ b/launcher/tests/cancel.rs @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Cancel pressed before the running command has said it started: there is no process to stop +//! yet, so the launcher stops it when its `Started` arrives. A stand-in that would run for half a +//! minute plays the command, started the way the launcher starts one (its own process group +//! elsewhere than on Windows, where `taskkill /T` ends its tree), and has to end within seconds. + +mod common; + +use std::process::{Child, Stdio}; +use std::time::{Duration, Instant}; + +use leonida_launcher::app::{Message, Running}; +use leonida_launcher::commands::Command; +use leonida_launcher::output::Tracker; +use leonida_launcher::process::Event; +use leonida_launcher::state::{Action, Kind}; + +/// A process that would run for about 30 seconds, started as the launcher starts a command. +fn stand_in() -> Child { + let mut command = if cfg!(windows) { + let mut command = std::process::Command::new("cmd"); + command.args(["/C", "ping -n 31 127.0.0.1 >NUL"]); + command + } else { + let mut command = std::process::Command::new("sh"); + command.args(["-c", "sleep 30"]); + command + }; + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + command.process_group(0); + } + command + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("the stand-in starts") +} + +/// Whether the child has ended within `within`. +fn ends_within(child: &mut Child, within: Duration) -> bool { + let until = Instant::now() + within; + while Instant::now() < until { + if matches!(child.try_wait(), Ok(Some(_))) { + return true; + } + std::thread::sleep(Duration::from_millis(50)); + } + false +} + +#[test] +fn cancel_before_started_stops_the_process_once_it_has_started() { + let mut child = stand_in(); + let pid = child.id(); + let mut launcher = common::launcher(); + launcher.running = Some(Running { + kind: Kind::Build, + command: Command { + program: "stand-in".to_owned(), + args: Vec::new(), + env: Vec::new(), + cwd: String::new(), + }, + pid: None, + tracker: Tracker::build(None), + cancelled: false, + }); + + // Cancel first: nothing to stop yet, so the process runs on. + let _ = launcher.update(Message::Act(Action::Cancel)); + assert!( + launcher + .running + .as_ref() + .is_some_and(|running| running.cancelled) + ); + assert!( + !ends_within(&mut child, Duration::from_millis(300)), + "the stand-in ended before it was stopped" + ); + + // Then the process says it started: the launcher stops it now. + let _ = launcher.update(Message::Process(Event::Started(pid))); + let ended = ends_within(&mut child, Duration::from_secs(10)); + if !ended { + let _ = child.kill(); + let _ = child.wait(); + } + assert!(ended, "a Cancel before Started left the process running"); +} diff --git a/launcher/tests/chips.rs b/launcher/tests/chips.rs new file mode 100644 index 0000000000..59d00976eb --- /dev/null +++ b/launcher/tests/chips.rs @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Every status chip, side by side on the Play page's scene in each mode, at the page's left and +//! over the scene's bright part. Written as a PNG for the eye, to +//! `$LEONIDA_LAUNCHER_SCREENSHOTS/chips-<mode>.png`; checked here for its words' contrast on the +//! chip, over the page's background. + +mod common; + +use std::path::PathBuf; + +use iced::Size; +use iced::widget::{Stack, column, container, image, row}; + +use leonida_launcher::app::Message; +use leonida_launcher::scene::{self, Colors, Input}; +use leonida_launcher::ui::theme::Status; +use leonida_launcher::ui::tokens::color::contrast; +use leonida_launcher::ui::tokens::{Palette, Surface, space}; +use leonida_launcher::ui::{Element, Theme, status}; + +const STATES: [(Status, &str); 6] = [ + (Status::Waiting, "Setup"), + (Status::Running, "Running"), + (Status::Passed, "Checked"), + (Status::Info, "Not bootable yet"), + (Status::Warning, "Warning"), + (Status::Failed, "Failed"), +]; + +#[test] +fn every_chip_on_the_play_pages_background() { + let size = Size::new(1040.0, 360.0); + let folder = std::env::var_os("LEONIDA_LAUNCHER_SCREENSHOTS") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("screenshots")); + for palette in Palette::ALL { + let theme = Theme::new(palette); + let picture = scene::generate(&Input { + colors: Colors::of(&palette), + width: size.width as u32, + height: size.height as u32, + scale: 1.0, + corner: None, + }) + .unwrap(); + let chips = || { + column(STATES.map(|(state, word)| Element::<Message>::from(status(state, word)))) + .spacing(space::M) + }; + let view: Element<'_, Message> = Stack::with_children([ + image(image::Handle::from_rgba( + picture.width, + picture.height, + picture.rgba, + )) + .into(), + container(row![chips(), iced::widget::space().width(600), chips()]) + .padding(space::XXL) + .into(), + ]) + .into(); + let rgba = common::render_view(view, &theme, size); + common::write_png( + &folder.join(format!("chips-{}.png", palette.name)), + (size.width as u32, size.height as u32), + &rgba, + ); + // Each chip's word on its own tint, over the column's background, keeps 4.5:1. + let bg = palette.surface(Surface::Bg); + for (state, _) in STATES { + let look = theme.status(state); + let fill = look.fill.map_or(bg, |fill| fill.over(bg)); + let ratio = contrast(look.ink, fill); + assert!(ratio >= 4.5, "{}: {state:?}: {ratio:.2}", palette.name); + } + } +} diff --git a/launcher/tests/common/mod.rs b/launcher/tests/common/mod.rs new file mode 100644 index 0000000000..953e3b03e9 --- /dev/null +++ b/launcher/tests/common/mod.rs @@ -0,0 +1,203 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Drawing and driving the launcher's view offscreen, with no window: iced's user interface on +//! its tiny-skia renderer, all on the CPU. +//! Nothing here touches a display or a GPU. + +#![allow(dead_code)] + +use std::path::{Path, PathBuf}; + +use iced::advanced::renderer::{Headless, Style}; +use iced::advanced::{clipboard, mouse}; +use iced::keyboard::{self, Key, Location, Modifiers, key::Physical}; +use iced::time::Instant; +use iced::{Event, Pixels, Size, window}; +use iced_runtime::user_interface::{Cache, UserInterface}; + +use leonida_launcher::app::{Launcher, Message}; +use leonida_launcher::ui::font; +use leonida_launcher::ui::window::FrameSetting; + +/// A tiny-skia renderer, the launcher's fonts loaded. +pub fn renderer() -> iced::Renderer { + font::load(); + iced::futures::executor::block_on(<iced::Renderer as Headless>::new( + font::DEFAULT, + Pixels(14.0), + Some(&std::env::var("LEONIDA_TEST_RENDERER").unwrap_or_else(|_| "tiny-skia".to_owned())), + )) + .expect("tiny-skia draws without a GPU") +} + +/// A launcher with no settings file, for a made-up repository. +pub fn launcher() -> Launcher { + let mut launcher = Launcher::new( + Ok(PathBuf::from(if cfg!(windows) { + "C:\\src\\Leonida" + } else { + "/src/Leonida" + })), + None, + FrameSetting::Drawn, + ); + launcher.note = None; + launcher +} + +/// A view driven by events, as a window drives it. +pub struct Session { + pub launcher: Launcher, + renderer: iced::Renderer, + cache: Cache, + size: Size, + cursor: mouse::Cursor, + pub messages: Vec<Message>, +} + +impl Session { + pub fn new(launcher: Launcher, size: Size) -> Self { + let mut session = Self { + launcher, + renderer: renderer(), + cache: Cache::default(), + size, + cursor: mouse::Cursor::Unavailable, + messages: Vec::new(), + }; + session.launcher.resize(size); + session + } + + /// The window resized, as its event says: drawn at the new size from now on. + pub fn resize_to(&mut self, size: Size) { + self.size = size; + let id = window::Id::unique(); + let _ = self.launcher.update(Message::Chrome( + leonida_launcher::ui::window::ChromeMessage::Resized(id, size), + )); + } + + /// Makes the Play page's scene for the current size, mode and scale, at once, as the window + /// would once its size has held. + pub fn settle_scene(&mut self, scale: f32) { + self.launcher.synchronous = true; + let _ = self.launcher.update(Message::Scale(scale)); + let later = Instant::now() + leonida_launcher::backdrop::DEBOUNCE * 2; + let _ = self.launcher.update(Message::SceneTick(later)); + // Its fade, run to the end, as the window's frames would. + let _ = self.launcher.update(Message::SceneFrame(later)); + let whole = later + leonida_launcher::ui::tokens::motion::SCENE_IN; + let _ = self.launcher.update(Message::SceneFrame(whole)); + } + + /// Sends events to the view; the messages it publishes are kept, not applied. + pub fn send(&mut self, events: &[Event]) { + let cache = std::mem::take(&mut self.cache); + let mut ui = + UserInterface::build(self.launcher.view(), self.size, cache, &mut self.renderer); + let mut clipboard = clipboard::Null; + let _ = ui.update( + events, + self.cursor, + &mut self.renderer, + &mut clipboard, + &mut self.messages, + ); + self.cache = ui.into_cache(); + } + + /// Sends events, then applies what they published, as the app would. + pub fn apply(&mut self, events: &[Event]) { + self.send(events); + for message in std::mem::take(&mut self.messages) { + let _ = self.launcher.update(message); + } + } + + /// A key pressed and released. + pub fn press(&mut self, key: Key, modifiers: Modifiers) { + self.send(&[key_event(key.clone(), modifiers, true)]); + self.send(&[key_event(key, modifiers, false)]); + } + + /// Draws a frame (so animations settle on a time), then the picture, RGBA. + pub fn render(&mut self, scale: f32) -> Vec<u8> { + self.send(&[Event::Window( + window::Event::RedrawRequested(Instant::now()), + )]); + let cache = std::mem::take(&mut self.cache); + let mut ui = + UserInterface::build(self.launcher.view(), self.size, cache, &mut self.renderer); + let theme = self.launcher.theme(); + let style = Style { + text_color: iced::theme::Base::base(&theme).text_color, + }; + ui.draw(&mut self.renderer, &theme, &style, self.cursor); + self.cache = ui.into_cache(); + let background = self.launcher.style(&theme).background_color; + let physical = Size::new( + (self.size.width * scale).round() as u32, + (self.size.height * scale).round() as u32, + ); + self.renderer.screenshot(physical, scale, background) + } +} + +pub fn key_event(key: Key, modifiers: Modifiers, pressed: bool) -> Event { + let physical = Physical::Unidentified(keyboard::key::NativeCode::Unidentified); + let text = match &key { + Key::Character(c) if pressed => Some(c.clone()), + Key::Named(keyboard::key::Named::Space) if pressed => Some(" ".into()), + _ => None, + }; + Event::Keyboard(if pressed { + keyboard::Event::KeyPressed { + key: key.clone(), + modified_key: key, + physical_key: physical, + location: Location::Standard, + modifiers, + text, + repeat: false, + } + } else { + keyboard::Event::KeyReleased { + key: key.clone(), + modified_key: key, + physical_key: physical, + location: Location::Standard, + modifiers, + } + }) +} + +/// Writes RGBA pixels as a PNG. +/// Draws any view of the launcher's kit, in a theme, at a size: for pictures of parts. +pub fn render_view( + view: leonida_launcher::ui::Element<'_, Message>, + theme: &leonida_launcher::ui::Theme, + size: Size, +) -> Vec<u8> { + let mut renderer = renderer(); + let mut ui = UserInterface::build(view, size, Cache::default(), &mut renderer); + let style = Style { + text_color: iced::theme::Base::base(theme).text_color, + }; + ui.draw(&mut renderer, theme, &style, mouse::Cursor::Unavailable); + let background = iced::theme::Base::base(theme).background_color; + let physical = Size::new(size.width as u32, size.height as u32); + renderer.screenshot(physical, 1.0, background) +} + +pub fn write_png(path: &Path, size: (u32, u32), rgba: &[u8]) { + if let Some(folder) = path.parent() { + std::fs::create_dir_all(folder).unwrap(); + } + let file = std::fs::File::create(path).unwrap(); + let mut encoder = png::Encoder::new(std::io::BufWriter::new(file), size.0, size.1); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + let mut writer = encoder.write_header().unwrap(); + writer.write_image_data(rgba).unwrap(); +} diff --git a/launcher/tests/glows.rs b/launcher/tests/glows.rs new file mode 100644 index 0000000000..b035566b79 --- /dev/null +++ b/launcher/tests/glows.rs @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Every glow comes and goes on the buttons' timing: a button and a text field under the +//! pointer, and a switch turned on, are part lit halfway through `motion::GLOW_IN` and whole at +//! its end. Drawn offscreen, the pictures compared. + +mod common; + +use std::time::Instant; + +use iced::advanced::renderer::{Headless, Style}; +use iced::advanced::{clipboard, mouse}; +use iced::{Event, Point, Size, window}; +use iced_runtime::user_interface::{Cache, UserInterface}; + +use leonida_launcher::app::Message; +use leonida_launcher::ui::tokens::{Palette, motion}; +use leonida_launcher::ui::widget::container; +use leonida_launcher::ui::{Element, Theme, button, switch, text_field}; + +const SIZE: Size = Size::new(240.0, 120.0); + +/// One control, centred, with room for its glow. +fn view(which: &str, on: bool) -> Element<'static, Message> { + let control: Element<'static, Message> = match which { + "button" => button("Check").on_press(Message::Scale(1.0)).into(), + "field" => text_field("A folder", "") + .on_input(|_| Message::Scale(1.0)) + .into(), + "switch" => switch(on).on_toggle(|_| Message::Scale(1.0)).into(), + _ => unreachable!(), + }; + container(control) + .width(iced::Fill) + .height(iced::Fill) + .center_x(iced::Fill) + .center_y(iced::Fill) + .padding(32) + .into() +} + +struct Harness { + which: &'static str, + on: bool, + renderer: iced::Renderer, + cache: Cache, + cursor: mouse::Cursor, + theme: Theme, +} + +impl Harness { + fn send(&mut self, events: &[Event]) { + let cache = std::mem::take(&mut self.cache); + let mut ui = + UserInterface::build(view(self.which, self.on), SIZE, cache, &mut self.renderer); + let mut messages = Vec::new(); + let _ = ui.update( + events, + self.cursor, + &mut self.renderer, + &mut clipboard::Null, + &mut messages, + ); + self.cache = ui.into_cache(); + } + + /// A frame at `now`, then its picture. + fn render_at(&mut self, now: Instant) -> Vec<u8> { + self.send(&[Event::Window(window::Event::RedrawRequested(now))]); + let cache = std::mem::take(&mut self.cache); + let mut ui = + UserInterface::build(view(self.which, self.on), SIZE, cache, &mut self.renderer); + let style = Style { + text_color: iced::theme::Base::base(&self.theme).text_color, + }; + ui.draw(&mut self.renderer, &self.theme, &style, self.cursor); + self.cache = ui.into_cache(); + let background = iced::theme::Base::base(&self.theme).background_color; + self.renderer.screenshot( + Size::new(SIZE.width as u32, SIZE.height as u32), + 1.0, + background, + ) + } +} + +fn difference(a: &[u8], b: &[u8]) -> u64 { + a.iter() + .zip(b) + .map(|(a, b)| u64::from(a.abs_diff(*b))) + .sum() +} + +#[test] +fn every_glow_fades_in_over_the_buttons_time() { + let centre = Point::new(SIZE.width / 2.0, SIZE.height / 2.0); + for palette in Palette::ALL { + for which in ["button", "field", "switch"] { + let mut harness = Harness { + which, + on: false, + renderer: common::renderer(), + cache: Cache::default(), + cursor: mouse::Cursor::Unavailable, + theme: Theme::new(palette), + }; + let start = Instant::now(); + let before = harness.render_at(start); + // Lit: the pointer comes over the button and the field; the switch turns on, the + // pointer kept away so that only its being on lights it. + if which == "switch" { + // Its new value is seen on the next event, as a window's next one would be. + harness.on = true; + harness.send(&[Event::Mouse(mouse::Event::CursorLeft)]); + } else { + harness.cursor = mouse::Cursor::Available(centre); + harness.send(&[Event::Mouse(mouse::Event::CursorMoved { position: centre })]); + } + harness.send(&[Event::Window(window::Event::RedrawRequested(start))]); + let half = harness.render_at(start + motion::GLOW_IN / 2); + let whole = harness.render_at(start + motion::GLOW_IN); + let later = harness.render_at(start + motion::GLOW_IN * 2); + let name = format!("{} {which}", palette.name); + assert!(difference(&before, &half) > 0, "{name}: halfway, some glow"); + assert!( + difference(&half, &whole) > 0, + "{name}: halfway, not yet whole" + ); + assert_eq!( + difference(&whole, &later), + 0, + "{name}: whole at the end of GLOW_IN" + ); + } + } +} diff --git a/launcher/tests/keyboard.rs b/launcher/tests/keyboard.rs new file mode 100644 index 0000000000..8c349c1db2 --- /dev/null +++ b/launcher/tests/keyboard.rs @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! The launcher by keyboard alone, offscreen (tiny-skia, no window): Tab and Shift+Tab move focus +//! through the header bar, the sidebar and the page, round the end; Enter and Space press the +//! focused button, close button and switch; the arrows move the sidebar's and the pill's choice; +//! a focused field takes typing; Ctrl+Page Down and Ctrl+Page Up step through the pages, and +//! Ctrl+L switches light and dark. + +mod common; + +use iced::Size; +use iced::keyboard::{Key, Modifiers, key::Named}; + +use leonida_launcher::app::{Folder, Message, Page}; +use leonida_launcher::config::Shade; +use leonida_launcher::state::{Action, Kind}; +use leonida_launcher::ui::window::ChromeMessage; + +use common::{Session, launcher}; + +const WIDE: Size = Size::new(980.0, 680.0); + +fn tab(session: &mut Session, times: usize) { + for _ in 0..times { + session.press(Key::Named(Named::Tab), Modifiers::empty()); + } +} + +fn names(messages: &[Message]) -> Vec<String> { + messages + .iter() + .map(|message| format!("{message:?}")) + .collect() +} + +/// Tabs from nothing focused until pressing Enter sends a message, and returns how many Tabs and +/// the message. +fn find_by_tab(session: &mut Session, key: Named, wanted: impl Fn(&Message) -> bool) -> usize { + for tabs in 1..40 { + tab(session, 1); + session.messages.clear(); + session.press(Key::Named(key), Modifiers::empty()); + if session.messages.iter().any(&wanted) { + return tabs; + } + } + panic!("nothing reached by Tab: {:?}", names(&session.messages)); +} + +#[test] +fn tab_reaches_the_primary_button_and_enter_presses_it() { + let mut app = launcher(); + app.settings.package = "/games/made-up-package".to_owned(); + app.disk.package = true; + let mut session = Session::new(app, WIDE); + find_by_tab(&mut session, Named::Enter, |message| { + matches!(message, Message::Act(Action::Run(Kind::Check))) + }); + // Space presses it too, while it keeps focus. + session.messages.clear(); + session.press(Key::Named(Named::Space), Modifiers::empty()); + assert!( + session + .messages + .iter() + .any(|message| matches!(message, Message::Act(Action::Run(Kind::Check)))), + "{:?}", + names(&session.messages) + ); +} + +#[test] +fn a_disabled_primary_button_takes_no_focus() { + // Nothing configured: Check is disabled, so no Tab stop presses it. + let mut session = Session::new(launcher(), WIDE); + for _ in 0..12 { + tab(&mut session, 1); + session.press(Key::Named(Named::Enter), Modifiers::empty()); + } + assert!( + !session + .messages + .iter() + .any(|message| matches!(message, Message::Act(_))), + "{:?}", + names(&session.messages) + ); +} + +#[test] +fn the_close_button_is_a_tab_stop_and_enter_closes() { + let mut session = Session::new(launcher(), WIDE); + find_by_tab(&mut session, Named::Enter, |message| { + matches!(message, Message::Chrome(ChromeMessage::Close)) + }); +} + +#[test] +fn shift_tab_goes_round_the_other_way() { + let mut session = Session::new(launcher(), WIDE); + // From nothing, Shift+Tab focuses the last stop; the first Tab after that goes round to the + // first, and Shift+Tab back again to the last. + session.press(Key::Named(Named::Tab), Modifiers::SHIFT); + session.messages.clear(); + session.press(Key::Named(Named::Enter), Modifiers::empty()); + let last = names(&session.messages); + tab(&mut session, 1); + session.press(Key::Named(Named::Tab), Modifiers::SHIFT); + session.messages.clear(); + session.press(Key::Named(Named::Enter), Modifiers::empty()); + assert_eq!(names(&session.messages), last); +} + +#[test] +fn the_sidebar_moves_by_arrows() { + let mut session = Session::new(launcher(), WIDE); + let tabs = find_by_tab(&mut session, Named::ArrowDown, |message| { + matches!(message, Message::Show(Page::GameFiles)) + }); + assert!(tabs >= 1); + let messages = std::mem::take(&mut session.messages); + for message in messages { + let _ = session.launcher.update(message); + } + assert_eq!(session.launcher.page, Page::GameFiles); +} + +#[test] +fn the_pill_switches_light_and_dark_by_arrows() { + let mut session = Session::new(launcher(), WIDE); + find_by_tab(&mut session, Named::ArrowRight, |message| { + matches!(message, Message::Shade(Shade::Light)) + }); +} + +#[test] +fn switches_take_space() { + let mut app = launcher(); + app.page = Page::Performance; + let mut session = Session::new(app, WIDE); + find_by_tab(&mut session, Named::Space, |message| { + matches!(message, Message::Validation(true)) + }); + let mut app = launcher(); + app.page = Page::Build; + let mut session = Session::new(app, WIDE); + find_by_tab(&mut session, Named::Space, |message| { + matches!(message, Message::Stage("shaders", false)) + }); + let mut app = launcher(); + app.page = Page::Diagnostics; + let mut session = Session::new(app, WIDE); + find_by_tab(&mut session, Named::Space, |message| { + matches!(message, Message::TraceD3d12(true)) + }); +} + +#[test] +fn a_focused_field_takes_typing() { + let mut app = launcher(); + app.page = Page::GameFiles; + let mut session = Session::new(app, WIDE); + // Tab until a field is focused: typing then sends its text. + for _ in 0..20 { + tab(&mut session, 1); + session.messages.clear(); + session.press(Key::Character("x".into()), Modifiers::empty()); + if let Some(Message::Folder(folder, value)) = session.messages.first() { + assert_eq!((*folder, value.as_str()), (Folder::Package, "x")); + return; + } + } + panic!("no field took the typing"); +} + +#[test] +fn ctrl_page_down_and_up_step_through_the_pages_and_ctrl_l_switches_the_shade() { + let mut app = launcher(); + assert_eq!(app.page, Page::Play); + let _ = app.update(Message::Step(true)); + assert_eq!(app.page, Page::GameFiles); + for _ in 0..4 { + let _ = app.update(Message::Step(true)); + } + assert_eq!(app.page, Page::Play, "round the end"); + let _ = app.update(Message::Step(false)); + assert_eq!(app.page, Page::Diagnostics); + let _ = app.update(Message::ToggleShade); + assert_eq!(app.settings.shade, Shade::Light); +} diff --git a/launcher/tests/launch.rs b/launcher/tests/launch.rs new file mode 100644 index 0000000000..ec640b85e7 --- /dev/null +++ b/launcher/tests/launch.rs @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! A launch, as `main` boots the launcher: only what a real window delivers (its size once it +//! opens, its scale factor), the tasks the launcher returns run as the runtime runs them, on +//! threads, with the real generator. The Play page's scene must be made, both modes once, and +//! shown, then fade in and stop: at the default size and scale, on another page, folded, and with +//! the frame off. + +use std::path::PathBuf; +use std::sync::mpsc; +use std::time::{Duration, Instant}; + +use iced::futures::StreamExt; +use iced::futures::executor::block_on; +use iced::{Size, Task, window}; +use iced_runtime::Action; + +use leonida_launcher::app::{Launcher, Message, Page, SIZE}; +use leonida_launcher::ui::tokens::motion; +use leonida_launcher::ui::window::{ChromeMessage, FrameSetting}; + +/// Runs a task's stream on a thread, sending what it outputs. A task that waits on the window +/// (none answers here) just never sends. +fn run(task: Task<Message>, sender: &mpsc::Sender<Message>) { + if let Some(stream) = iced_runtime::task::into_stream(task) { + let sender = sender.clone(); + std::thread::spawn(move || { + block_on(stream.for_each(|action| { + if let Action::Output(message) = action { + let _ = sender.send(message); + } + std::future::ready(()) + })); + }); + } +} + +fn launch(frame: FrameSetting, size: Size, page: Page) { + let repo = PathBuf::from("/src/Leonida"); + let (mut launcher, boot) = Launcher::boot(Ok(repo), None, frame); + launcher.page = page; + let (sender, receiver) = mpsc::channel(); + run(boot, &sender); + // What the window says as it opens: its size, and its scale. + let id = window::Id::unique(); + run( + launcher.update(Message::Chrome(ChromeMessage::Resized(id, size))), + &sender, + ); + run(launcher.update(Message::Scale(1.0)), &sender); + let deadline = Instant::now() + Duration::from_secs(120); + while launcher.backdrop.layers().1.is_none() || launcher.backdrop.generations < 2 { + let left = deadline.saturating_duration_since(Instant::now()); + let message = receiver + .recv_timeout(left) + .unwrap_or_else(|_| panic!("{frame:?} {size:?} {page:?}: no picture")); + run(launcher.update(message), &sender); + } + // Both modes, once each; the current one showing, fading in. + assert_eq!( + launcher.backdrop.generations, 2, + "{frame:?} {size:?} {page:?}" + ); + let (_, shown) = launcher.backdrop.layers(); + let (shown, _) = shown.unwrap(); + assert!(shown.handle.is_some(), "a picture, not an empty one"); + assert!(launcher.backdrop.is_fading(), "it fades in once it's ready"); + // The fade's frames, until it's whole: then it stops. + let start = Instant::now(); + let _ = launcher.update(Message::SceneFrame(start)); + let _ = launcher.update(Message::SceneFrame(start + motion::SCENE_IN)); + assert!(!launcher.backdrop.is_fading()); + assert_eq!(launcher.backdrop.layers().1.unwrap().1, 1.0); + // Nothing more is wanted, and nothing more is made. + let _ = launcher.update(Message::Show(Page::Play)); + assert_eq!(launcher.backdrop.generations, 2); +} + +#[test] +fn a_launch_at_the_default_size_and_scale_shows_the_scene() { + launch(FrameSetting::Drawn, SIZE, Page::Play); +} + +#[test] +fn a_launch_on_another_page_has_the_scene_ready_for_play() { + launch(FrameSetting::Drawn, SIZE, Page::Build); +} + +#[test] +fn a_launch_folded_and_without_a_frame_shows_the_scene() { + launch(FrameSetting::Drawn, Size::new(520.0, 680.0), Page::Play); + launch(FrameSetting::Off, SIZE, Page::Play); +} diff --git a/launcher/tests/polish.rs b/launcher/tests/polish.rs new file mode 100644 index 0000000000..f6a7c5702b --- /dev/null +++ b/launcher/tests/polish.rs @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Every page and the Play page's states, in both modes, at the smallest window, the default and +//! 1920x1080, drawn offscreen for a look over the whole launcher: written as PNGs to +//! `$LEONIDA_LAUNCHER_SCREENSHOTS/polish/<size>/<name>-<mode>.png`. Each is checked not to be +//! blank, and its middle opaque. Everything shown is made up. + +mod common; + +use std::path::PathBuf; + +use iced::Size; + +use leonida_launcher::app::{LEAST, Launcher, Page, SIZE}; +use leonida_launcher::config::{Checked, Shade}; +use leonida_launcher::state::{Kind, Outcome}; + +use common::{Session, launcher, write_png}; + +fn set_up(launcher: &mut Launcher, state: &str) { + let configured = |launcher: &mut Launcher| { + launcher.settings.package = "/games/made-up-package".to_owned(); + launcher.settings.output = "/home/player/Leonida".to_owned(); + launcher.disk.package = true; + launcher.settings.checked = Some(Checked { + package: launcher.settings.package.clone(), + game: "Xbox Series package 1.0.2.1".to_owned(), + }); + }; + match state { + "play-idle" => {} + "play-not-bootable" => { + configured(launcher); + launcher.disk.loader = true; + } + "play-failed" => { + configured(launcher); + let mut tracker = leonida_launcher::output::Tracker::build(None); + tracker.feed("ERROR: made-up failure with a long message that has to wrap inside the text column, as a real one might"); + launcher.last = Some(( + Outcome { + kind: Kind::Build, + code: Some(1), + cancelled: false, + words: tracker.last_words(), + }, + leonida_launcher::commands::Command { + program: "python3".to_owned(), + args: vec!["-I".to_owned(), "-u".to_owned(), "make_game.py".to_owned()], + env: Vec::new(), + cwd: String::new(), + }, + tracker, + )); + } + "game-files" => { + configured(launcher); + launcher.settings.work = + "/a/very/long/path/to/a/work/folder/on/another/drive/leonida-work".to_owned(); + launcher.page = Page::GameFiles; + } + "build" => launcher.page = Page::Build, + "performance" => launcher.page = Page::Performance, + "diagnostics" => launcher.page = Page::Diagnostics, + _ => unreachable!(), + } +} + +#[test] +fn every_page_at_three_sizes() { + let folder = std::env::var_os("LEONIDA_LAUNCHER_SCREENSHOTS") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("screenshots")) + .join("polish"); + let sizes = [ + ("smallest", LEAST), + ("default", SIZE), + ("large", Size::new(1920.0, 1080.0)), + ]; + let states = [ + "play-idle", + "play-not-bootable", + "play-failed", + "game-files", + "build", + "performance", + "diagnostics", + ]; + for (label, size) in sizes { + for state in states { + for shade in [Shade::Dark, Shade::Light] { + let mut app = launcher(); + app.settings.shade = shade; + set_up(&mut app, state); + let mut session = Session::new(app, size); + session.settle_scene(1.0); + let rgba = session.render(1.0); + let (width, height) = (size.width as u32, size.height as u32); + let middle = ((height / 2 * width + width / 2) * 4 + 3) as usize; + assert_eq!(rgba[middle], 255, "{label} {state}"); + let mode = match shade { + Shade::Dark => "dark", + Shade::Light => "light", + }; + write_png( + &folder.join(label).join(format!("{state}-{mode}.png")), + (width, height), + &rgba, + ); + } + } + } +} diff --git a/launcher/tests/screenshots.rs b/launcher/tests/screenshots.rs new file mode 100644 index 0000000000..1244ea8de5 --- /dev/null +++ b/launcher/tests/screenshots.rs @@ -0,0 +1,212 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Screenshots of the launcher's window, drawn offscreen on tiny-skia (no GPU, no display): every +//! page in Sunset dark and light, the Play page's states, and the folded sidebar. Each is written +//! as a PNG to `$LEONIDA_LAUNCHER_SCREENSHOTS`, or to `target/tmp/screenshots`, to look at; the +//! test checks what can be checked of a picture: its size, the window's clear corners, and that +//! it isn't blank. Everything shown is made up: no game files are read. + +mod common; + +use std::path::PathBuf; + +use iced::Size; + +use leonida_launcher::app::{Launcher, Page, Running}; +use leonida_launcher::commands::{self, Platform}; +use leonida_launcher::config::{Checked, Shade}; +use leonida_launcher::output::Tracker; +use leonida_launcher::state::{Kind, Outcome}; + +use common::{Session, launcher, write_png}; + +const WIDE: Size = Size::new(980.0, 680.0); +const NARROW: Size = Size::new(520.0, 680.0); +/// The reference sketch's window, its page 1040 by 754 as the scene's budget is measured. +const LARGE: Size = Size::new(1282.0, 802.0); + +fn folder() -> PathBuf { + std::env::var_os("LEONIDA_LAUNCHER_SCREENSHOTS") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("screenshots")) +} + +/// Made-up folders. +fn configured(launcher: &mut Launcher) { + launcher.settings.package = "/games/made-up-package".to_owned(); + launcher.settings.output = "/home/player/Leonida".to_owned(); + launcher.settings.work = "/scratch/leonida-work".to_owned(); + launcher.disk.package = true; +} + +fn checked(launcher: &mut Launcher) { + configured(launcher); + launcher.settings.checked = Some(Checked { + package: launcher.settings.package.clone(), + game: "Xbox Series package 1.0.2.1".to_owned(), + }); +} + +/// A build part of the way, as made-up make_game.py lines say. +fn building(launcher: &mut Launcher) { + checked(launcher); + let command = commands::build(Platform::current(), "/src/Leonida", &launcher.settings).unwrap(); + let mut tracker = Tracker::build(None); + for line in [ + "12:00:00 check: Xbox Series package 1.0.2.1, 1234 files", + "12:00:01 check: all files present. Executable found.", + "12:00:02 building into /home/player/Leonida (work files in /scratch/leonida-work)", + "12:00:03 shaders: carving shaders.rpf", + "12:00:09 shaders: unpacking native code", + "12:01:30 shaders: disassembling (gfx1013)", + "12:04:12 shaders: translating RDNA2 to SPIR-V on 8 processes (the longest step)", + " [made-up progress line from a tool]", + ] { + tracker.feed(line); + } + launcher.running = Some(Running { + kind: Kind::Build, + command, + pid: None, + tracker, + cancelled: false, + }); +} + +fn not_bootable(launcher: &mut Launcher) { + checked(launcher); + launcher.disk.loader = true; + launcher.disk.exe = false; +} + +fn failed(launcher: &mut Launcher) { + checked(launcher); + let command = commands::build(Platform::current(), "/src/Leonida", &launcher.settings).unwrap(); + let mut tracker = Tracker::build(None); + for line in [ + "12:00:00 check: Xbox Series package 1.0.2.1, 1234 files", + "12:00:02 building into /home/player/Leonida (work files in /scratch/leonida-work)", + "12:00:03 shaders: carving shaders.rpf", + "", + "ERROR: llvm-mc wasn't found. Set LLVM_MC (made-up failure for the screenshot)", + ] { + tracker.feed(line); + } + launcher.last = Some(( + Outcome { + kind: Kind::Build, + code: Some(1), + cancelled: false, + words: tracker.last_words(), + }, + command, + tracker, + )); +} + +/// Draws one screenshot, checks it, and writes it. +fn shot(name: &str, shade: Shade, size: Size, set_up: impl Fn(&mut Launcher)) { + let mut launcher = launcher(); + launcher.settings.shade = shade; + set_up(&mut launcher); + let mut session = Session::new(launcher, size); + session.settle_scene(1.0); + let rgba = session.render(1.0); + let (width, height) = (size.width as u32, size.height as u32); + assert_eq!(rgba.len(), (width * height * 4) as usize, "{name}"); + let alpha = |x: u32, y: u32| rgba[((y * width + x) * 4 + 3) as usize]; + // The frame's corners are clear on a transparent window (Linux); the middle is opaque. + if session + .launcher + .style(&session.launcher.theme()) + .background_color + .a + == 0.0 + { + assert_eq!(alpha(0, 0), 0, "{name}: top left corner"); + assert_eq!( + alpha(width - 1, height - 1), + 0, + "{name}: bottom right corner" + ); + } + assert_eq!(alpha(width / 2, height / 2), 255, "{name}: the middle"); + // Not one color: something's drawn. + let first = &rgba[(width * height * 2) as usize..(width * height * 2 + 4) as usize]; + assert!(rgba.chunks(4).any(|pixel| pixel != first), "{name}: blank"); + let mode = match shade { + Shade::Dark => "dark", + Shade::Light => "light", + }; + write_png( + &folder().join(format!("{name}-{mode}.png")), + (width, height), + &rgba, + ); +} + +fn both(name: &str, size: Size, set_up: impl Fn(&mut Launcher)) { + for shade in [Shade::Dark, Shade::Light] { + shot(name, shade, size, &set_up); + } +} + +#[test] +fn play_idle_with_nothing_configured() { + both("play-idle", WIDE, |_| {}); +} + +#[test] +fn play_build_running() { + both("play-building", WIDE, building); +} + +#[test] +fn play_not_bootable_yet() { + both("play-not-bootable", WIDE, not_bootable); +} + +#[test] +fn play_failed_command() { + both("play-failed", WIDE, failed); +} + +#[test] +fn settings_pages() { + both("game-files", WIDE, |launcher| { + configured(launcher); + launcher.page = Page::GameFiles; + }); + both("build", WIDE, |launcher| { + launcher.page = Page::Build; + launcher.settings.stages.retain(|stage| stage != "assets"); + }); + both("diagnostics", WIDE, |launcher| { + launcher.page = Page::Diagnostics; + launcher.settings.trace_d3d12 = true; + }); +} + +#[test] +fn performance_page() { + both("performance", WIDE, |launcher| { + launcher.page = Page::Performance; + launcher.settings.gpu = "radeon".to_owned(); + launcher.settings.jobs = "8".to_owned(); + }); +} + +#[test] +fn play_scene_at_the_sketchs_size() { + both("play-scene-large", LARGE, not_bootable); + both("play-scene-large-building", LARGE, building); +} + +#[test] +fn folded_sidebar() { + both("folded-sidebar", NARROW, |_| {}); + both("folded-page", NARROW, |launcher| { + not_bootable(launcher); + launcher.chrome.show_page(); + }); +} diff --git a/tests/test_docs_cli_flags.py b/tests/test_docs_cli_flags.py index c88e4b85a1..816855f3b4 100644 --- a/tests/test_docs_cli_flags.py +++ b/tests/test_docs_cli_flags.py @@ -23,10 +23,12 @@ SOURCE_SUFFIXES = (".py", ".ps1", ".cpp", ".cc", ".c", ".h", ".hpp", ".cmake", ".txt", ".cs", ".cjs", ".js", ".html", ".bat", ".sh", ".yml", ".yaml", ".csproj") # Flags of other programs the docs quote: gh (AGENTS.md), pip (docs/shader_validation.md), argparse itself, and -# the spirv-opt passes docs/embedded_shaders.md tried on one module. +# the spirv-opt passes docs/embedded_shaders.md tried on one module, and cargo and Rust's test runner +# (launcher/README.md). FOREIGN = {"--search", "--state", "--index-url", "--help", "--ssa-rewrite", "--eliminate-dead-code-aggressive", "--eliminate-dead-branches", "--merge-blocks", - "--cfg-cleanup", "--merge-return", "--scalar-replacement"} + "--cfg-cleanup", "--merge-return", "--scalar-replacement", + "--all-targets", "--ignored", "--nocapture"} # Pages that quote another project's tree (SCARAB, americas-recomp). OTHER_PROJECTS = {"docs/fssm_crosscheck.md", "docs/d3d12_xs_surface.md"} COMMAND = re.compile(r"\bpython3?(?: -I)? ((?:tools|scripts)/[\w/]+\.py|make_game\.py)\b")